diff --git a/extras/pandora_update_version.sh b/extras/pandora_update_version.sh index 0b22878285..90c4bf6519 100755 --- a/extras/pandora_update_version.sh +++ b/extras/pandora_update_version.sh @@ -16,7 +16,7 @@ else fi VERSION=$2 if [ $# == 2 ]; then - BUILD=`date +%g%m%d` + BUILD=`date +%y%m%d` else BUILD=$3 fi diff --git a/pandora_agents/pc/AIX/pandora_agent.conf b/pandora_agents/pc/AIX/pandora_agent.conf index ad9f9f3c3d..bff05d8732 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.729, AIX version +# Version 7.0NG.731, 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 8de6468c19..938691a2af 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.729, FreeBSD Version +# Version 7.0NG.731, 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 0c7582879b..d6f6d248c9 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.729, HP-UX Version +# Version 7.0NG.731, 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 17b4e3ec67..0de221f790 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.729, GNU/Linux +# Version 7.0NG.731, 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 15f274095a..cb90a522a3 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.729, GNU/Linux +# Version 7.0NG.731, 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 b4e901951d..1758206b7b 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.729, Solaris Version +# Version 7.0NG.731, 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 bbf52b6bc1..bc4a50047f 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.729 +# Version 7.0NG.731 # 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 72375ecebe..6ca5613d16 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.729, AIX version +# Version 7.0NG.731, 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 6d08062786..b55b3033f6 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.729 +# Version 7.0NG.731 # 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 9b452127ca..4a5a240381 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.729, HPUX Version +# Version 7.0NG.731, HPUX Version # General Parameters # ================== diff --git a/pandora_agents/shellscript/linux/pandora_agent.conf b/pandora_agents/shellscript/linux/pandora_agent.conf index c8ebc2b25f..8e2600567a 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.729 +# Version 7.0NG.731 # 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 d0044b7398..8dfed3e54d 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.729 +# Version 7.0NG.731 # 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 53b696ba06..ca04eca187 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.729 +# Version 7.0NG.731 # 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 c592279323..563805acdb 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.729, Solaris version +# Version 7.0NG.731, Solaris version # General Parameters # ================== diff --git a/pandora_agents/unix/AIX/pandora_agent.conf b/pandora_agents/unix/AIX/pandora_agent.conf index 64671fae84..9d787783ff 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.729, AIX version +# Version 7.0NG.731, 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 4fec552986..c9e01190e9 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.729-181210 +Version: 7.0NG.731-190215 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 3e41fa8411..f50b4ee8dc 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.729-181210" +pandora_version="7.0NG.731-190215" 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 160a20b253..2164faaedc 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.729, GNU/Linux +# Version 7.0NG.731, 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 e97a1675fb..0c5a190f9b 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.729, FreeBSD Version +# Version 7.0NG.731, 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 366928ea65..f039431f7a 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.729, HP-UX Version +# Version 7.0NG.731, 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 e6a3200726..df03402446 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.729, GNU/Linux +# Version 7.0NG.731, 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 c3f4b791f1..12421565e8 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.729, GNU/Linux +# Version 7.0NG.731, 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 8efe821f74..6dd394db7a 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.729, NetBSD Version +# Version 7.0NG.731, 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 b32f162d4b..3d7294a56a 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.729, Solaris Version +# Version 7.0NG.731, 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 9dc1d6223c..187f94b41d 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.729'; -use constant AGENT_BUILD => '181210'; +use constant AGENT_VERSION => '7.0NG.731'; +use constant AGENT_BUILD => '190215'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; @@ -516,11 +516,18 @@ sub parse_conf_modules($) { log_message ('setup', "Invalid regular expression in intensive condition: $line"); } } - } elsif ($line =~ /^\s*module_crontab\s+(((\*|(\d+(-\d+){0,1}))\s*){5}).*$/) { + } elsif ($line =~ /^\s*module_crontab\s+(.*)$/) { my $cron_text = $1; chomp ($cron_text); + $cron_text =~ s/\s+$//; + # Get module name if is already read. + my $module_name_message = ""; + $module_name_message = " (module $module->{'name'})" if defined($module->{'name'}); if (cron_check_syntax($cron_text)) { $module->{'cron'} = $cron_text; + log_message('debug', "Cron '$module->{'cron'}' configured $module_name_message."); + } else { + log_message('setup', "Incorrect cron syntax '$cron_text'. This module$module_name_message will be executed always."); } } elsif ($line =~ /^\s*module_end\s*$/) { @@ -2397,6 +2404,7 @@ sub check_module_cron { $interval ); + my $is_first = ($module->{'cron_utimestamp'} == 0) ? 1 : 0; $module->{'cron_utimestamp'} = $now + $time_to_next_execution; $module->{'cron_interval'} = $time_to_next_execution; @@ -2405,7 +2413,7 @@ sub check_module_cron { } # On first execution checking if cron is valid is required - return 1 unless ($module->{'cron_utimestamp'} == 0); + return 1 unless ($is_first); # Check if current timestamp is a valid cron date my $next_execution = cron_next_execution_date( diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 5d1e0c2729..16bf75ef2f 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.729 -%define release 181210 +%define version 7.0NG.731 +%define release 190215 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 f98db0dc4a..1dd06bf43e 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.729 -%define release 181210 +%define version 7.0NG.731 +%define release 190215 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 d78b9a021f..340a0c2712 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.729" -PI_BUILD="181210" +PI_VERSION="7.0NG.731" +PI_BUILD="190215" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/win32/bin/pandora_agent.conf b/pandora_agents/win32/bin/pandora_agent.conf index 9ba6eff68d..aab9a2f315 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.729 +# Version 7.0NG.731 # 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 5431415815..b7dff2f2ec 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.729} +{Pandora FMS Windows Agent v7.0NG.731} ApplicationID {17E3D2CF-CA02-406B-8A80-9D31C17BD08F} @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{181210} +{190215} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 92a0ac3bd6..48aba959cb 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.729(Build 181210)") +#define PANDORA_VERSION ("7.0NG.731(Build 190215)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index 5de93117ea..2b58063706 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.729(Build 181210))" + VALUE "ProductVersion", "(7.0NG.731(Build 190215))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 2c93228053..12ecde5daf 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.729-181210 +Version: 7.0NG.731-190215 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 8361ef879e..0171643ae5 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/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.729-181210" +pandora_version="7.0NG.731-190215" package_pear=0 package_pandora=1 diff --git a/pandora_console/ajax.php b/pandora_console/ajax.php index 97ffe031a9..92f6c146bc 100644 --- a/pandora_console/ajax.php +++ b/pandora_console/ajax.php @@ -4,88 +4,101 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +// Enable profiler for testing +if (!defined('__PAN_XHPROF__')) { + define('__PAN_XHPROF__', 0); +} -if ((! file_exists("include/config.php")) || (! is_readable("include/config.php"))) { - exit; +if (__PAN_XHPROF__ === 1) { + if (function_exists('tideways_xhprof_enable')) { + tideways_xhprof_enable(); + } +} + +if ((! file_exists('include/config.php')) || (! is_readable('include/config.php'))) { + exit; } // Don't start a session before this import. // The session is configured and started inside the config process. -require_once ('include/config.php'); -require_once ('include/functions.php'); -require_once ('include/functions_db.php'); -require_once ('include/auth/mysql.php'); +require_once 'include/config.php'; +require_once 'include/functions.php'; +require_once 'include/functions_db.php'; +require_once 'include/auth/mysql.php'; // Hash login process -if (isset ($_GET["loginhash"])) { - - $loginhash_data = get_parameter("loginhash_data", ""); - $loginhash_user = str_rot13(get_parameter("loginhash_user", "")); - - if ($config["loginhash_pwd"] != "" - && $loginhash_data == md5($loginhash_user.io_output_password($config["loginhash_pwd"]))) { - db_logon ($loginhash_user, $_SERVER['REMOTE_ADDR']); - $_SESSION['id_usuario'] = $loginhash_user; - $config["id_user"] = $loginhash_user; - } - else { - require_once ('general/login_page.php'); - db_pandora_audit("Logon Failed (loginhash", "", "system"); - while (@ob_end_flush ()); - exit (""); - } +if (isset($_GET['loginhash'])) { + $loginhash_data = get_parameter('loginhash_data', ''); + $loginhash_user = str_rot13(get_parameter('loginhash_user', '')); + + if ($config['loginhash_pwd'] != '' + && $loginhash_data == md5($loginhash_user.io_output_password($config['loginhash_pwd'])) + ) { + db_logon($loginhash_user, $_SERVER['REMOTE_ADDR']); + $_SESSION['id_usuario'] = $loginhash_user; + $config['id_user'] = $loginhash_user; + } else { + include_once 'general/login_page.php'; + db_pandora_audit('Logon Failed (loginhash', '', 'system'); + while (@ob_end_flush()) { + } + + exit(''); + } } $public_hash = get_parameter('hash', false); // Check user if ($public_hash == false) { - check_login(); + check_login(); } else { - enterprise_include_once('include/functions_dashboard.php'); - if (dashboard_check_public_hash($public_hash) === false) { - db_pandora_audit("Invalid public hash", "Trying to access public dashboard"); - require ("general/noaccess.php"); - exit; - } + enterprise_include_once('include/functions_dashboard.php'); + if (dashboard_check_public_hash($public_hash) === false) { + db_pandora_audit('Invalid public hash', 'Trying to access public dashboard'); + include 'general/noaccess.php'; + exit; + } } -define ('AJAX', true); +define('AJAX', true); -/* Enterprise support */ -if (file_exists (ENTERPRISE_DIR."/load_enterprise.php")) { - include_once (ENTERPRISE_DIR."/load_enterprise.php"); +// Enterprise support +if (file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) { + include_once ENTERPRISE_DIR.'/load_enterprise.php'; } -$config["remote_addr"] = $_SERVER['REMOTE_ADDR']; +$config['remote_addr'] = $_SERVER['REMOTE_ADDR']; -$page = (string) get_parameter ('page'); -$page = safe_url_extraclean ($page); +$page = (string) get_parameter('page'); +$page = safe_url_extraclean($page); $page .= '.php'; -$config["id_user"] = $_SESSION["id_usuario"]; -$isFunctionSkins = enterprise_include_once ('include/functions_skins.php'); -if ($isFunctionSkins !== ENTERPRISE_NOT_HOOK) - $config["relative_path"] = enterprise_hook('skins_set_image_skin_path',array($config['id_user'])); +$config['id_user'] = $_SESSION['id_usuario']; +$isFunctionSkins = enterprise_include_once('include/functions_skins.php'); +if ($isFunctionSkins !== ENTERPRISE_NOT_HOOK) { + $config['relative_path'] = enterprise_hook('skins_set_image_skin_path', [$config['id_user']]); +} if (isset($config['metaconsole'])) { - // Not cool way of know if we are executing from metaconsole or normal console - if ($config['metaconsole']) - define ('METACONSOLE', true); + // Not cool way of know if we are executing from metaconsole or normal console + if ($config['metaconsole']) { + define('METACONSOLE', true); + } } -if (file_exists ($page)) { - require_once ($page); +if (file_exists($page)) { + include_once $page; +} else { + echo '
Sorry! I can\'t find the page '.$page.'!'; } -else { - echo '
Sorry! I can\'t find the page '.$page.'!'; + +if (__PAN_XHPROF__ === 1) { + pandora_xhprof_display_result('ajax', 'console'); } -?> diff --git a/pandora_console/attachment/index.html b/pandora_console/attachment/index.html index bb9bc18033..f5b135cf47 100644 --- a/pandora_console/attachment/index.html +++ b/pandora_console/attachment/index.html @@ -1,3 +1,3 @@ - + diff --git a/pandora_console/attachment/mibs/index.html b/pandora_console/attachment/mibs/index.html index bb9bc18033..f5b135cf47 100644 --- a/pandora_console/attachment/mibs/index.html +++ b/pandora_console/attachment/mibs/index.html @@ -1,3 +1,3 @@ - + diff --git a/pandora_console/attachment/plugin/index.html b/pandora_console/attachment/plugin/index.html index bb9bc18033..f5b135cf47 100644 --- a/pandora_console/attachment/plugin/index.html +++ b/pandora_console/attachment/plugin/index.html @@ -1,3 +1,3 @@ - + diff --git a/pandora_console/composer.json b/pandora_console/composer.json index 1138ecf522..acc6a3e352 100644 --- a/pandora_console/composer.json +++ b/pandora_console/composer.json @@ -1,14 +1,14 @@ { - "name": "Pandora FMS", - "description": "Pandora Flexible Monitoring System ", - "authors": [ - { - "name": "Artica", - "email": "info@artica.es" - } - ], - "require": { - "mpdf/mpdf": "^7.1", - "swiftmailer/swiftmailer": "^6.0" + "name": "Pandora FMS", + "description": "Pandora Flexible Monitoring System ", + "authors": [ + { + "name": "Artica", + "email": "info@artica.es" } + ], + "require": { + "mpdf/mpdf": "^7.1", + "swiftmailer/swiftmailer": "^6.0" + } } diff --git a/pandora_console/extensions/agents_alerts.php b/pandora_console/extensions/agents_alerts.php index 7669fa00c5..46272504f6 100755 --- a/pandora_console/extensions/agents_alerts.php +++ b/pandora_console/extensions/agents_alerts.php @@ -4,499 +4,564 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_users.php'; -include_once($config['homedir'] . "/include/functions_agents.php"); -include_once($config['homedir'] . "/include/functions_modules.php"); -include_once($config['homedir'] . '/include/functions_users.php'); -function mainAgentsAlerts() { - global $config; - - // Load global vars - require_once ("include/config.php"); - require_once ("include/functions_reporting.php"); - - check_login (); - // ACL Check - if (! check_acl ($config['id_user'], 0, "AR")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent view (Grouped)"); - require ("general/noaccess.php"); - exit; - } - - // Update network modules for this group - // Check for Network FLAG change request - // Made it a subquery, much faster on both the database and server side - if (isset ($_GET["update_netgroup"])) { - $group = get_parameter_get ("update_netgroup", 0); - if (check_acl ($config['id_user'], $group, "AW")) { - $where = array("id_agente" => "ANY(SELECT id_agente FROM tagente WHERE id_grupo = " . $group); - - db_process_sql_update('tagente_modulo', array("flag" => 1), $where); - } - else { - db_pandora_audit("ACL Violation", "Trying to set flag for groups"); - require ("general/noaccess.php"); - exit; - } - } - - if ($config["realtimestats"] == 0) { - $updated_info = __('Last update'). " : ". ui_print_timestamp (db_get_sql ("SELECT min(utimestamp) FROM tgroup_stat"), true); - } - else { - // $updated_info = __("Updated at realtime"); - $updated_info = ""; - } - - $updated_time = $updated_info; - $create_alert = (int)get_parameter ("create_alert",0); - - if($create_alert){ - $template2 = get_parameter("template"); - $module_action_threshold = get_parameter("module_action_threshold"); - - $id_alert = alerts_create_alert_agent_module ($create_alert, $template2); - - if ($id_alert !== false) { - $action_select = get_parameter("action_select",0); - - if ($action_select != 0) { - $values = array(); - $values['fires_min'] = 0; - $values['fires_max'] = 0; - $values['module_action_threshold'] = - (int)get_parameter ('module_action_threshold'); - - alerts_add_alert_agent_module_action ($id_alert, $action_select, $values); - } - } - - } - $refr = (int) get_parameter('refr', 30); // By default 30 seconds - $show_modules = (bool) get_parameter ("show_modules",0); - $group_id = get_parameter('group_id', 0); - $offset = get_parameter('offset', 0); - $hor_offset = get_parameter('hor_offset', 0); - $block = 20; - - $groups = users_get_groups (); - - $filter_groups .= ''.__('Group').''; - $filter_groups .= html_print_select_groups(false, "AR", true, 'group_id', $group_id, false, '', '', true, false, true, '', false , 'margin-right: 10px; margin-top: 5px;'); - - $check = ''.__('Show modules without alerts').''; - $check .= html_print_checkbox('slides_ids[]', $d['id'], $show_modules, true, false, '', true); - - - $comborefr = '
'; - $comborefr .= ''.__('Refresh').''; - $comborefr .= html_print_select ( - array('30' => '30 '.__('seconds'), - (string)SECONDS_1MINUTE => __('1 minute'), - (string)SECONDS_2MINUTES => __('2 minutes'), - (string)SECONDS_5MINUTES => __('5 minutes'), - (string)SECONDS_10MINUTES => __('10 minutes')) - , 'refr', (int)get_parameter('refr', 0), $script = 'this.form.submit()', '', 0, true, false, false, '', false, 'width: 100px; margin-right: 10px; margin-top: 5px;'); - $comborefr .= "
"; - - if ($config["pure"] == 0) { - $fullscreen['text'] = '' - . html_print_image ("images/full_screen.png", true, array ("title" => __('Full screen mode'))) - . ""; - } - else { - $fullscreen['text'] = '' - . html_print_image ("images/normal_screen.png", true, array ("title" => __('Back to normal mode'))) - . ""; - $config['refr'] = $refr; - } - - $onheader = array('updated_time' => $updated_time, 'fullscreen' => $fullscreen, - 'combo_groups' => $filter_groups); - - if ($config['pure'] == 1) { - $onheader['combo_refr'] = $comborefr; - } - - // Header - ui_print_page_header (__("Agents/Alerts"), "images/op_alerts.png", false, "", false, $updated_time); - - // Old style table, we need a lot of special formatting,don't use table function - // Prepare old-style table - echo ''; - echo ""; - echo ""; - echo ""; - if ($config['pure'] == 1) - echo ""; - echo ""; - echo ""; - echo "
" . $filter_groups . "" . $check . "" . $comborefr . " " . __("Full screen") . "" . $fullscreen['text'] . "
"; - - if($show_modules){ - - - if($group_id > 0){ - $grupo = " AND tagente.id_grupo = $group_id"; - } else { - $grupo =''; - } - - $offset_modules = get_parameter ("offset",0); - $sql_count = "SELECT COUNT(tagente_modulo.nombre) FROM tagente_modulo +function mainAgentsAlerts() +{ + global $config; + + // Load global vars + include_once 'include/config.php'; + include_once 'include/functions_reporting.php'; + + check_login(); + // ACL Check + if (! check_acl($config['id_user'], 0, 'AR')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent view (Grouped)' + ); + include 'general/noaccess.php'; + exit; + } + + // Update network modules for this group + // Check for Network FLAG change request + // Made it a subquery, much faster on both the database and server side + if (isset($_GET['update_netgroup'])) { + $group = get_parameter_get('update_netgroup', 0); + if (check_acl($config['id_user'], $group, 'AW')) { + $where = ['id_agente' => 'ANY(SELECT id_agente FROM tagente WHERE id_grupo = '.$group]; + + db_process_sql_update('tagente_modulo', ['flag' => 1], $where); + } else { + db_pandora_audit('ACL Violation', 'Trying to set flag for groups'); + include 'general/noaccess.php'; + exit; + } + } + + if ($config['realtimestats'] == 0) { + $updated_info = __('Last update').' : '.ui_print_timestamp(db_get_sql('SELECT min(utimestamp) FROM tgroup_stat'), true); + } else { + // $updated_info = __("Updated at realtime"); + $updated_info = ''; + } + + $updated_time = $updated_info; + $create_alert = (int) get_parameter('create_alert', 0); + + if ($create_alert) { + $template2 = get_parameter('template'); + $module_action_threshold = get_parameter('module_action_threshold'); + + $id_alert = alerts_create_alert_agent_module($create_alert, $template2); + + if ($id_alert !== false) { + $action_select = get_parameter('action_select', 0); + + if ($action_select != 0) { + $values = []; + $values['fires_min'] = 0; + $values['fires_max'] = 0; + $values['module_action_threshold'] = (int) get_parameter('module_action_threshold'); + + alerts_add_alert_agent_module_action($id_alert, $action_select, $values); + } + } + } + + $refr = (int) get_parameter('refr', 30); + // By default 30 seconds + $show_modules = (bool) get_parameter('show_modules', 0); + $group_id = get_parameter('group_id', 0); + $offset = get_parameter('offset', 0); + $hor_offset = get_parameter('hor_offset', 0); + $block = 20; + + $groups = users_get_groups(); + + $filter_groups .= ''.__('Group').''; + $filter_groups .= html_print_select_groups(false, 'AR', true, 'group_id', $group_id, false, '', '', true, false, true, '', false, 'margin-right: 10px; margin-top: 5px;'); + + $check = ''.__('Show modules without alerts').''; + $check .= html_print_checkbox('slides_ids[]', $d['id'], $show_modules, true, false, '', true); + + $comborefr = '
'; + $comborefr .= ''.__('Refresh').''; + $comborefr .= html_print_select( + [ + '30' => '30 '.__('seconds'), + (string) SECONDS_1MINUTE => __('1 minute'), + (string) SECONDS_2MINUTES => __('2 minutes'), + (string) SECONDS_5MINUTES => __('5 minutes'), + (string) SECONDS_10MINUTES => __('10 minutes'), + ], + 'refr', + (int) get_parameter('refr', 0), + $script = 'this.form.submit()', + '', + 0, + true, + false, + false, + '', + false, + 'width: 100px; margin-right: 10px; margin-top: 5px;' + ); + $comborefr .= '
'; + + if ($config['pure'] == 0) { + $fullscreen['text'] = ''.html_print_image('images/full_screen.png', true, ['title' => __('Full screen mode')]).''; + } else { + $fullscreen['text'] = ''.html_print_image('images/normal_screen.png', true, ['title' => __('Back to normal mode')]).''; + $config['refr'] = $refr; + } + + $onheader = [ + 'updated_time' => $updated_time, + 'fullscreen' => $fullscreen, + 'combo_groups' => $filter_groups, + ]; + + if ($config['pure'] == 1) { + $onheader['combo_refr'] = $comborefr; + } + + // Header + ui_print_page_header(__('Agents/Alerts'), 'images/op_alerts.png', false, '', false, $updated_time); + + // Old style table, we need a lot of special formatting,don't use table function + // Prepare old-style table + echo ''; + echo ''; + echo ''; + echo ''; + if ($config['pure'] == 1) { + echo ''; + } + + echo ''; + echo ''; + echo '
'.$filter_groups.''.$check.''.$comborefr.' '.__('Full screen').''.$fullscreen['text'].'
'; + + if ($show_modules) { + if ($group_id > 0) { + $grupo = " AND tagente.id_grupo = $group_id"; + } else { + $grupo = ''; + } + + $offset_modules = get_parameter('offset', 0); + $sql_count = "SELECT COUNT(tagente_modulo.nombre) FROM tagente_modulo INNER JOIN tagente ON tagente.id_agente = tagente_modulo.id_agente WHERE id_agente_modulo NOT IN (SELECT id_agent_module FROM talert_template_modules) $grupo"; - $count_agent_module = db_get_all_rows_sql($sql_count); - - $sql = "SELECT tagente.alias, tagente_modulo.nombre, + $count_agent_module = db_get_all_rows_sql($sql_count); + + $sql = "SELECT tagente.alias, tagente_modulo.nombre, tagente_modulo.id_agente_modulo FROM tagente_modulo INNER JOIN tagente ON tagente.id_agente = tagente_modulo.id_agente WHERE id_agente_modulo NOT IN (SELECT id_agent_module FROM talert_template_modules) $grupo LIMIT 20 OFFSET $offset_modules"; - $agent_modules = db_get_all_rows_sql($sql); - - ui_pagination ($count_agent_module[0]['COUNT(tagente_modulo.nombre)'], - ui_get_url_refresh(),0,0,false,'offset',true,'', - '',false,'alerts_modules'); - - $table->width = '100%'; - $table->class = "databox data"; - $table->id = "table_agent_module"; - $table->data = array (); - - $table->head[0] = __('Agents'); - $table->head[1] = __('Modules'); - $table->head[2] = __('Actions'); - - $table->style[0]= 'width: 25%;'; - $table->style[1]= 'width: 33%;'; - $table->style[2]= 'width: 33%;'; - - foreach($agent_modules as $agent_module) { - $data[0] = io_safe_output($agent_module['alias']); - $data[1] = io_safe_output($agent_module['nombre']); - $uniqid = $agent_module['id_agente_modulo']; - $data[2] = "".html_print_image('images/add_mc.png', true).""; - array_push ($table->data, $data); - - $table2->width = '100%'; - $table2->id = "table_add_alert"; - $table2->class = 'databox filters'; - $table2->data = array (); - // $data[0] = - $table2->data[0][0] = __('Actions'); + $agent_modules = db_get_all_rows_sql($sql); - $groups_user = users_get_groups($config["id_user"]); - if (!empty($groups_user)) { - $groups = implode(',', array_keys($groups_user)); - $sql = "SELECT id, name FROM talert_actions WHERE id_group IN ($groups)"; - $actions = db_get_all_rows_sql($sql); - } + ui_pagination( + $count_agent_module[0]['COUNT(tagente_modulo.nombre)'], + ui_get_url_refresh(), + 0, + 0, + false, + 'offset', + true, + '', + '', + false, + 'alerts_modules' + ); - $table2->data[0][1] = html_print_select( - index_array($actions, 'id', 'name'), 'action_select', '', '', - __('Default action'), '0', true, '', true, '', false, - 'width: 250px;'); - $table2->data[0][1] .= ''; - if (check_acl ($config['id_user'], 0, "LM")) { + $table->width = '100%'; + $table->class = 'databox data'; + $table->id = 'table_agent_module'; + $table->data = []; - $table2->data[0][1] .= ''; - $table2->data[0][1] .= html_print_image ('images/add.png', true); - $table2->data[0][1] .= ''.__('Create Action').''; - $table2->data[0][1] .= ''; - } - - $table2->data[1][0] = __('Template'); - $own_info = get_user_info ($config['id_user']); - if ($own_info['is_admin'] || check_acl ($config['id_user'], 0, "PM")) - $templates = alerts_get_alert_templates (false, array ('id', 'name')); - else { - $usr_groups = users_get_groups($config['id_user'], 'LW', true); - $filter_groups = ''; - $filter_groups = implode(',', array_keys($usr_groups)); - $templates = alerts_get_alert_templates (array ('id_group IN (' . $filter_groups . ')'), array ('id', 'name')); - } + $table->head[0] = __('Agents'); + $table->head[1] = __('Modules'); + $table->head[2] = __('Actions'); - $table2->data[1][1] = html_print_select (index_array ($templates, 'id', 'name'), - 'template', '', '', __('Select'), 0, true, false, true, '', false, 'width: 250px;'); - $table2->data[1][1] .= ' '; - if (check_acl ($config['id_user'], 0, "LM")) { - $table2->data[1][1] .= ''; - $table2->data[1][1] .= html_print_image ('images/add.png', true); - $table2->data[1][1] .= ''.__('Create Template').''; - $table2->data[1][1] .= ''; - } - $table2->data[2][0] = __('Threshold'); - $table2->data[2][1] = html_print_input_text ('module_action_threshold', '0', '', 5, 7, true); - $table2->data[2][1] .= ' ' . __('seconds') . ui_print_help_icon ('action_threshold', true); - - $content2 = '
'; - $content2 .= html_print_table($table2,true); - - $content2 .= '
'; - $content2 .= html_print_submit_button (__('Add alert'), 'add', false, 'class="sub wand"',true); - $content2 .= html_print_input_hidden ('create_alert', $uniqid,true); - $content2 .= '
'; - - $module_name = ui_print_truncate_text(io_safe_output($agent_module['nombre']), 40, false, true, false, '…', false); - echo ''; - } - - html_print_table($table); - - } else { - - $filter = array ('offset' => (int) $offset, - 'limit' => (int) $config['block_size']); - $filter_count = array(); - - if ($group_id > 0) { - $filter['id_grupo'] = $group_id; - $filter_count['id_grupo'] = $group_id; - } - - // Get the id of all agents with alerts - $sql = 'SELECT DISTINCT(id_agente) + $table->style[0] = 'width: 25%;'; + $table->style[1] = 'width: 33%;'; + $table->style[2] = 'width: 33%;'; + + foreach ($agent_modules as $agent_module) { + $data[0] = io_safe_output($agent_module['alias']); + $data[1] = io_safe_output($agent_module['nombre']); + $uniqid = $agent_module['id_agente_modulo']; + $data[2] = "".html_print_image('images/add_mc.png', true).''; + array_push($table->data, $data); + + $table2->width = '100%'; + $table2->id = 'table_add_alert'; + $table2->class = 'databox filters'; + $table2->data = []; + // $data[0] = + $table2->data[0][0] = __('Actions'); + + $groups_user = users_get_groups($config['id_user']); + if (!empty($groups_user)) { + $groups = implode(',', array_keys($groups_user)); + $sql = "SELECT id, name FROM talert_actions WHERE id_group IN ($groups)"; + $actions = db_get_all_rows_sql($sql); + } + + $table2->data[0][1] = html_print_select( + index_array($actions, 'id', 'name'), + 'action_select', + '', + '', + __('Default action'), + '0', + true, + '', + true, + '', + false, + 'width: 250px;' + ); + $table2->data[0][1] .= ''; + if (check_acl($config['id_user'], 0, 'LM')) { + $table2->data[0][1] .= ''; + $table2->data[0][1] .= html_print_image('images/add.png', true); + $table2->data[0][1] .= ''.__('Create Action').''; + $table2->data[0][1] .= ''; + } + + $table2->data[1][0] = __('Template'); + $own_info = get_user_info($config['id_user']); + if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { + $templates = alerts_get_alert_templates(false, ['id', 'name']); + } else { + $usr_groups = users_get_groups($config['id_user'], 'LW', true); + $filter_groups = ''; + $filter_groups = implode(',', array_keys($usr_groups)); + $templates = alerts_get_alert_templates(['id_group IN ('.$filter_groups.')'], ['id', 'name']); + } + + $table2->data[1][1] = html_print_select( + index_array($templates, 'id', 'name'), + 'template', + '', + '', + __('Select'), + 0, + true, + false, + true, + '', + false, + 'width: 250px;' + ); + $table2->data[1][1] .= ' '; + if (check_acl($config['id_user'], 0, 'LM')) { + $table2->data[1][1] .= ''; + $table2->data[1][1] .= html_print_image('images/add.png', true); + $table2->data[1][1] .= ''.__('Create Template').''; + $table2->data[1][1] .= ''; + } + + $table2->data[2][0] = __('Threshold'); + $table2->data[2][1] = html_print_input_text('module_action_threshold', '0', '', 5, 7, true); + $table2->data[2][1] .= ' '.__('seconds').ui_print_help_icon('action_threshold', true); + + $content2 = '
'; + $content2 .= html_print_table($table2, true); + + $content2 .= '
'; + $content2 .= html_print_submit_button(__('Add alert'), 'add', false, 'class="sub wand"', true); + $content2 .= html_print_input_hidden('create_alert', $uniqid, true); + $content2 .= '
'; + + $module_name = ui_print_truncate_text(io_safe_output($agent_module['nombre']), 40, false, true, false, '…', false); + echo ''; + } + + html_print_table($table); + } else { + $filter = [ + 'offset' => (int) $offset, + 'limit' => (int) $config['block_size'], + ]; + $filter_count = []; + + if ($group_id > 0) { + $filter['id_grupo'] = $group_id; + $filter_count['id_grupo'] = $group_id; + } + + // Get the id of all agents with alerts + $sql = 'SELECT DISTINCT(id_agente) FROM tagente_modulo WHERE id_agente_modulo IN (SELECT id_agent_module FROM talert_template_modules)'; - $agents_with_alerts_raw = db_get_all_rows_sql($sql); - - if ($agents_with_alerts_raw === false) { - $agents_with_alerts_raw = array(); - } - - $agents_with_alerts = array(); - foreach ($agents_with_alerts_raw as $awar) { - $agents_with_alerts[] = $awar['id_agente']; - } - - $filter['id_agente'] = $agents_with_alerts; - $filter_count['id_agente'] = $agents_with_alerts; - - $agents = agents_get_agents ($filter); - - $nagents = count(agents_get_agents ($filter_count)); - - if ($agents == false) { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no agents with alerts') ) ); - return; - } - - $all_alerts = agents_get_alerts_simple (); - - if($config["pure"] == 1) { - $block = count($all_alerts); - } - - $templates = array(); - $agent_alerts = array(); - foreach ($all_alerts as $alert) { - $templates[$alert['id_alert_template']] = ''; - $agent_alerts[$alert['agent_name']][$alert['id_alert_template']][] = $alert; - } - - // Prepare pagination - ui_pagination ($nagents,false,0,0,false,'offset',true,'', - '',array('count' => '', 'offset' => 'offset_param'),'alerts_agents'); - - echo ''; - echo ""; - - if ($hor_offset > 0) { - $new_hor_offset = $hor_offset-$block; - echo ""; - } - - $templates_raw = array(); - if (!empty($templates)) { - $sql = sprintf('SELECT id, name + $agents_with_alerts_raw = db_get_all_rows_sql($sql); + + if ($agents_with_alerts_raw === false) { + $agents_with_alerts_raw = []; + } + + $agents_with_alerts = []; + foreach ($agents_with_alerts_raw as $awar) { + $agents_with_alerts[] = $awar['id_agente']; + } + + $filter['id_agente'] = $agents_with_alerts; + $filter_count['id_agente'] = $agents_with_alerts; + + $agents = agents_get_agents($filter); + + $nagents = count(agents_get_agents($filter_count)); + + if ($agents == false) { + ui_print_info_message(['no_close' => true, 'message' => __('There are no agents with alerts') ]); + return; + } + + $all_alerts = agents_get_alerts_simple(); + + if ($config['pure'] == 1) { + $block = count($all_alerts); + } + + $templates = []; + $agent_alerts = []; + foreach ($all_alerts as $alert) { + $templates[$alert['id_alert_template']] = ''; + $agent_alerts[$alert['agent_name']][$alert['id_alert_template']][] = $alert; + } + + // Prepare pagination + ui_pagination( + $nagents, + false, + 0, + 0, + false, + 'offset', + true, + '', + '', + [ + 'count' => '', + 'offset' => 'offset_param', + ], + 'alerts_agents' + ); + + echo '
".__("Agents")." / ".__("Alert templates")." - ". - html_print_image("images/darrowleft.png",true, array('title' => __('Previous templates')))."
'; + echo "'; + + if ($hor_offset > 0) { + $new_hor_offset = ($hor_offset - $block); + echo "'; + } + + $templates_raw = []; + if (!empty($templates)) { + $sql = sprintf( + 'SELECT id, name FROM talert_templates - WHERE id IN (%s)',implode(',',array_keys($templates))); - - $templates_raw = db_get_all_rows_sql($sql); - } - - if (empty($templates_raw)) - $templates_raw = array(); - - $alerts = array(); - $ntemplates = 0; - foreach ($templates_raw as $temp) { - if (isset($templates[$temp['id']]) && $templates[$temp['id']] == '') { - $ntemplates++; - if ($ntemplates <= $hor_offset || $ntemplates > ($hor_offset+$block)) { - continue; - } - $templates[$temp['id']] = $temp['name']; - } - } - - foreach ($templates as $tid => $tname) { - if ($tname == '') { - continue; - } - echo '"; - } - - if (($hor_offset + $block) < $ntemplates) { - $new_hor_offset = $hor_offset+$block; - echo ""; - } - - foreach ($agents as $agent) { - $alias = db_get_row ('tagente', 'id_agente', $agent['id_agente']); - echo ''; - // Name of the agent - echo ''; - - // Alerts of the agent - $anyfired = false; - foreach ($templates as $tid => $tname) { - if ($tname == '') { - continue; - } - if (isset($agent_alerts[$agent['nombre']][$tid])) { - foreach($agent_alerts[$agent['nombre']][$tid] as $alert) { - if($alert["times_fired"] > 0) { - $anyfired = true; - } - } - - $cellstyle = ''; - if($anyfired) { - $cellstyle = 'background:'.COL_ALERTFIRED.';'; - } - - echo ''; - } - echo ''; - } - - echo '
".__('Agents').' / '.__('Alert templates').' + ".html_print_image('images/darrowleft.png', true, ['title' => __('Previous templates')]).' '. io_safe_output($tname) . html_print_image('images/information_alerts.png', true, array('title' => io_safe_output($tname),'style' => 'margin-left:5px' )) ." - ".html_print_image("images/darrowright.png",true, array('title' => __('More templates')))."
'.$alias['alias'].' '; - - $uniqid = uniqid(); - echo "
"; - - echo count($agent_alerts[$agent['nombre']][$tid])." ".__('Alerts')." "; - - echo "".html_print_image('images/zoom.png', true).""; - - echo "
"; - - print_alerts_summary_modal_window($uniqid, $agent_alerts[$agent['nombre']][$tid]); - } - else { - echo '
'; - } - echo '
'; - } - - + WHERE id IN (%s)', + implode(',', array_keys($templates)) + ); + + $templates_raw = db_get_all_rows_sql($sql); + } + + if (empty($templates_raw)) { + $templates_raw = []; + } + + $alerts = []; + $ntemplates = 0; + foreach ($templates_raw as $temp) { + if (isset($templates[$temp['id']]) && $templates[$temp['id']] == '') { + $ntemplates++; + if ($ntemplates <= $hor_offset || $ntemplates > ($hor_offset + $block)) { + continue; + } + + $templates[$temp['id']] = $temp['name']; + } + } + + foreach ($templates as $tid => $tname) { + if ($tname == '') { + continue; + } + + echo ''.io_safe_output($tname).html_print_image('images/information_alerts.png', true, ['title' => io_safe_output($tname), 'style' => 'margin-left:5px' ]).''; + } + + if (($hor_offset + $block) < $ntemplates) { + $new_hor_offset = ($hor_offset + $block); + echo " + ".html_print_image('images/darrowright.png', true, ['title' => __('More templates')]).' '; + } + + foreach ($agents as $agent) { + $alias = db_get_row('tagente', 'id_agente', $agent['id_agente']); + echo ''; + // Name of the agent + echo ''.$alias['alias'].''; + + // Alerts of the agent + $anyfired = false; + foreach ($templates as $tid => $tname) { + if ($tname == '') { + continue; + } + + if (isset($agent_alerts[$agent['nombre']][$tid])) { + foreach ($agent_alerts[$agent['nombre']][$tid] as $alert) { + if ($alert['times_fired'] > 0) { + $anyfired = true; + } + } + + $cellstyle = ''; + if ($anyfired) { + $cellstyle = 'background:'.COL_ALERTFIRED.';'; + } + + echo ' '; + + $uniqid = uniqid(); + echo '
'; + + echo count($agent_alerts[$agent['nombre']][$tid]).' '.__('Alerts').' '; + + echo "".html_print_image('images/zoom.png', true).''; + + echo '
'; + + print_alerts_summary_modal_window($uniqid, $agent_alerts[$agent['nombre']][$tid]); + } else { + echo ' '; + } + + echo ''; + } + + echo ''; + } + + echo ''; + } + } + // Print the modal window for the summary of each alerts group -function print_alerts_summary_modal_window($id, $alerts) { - - $table->width = '98%'; - $table->class = "databox"; - $table->data = array (); - - $table->head[0] = __('Module'); - $table->head[1] = __('Action'); - $table->head[2] = __('Last fired'); - $table->head[3] = __('Status'); - - foreach($alerts as $alert) { - $data[0] = modules_get_agentmodule_name ($alert['id_agent_module']); - - $actions = alerts_get_alert_agent_module_actions ($alert['id']); - - $actionDefault = db_get_value_sql(" +function print_alerts_summary_modal_window($id, $alerts) +{ + $table->width = '98%'; + $table->class = 'databox'; + $table->data = []; + + $table->head[0] = __('Module'); + $table->head[1] = __('Action'); + $table->head[2] = __('Last fired'); + $table->head[3] = __('Status'); + + foreach ($alerts as $alert) { + $data[0] = modules_get_agentmodule_name($alert['id_agent_module']); + + $actions = alerts_get_alert_agent_module_actions($alert['id']); + + $actionDefault = db_get_value_sql( + ' SELECT id_alert_action FROM talert_templates - WHERE id = " . $alert['id_alert_template']); - - $actionText = ''; - - if (!empty($actions)) { - $actionText = '
'; - } - else { - if (!empty($actionDefault)) { - $actionText = db_get_sql ("SELECT name + WHERE id = '.$alert['id_alert_template'] + ); + + $actionText = ''; + + if (!empty($actions)) { + $actionText = '
'; + } else { + if (!empty($actionDefault)) { + $actionText = db_get_sql( + "SELECT name FROM talert_actions - WHERE id = $actionDefault") . - " (" . __("Default") . ")"; - } - } - - $data[1] = $actionText; - $data[2] = ui_print_timestamp ($alert["last_fired"], true); - - $status = STATUS_ALERT_NOT_FIRED; - - if ($alert["times_fired"] > 0) { - $status = STATUS_ALERT_FIRED; - $title = __('Alert fired').' '.$alert["internal_counter"].' '.__('time(s)'); - } - elseif ($alert["disabled"] > 0) { - $status = STATUS_ALERT_DISABLED; - $title = __('Alert disabled'); - } - else { - $status = STATUS_ALERT_NOT_FIRED; - $title = __('Alert not fired'); - } - - $data[3] = ui_print_status_image($status, $title, true); - - array_push ($table->data, $data); - } - - $content = html_print_table($table,true); - - $agent = modules_get_agentmodule_agent_alias($alerts[0]['id_agent_module']); - $template = alerts_get_alert_template_name($alerts[0]['id_alert_template']); - - echo ''; + WHERE id = $actionDefault" + ).' ('.__('Default').')'; + } + } + + $data[1] = $actionText; + $data[2] = ui_print_timestamp($alert['last_fired'], true); + + $status = STATUS_ALERT_NOT_FIRED; + + if ($alert['times_fired'] > 0) { + $status = STATUS_ALERT_FIRED; + $title = __('Alert fired').' '.$alert['internal_counter'].' '.__('time(s)'); + } else if ($alert['disabled'] > 0) { + $status = STATUS_ALERT_DISABLED; + $title = __('Alert disabled'); + } else { + $status = STATUS_ALERT_NOT_FIRED; + $title = __('Alert not fired'); + } + + $data[3] = ui_print_status_image($status, $title, true); + + array_push($table->data, $data); + } + + $content = html_print_table($table, true); + + $agent = modules_get_agentmodule_agent_alias($alerts[0]['id_agent_module']); + $template = alerts_get_alert_template_name($alerts[0]['id_alert_template']); + + echo ''; } -extensions_add_operation_menu_option(__("Agents/Alerts view"), 'estado', null, "v1r1","view"); + +extensions_add_operation_menu_option(__('Agents/Alerts view'), 'estado', null, 'v1r1', 'view'); extensions_add_main_function('mainAgentsAlerts'); ui_require_jquery_file('pandora'); @@ -504,55 +569,55 @@ ui_require_jquery_file('pandora'); ?> diff --git a/pandora_console/extensions/agents_modules.php b/pandora_console/extensions/agents_modules.php index 61675912c3..798f4e140e 100644 --- a/pandora_console/extensions/agents_modules.php +++ b/pandora_console/extensions/agents_modules.php @@ -4,820 +4,828 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +$refr = (int) get_parameter('refresh', 0); +// By default 30 seconds +function mainAgentsModules() +{ + global $config; -$refr = (int) get_parameter('refresh', 0); // By default 30 seconds -function mainAgentsModules() { - global $config; - - // Load global vars - require_once ("include/config.php"); - require_once ("include/functions_reporting.php"); - include_once($config['homedir'] . "/include/functions_agents.php"); - include_once($config['homedir'] . "/include/functions_modules.php"); - include_once($config['homedir'] . '/include/functions_users.php'); - - check_login (); - // ACL Check - if (! check_acl ($config['id_user'], 0, "AR")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent view (Grouped)"); - require ("general/noaccess.php"); - exit; - } - - // Update network modules for this group - // Check for Network FLAG change request - // Made it a subquery, much faster on both the database and server side - if (isset ($_GET["update_netgroup"])) { - $group = get_parameter_get ("update_netgroup", 0); - if (check_acl ($config['id_user'], $group, "AW")) { - $where = array("id_agente" => "ANY(SELECT id_agente FROM tagente WHERE id_grupo = " . $group); - - db_process_sql_update('tagente_modulo', array("flag" => 1), $where); - } - else { - db_pandora_audit("ACL Violation", "Trying to set flag for groups"); - require ("general/noaccess.php"); - exit; - } - } - - if ($config["realtimestats"] == 0) { - $updated_info = __('Last update'). " : ". ui_print_timestamp (db_get_sql ("SELECT min(utimestamp) FROM tgroup_stat"), true); - } - else { - // $updated_info = __("Updated at realtime"); - $updated_info = ""; - } - - $updated_time = $updated_info; - - $modulegroup = get_parameter('modulegroup', 0); - $refr = (int) get_parameter('refresh', 0); // By default 30 seconds - - $recursion = get_parameter('recursion', 0); - $group_id = (int)get_parameter('group_id', 0); - $offset = (int)get_parameter('offset', 0); - $hor_offset = (int)get_parameter('hor_offset', 0); - $block = $config['block_size']; - if(get_parameter('modulegroup') != null){ - $agents_id = (array)get_parameter('id_agents2', null); - } - $selection_a_m = (int)get_parameter('selection_agent_module'); - $modules_selected = (array)get_parameter('module', 0); - $update_item = (string)get_parameter('edit_item',''); - $save_serialize = (int)get_parameter('save_serialize', 0); - $full_modules_selected = explode(";",get_parameter('full_modules_selected', 0)); - $full_agents_id = explode(";",get_parameter('full_agents_id', 0)); - - if($save_serialize && $update_item == ''){ - $unserialize_modules_selected = unserialize_in_temp($config['id_user']."_agent_module", true, 1); - $unserialize_agents_id = unserialize_in_temp($config['id_user']."_agents", true, 1); - if($unserialize_modules_selected){ - $modules_selected = $unserialize_modules_selected; - } - if($unserialize_agents_id){ - $agents_id = $unserialize_agents_id; - } - } - else{ - unserialize_in_temp($config['id_user']."_agent_module", true, 1); - unserialize_in_temp($config['id_user']."_agents", true, 1); - } - - if($modules_selected[0]){ - serialize_in_temp($modules_selected, $config['id_user']."_agent_module", 1); - } - if($agents_id[0] != -1 ){ - serialize_in_temp($agents_id, $config['id_user']."_agents", 1); - } + // Load global vars + include_once 'include/config.php'; + include_once 'include/functions_reporting.php'; + include_once $config['homedir'].'/include/functions_agents.php'; + include_once $config['homedir'].'/include/functions_modules.php'; + include_once $config['homedir'].'/include/functions_users.php'; + check_login(); + // ACL Check + if (! check_acl($config['id_user'], 0, 'AR')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent view (Grouped)' + ); + include 'general/noaccess.php'; + exit; + } - //if($agents_id != -1) $agents_id = null; - - if ($config["pure"] == 0) { - if($modules_selected[0] && $agents_id[0]){ - - $full_modules = urlencode(implode(";",$modules_selected)); - $full_agents = urlencode(implode(";",$agents_id)); - - $fullscreen['text'] = '' - . html_print_image ("images/full_screen.png", true, array ("title" => __('Full screen mode'))) - . ""; - - } else if($full_modules_selected[0] && $full_agents_id[0]){ - - $full_modules = urlencode(implode(";",$full_modules_selected)); - $full_agents = urlencode(implode(";",$full_agents_id)); - - $fullscreen['text'] = ''.html_print_image('images/full_screen.png', true, ['title' => __('Full screen mode')]).''; + } else if ($full_modules_selected[0] && $full_agents_id[0]) { + $full_modules = urlencode(implode(';', $full_modules_selected)); + $full_agents = urlencode(implode(';', $full_agents_id)); + + $fullscreen['text'] = '' - . html_print_image ("images/full_screen.png", true, array ("title" => __('Full screen mode'))) - . ""; - - } else { - $fullscreen['text'] = '' - . html_print_image ("images/full_screen.png", true, array ("title" => __('Full screen mode'))) - . ""; - } - } - - //groups - $filter_groups_label = ''.__('Group').''; - $filter_groups = html_print_select_groups(false, "AR", true, 'group_id', $group_id, '', '', '', true, false, true, '', false , 'width: auto;'); - - $filter_recursion_label = ''.__('Recursion').''; - $filter_recursion = html_print_checkbox('recursion', 1, 0, true); - //groups module - $filter_module_groups_label = ''.__('Module group').''; - $filter_module_groups = html_print_select_from_sql ("SELECT * FROM tmodule_group ORDER BY name", - 'modulegroup', $modulegroup, '',__('All'), 0, true, false, true, false, 'width: auto;'); + &full_agents_id='.$full_agents.'&selection_agent_module='.$selection_a_m.'">'.html_print_image('images/full_screen.png', true, ['title' => __('Full screen mode')]).''; + } else { + $fullscreen['text'] = ''.html_print_image('images/full_screen.png', true, ['title' => __('Full screen mode')]).''; + } + } - //agent - $agents = agents_get_group_agents($group_id); - if ((empty($agents)) || $agents == -1) $agents = array(); - $filter_agents_label = ''.__('Agents').''; - $filter_agents = html_print_select($agents, 'id_agents2[]', $agents_id, '', '', 0, true, true, true, '', false, "min-width: 180px; max-width: 200px;"); + // groups + $filter_groups_label = ''.__('Group').''; + $filter_groups = html_print_select_groups(false, 'AR', true, 'group_id', $group_id, '', '', '', true, false, true, '', false, 'width: auto;'); - //type show - $selection = array(0 => __('Show common modules'), - 1=> __('Show all modules')); - $filter_type_show_label = ''.__('Show common modules').''; - $filter_type_show = html_print_select($selection, 'selection_agent_module', $selection_a_m, '', "", 0, true, false, true, '', false, "min-width: 180px;"); + $filter_recursion_label = ''.__('Recursion').''; + $filter_recursion = html_print_checkbox('recursion', 1, 0, true); + // groups module + $filter_module_groups_label = ''.__('Module group').''; + $filter_module_groups = html_print_select_from_sql( + 'SELECT * FROM tmodule_group ORDER BY name', + 'modulegroup', + $modulegroup, + '', + __('All'), + 0, + true, + false, + true, + false, + 'width: auto;' + ); - //modules - $all_modules = select_modules_for_agent_group($group_id, $agents_id, $selection_a_m, false); - $filter_modules_label = ''.__('Module').''; - $filter_modules = html_print_select($all_modules, 'module[]', $modules_selected, '', '', 0, true, true, false, '', false, "min-width: 180px; max-width: 200px;"); + // agent + $agents = agents_get_group_agents($group_id); + if ((empty($agents)) || $agents == -1) { + $agents = []; + } - //update - $filter_update = html_print_submit_button(__('Update item'), 'edit_item', false, 'class="sub upd"', true); + $filter_agents_label = ''.__('Agents').''; + $filter_agents = html_print_select($agents, 'id_agents2[]', $agents_id, '', '', 0, true, true, true, '', false, 'min-width: 180px; max-width: 200px;'); - $onheader = array('updated_time' => $updated_time, 'fullscreen' => $fullscreen, - 'combo_module_groups' => $filter_module_groups, - 'combo_groups' => $filter_groups); - - // Old style table, we need a lot of special formatting,don't use table function - // Prepare old-style table - if ($config['pure'] == 0){ - // Header - ui_print_page_header (__("Agents/Modules"), "images/module_mc.png", false, "", false, $updated_time); - echo ''; - echo ""; - echo ""; - echo ""; - echo "
" . $fullscreen['text'] . "
"; - } else { - if ($full_agents_id[0]){ - - $full_modules = urlencode(implode(";",$full_modules_selected)) ; - $full_agents = urlencode(implode(";",$full_agents_id)); - - $url =" index.php?sec=view&sec2=extensions/agents_modules&pure=0&offset=$offset + // type show + $selection = [ + 0 => __('Show common modules'), + 1 => __('Show all modules'), + ]; + $filter_type_show_label = ''.__('Show common modules').''; + $filter_type_show = html_print_select($selection, 'selection_agent_module', $selection_a_m, '', '', 0, true, false, true, '', false, 'min-width: 180px;'); + + // modules + $all_modules = select_modules_for_agent_group($group_id, $agents_id, $selection_a_m, false); + $filter_modules_label = ''.__('Module').''; + $filter_modules = html_print_select($all_modules, 'module[]', $modules_selected, '', '', 0, true, true, false, '', false, 'min-width: 180px; max-width: 200px;'); + + // update + $filter_update = html_print_submit_button(__('Update item'), 'edit_item', false, 'class="sub upd"', true); + + $onheader = [ + 'updated_time' => $updated_time, + 'fullscreen' => $fullscreen, + 'combo_module_groups' => $filter_module_groups, + 'combo_groups' => $filter_groups, + ]; + + // Old style table, we need a lot of special formatting,don't use table function + // Prepare old-style table + if ($config['pure'] == 0) { + // Header + ui_print_page_header(__('Agents/Modules'), 'images/module_mc.png', false, '', false, $updated_time); + echo ''; + echo ''; + echo "'; + echo ''; + echo '
".$fullscreen['text'].'
'; + } else { + if ($full_agents_id[0]) { + $full_modules = urlencode(implode(';', $full_modules_selected)); + $full_agents = urlencode(implode(';', $full_agents_id)); + + $url = " index.php?sec=view&sec2=extensions/agents_modules&pure=0&offset=$offset &group_id=$group_id&modulegroup=$modulegroup&refresh=$refr&full_modules_selected=$full_modules &full_agents_id=$full_agents&selection_agent_module=$selection_a_m"; - - } else { - $url =" index.php?sec=view&sec2=extensions/agents_modules&pure=0&offset=$offset&group_id=$group_id&modulegroup=$modulegroup&refresh=$refr"; - } - - // Floating menu - Start - echo '
'; + } else { + $url = " index.php?sec=view&sec2=extensions/agents_modules&pure=0&offset=$offset&group_id=$group_id&modulegroup=$modulegroup&refresh=$refr"; + } - echo ''; - $count = 0; - foreach ($agents as $agent) { - // TODO TAGS agents_get_modules - $module = agents_get_modules($agent, false, - $filter_module_group, true, true); - if ($module == false) { - unset($agents[$count]); - } - $count++; - } - $total_pagination = count($agents); - if($agents_id[0] != -1){ - $all_modules = array(); - foreach ($modules_selected as $key => $value) { - $name = modules_get_agentmodule_name($value); - $sql = "SELECT id_agente_modulo + echo '
'; + // Floating menu - End + ui_require_jquery_file('countdown'); + } + + if ($config['pure'] != 1) { + echo '
'; + + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo "'; + echo ''; + echo '
'.$filter_groups_label.''.$filter_groups.'   '.$filter_recursion_label.$filter_recursion.''.$filter_module_groups_label.''.$filter_module_groups.'
'.$filter_agents_label.''.$filter_agents.''.$filter_type_show_label.''.$filter_type_show.''.$filter_modules_label.''.$filter_modules.'
".$filter_update.'
'; + echo '
'; + } + + if ($agents_id[0] != -1) { + $agents = $agents_id; + } else { + if ($full_agents_id[0]) { + $agents = $full_agents_id; + } else { + $agents = ''; + $agents = agents_get_group_agents($group_id, ['disabled' => 0]); + $agents = array_keys($agents); + } + } + + $filter_module_group = ['disabled' => 0]; + + if ($modulegroup > 0) { + $filter_module_group['id_module_group'] = $modulegroup; + } + + $count = 0; + foreach ($agents as $agent) { + // TODO TAGS agents_get_modules + $module = agents_get_modules( + $agent, + false, + $filter_module_group, + true, + true + ); + if ($module == false) { + unset($agents[$count]); + } + + $count++; + } + + $total_pagination = count($agents); + if ($agents_id[0] != -1) { + $all_modules = []; + foreach ($modules_selected as $key => $value) { + $name = modules_get_agentmodule_name($value); + $sql = "SELECT id_agente_modulo FROM tagente_modulo - WHERE nombre = '". $name ."';"; + WHERE nombre = '".$name."';"; - $result_sql = db_get_all_rows_sql($sql); - - if(is_array($result_sql)){ - foreach ($result_sql as $key => $value) { - $all_modules[$value['id_agente_modulo']] = io_safe_output($name); - } - } - } - } - else{ - if ($full_modules_selected[0]){ - foreach ($full_modules_selected as $key => $value) { - $name = modules_get_agentmodule_name($value); - $sql = "SELECT id_agente_modulo + $result_sql = db_get_all_rows_sql($sql); + + if (is_array($result_sql)) { + foreach ($result_sql as $key => $value) { + $all_modules[$value['id_agente_modulo']] = io_safe_output($name); + } + } + } + } else { + if ($full_modules_selected[0]) { + foreach ($full_modules_selected as $key => $value) { + $name = modules_get_agentmodule_name($value); + $sql = "SELECT id_agente_modulo FROM tagente_modulo - WHERE nombre = '". $name ."';"; + WHERE nombre = '".$name."';"; - $result_sql = db_get_all_rows_sql($sql); - if(is_array($result_sql)){ - foreach ($result_sql as $key => $value) { - $all_modules[$value['id_agente_modulo']] = io_safe_output($name); - } - } - } + $result_sql = db_get_all_rows_sql($sql); + if (is_array($result_sql)) { + foreach ($result_sql as $key => $value) { + $all_modules[$value['id_agente_modulo']] = io_safe_output($name); + } + } + } + } else { + // TODO TAGS agents_get_modules + $all_modules = agents_get_modules( + $agents, + false, + $filter_module_group, + true, + true + ); + } + } - } else { - // TODO TAGS agents_get_modules - $all_modules = agents_get_modules($agents, false, - $filter_module_group, true, true); - } - - } + $modules_by_name = []; + $name = ''; + $cont = 0; + foreach ($all_modules as $key => $module) { + if ($module == $name) { + $modules_by_name[($cont - 1)]['id'][] = $key; + } else { + $name = $module; + $modules_by_name[$cont]['name'] = $name; + $modules_by_name[$cont]['id'][] = $key; + $cont ++; + } + } - $modules_by_name = array(); - $name = ''; - $cont = 0; - foreach ($all_modules as $key => $module) { - if ($module == $name) { - $modules_by_name[$cont-1]['id'][] = $key; - } - else { - $name = $module; - $modules_by_name[$cont]['name'] = $name; - $modules_by_name[$cont]['id'][] = $key; - $cont ++; - } - } - if ($config["pure"] == 1) { - $block = count($modules_by_name); - } - - if($update_item == ''){ - $filter_groups = array ('offset' => (int) $offset, - 'limit' => (int) $config['block_size'], 'disabled' => 0,'id_agente'=>$agents); - } - else{ - $filter_groups = array ('offset' => 0, - 'limit' => (int) $config['block_size'], 'disabled' => 0,'id_agente'=>$agents); - } + if ($config['pure'] == 1) { + $block = count($modules_by_name); + } - if ($group_id > 0) { - if($recursion){ - $filter_groups['id_grupo'] = array_merge($group_id, - groups_get_id_recursive($group_id, true)); - } - else{ - $filter_groups['id_grupo'] = $group_id; - } - } + if ($update_item == '') { + $filter_groups = [ + 'offset' => (int) $offset, + 'limit' => (int) $config['block_size'], + 'disabled' => 0, + 'id_agente' => $agents, + ]; + } else { + $filter_groups = [ + 'offset' => 0, + 'limit' => (int) $config['block_size'], + 'disabled' => 0, + 'id_agente' => $agents, + ]; + } - if (!empty($filter_groups['id_agente'])) { - $agents = agents_get_agents ($filter_groups); - } - $nagents = count($agents); + if ($group_id > 0) { + if ($recursion) { + $filter_groups['id_grupo'] = array_merge( + $group_id, + groups_get_id_recursive($group_id, true) + ); + } else { + $filter_groups['id_grupo'] = $group_id; + } + } - if ($all_modules == false || $agents == false) { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no agents with modules') ) ); - return; - } - - echo ''; - - echo ""; - - echo ""; - - if ($hor_offset > 0) { - $new_hor_offset = $hor_offset-$block; - echo ""; - } - $nmodules = 0; - foreach ($modules_by_name as $module) { - $nmodules++; - - if ($nmodules <= $hor_offset || $nmodules > ($hor_offset+$block)) { - continue; - } - - $text = ui_print_truncate_text(io_safe_output($module['name']), 'module_small'); - - echo ''; + } + + echo ''; + + $filter_agents = [ + 'offset' => (int) $offset, + 'disabled' => 0, + ]; + if ($group_id > 0) { + $filter_agents['id_grupo'] = $group_id; + } + + // Prepare pagination + $url = 'index.php?extension_in_menu=estado&sec=extensions&sec2=extensions/agents_modules&save_serialize=1&'.'hor_offset='.$hor_offset.'&selection_a_m='.$selection_a_m; + ui_pagination($total_pagination, $url); + + foreach ($agents as $agent) { + // Get stats for this group + $agent_status = agents_get_status($agent['id_agente']); + $alias = db_get_row('tagente', 'id_agente', $agent['id_agente']); + if (empty($alias['alias'])) { + $alias['alias'] = $agent['nombre']; + } + + switch ($agent_status) { + case 4: + // Alert fired status + $rowcolor = 'group_view_alrm'; + break; + + case 1: + // Critical status + $rowcolor = 'group_view_crit'; + break; + + case 2: + // Warning status + $rowcolor = 'group_view_warn'; + break; + + case 0: + // Normal status + $rowcolor = 'group_view_ok'; + break; + + case 3: + case -1: + default: + // Unknown status + $rowcolor = 'group_view_unk'; + break; + } + + echo ""; + + echo "'; + // TODO TAGS agents_get_modules + $agent_modules = agents_get_modules($agent['id_agente'], false, $filter_module_group, true, true); + + $nmodules = 0; + foreach ($modules_by_name as $module) { + $nmodules++; + + if ($nmodules <= $hor_offset || $nmodules > ($hor_offset + $block)) { + continue; + } + + $match = false; + + foreach ($module['id'] as $module_id) { + if (!$match && array_key_exists($module_id, $agent_modules)) { + $status = modules_get_agentmodule_status($module_id); + echo "'; + $match = true; + } + } + + if (!$match) { + echo ''; + } + } + + echo ''; + } + + echo '
" . __("Agents") . " / " . __("Modules") . "" . - "" . - html_print_image("images/arrow_left.png", true, - array('title' => __('Previous modules'))) . - "" . - " + if (!empty($filter_groups['id_agente'])) { + $agents = agents_get_agents($filter_groups); + } + + $nagents = count($agents); + + if ($all_modules == false || $agents == false) { + ui_print_info_message(['no_close' => true, 'message' => __('There are no agents with modules') ]); + return; + } + + echo ''; + + echo ''; + + echo "'; + + if ($hor_offset > 0) { + $new_hor_offset = ($hor_offset - $block); + echo "'; + } + + $nmodules = 0; + foreach ($modules_by_name as $module) { + $nmodules++; + + if ($nmodules <= $hor_offset || $nmodules > ($hor_offset + $block)) { + continue; + } + + $text = ui_print_truncate_text(io_safe_output($module['name']), 'module_small'); + + echo ''; - } - - if (($hor_offset + $block) < $nmodules) { - $new_hor_offset = $hor_offset+$block; - echo ""; - } - - echo ""; - - $filter_agents = array('offset' => (int) $offset, 'disabled' => 0); - if ($group_id > 0) { - $filter_agents['id_grupo'] = $group_id; - } - // Prepare pagination - $url = 'index.php?extension_in_menu=estado&sec=extensions&sec2=extensions/agents_modules&save_serialize=1&' . "hor_offset=" . $hor_offset ."&selection_a_m=" . $selection_a_m; - ui_pagination ($total_pagination, $url); - - foreach ($agents as $agent) { - // Get stats for this group - $agent_status = agents_get_status($agent['id_agente']); - $alias = db_get_row ("tagente", "id_agente", $agent['id_agente']); - if (empty($alias['alias'])){ - $alias['alias'] = $agent['nombre']; - } - - switch($agent_status) { - case 4: // Alert fired status - $rowcolor = 'group_view_alrm'; - break; - case 1: // Critical status - $rowcolor = 'group_view_crit'; - break; - case 2: // Warning status - $rowcolor = 'group_view_warn'; - break; - case 0: // Normal status - $rowcolor = "group_view_ok"; - break; - case 3: - case -1: - default: // Unknown status - $rowcolor = 'group_view_unk'; - break; - } - - echo ""; - - echo ""; - // TODO TAGS agents_get_modules - $agent_modules = agents_get_modules($agent['id_agente'], false, $filter_module_group, true, true); - - $nmodules = 0; - foreach ($modules_by_name as $module) { - $nmodules++; - - if ($nmodules <= $hor_offset || $nmodules > ($hor_offset+$block)) { - continue; - } - - $match = false; - - foreach ($module['id'] as $module_id) { - if (!$match && array_key_exists($module_id,$agent_modules)) { - $status = modules_get_agentmodule_status($module_id); - echo ""; - $match = true; - } - } - - if (!$match) { - echo ""; - } - } - echo ""; - } + } - echo "
".__('Agents').' / '.__('Modules').'"."".html_print_image( + 'images/arrow_left.png', + true, + ['title' => __('Previous modules')] + ).''.'
- +
" . - "" . - html_print_image( - "images/arrow.png", true, - array('title' => __('More modules'))) . - "" . - "
- " . - $alias['alias'] . - ""; - $win_handle = dechex(crc32($module_id.$module["name"])); - $graph_type = return_graphtype (modules_get_agentmodule_type($module_id)); - $link ="winopeng('" . - "operation/agentes/stat_win.php?" . - "type=$graph_type&" . - "period=" . SECONDS_1DAY . "&" . - "id=" . $module_id . "&" . - "label=" . rawurlencode( - urlencode( - base64_encode($module["name"]))) . "&" . - "refresh=" . SECONDS_10MINUTES . "', 'day_".$win_handle."')"; - - echo ''; - switch ($status) { - case AGENT_MODULE_STATUS_NORMAL: - ui_print_status_image ('module_ok.png', modules_get_last_value($module_id), false); - break; - case AGENT_MODULE_STATUS_CRITICAL_BAD: - ui_print_status_image ('module_critical.png', modules_get_last_value($module_id), false); - break; - case AGENT_MODULE_STATUS_WARNING: - ui_print_status_image ('module_warning.png', modules_get_last_value($module_id), false); - break; - case AGENT_MODULE_STATUS_UNKNOWN: - ui_print_status_image ('module_unknown.png', modules_get_last_value($module_id), false); - break; - case AGENT_MODULE_STATUS_NORMAL_ALERT: - case AGENT_MODULE_STATUS_WARNING_ALERT: - case AGENT_MODULE_STATUS_CRITICAL_ALERT: - ui_print_status_image ('module_alertsfired.png', modules_get_last_value($module_id), false); - break; - case 4: - ui_print_status_image ('module_no_data.png', modules_get_last_value($module_id), false); - break; - } - echo ''; - echo "
"; - - echo "
"; - - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo "
" . __('Legend') . "
" . __("Orange cell when the module has fired alerts") . "
" . __("Red cell when the module has a critical status") . "
" . __("Yellow cell when the module has a warning status") . "
" . __("Green cell when the module has a normal status") . "
" . __("Grey cell when the module has an unknown status") . "
" . __("Cell turns blue when the module is in 'not initialize' status") . "
"; - echo "
"; - $pure_var = $config['pure']; - if($pure_var){ - $pure_var = 1; - } - else{ - $pure_var = 0; - } + if (($hor_offset + $block) < $nmodules) { + $new_hor_offset = ($hor_offset + $block); + echo "
"."".html_print_image( + 'images/arrow.png', + true, + ['title' => __('More modules')] + ).''.'
+ ".$alias['alias'].'"; + $win_handle = dechex(crc32($module_id.$module['name'])); + $graph_type = return_graphtype(modules_get_agentmodule_type($module_id)); + $link = "winopeng('".'operation/agentes/stat_win.php?'."type=$graph_type&".'period='.SECONDS_1DAY.'&'.'id='.$module_id.'&'.'label='.rawurlencode( + urlencode( + base64_encode($module['name']) + ) + ).'&'.'refresh='.SECONDS_10MINUTES."', 'day_".$win_handle."')"; + + echo ''; + switch ($status) { + case AGENT_MODULE_STATUS_NORMAL: + ui_print_status_image('module_ok.png', modules_get_last_value($module_id), false); + break; + + case AGENT_MODULE_STATUS_CRITICAL_BAD: + ui_print_status_image('module_critical.png', modules_get_last_value($module_id), false); + break; + + case AGENT_MODULE_STATUS_WARNING: + ui_print_status_image('module_warning.png', modules_get_last_value($module_id), false); + break; + + case AGENT_MODULE_STATUS_UNKNOWN: + ui_print_status_image('module_unknown.png', modules_get_last_value($module_id), false); + break; + + case AGENT_MODULE_STATUS_NORMAL_ALERT: + case AGENT_MODULE_STATUS_WARNING_ALERT: + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + ui_print_status_image('module_alertsfired.png', modules_get_last_value($module_id), false); + break; + + case 4: + ui_print_status_image('module_no_data.png', modules_get_last_value($module_id), false); + break; + } + + echo ''; + echo '
'; + + echo "
"; + + echo ''; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo '
".__('Legend').'
".__('Orange cell when the module has fired alerts').'
".__('Red cell when the module has a critical status').'
".__('Yellow cell when the module has a warning status').'
".__('Green cell when the module has a normal status').'
".__('Grey cell when the module has an unknown status').'
".__("Cell turns blue when the module is in 'not initialize' status").'
'; + echo '
'; + $pure_var = $config['pure']; + if ($pure_var) { + $pure_var = 1; + } else { + $pure_var = 0; + } } -extensions_add_operation_menu_option(__("Agents/Modules view"), 'estado', 'agents_modules/icon_menu.png', "v1r1","view"); + +extensions_add_operation_menu_option(__('Agents/Modules view'), 'estado', 'agents_modules/icon_menu.png', 'v1r1', 'view'); extensions_add_main_function('mainAgentsModules'); -$ignored_params['refresh']=''; +$ignored_params['refresh'] = ''; ?> \ No newline at end of file diff --git a/pandora_console/extensions/api_checker.php b/pandora_console/extensions/api_checker.php index 24f7bc31ed..95324eea71 100755 --- a/pandora_console/extensions/api_checker.php +++ b/pandora_console/extensions/api_checker.php @@ -4,226 +4,250 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function api_execute($url, $ip, $pandora_url, $apipass, $user, $password, $op, $op2, $id, $id2, $return_type, $other, $other_mode) +{ + if (empty($url)) { + $url = 'http://'.$ip.$pandora_url.'/include/api.php'; -function api_execute($url, $ip, $pandora_url, $apipass, $user, $password, $op, $op2, $id, $id2, $return_type, $other, $other_mode) { - - if (empty($url)) { - $url = "http://" . $ip . $pandora_url . "/include/api.php"; - - $url .= "?"; - $url .= "apipass=" . $apipass; - $url .= "&user=" . $user; - $url .= "&pass=" . $password; - $url .= "&op=" . $op; - $url .= "&op2=" . $op2; - if ($id !== '') { - $url .= "&id=" . $id; - } - if ($id2 !== '') { - $url .= "&id2=" . $id2; - } - if ($return_type !== '') { - $url .= "&return_type=" . $return_type; - } - if ($other !== '') { - $url .= "&other_mode=" . $other_mode; - $url .= "&other=" . $other; - } - } - - $curlObj = curl_init(); - curl_setopt($curlObj, CURLOPT_URL, $url); - curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); - $result = curl_exec($curlObj); - curl_close($curlObj); - - $return = array('url' => $url, 'result' => $result); - - return $return; + $url .= '?'; + $url .= 'apipass='.$apipass; + $url .= '&user='.$user; + $url .= '&pass='.$password; + $url .= '&op='.$op; + $url .= '&op2='.$op2; + if ($id !== '') { + $url .= '&id='.$id; + } + + if ($id2 !== '') { + $url .= '&id2='.$id2; + } + + if ($return_type !== '') { + $url .= '&return_type='.$return_type; + } + + if ($other !== '') { + $url .= '&other_mode='.$other_mode; + $url .= '&other='.$other; + } + } + + $curlObj = curl_init(); + curl_setopt($curlObj, CURLOPT_URL, $url); + curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); + $result = curl_exec($curlObj); + curl_close($curlObj); + + $return = [ + 'url' => $url, + 'result' => $result, + ]; + + return $return; } -function extension_api_checker() { - global $config; - - check_login (); - - if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Profile Management"); - require ("general/noaccess.php"); - return; - } - - $url = io_safe_output(get_parameter('url', '')); - - $ip = io_safe_output(get_parameter('ip', '127.0.0.1')); - $pandora_url = io_safe_output(get_parameter('pandora_url', $config['homeurl_static'])); - $apipass = io_safe_output(get_parameter('apipass', '')); - $user = io_safe_output(get_parameter('user', $config['id_user'])); - $password = io_safe_output(get_parameter('password', '')); - - $op = io_safe_output(get_parameter('op', 'get')); - $op2 = io_safe_output(get_parameter('op2', 'test')); - $id = io_safe_output(get_parameter('id', '')); - $id2 = io_safe_output(get_parameter('id2', '')); - $return_type = io_safe_output(get_parameter('return_type', '')); - $other = io_safe_output(get_parameter('other', '')); - $other_mode = io_safe_output(get_parameter('other_mode', 'url_encode_separator_|')); - - $api_execute = get_parameter('api_execute', 0); - - $return_call_api = ''; - if ($api_execute) { - $return_call_api = - api_execute($url, $ip, $pandora_url, $apipass, $user, $password, - $op, $op2, urlencode($id), urlencode($id2), - $return_type, urlencode($other), $other_mode); - } - - ui_print_page_header (__("API checker"), - "images/extensions.png", false, "", true, ""); - - $table = null; - $table->data = array(); - - $row = array(); - $row[] = __("IP"); - $row[] = html_print_input_text('ip', $ip, '', 50, 255, true); - $table->data[] = $row; - - $row = array(); - $row[] = __("%s Console URL", get_product_name()); - $row[] = html_print_input_text('pandora_url', $pandora_url, '', 50, 255, true); - $table->data[] = $row; - - $row = array(); - $row[] = __("API Pass"); - $row[] = html_print_input_password('apipass', $apipass, '', 50, 255, true); - $table->data[] = $row; - - $row = array(); - $row[] = __("User"); - $row[] = html_print_input_text('user', $user, '', 50, 255, true); - $table->data[] = $row; - - $row = array(); - $row[] = __("Password"); - $row[] = html_print_input_password('password', $password, '', 50, 255, true); - $table->data[] = $row; - - $table2 = null; - $table2->data = array(); - - $row = array(); - $row[] = __("Action (get or set)"); - $row[] = html_print_input_text('op', $op, '', 50, 255, true); - $table2->data[] = $row; - - $row = array(); - $row[] = __("Operation"); - $row[] = html_print_input_text('op2', $op2, '', 50, 255, true); - $table2->data[] = $row; - - $row = array(); - $row[] = __("ID"); - $row[] = html_print_input_text('id', $id, '', 50, 255, true); - $table2->data[] = $row; - - $row = array(); - $row[] = __("ID 2"); - $row[] = html_print_input_text('id2', $id2, '', 50, 255, true); - $table2->data[] = $row; - - $row = array(); - $row[] = __("Return Type"); - $row[] = html_print_input_text('return_type', $return_type, '', 50, 255, true); - $table2->data[] = $row; - - $row = array(); - $row[] = __("Other"); - $row[] = html_print_input_text('other', $other, '', 50, 255, true); - $table2->data[] = $row; - - $row = array(); - $row[] = __("Other Mode"); - $row[] = html_print_input_text('other_mode', $other_mode, '', 50, 255, true); - $table2->data[] = $row; - - $table3 = null; - $table3->data = array(); - - $row = array(); - $row[] = __("Raw URL"); - $row[] = html_print_input_text('url', $url, '', 150, 2048, true); - $table3->data[] = $row; - - echo "
"; - echo "
"; - echo "" . __('Credentials') . ""; - html_print_table($table); - echo "
"; - - echo "
"; - echo "" . __('Call parameters') . ""; - html_print_table($table2); - echo "
"; - echo "
"; - html_print_input_hidden('api_execute', 1); - html_print_submit_button(__('Call'), 'submit', false, 'class="sub next"'); - echo "
"; - echo "
"; - - - echo "
"; - echo "
"; - echo "" . __('Custom URL') . ""; - html_print_table($table3); - echo "
"; - - echo "
"; - html_print_input_hidden('api_execute', 1); - html_print_submit_button(__('Call'), 'submit', false, 'class="sub next"'); - echo "
"; - echo "
"; - - if ($api_execute) { - echo "
"; - echo "" . __('Result') . ""; - echo __('URL') . "
"; - html_print_input_password('url', $return_call_api['url'], '', 150, 255, false, true); - echo " "; - html_print_image("images/input_zoom.png"); - echo ""; - echo "
"; - echo __('Result') . "
"; - html_print_textarea('result', 30, 20, $return_call_api['result'], 'readonly="readonly"'); - echo "
"; - } - ?> - - data = []; + + $row = []; + $row[] = __('IP'); + $row[] = html_print_input_text('ip', $ip, '', 50, 255, true); + $table->data[] = $row; + + $row = []; + $row[] = __('%s Console URL', get_product_name()); + $row[] = html_print_input_text('pandora_url', $pandora_url, '', 50, 255, true); + $table->data[] = $row; + + $row = []; + $row[] = __('API Pass'); + $row[] = html_print_input_password('apipass', $apipass, '', 50, 255, true); + $table->data[] = $row; + + $row = []; + $row[] = __('User'); + $row[] = html_print_input_text('user', $user, '', 50, 255, true); + $table->data[] = $row; + + $row = []; + $row[] = __('Password'); + $row[] = html_print_input_password('password', $password, '', 50, 255, true); + $table->data[] = $row; + + $table2 = null; + $table2->data = []; + + $row = []; + $row[] = __('Action (get or set)'); + $row[] = html_print_input_text('op', $op, '', 50, 255, true); + $table2->data[] = $row; + + $row = []; + $row[] = __('Operation'); + $row[] = html_print_input_text('op2', $op2, '', 50, 255, true); + $table2->data[] = $row; + + $row = []; + $row[] = __('ID'); + $row[] = html_print_input_text('id', $id, '', 50, 255, true); + $table2->data[] = $row; + + $row = []; + $row[] = __('ID 2'); + $row[] = html_print_input_text('id2', $id2, '', 50, 255, true); + $table2->data[] = $row; + + $row = []; + $row[] = __('Return Type'); + $row[] = html_print_input_text('return_type', $return_type, '', 50, 255, true); + $table2->data[] = $row; + + $row = []; + $row[] = __('Other'); + $row[] = html_print_input_text('other', $other, '', 50, 255, true); + $table2->data[] = $row; + + $row = []; + $row[] = __('Other Mode'); + $row[] = html_print_input_text('other_mode', $other_mode, '', 50, 255, true); + $table2->data[] = $row; + + $table3 = null; + $table3->data = []; + + $row = []; + $row[] = __('Raw URL'); + $row[] = html_print_input_text('url', $url, '', 150, 2048, true); + $table3->data[] = $row; + + echo "
"; + echo '
'; + echo ''.__('Credentials').''; + html_print_table($table); + echo '
'; + + echo '
'; + echo ''.__('Call parameters').''; + html_print_table($table2); + echo '
'; + echo "
"; + html_print_input_hidden('api_execute', 1); + html_print_submit_button(__('Call'), 'submit', false, 'class="sub next"'); + echo '
'; + echo '
'; + + echo "
"; + echo '
'; + echo ''.__('Custom URL').''; + html_print_table($table3); + echo '
'; + + echo "
"; + html_print_input_hidden('api_execute', 1); + html_print_submit_button(__('Call'), 'submit', false, 'class="sub next"'); + echo '
'; + echo '
'; + + if ($api_execute) { + echo '
'; + echo ''.__('Result').''; + echo __('URL').'
'; + html_print_input_password('url', $return_call_api['url'], '', 150, 255, false, true); + echo " "; + html_print_image('images/input_zoom.png'); + echo ''; + echo '
'; + echo __('Result').'
'; + html_print_textarea('result', 30, 20, $return_call_api['result'], 'readonly="readonly"'); + echo '
'; + } + ?> + + \ No newline at end of file +extensions_add_godmode_menu_option(__('API checker'), 'PM', 'gextensions', null, 'v1r1'); + diff --git a/pandora_console/extensions/db_status.php b/pandora_console/extensions/db_status.php index e873ea76aa..435474dc53 100755 --- a/pandora_console/extensions/db_status.php +++ b/pandora_console/extensions/db_status.php @@ -4,423 +4,450 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function extension_db_status() +{ + global $config; -function extension_db_status() { - global $config; + $db_user = get_parameter('db_user', ''); + $db_password = get_parameter('db_password', ''); + $db_host = get_parameter('db_host', ''); + $db_name = get_parameter('db_name', ''); + $db_status_execute = (bool) get_parameter('db_status_execute', false); - $db_user = get_parameter('db_user', ''); - $db_password = get_parameter('db_password', ''); - $db_host = get_parameter('db_host', ''); - $db_name = get_parameter('db_name', ''); - $db_status_execute = (bool)get_parameter('db_status_execute', false); + ui_print_page_header( + __('DB Schema check'), + 'images/extensions.png', + false, + '', + true, + '' + ); - ui_print_page_header (__("DB Schema check"), - "images/extensions.png", false, "", true, ""); + if (!is_user_admin($config['id_user'])) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access db status' + ); + include 'general/noaccess.php'; + return; + } - if (!is_user_admin($config['id_user'])) { - db_pandora_audit("ACL Violation", - "Trying to access db status"); - require ("general/noaccess.php"); - return; - } + ui_print_info_message( + __('This extension checks the DB is correct. Because sometimes the old DB from a migration has not some fields in the tables or the data is changed.') + ); + ui_print_info_message( + __('At the moment the checks is for MySQL/MariaDB.') + ); - ui_print_info_message( - __('This extension checks the DB is correct. Because sometimes the old DB from a migration has not some fields in the tables or the data is changed.')); - ui_print_info_message( - __('At the moment the checks is for MySQL/MariaDB.')); + echo "
"; - echo ""; + echo '
'; + echo ''.__('DB settings').''; + $table = new stdClass(); + $table->data = []; + $row = []; + $row[] = __('DB User with privileges'); + $row[] = html_print_input_text('db_user', $db_user, '', 50, 255, true); + $row[] = __('DB Password for this user'); + $row[] = html_print_input_password('db_password', $db_password, '', 50, 255, true); + $table->data[] = $row; + $row = []; + $row[] = __('DB Hostname'); + $row[] = html_print_input_text('db_host', $db_host, '', 50, 255, true); + $row[] = __('DB Name (temporal for testing)'); + $row[] = html_print_input_text('db_name', $db_name, '', 50, 255, true); + $table->data[] = $row; + html_print_table($table); + echo '
'; - echo "
"; - echo "" . __('DB settings') . ""; - $table = new stdClass(); - $table->data = array(); - $row = array(); - $row[] = __("DB User with privileges"); - $row[] = html_print_input_text('db_user', $db_user, '', 50, 255, true); - $row[] = __("DB Password for this user"); - $row[] = html_print_input_password('db_password', $db_password, '', 50, 255, true); - $table->data[] = $row; - $row = array(); - $row[] = __("DB Hostname"); - $row[] = html_print_input_text('db_host', $db_host, '', 50, 255, true); - $row[] = __("DB Name (temporal for testing)"); - $row[] = html_print_input_text('db_name', $db_name, '', 50, 255, true); - $table->data[] = $row; - html_print_table($table); - echo "
"; + echo "
"; + html_print_input_hidden('db_status_execute', 1); + html_print_submit_button(__('Execute Test'), 'submit', false, 'class="sub"'); + echo '
'; - echo "
"; - html_print_input_hidden('db_status_execute', 1); - html_print_submit_button(__('Execute Test'), 'submit', false, 'class="sub"'); - echo "
"; + echo '
'; - echo ""; - - if ($db_status_execute) { - extension_db_status_execute_checks($db_user, $db_password, - $db_host, $db_name); - } + if ($db_status_execute) { + extension_db_status_execute_checks( + $db_user, + $db_password, + $db_host, + $db_name + ); + } } -function extension_db_status_execute_checks($db_user, $db_password, $db_host, $db_name) { - global $config; - $connection_system = $config['dbconnection']; +function extension_db_status_execute_checks($db_user, $db_password, $db_host, $db_name) +{ + global $config; - // Avoid SQL injection - $db_name = io_safe_output($db_name); - $db_name = str_replace(';', ' ', $db_name); - $db_name = explode(" ", $db_name); - $db_name = $db_name[0]; + $connection_system = $config['dbconnection']; - if ($config["mysqli"] === true) { - $connection_test = mysqli_connect($db_host, $db_user, $db_password); - } - else{ - $connection_test = mysql_connect($db_host, $db_user, $db_password); - } + // Avoid SQL injection + $db_name = io_safe_output($db_name); + $db_name = str_replace(';', ' ', $db_name); + $db_name = explode(' ', $db_name); + $db_name = $db_name[0]; - if (!$connection_test) { - ui_print_error_message( - __('Unsuccessful connected to the DB')); - } - else { - if($config["mysqli"] === true){ - $create_db = mysqli_query($connection_test, "CREATE DATABASE `$db_name`"); - }else{ - $create_db = mysql_query("CREATE DATABASE `$db_name`"); - } + if ($config['mysqli'] === true) { + $connection_test = mysqli_connect($db_host, $db_user, $db_password); + } else { + $connection_test = mysql_connect($db_host, $db_user, $db_password); + } - if (!$create_db) { - ui_print_error_message( - __('Unsuccessful created the testing DB')); - } - else { - if ($config["mysqli"] === true) { - mysqli_select_db($connection_test, $db_name); - } - else{ - mysql_select_db($db_name, $connection_test); - } + if (!$connection_test) { + ui_print_error_message( + __('Unsuccessful connected to the DB') + ); + } else { + if ($config['mysqli'] === true) { + $create_db = mysqli_query($connection_test, "CREATE DATABASE `$db_name`"); + } else { + $create_db = mysql_query("CREATE DATABASE `$db_name`"); + } - $install_tables = extension_db_status_execute_sql_file( - $config['homedir'] . "/pandoradb.sql", - $connection_test); + if (!$create_db) { + ui_print_error_message( + __('Unsuccessful created the testing DB') + ); + } else { + if ($config['mysqli'] === true) { + mysqli_select_db($connection_test, $db_name); + } else { + mysql_select_db($db_name, $connection_test); + } - if (!$install_tables) { - ui_print_error_message( - __('Unsuccessful installed tables into the testing DB')); - } - else { - extension_db_check_tables_differences( - $connection_test, - $connection_system, - $db_name, - $config['dbname']); - } + $install_tables = extension_db_status_execute_sql_file( + $config['homedir'].'/pandoradb.sql', + $connection_test + ); - if ($config["mysqli"] === true) { - mysqli_select_db($connection_test, $db_name); - mysqli_query($connection_test, "DROP DATABASE IF EXISTS `$db_name`"); - } - else{ - mysql_select_db($db_name, $connection_test); - mysql_query("DROP DATABASE IF EXISTS `$db_name`", $connection_test); - } - } - } + if (!$install_tables) { + ui_print_error_message( + __('Unsuccessful installed tables into the testing DB') + ); + } else { + extension_db_check_tables_differences( + $connection_test, + $connection_system, + $db_name, + $config['dbname'] + ); + } + + if ($config['mysqli'] === true) { + mysqli_select_db($connection_test, $db_name); + mysqli_query($connection_test, "DROP DATABASE IF EXISTS `$db_name`"); + } else { + mysql_select_db($db_name, $connection_test); + mysql_query("DROP DATABASE IF EXISTS `$db_name`", $connection_test); + } + } + } } -function extension_db_check_tables_differences($connection_test, - $connection_system, $db_name_test, $db_name_system) { - global $config; +function extension_db_check_tables_differences( + $connection_test, + $connection_system, + $db_name_test, + $db_name_system +) { + global $config; - // --------- Check the tables -------------------------------------- - if ($config["mysqli"] === true) { - mysqli_select_db($connection_test, $db_name_test); - $result = mysqli_query($connection_test, "SHOW TABLES"); - }else{ - mysql_select_db($db_name_test, $connection_test); - $result = mysql_query("SHOW TABLES", $connection_test); - } + // --------- Check the tables -------------------------------------- + if ($config['mysqli'] === true) { + mysqli_select_db($connection_test, $db_name_test); + $result = mysqli_query($connection_test, 'SHOW TABLES'); + } else { + mysql_select_db($db_name_test, $connection_test); + $result = mysql_query('SHOW TABLES', $connection_test); + } - $tables_test = array(); + $tables_test = []; - if ($config["mysqli"] === true) { - while ($row = mysqli_fetch_array($result)) { - $tables_test[] = $row[0]; - } - mysqli_free_result($result); + if ($config['mysqli'] === true) { + while ($row = mysqli_fetch_array($result)) { + $tables_test[] = $row[0]; + } - mysqli_select_db($connection_test, $db_name_system); + mysqli_free_result($result); - $result = mysqli_query( $connection_test, "SHOW TABLES"); - } - else{ - while ($row = mysql_fetch_array($result)) { - $tables_test[] = $row[0]; - } - mysql_free_result($result); + mysqli_select_db($connection_test, $db_name_system); - mysql_select_db($db_name_system, $connection_test); + $result = mysqli_query($connection_test, 'SHOW TABLES'); + } else { + while ($row = mysql_fetch_array($result)) { + $tables_test[] = $row[0]; + } - $result = mysql_query("SHOW TABLES", $connection_test); - } + mysql_free_result($result); - $tables_system = array(); + mysql_select_db($db_name_system, $connection_test); - if ($config["mysqli"] === true) { - while ($row = mysqli_fetch_array ($result)) { - $tables_system[] = $row[0]; - } - mysqli_free_result($result); - } - else{ - while ($row = mysql_fetch_array ($result)) { - $tables_system[] = $row[0]; - } - mysql_free_result($result); - } + $result = mysql_query('SHOW TABLES', $connection_test); + } - $diff_tables = array_diff($tables_test, $tables_system); + $tables_system = []; - ui_print_result_message( - !empty($diff_tables), - __('Success! %s DB contains all tables', get_product_name()), - __('%s DB could not retrieve all tables. The missing tables are (%s)', - get_product_name(), implode(", ", $diff_tables))); + if ($config['mysqli'] === true) { + while ($row = mysqli_fetch_array($result)) { + $tables_system[] = $row[0]; + } - if (!empty($diff_tables)) { - foreach ($diff_tables as $table) { - if ($config["mysqli"] === true) { - mysqli_select_db($connection_test, $db_name_test); - $result = mysqli_query($connection_test, "SHOW CREATE TABLE " . $table); - $tables_test = array(); - while ($row = mysql_fetch_array($result)) { - ui_print_info_message( - __('You can execute this SQL query for to fix.') . "
" . - '
' .
-							$row[1] .
-						'
' - ); - } - mysqli_free_result($result); - } - else{ - mysql_select_db($db_name_test, $connection_test); - $result = mysql_query("SHOW CREATE TABLE " . $table, $connection_test); - $tables_test = array(); - while ($row = mysql_fetch_array($result)) { - ui_print_info_message( - __('You can execute this SQL query for to fix.') . "
" . - '
' .
-							$row[1] .
-						'
' - ); - } - mysql_free_result($result); - } - } - } + mysqli_free_result($result); + } else { + while ($row = mysql_fetch_array($result)) { + $tables_system[] = $row[0]; + } - // --------------- Check the fields ------------------------------- - $correct_fields = true; + mysql_free_result($result); + } - foreach ($tables_system as $table) { - if ($config["mysqli"] === true) { - mysqli_select_db($connection_test, $db_name_test); - $result = mysqli_query($connection_test, "EXPLAIN " . $table); - } - else{ - mysql_select_db($db_name_test, $connection_test); - $result = mysql_query("EXPLAIN " . $table, $connection_test); - } + $diff_tables = array_diff($tables_test, $tables_system); - $fields_test = array(); - if (!empty($result)) { - if ($config["mysqli"] === true) { - while ($row = mysqli_fetch_array ($result)) { - $fields_test[$row[0]] = array( - 'field ' => $row[0], - 'type' => $row[1], - 'null' => $row[2], - 'key' => $row[3], - 'default' => $row[4], - 'extra' => $row[5]); - } - mysqli_free_result ($result); - mysqli_select_db($connection_test, $db_name_system); - } - else{ - while ($row = mysql_fetch_array ($result)) { - $fields_test[$row[0]] = array( - 'field ' => $row[0], - 'type' => $row[1], - 'null' => $row[2], - 'key' => $row[3], - 'default' => $row[4], - 'extra' => $row[5]); - } - mysql_free_result ($result); - mysql_select_db($db_name_system, $connection_test); - } - } + ui_print_result_message( + !empty($diff_tables), + __('Success! %s DB contains all tables', get_product_name()), + __( + '%s DB could not retrieve all tables. The missing tables are (%s)', + get_product_name(), + implode(', ', $diff_tables) + ) + ); - if($config["mysqli"] === true){ - $result = mysqli_query($connection_test, "EXPLAIN " . $table); - } - else{ - $result = mysql_query("EXPLAIN " . $table, $connection_test); - } + if (!empty($diff_tables)) { + foreach ($diff_tables as $table) { + if ($config['mysqli'] === true) { + mysqli_select_db($connection_test, $db_name_test); + $result = mysqli_query($connection_test, 'SHOW CREATE TABLE '.$table); + $tables_test = []; + while ($row = mysql_fetch_array($result)) { + ui_print_info_message( + __('You can execute this SQL query for to fix.').'
'.'
'.$row[1].'
' + ); + } - $fields_system = array(); - if (!empty($result)) { - if ($config["mysqli"] === true) { - while ($row = mysqli_fetch_array ($result)) { - $fields_system[$row[0]] = array( - 'field ' => $row[0], - 'type' => $row[1], - 'null' => $row[2], - 'key' => $row[3], - 'default' => $row[4], - 'extra' => $row[5]); - } - mysqli_free_result($result); - } - else{ - while ($row = mysql_fetch_array($result)) { - $fields_system[$row[0]] = array( - 'field ' => $row[0], - 'type' => $row[1], - 'null' => $row[2], - 'key' => $row[3], - 'default' => $row[4], - 'extra' => $row[5]); - } - mysql_free_result($result); - } - } - foreach ($fields_test as $name_field => $field_test) { - if (!isset($fields_system[$name_field])) { - $correct_fields = false; + mysqli_free_result($result); + } else { + mysql_select_db($db_name_test, $connection_test); + $result = mysql_query('SHOW CREATE TABLE '.$table, $connection_test); + $tables_test = []; + while ($row = mysql_fetch_array($result)) { + ui_print_info_message( + __('You can execute this SQL query for to fix.').'
'.'
'.$row[1].'
' + ); + } - ui_print_error_message( - __('Unsuccessful the table %s has not the field %s', - $table, $name_field)); - ui_print_info_message( - __('You can execute this SQL query for to fix.') . "
" . - '
' .
-						"ALTER TABLE " . $table . " ADD COLUMN " . $name_field . " text;" .
-					'
' - ); - } - else { - $correct_fields = false; - $field_system = $fields_system[$name_field]; + mysql_free_result($result); + } + } + } - $diff = array_diff($field_test, $field_system); + // --------------- Check the fields ------------------------------- + $correct_fields = true; - if (!empty($diff)) { - $info_message = ""; - $error_message = ""; - if($diff['type']){ - $error_message .= "Unsuccessful the field ".$name_field." in the table ".$table." must be set the type with ".$diff['type']."
"; - } + foreach ($tables_system as $table) { + if ($config['mysqli'] === true) { + mysqli_select_db($connection_test, $db_name_test); + $result = mysqli_query($connection_test, 'EXPLAIN '.$table); + } else { + mysql_select_db($db_name_test, $connection_test); + $result = mysql_query('EXPLAIN '.$table, $connection_test); + } - if($diff['null']){ - $error_message .= "Unsuccessful the field $name_field in the table $table must be null: (".$diff['null'].").
"; - } + $fields_test = []; + if (!empty($result)) { + if ($config['mysqli'] === true) { + while ($row = mysqli_fetch_array($result)) { + $fields_test[$row[0]] = [ + 'field ' => $row[0], + 'type' => $row[1], + 'null' => $row[2], + 'key' => $row[3], + 'default' => $row[4], + 'extra' => $row[5], + ]; + } - if($diff['default']){ - $error_message .= "Unsuccessful the field $name_field in the table $table must be set ".$diff['default']." as default value.
"; - } + mysqli_free_result($result); + mysqli_select_db($connection_test, $db_name_system); + } else { + while ($row = mysql_fetch_array($result)) { + $fields_test[$row[0]] = [ + 'field ' => $row[0], + 'type' => $row[1], + 'null' => $row[2], + 'key' => $row[3], + 'default' => $row[4], + 'extra' => $row[5], + ]; + } - if($field_test['null'] == "YES" || !isset($field_test['null']) || $field_test['null'] == ""){ - $null_defect = " NULL"; - } - else{ - $null_defect = " NOT NULL"; - } + mysql_free_result($result); + mysql_select_db($db_name_system, $connection_test); + } + } - if(!isset($field_test['default']) || $field_test['default'] == ""){ - $default_value = ""; - } - else{ - $default_value = " DEFAULT ".$field_test['default']; - } + if ($config['mysqli'] === true) { + $result = mysqli_query($connection_test, 'EXPLAIN '.$table); + } else { + $result = mysql_query('EXPLAIN '.$table, $connection_test); + } - if($diff['type'] || $diff['null'] || $diff['default']){ - $info_message .= "ALTER TABLE " . $table . " MODIFY COLUMN " . $name_field . " " . $field_test['type'] . $null_defect . $default_value.";"; - } + $fields_system = []; + if (!empty($result)) { + if ($config['mysqli'] === true) { + while ($row = mysqli_fetch_array($result)) { + $fields_system[$row[0]] = [ + 'field ' => $row[0], + 'type' => $row[1], + 'null' => $row[2], + 'key' => $row[3], + 'default' => $row[4], + 'extra' => $row[5], + ]; + } - if($diff['key']){ - $error_message .= "Unsuccessful the field $name_field in the table $table must be set the key as defined in the SQL file.
"; - $info_message .= "

Please check the SQL file for to know the kind of key needed."; - } + mysqli_free_result($result); + } else { + while ($row = mysql_fetch_array($result)) { + $fields_system[$row[0]] = [ + 'field ' => $row[0], + 'type' => $row[1], + 'null' => $row[2], + 'key' => $row[3], + 'default' => $row[4], + 'extra' => $row[5], + ]; + } - if($diff['extra']){ - $error_message .= "Unsuccessful the field $name_field in the table $table must be set as defined in the SQL file.
"; - $info_message .= "

Please check the SQL file for to know the kind of extra config needed."; - } + mysql_free_result($result); + } + } - ui_print_error_message(__($error_message)); + foreach ($fields_test as $name_field => $field_test) { + if (!isset($fields_system[$name_field])) { + $correct_fields = false; - ui_print_info_message(__($info_message)); - } - } - } - } - if ($correct_fields) { - ui_print_success_message( - __('Successful all the tables have the correct fields') - ); - } + ui_print_error_message( + __( + 'Unsuccessful the table %s has not the field %s', + $table, + $name_field + ) + ); + ui_print_info_message( + __('You can execute this SQL query for to fix.').'
'.'
'.'ALTER TABLE '.$table.' ADD COLUMN '.$name_field.' text;'.'
' + ); + } else { + $correct_fields = false; + $field_system = $fields_system[$name_field]; + + $diff = array_diff($field_test, $field_system); + + if (!empty($diff)) { + $info_message = ''; + $error_message = ''; + if ($diff['type']) { + $error_message .= 'Unsuccessful the field '.$name_field.' in the table '.$table.' must be set the type with '.$diff['type'].'
'; + } + + if ($diff['null']) { + $error_message .= "Unsuccessful the field $name_field in the table $table must be null: (".$diff['null'].').
'; + } + + if ($diff['default']) { + $error_message .= "Unsuccessful the field $name_field in the table $table must be set ".$diff['default'].' as default value.
'; + } + + if ($field_test['null'] == 'YES' || !isset($field_test['null']) || $field_test['null'] == '') { + $null_defect = ' NULL'; + } else { + $null_defect = ' NOT NULL'; + } + + if (!isset($field_test['default']) || $field_test['default'] == '') { + $default_value = ''; + } else { + $default_value = ' DEFAULT '.$field_test['default']; + } + + if ($diff['type'] || $diff['null'] || $diff['default']) { + $info_message .= 'ALTER TABLE '.$table.' MODIFY COLUMN '.$name_field.' '.$field_test['type'].$null_defect.$default_value.';'; + } + + if ($diff['key']) { + $error_message .= "Unsuccessful the field $name_field in the table $table must be set the key as defined in the SQL file.
"; + $info_message .= '

Please check the SQL file for to know the kind of key needed.'; + } + + if ($diff['extra']) { + $error_message .= "Unsuccessful the field $name_field in the table $table must be set as defined in the SQL file.
"; + $info_message .= '

Please check the SQL file for to know the kind of extra config needed.'; + } + + ui_print_error_message(__($error_message)); + + ui_print_info_message(__($info_message)); + } + } + } + } + + if ($correct_fields) { + ui_print_success_message( + __('Successful all the tables have the correct fields') + ); + } } -function extension_db_status_execute_sql_file($url, $connection) { - global $config; - if (file_exists($url)) { - $file_content = file($url); - $query = ""; - foreach ($file_content as $sql_line) { - if (trim($sql_line) != "" && strpos($sql_line, "--") === false) { - $query .= $sql_line; - if (preg_match("/;[\040]*\$/", $sql_line)) { - if ($config["mysqli"] === true) { - if (!$result = mysqli_query($connection, $query)) { - echo mysqli_error(); //Uncomment for debug - echo "
$query
"; - return 0; - } - } - else{ - if (!$result = mysql_query($query, $connection)) { - echo mysql_error(); //Uncomment for debug - echo "
$query
"; - return 0; - } - } - $query = ""; - } - } - } - return 1; - } - else - return 0; + +function extension_db_status_execute_sql_file($url, $connection) +{ + global $config; + if (file_exists($url)) { + $file_content = file($url); + $query = ''; + foreach ($file_content as $sql_line) { + if (trim($sql_line) != '' && strpos($sql_line, '--') === false) { + $query .= $sql_line; + if (preg_match("/;[\040]*\$/", $sql_line)) { + if ($config['mysqli'] === true) { + if (!$result = mysqli_query($connection, $query)) { + echo mysqli_error(); + // Uncomment for debug + echo "
$query
"; + return 0; + } + } else { + if (!$result = mysql_query($query, $connection)) { + echo mysql_error(); + // Uncomment for debug + echo "
$query
"; + return 0; + } + } + + $query = ''; + } + } + } + + return 1; + } else { + return 0; + } } + extensions_add_godmode_function('extension_db_status'); -extensions_add_godmode_menu_option(__('DB Schema check'), 'DM', 'gextensions', null, "v1r1", 'gdbman'); -?> +extensions_add_godmode_menu_option(__('DB Schema check'), 'DM', 'gextensions', null, 'v1r1', 'gdbman'); diff --git a/pandora_console/extensions/dbmanager.php b/pandora_console/extensions/dbmanager.php index 1ed38b3575..2aface6996 100644 --- a/pandora_console/extensions/dbmanager.php +++ b/pandora_console/extensions/dbmanager.php @@ -4,160 +4,162 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function dbmanager_query($sql, &$error, $dbconnection) +{ + global $config; -function dbmanager_query ($sql, &$error, $dbconnection) { - global $config; + $retval = []; - $retval = array(); + if ($sql == '') { + return false; + } - if ($sql == '') - return false; + $sql = html_entity_decode($sql, ENT_QUOTES); + if ($config['mysqli']) { + $result = mysqli_query($dbconnection, $sql); + if ($result === false) { + $backtrace = debug_backtrace(); + $error = mysqli_error($dbconnection); + return false; + } + } else { + $result = mysql_query($sql, $dbconnection); + if ($result === false) { + $backtrace = debug_backtrace(); + $error = mysql_error(); + return false; + } + } - $sql = html_entity_decode($sql, ENT_QUOTES); - if ($config["mysqli"]) { - $result = mysqli_query ($dbconnection, $sql); - if ($result === false) { - $backtrace = debug_backtrace (); - $error = mysqli_error ($dbconnection); - return false; - } - } - else{ - $result = mysql_query ($sql, $dbconnection); - if ($result === false) { - $backtrace = debug_backtrace (); - $error = mysql_error (); - return false; - } - } + if ($result === true) { + if ($config['mysqli']) { + return mysqli_affected_rows($dbconnection); + } else { + return mysql_affected_rows(); + } + } - if ($result === true) { - if($config["mysqli"]){ - return mysqli_affected_rows ($dbconnection); - } - else{ - return mysql_affected_rows (); - } - } + if ($config['mysqli']) { + while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { + array_push($retval, $row); + } + } else { + while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { + array_push($retval, $row); + } + } - if($config["mysqli"]){ - while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)) { - array_push ($retval, $row); - } - } - else{ - while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { - array_push ($retval, $row); - } - } + if ($config['mysqli']) { + mysqli_free_result($result); + } else { + mysql_free_result($result); + } - if($config["mysqli"]){ - mysqli_free_result ($result); - } - else{ - mysql_free_result ($result); - } + if (! empty($retval)) { + return $retval; + } - if (! empty ($retval)) - return $retval; - - //Return false, check with === or !== - return "Empty"; + // Return false, check with === or !== + return 'Empty'; } -function dbmgr_extension_main () { - ui_require_css_file ('dbmanager', 'extensions/dbmanager/'); +function dbmgr_extension_main() +{ + ui_require_css_file('dbmanager', 'extensions/dbmanager/'); - global $config; + global $config; - if (!is_user_admin($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; - } + if (!is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; + } - $sql = (string) get_parameter ('sql'); + $sql = (string) get_parameter('sql'); - ui_print_page_header (__('Database interface'), "images/gm_db.png", false, false, true); + ui_print_page_header(__('Database interface'), 'images/gm_db.png', false, false, true); - echo '
'; - echo __("This is an advanced extension to interface with %s database directly from WEB console + echo '
'; + echo __( + "This is an advanced extension to interface with %s database directly from WEB console using native SQL sentences. Please note that you can damage your %s installation if you don't know exactly what are you are doing, this means that you can severily damage your setup using this extension. This extension is intended to be used only by experienced users with a depth knowledge of %s internals.", - get_product_name(), get_product_name(), get_product_name()); - echo '
'; + get_product_name(), + get_product_name(), + get_product_name() + ); + echo '
'; - echo "
"; - echo "Some samples of usage:
SHOW STATUS;
DESCRIBE tagente
SELECT * FROM tserver
UPDATE tagente SET id_grupo = 15 WHERE nombre LIKE '%194.179%'
"; + echo '
'; + echo "Some samples of usage:
SHOW STATUS;
DESCRIBE tagente
SELECT * FROM tserver
UPDATE tagente SET id_grupo = 15 WHERE nombre LIKE '%194.179%'
"; - echo "

"; - echo "
"; - html_print_textarea ('sql', 5, 50, html_entity_decode($sql, ENT_QUOTES)); - echo '
'; - echo '
'; - echo '
'; - html_print_submit_button (__('Execute SQL'), '', false, 'class="sub next"'); - echo '
'; - echo "
"; + echo '

'; + echo "
"; + html_print_textarea('sql', 5, 50, html_entity_decode($sql, ENT_QUOTES)); + echo '
'; + echo '
'; + echo '
'; + html_print_submit_button(__('Execute SQL'), '', false, 'class="sub next"'); + echo '
'; + echo '
'; - // Processing SQL Code - if ($sql == '') - return; + // Processing SQL Code + if ($sql == '') { + return; + } - echo "
"; - echo "
"; - echo "
"; + echo '
'; + echo '
'; + echo '
'; - $dbconnection = $config['dbconnection']; - $error = ''; + $dbconnection = $config['dbconnection']; + $error = ''; - $result = dbmanager_query ($sql, $error, $dbconnection); + $result = dbmanager_query($sql, $error, $dbconnection); - if ($result === false) { - echo 'An error has occured when querying the database.
'; - echo $error; + if ($result === false) { + echo 'An error has occured when querying the database.
'; + echo $error; - db_pandora_audit("DB Interface Extension", "Error in SQL", false, false, $sql); + db_pandora_audit('DB Interface Extension', 'Error in SQL', false, false, $sql); - return; - } + return; + } - if (! is_array ($result)) { - echo "Output: ".$result; + if (! is_array($result)) { + echo 'Output: '.$result; - db_pandora_audit("DB Interface Extension", "SQL", false, false, $sql); + db_pandora_audit('DB Interface Extension', 'SQL', false, false, $sql); - return; - } + return; + } - echo "
"; - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox data'; - $table->head = array_keys ($result[0]); + echo "
"; + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox data'; + $table->head = array_keys($result[0]); - $table->data = $result; + $table->data = $result; - html_print_table ($table); - echo "
"; + html_print_table($table); + echo '
'; } -/* This adds a option in the operation menu */ -extensions_add_godmode_menu_option (__('DB interface'), 'PM','gextensions',"dbmanager/icon.png","v1r1", 'gdbman'); -/* This sets the function to be called when the extension is selected in the operation menu */ -extensions_add_godmode_function ('dbmgr_extension_main'); -?> +// This adds a option in the operation menu +extensions_add_godmode_menu_option(__('DB interface'), 'PM', 'gextensions', 'dbmanager/icon.png', 'v1r1', 'gdbman'); + +// This sets the function to be called when the extension is selected in the operation menu +extensions_add_godmode_function('dbmgr_extension_main'); diff --git a/pandora_console/extensions/dbmanager/dbmanager.css b/pandora_console/extensions/dbmanager/dbmanager.css index 81472c088b..1e44dce3a8 100644 --- a/pandora_console/extensions/dbmanager/dbmanager.css +++ b/pandora_console/extensions/dbmanager/dbmanager.css @@ -1,29 +1,30 @@ - -table.dbmanager, table.dbmanager td, table.dbmanager th { - border:1px solid #888; - border-collapse: collapse; - margin: 0; - padding: 0; +table.dbmanager, +table.dbmanager td, +table.dbmanager th { + border: 1px solid #888; + border-collapse: collapse; + margin: 0; + padding: 0; } -table.dbmanager td, table.dbmanager th { - padding:.2em .5em; - vertical-align: top; - font-weight: normal; - background: #fafafa; - color: #000; - font-size: 9px; +table.dbmanager td, +table.dbmanager th { + padding: 0.2em 0.5em; + vertical-align: top; + font-weight: normal; + background: #fafafa; + color: #000; + font-size: 9px; } table.dbmanager th { - color: #fff; - font-size: 10px; - background: #888; + color: #fff; + font-size: 10px; + background: #888; } textarea { - min-height: 50px; - height: 50px; - width: 95%; + min-height: 50px; + height: 50px; + width: 95%; } - diff --git a/pandora_console/extensions/disabled/matrix_events.php b/pandora_console/extensions/disabled/matrix_events.php index 21ca7d27a4..361d10cf88 100644 --- a/pandora_console/extensions/disabled/matrix_events.php +++ b/pandora_console/extensions/disabled/matrix_events.php @@ -4,262 +4,259 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function load_matrix_console() +{ + global $config; -function load_matrix_console() { - global $config; - - if (! check_acl ($config["id_user"], 0, "ER")) { - db_pandora_audit("ACL Violation", "Trying to access event viewer"); - require ("general/noaccess.php"); - return; - } + if (! check_acl($config['id_user'], 0, 'ER')) { + db_pandora_audit('ACL Violation', 'Trying to access event viewer'); + include 'general/noaccess.php'; + return; + } - $pure = (bool) get_parameter('pure'); + $pure = (bool) get_parameter('pure'); - if (! $pure) { - $title_menu = __("Matrix events"); - $fullscreen['text'] = '' - . html_print_image ("images/full_screen.png", true, array ("title" => __('Full screen mode'))) - . ""; - $onheader = array('fullscreen' => $fullscreen); - ui_print_page_header ($title_menu, "images/op_monitoring.png", false, "", false, $onheader); - } + if (! $pure) { + $title_menu = __('Matrix events'); + $fullscreen['text'] = ''.html_print_image('images/full_screen.png', true, ['title' => __('Full screen mode')]).''; + $onheader = ['fullscreen' => $fullscreen]; + ui_print_page_header($title_menu, 'images/op_monitoring.png', false, '', false, $onheader); + } - echo ""; + echo ''; -?> - - 0) { + event = events.shift(); + terminal.showEvent(event.agent + " - " + event.text + " - " + event.date); + } + var showEventsInterval = function () { + if (events.length > 0) { + event = events.shift(); + terminal.showEvent(event.agent + " - " + event.text + " - " + event.date); + } else { + showLastEvents(); + } + } + terminal.timers.events = setInterval(showEventsInterval, 20000); + } + }); + } + + + diff --git a/pandora_console/extensions/extension_uploader.php b/pandora_console/extensions/extension_uploader.php index e359d16855..5dc40296ea 100644 --- a/pandora_console/extensions/extension_uploader.php +++ b/pandora_console/extensions/extension_uploader.php @@ -4,89 +4,93 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function extension_uploader_extensions() +{ + global $config; -function extension_uploader_extensions() { - global $config; - - if (!check_acl($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Group Management"); - require ("general/noaccess.php"); - - return; - } - - ui_print_page_header (__("Uploader extension"), - "images/extensions.png", false, "", true, ""); - - $upload = (bool)get_parameter('upload', 0); - $upload_enteprise = (bool)get_parameter('upload_enterprise', 0); - - if ($upload) { - $error = $_FILES['extension']['error']; - - if ($error == 0) { - $zip = new ZipArchive; - - $tmpName = $_FILES['extension']['tmp_name']; - - if ($upload_enteprise) { - $pathname = $config['homedir'] . '/' . ENTERPRISE_DIR . '/' . EXTENSIONS_DIR . '/'; - } - else { - $pathname = $config['homedir'] . '/' . EXTENSIONS_DIR . '/'; - } - - if ($zip->open($tmpName) === true) { - $result = $zip->extractTo($pathname); - } - else { - $result = false; - } - } - else { - $result = false; - } - - if ($result) { - db_pandora_audit ("Extension manager", "Upload extension " . $_FILES['extension']['name']); - } - - ui_print_result_message ($result, __('Success to upload extension'), - __('Fail to upload extension')); - } - - $table = null; - - $table->width = '100%'; - $table->class = 'databox filters'; - $table->data = array(); - $table->data[0][0] = __('Upload extension'); - $table->data[0][1] = html_print_input_file('extension', true) . - ui_print_help_tip (__("Upload the extension as a zip file."), true); - if (enterprise_installed()) { - $table->data[0][2] = __('Upload enterprise extension') . " " . - html_print_checkbox('upload_enterprise', 1, false, true); - } - - echo "
"; - html_print_table($table); - echo "
"; - html_print_input_hidden('upload', 1); - html_print_submit_button(__('Upload'), 'submit', false, 'class="sub add"'); - echo "
"; - echo "
"; + if (!check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Group Management' + ); + include 'general/noaccess.php'; + + return; + } + + ui_print_page_header( + __('Uploader extension'), + 'images/extensions.png', + false, + '', + true, + '' + ); + + $upload = (bool) get_parameter('upload', 0); + $upload_enteprise = (bool) get_parameter('upload_enterprise', 0); + + if ($upload) { + $error = $_FILES['extension']['error']; + + if ($error == 0) { + $zip = new ZipArchive; + + $tmpName = $_FILES['extension']['tmp_name']; + + if ($upload_enteprise) { + $pathname = $config['homedir'].'/'.ENTERPRISE_DIR.'/'.EXTENSIONS_DIR.'/'; + } else { + $pathname = $config['homedir'].'/'.EXTENSIONS_DIR.'/'; + } + + if ($zip->open($tmpName) === true) { + $result = $zip->extractTo($pathname); + } else { + $result = false; + } + } else { + $result = false; + } + + if ($result) { + db_pandora_audit('Extension manager', 'Upload extension '.$_FILES['extension']['name']); + } + + ui_print_result_message( + $result, + __('Success to upload extension'), + __('Fail to upload extension') + ); + } + + $table = null; + + $table->width = '100%'; + $table->class = 'databox filters'; + $table->data = []; + $table->data[0][0] = __('Upload extension'); + $table->data[0][1] = html_print_input_file('extension', true).ui_print_help_tip(__('Upload the extension as a zip file.'), true); + if (enterprise_installed()) { + $table->data[0][2] = __('Upload enterprise extension').' '.html_print_checkbox('upload_enterprise', 1, false, true); + } + + echo "
"; + html_print_table($table); + echo "
"; + html_print_input_hidden('upload', 1); + html_print_submit_button(__('Upload'), 'submit', false, 'class="sub add"'); + echo '
'; + echo '
'; } -extensions_add_godmode_menu_option(__('Extension uploader'), 'PM', null, null, "v1r1"); + +extensions_add_godmode_menu_option(__('Extension uploader'), 'PM', null, null, 'v1r1'); extensions_add_godmode_function('extension_uploader_extensions'); -?> diff --git a/pandora_console/extensions/files_repo.php b/pandora_console/extensions/files_repo.php index 59ef5206f6..c1170b3877 100644 --- a/pandora_console/extensions/files_repo.php +++ b/pandora_console/extensions/files_repo.php @@ -4,221 +4,238 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function pandora_files_repo_install() +{ + global $config; + if (isset($config['files_repo_installed']) && $config['files_repo_installed'] == 1) { + return; + } -function pandora_files_repo_install () { - global $config; - - - if (isset($config['files_repo_installed']) && $config['files_repo_installed'] == 1) - return; - - $full_extensions_dir = $config['homedir']."/".EXTENSIONS_DIR."/"; - $full_sql_dir = $full_extensions_dir."files_repo/sql/"; - - $file_path = ''; - switch ($config['dbtype']) { - case "mysql": - $file_path = $full_sql_dir . 'files_repo.sql'; - break; - case "postgresql": - $file_path = $full_sql_dir . 'files_repo.postgreSQL.sql'; - break; - case "oracle": - $file_path = $full_sql_dir . 'files_repo.oracle.sql'; - break; - } - - if (!empty($file_path)) { - $result = db_process_file($file_path); - - if ($result) { - /* Configuration values */ - $values = array( - "token" => "files_repo_installed", - "value" => 1 - ); - db_process_sql_insert('tconfig', $values); - } - } + $full_extensions_dir = $config['homedir'].'/'.EXTENSIONS_DIR.'/'; + $full_sql_dir = $full_extensions_dir.'files_repo/sql/'; + + $file_path = ''; + switch ($config['dbtype']) { + case 'mysql': + $file_path = $full_sql_dir.'files_repo.sql'; + break; + + case 'postgresql': + $file_path = $full_sql_dir.'files_repo.postgreSQL.sql'; + break; + + case 'oracle': + $file_path = $full_sql_dir.'files_repo.oracle.sql'; + break; + } + + if (!empty($file_path)) { + $result = db_process_file($file_path); + + if ($result) { + // Configuration values + $values = [ + 'token' => 'files_repo_installed', + 'value' => 1, + ]; + db_process_sql_insert('tconfig', $values); + } + } } -function pandora_files_repo_uninstall () { - global $config; - - switch ($config["dbtype"]) { - case "mysql": - db_process_sql('DROP TABLE `tfiles_repo_group`'); - db_process_sql('DROP TABLE `tfiles_repo`'); - db_process_sql('DELETE FROM `tconfig` - WHERE `token` LIKE "files_repo_%"'); - break; - case "postgresql": - db_process_sql('DROP TABLE "tfiles_repo_group"'); - db_process_sql('DROP TABLE "tfiles_repo"'); - db_process_sql('DELETE FROM "tconfig" - WHERE "token" LIKE \'files_repo_%\''); - break; - case "oracle": - db_process_sql('DROP TRIGGER "tfiles_repo_group_inc"'); - db_process_sql('DROP SEQUENCE "tfiles_repo_group_s"'); - db_process_sql('DROP TABLE "tfiles_repo_group"'); - db_process_sql('DROP TRIGGER "tfiles_repo_inc"'); - db_process_sql('DROP SEQUENCE "tfiles_repo_s"'); - db_process_sql('DROP TABLE "tfiles_repo"'); - db_process_sql('DELETE FROM tconfig - WHERE token LIKE \'files_repo_%\''); - break; - } - if (!empty($config['attachment_store'])) - delete_dir($config['attachment_store']."/files_repo"); +function pandora_files_repo_uninstall() +{ + global $config; + + switch ($config['dbtype']) { + case 'mysql': + db_process_sql('DROP TABLE `tfiles_repo_group`'); + db_process_sql('DROP TABLE `tfiles_repo`'); + db_process_sql( + 'DELETE FROM `tconfig` + WHERE `token` LIKE "files_repo_%"' + ); + break; + + case 'postgresql': + db_process_sql('DROP TABLE "tfiles_repo_group"'); + db_process_sql('DROP TABLE "tfiles_repo"'); + db_process_sql( + 'DELETE FROM "tconfig" + WHERE "token" LIKE \'files_repo_%\'' + ); + break; + + case 'oracle': + db_process_sql('DROP TRIGGER "tfiles_repo_group_inc"'); + db_process_sql('DROP SEQUENCE "tfiles_repo_group_s"'); + db_process_sql('DROP TABLE "tfiles_repo_group"'); + db_process_sql('DROP TRIGGER "tfiles_repo_inc"'); + db_process_sql('DROP SEQUENCE "tfiles_repo_s"'); + db_process_sql('DROP TABLE "tfiles_repo"'); + db_process_sql( + 'DELETE FROM tconfig + WHERE token LIKE \'files_repo_%\'' + ); + break; + } + + if (!empty($config['attachment_store'])) { + delete_dir($config['attachment_store'].'/files_repo'); + } } -function pandora_files_repo_godmode () { - global $config; - - if (!isset($config['files_repo_installed']) || !$config['files_repo_installed']) { - ui_print_error_message(__('Extension not installed')); - } - - // ACL Check - check_login (); - if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", "Trying to access to Files repository"); - require ("general/noaccess.php"); - return; - } - - // Header tabs - $godmode['text'] = '' - . html_print_image ("images/setup.png", true, array ("title" => __('Administration view'))) - . ""; - $godmode['godmode'] = 1; - $godmode['active'] = 1; - - $operation['text'] = '' - . html_print_image ("images/operation.png", true, array ("title" => __('Operation view'))) - . ""; - $operation['operation'] = 1; - - $onheader = array('godmode' => $godmode, 'operation' => $operation); - // Header - ui_print_page_header (__("Files repository manager"), "images/extensions.png", false, "", true, $onheader); - - $full_extensions_dir = $config['homedir']."/".EXTENSIONS_DIR."/"; - require_once ($full_extensions_dir . "files_repo/functions_files_repo.php"); - - // Directory files_repo check - if (!files_repo_check_directory(true)) { - return; - } - - $server_content_length = 0; - if (isset($_SERVER['CONTENT_LENGTH'])) - $server_content_length = $_SERVER['CONTENT_LENGTH']; - - // Check for an anoying error that causes the $_POST and $_FILES arrays - // were empty if the file is larger than the post_max_size - if (intval($server_content_length) > 0 && empty($_POST)) { - ui_print_error_message(__('The file exceeds the maximum size')); - } - - // GET and POST parameters - $file_id = (int) get_parameter ("file_id"); - $add_file = (bool) get_parameter ("add_file"); - $update_file = (bool) get_parameter ("update_file"); - $delete_file = (bool) get_parameter ("delete"); - - // File add or update - if ( $add_file || ($update_file && $file_id > 0) ) { - $groups = get_parameter ("groups", array()); - $public = (bool) get_parameter ("public"); - $description = io_safe_output((string) get_parameter ("description")); - if (mb_strlen($description, "UTF-8") > 200) { - $description = mb_substr($description, 0, 200, "UTF-8"); - } - $description = io_safe_input($description); - - if ($add_file) { - $result = files_repo_add_file("upfile", $description, $groups, $public); - } elseif ($update_file) { - $result = files_repo_update_file($file_id, $description, $groups, $public); - $file_id = 0; - } - if ($result['status'] == false) { - ui_print_error_message($result['message']); - } - } - // File delete - if ($delete_file && $file_id > 0) { - $result = files_repo_delete_file($file_id); - if ($result !== -1) { - ui_print_result_message($result, __('Successfully deleted'), __('Could not be deleted')); - } - $file_id = 0; - } - - // FORM - require ($full_extensions_dir."files_repo/files_repo_form.php"); - if (!$file_id) { - // LIST - $manage = true; - require ($full_extensions_dir."files_repo/files_repo_list.php"); - } + +function pandora_files_repo_godmode() +{ + global $config; + + if (!isset($config['files_repo_installed']) || !$config['files_repo_installed']) { + ui_print_error_message(__('Extension not installed')); + } + + // ACL Check + check_login(); + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit('ACL Violation', 'Trying to access to Files repository'); + include 'general/noaccess.php'; + return; + } + + // Header tabs + $godmode['text'] = ''.html_print_image('images/setup.png', true, ['title' => __('Administration view')]).''; + $godmode['godmode'] = 1; + $godmode['active'] = 1; + + $operation['text'] = ''.html_print_image('images/operation.png', true, ['title' => __('Operation view')]).''; + $operation['operation'] = 1; + + $onheader = [ + 'godmode' => $godmode, + 'operation' => $operation, + ]; + // Header + ui_print_page_header(__('Files repository manager'), 'images/extensions.png', false, '', true, $onheader); + + $full_extensions_dir = $config['homedir'].'/'.EXTENSIONS_DIR.'/'; + include_once $full_extensions_dir.'files_repo/functions_files_repo.php'; + + // Directory files_repo check + if (!files_repo_check_directory(true)) { + return; + } + + $server_content_length = 0; + if (isset($_SERVER['CONTENT_LENGTH'])) { + $server_content_length = $_SERVER['CONTENT_LENGTH']; + } + + // Check for an anoying error that causes the $_POST and $_FILES arrays + // were empty if the file is larger than the post_max_size + if (intval($server_content_length) > 0 && empty($_POST)) { + ui_print_error_message(__('The file exceeds the maximum size')); + } + + // GET and POST parameters + $file_id = (int) get_parameter('file_id'); + $add_file = (bool) get_parameter('add_file'); + $update_file = (bool) get_parameter('update_file'); + $delete_file = (bool) get_parameter('delete'); + + // File add or update + if ($add_file || ($update_file && $file_id > 0)) { + $groups = get_parameter('groups', []); + $public = (bool) get_parameter('public'); + $description = io_safe_output((string) get_parameter('description')); + if (mb_strlen($description, 'UTF-8') > 200) { + $description = mb_substr($description, 0, 200, 'UTF-8'); + } + + $description = io_safe_input($description); + + if ($add_file) { + $result = files_repo_add_file('upfile', $description, $groups, $public); + } else if ($update_file) { + $result = files_repo_update_file($file_id, $description, $groups, $public); + $file_id = 0; + } + + if ($result['status'] == false) { + ui_print_error_message($result['message']); + } + } + + // File delete + if ($delete_file && $file_id > 0) { + $result = files_repo_delete_file($file_id); + if ($result !== -1) { + ui_print_result_message($result, __('Successfully deleted'), __('Could not be deleted')); + } + + $file_id = 0; + } + + // FORM + include $full_extensions_dir.'files_repo/files_repo_form.php'; + if (!$file_id) { + // LIST + $manage = true; + include $full_extensions_dir.'files_repo/files_repo_list.php'; + } } -function pandora_files_repo_operation () { - global $config; - - // Header tabs - $onheader = array(); - if (check_acl($config['id_user'], 0, "PM")) { - $godmode['text'] = '' - . html_print_image ("images/setup.png", true, array ("title" => __('Administration view'))) - . ""; - $godmode['godmode'] = 1; - - $operation['text'] = '' - . html_print_image ("images/operation.png", true, array ("title" => __('Operation view'))) - . ""; - $operation['operation'] = 1; - $operation['active'] = 1; - - $onheader = array('godmode' => $godmode, 'operation' => $operation); - } - // Header - ui_print_page_header (__("Files repository"), "images/extensions.png", false, "", false, $onheader); - - $full_extensions_dir = $config['homedir']."/".EXTENSIONS_DIR."/"; - require_once ($full_extensions_dir."files_repo/functions_files_repo.php"); - - // Directory files_repo check - if (!files_repo_check_directory(true)) { - return; - } - - // LIST - $full_extensions_dir = $config['homedir']."/".EXTENSIONS_DIR."/"; - - require ($full_extensions_dir . "files_repo/files_repo_list.php"); + +function pandora_files_repo_operation() +{ + global $config; + + // Header tabs + $onheader = []; + if (check_acl($config['id_user'], 0, 'PM')) { + $godmode['text'] = ''.html_print_image('images/setup.png', true, ['title' => __('Administration view')]).''; + $godmode['godmode'] = 1; + + $operation['text'] = ''.html_print_image('images/operation.png', true, ['title' => __('Operation view')]).''; + $operation['operation'] = 1; + $operation['active'] = 1; + + $onheader = [ + 'godmode' => $godmode, + 'operation' => $operation, + ]; + } + + // Header + ui_print_page_header(__('Files repository'), 'images/extensions.png', false, '', false, $onheader); + + $full_extensions_dir = $config['homedir'].'/'.EXTENSIONS_DIR.'/'; + include_once $full_extensions_dir.'files_repo/functions_files_repo.php'; + + // Directory files_repo check + if (!files_repo_check_directory(true)) { + return; + } + + // LIST + $full_extensions_dir = $config['homedir'].'/'.EXTENSIONS_DIR.'/'; + + include $full_extensions_dir.'files_repo/files_repo_list.php'; } -extensions_add_operation_menu_option(__('Files repository'), null, null, "v1r1"); + +extensions_add_operation_menu_option(__('Files repository'), null, null, 'v1r1'); extensions_add_main_function('pandora_files_repo_operation'); -extensions_add_godmode_menu_option(__('Files repository manager'), 'PM', null, null, "v1r1"); +extensions_add_godmode_menu_option(__('Files repository manager'), 'PM', null, null, 'v1r1'); extensions_add_godmode_function('pandora_files_repo_godmode'); -//pandora_files_repo_uninstall(); +// pandora_files_repo_uninstall(); pandora_files_repo_install(); - -?> diff --git a/pandora_console/extensions/files_repo/files_repo_form.php b/pandora_console/extensions/files_repo/files_repo_form.php index 0a6e55433f..2035cfbd1a 100644 --- a/pandora_console/extensions/files_repo/files_repo_form.php +++ b/pandora_console/extensions/files_repo/files_repo_form.php @@ -4,71 +4,69 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - global $config; -$full_extensions_dir = $config['homedir']."/".EXTENSIONS_DIR."/"; -require_once ($full_extensions_dir."files_repo/functions_files_repo.php"); +$full_extensions_dir = $config['homedir'].'/'.EXTENSIONS_DIR.'/'; +require_once $full_extensions_dir.'files_repo/functions_files_repo.php'; -$file = array(); +$file = []; $file['name'] = ''; $file['description'] = ''; $file['hash'] = ''; -$file['groups'] = array(); +$file['groups'] = []; if (isset($file_id) && $file_id > 0) { - $file = files_repo_get_files(array('id' => $file_id)); - if (empty($file)) { - $file_id = 0; - } else { - $file = $file[$file_id]; - } + $file = files_repo_get_files(['id' => $file_id]); + if (empty($file)) { + $file_id = 0; + } else { + $file = $file[$file_id]; + } } $table = new stdClass(); $table->width = '100%'; $table->class = 'databox filters'; -$table->style = array(); -$table->style[0] = "font-weight: bold;"; -$table->style[2] = "text-align: center;"; -$table->colspan = array(); -$table->data = array(); +$table->style = []; +$table->style[0] = 'font-weight: bold;'; +$table->style[2] = 'text-align: center;'; +$table->colspan = []; +$table->data = []; // GROUPS $groups = groups_get_all(); // Add the All group to the beginning to be always the first // Use this instead array_unshift to keep the array keys -$groups = array(0 => __('All')) + $groups; -$html = ""; -$style = "style=\"padding: 2px 10px; display: inline-block;\""; +$groups = ([0 => __('All')] + $groups); +$html = ''; +$style = 'style="padding: 2px 10px; display: inline-block;"'; foreach ($groups as $id => $name) { - $checked = in_array($id, $file['groups']); - $all_checked = false; - if ($id === 0) { - $checkbox = html_print_checkbox_extended ('groups[]', $id, $checked, false, '', 'class="chkb_all"', true); - $all_checked = $checked; - } else { - $checkbox = html_print_checkbox_extended ('groups[]', $id, $checked, $all_checked, '', 'class="chkb_group"', true); - } - $html .= "
$name $checkbox
"; + $checked = in_array($id, $file['groups']); + $all_checked = false; + if ($id === 0) { + $checkbox = html_print_checkbox_extended('groups[]', $id, $checked, false, '', 'class="chkb_all"', true); + $all_checked = $checked; + } else { + $checkbox = html_print_checkbox_extended('groups[]', $id, $checked, $all_checked, '', 'class="chkb_group"', true); + } + + $html .= "
$name $checkbox
"; } -$row = array(); + +$row = []; $row[0] = __('Groups'); $row[1] = $html; $table->data[] = $row; $table->colspan[][1] = 3; // DESCRIPTION -$row = array(); +$row = []; $row[0] = __('Description'); $row[0] .= ui_print_help_tip(__('Only 200 characters are permitted'), true); $row[1] = html_print_textarea('description', 3, 20, $file['description'], 'style="min-height: 40px; max-height: 40px; width: 98%;"', true); @@ -76,54 +74,55 @@ $table->data[] = $row; $table->colspan[][1] = 3; // FILE and SUBMIT BUTTON -$row = array(); +$row = []; // Public checkbox -$checkbox = html_print_checkbox('public', 1, (bool)!empty($file['hash']), true); -$style = "style=\"padding: 2px 10px; display: inline-block;\""; +$checkbox = html_print_checkbox('public', 1, (bool) !empty($file['hash']), true); +$style = 'style="padding: 2px 10px; display: inline-block;"'; $row[0] = __('File'); if ($file_id > 0) { - $row[1] = $file['name']; - $row[2] = "
".__('Public link')." $checkbox
"; - $row[3] = html_print_submit_button(__('Update'), 'submit', false, 'class="sub upd"', true); - $row[3] .= html_print_input_hidden('update_file', 1, true); - $row[3] .= html_print_input_hidden('file_id', $file_id, true); + $row[1] = $file['name']; + $row[2] = "
".__('Public link')." $checkbox
"; + $row[3] = html_print_submit_button(__('Update'), 'submit', false, 'class="sub upd"', true); + $row[3] .= html_print_input_hidden('update_file', 1, true); + $row[3] .= html_print_input_hidden('file_id', $file_id, true); } else { - $row[1] = html_print_input_file('upfile', true); - $row[2] = "
".__('Public link')." $checkbox
"; - $row[3] = html_print_submit_button(__('Add'), 'submit', false, 'class="sub add"', true); - $row[3] .= html_print_input_hidden('add_file', 1, true); + $row[1] = html_print_input_file('upfile', true); + $row[2] = "
".__('Public link')." $checkbox
"; + $row[3] = html_print_submit_button(__('Add'), 'submit', false, 'class="sub add"', true); + $row[3] .= html_print_input_hidden('add_file', 1, true); } + $table->data[] = $row; $table->colspan[][1] = 1; -$url = ui_get_full_url("index.php?sec=godmode/extensions&sec2=extensions/files_repo"); +$url = ui_get_full_url('index.php?sec=godmode/extensions&sec2=extensions/files_repo'); echo "
"; html_print_table($table); -echo "
"; +echo ''; ?> \ No newline at end of file diff --git a/pandora_console/extensions/files_repo/files_repo_get_file.php b/pandora_console/extensions/files_repo/files_repo_get_file.php index aee720d050..9a1f7cf54b 100644 --- a/pandora_console/extensions/files_repo/files_repo_get_file.php +++ b/pandora_console/extensions/files_repo/files_repo_get_file.php @@ -4,18 +4,14 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - -require_once ("../../include/config.php"); +require_once '../../include/config.php'; $file_hash = (string) get_parameter('file'); @@ -25,46 +21,48 @@ $check_get = (count($_GET) === 1) ? true : false; $check_post = (count($_POST) === 0) ? true : false; // Only allow the parameter 'file' $check_parameter = (!empty($file_hash)) ? true : false; -$check_string = (preg_match("/^[0-9a-zA-Z]{8}$/", $file_hash) === 1) ? true : false; +$check_string = (preg_match('/^[0-9a-zA-Z]{8}$/', $file_hash) === 1) ? true : false; $checks = ($check_request && $check_get && $check_post && $check_parameter && $check_string); if (!$checks) { - throw_error(15); // ERROR + throw_error(15); + // ERROR } // Get the db file row -$file = db_get_row_filter("tfiles_repo", array('hash' => $file_hash)); +$file = db_get_row_filter('tfiles_repo', ['hash' => $file_hash]); if (!$file) { - throw_error(10); // ERROR + throw_error(10); + // ERROR } + // Case sensitive check $check_hash = ($file['hash'] == $file_hash) ? true : false; if (!$check_hash) { - throw_error(10); // ERROR + throw_error(10); + // ERROR } // Get the location -$files_repo_path = io_safe_output($config['attachment_store'])."/files_repo"; -$location = $files_repo_path."/".$file['id']."_".$file['name']; +$files_repo_path = io_safe_output($config['attachment_store']).'/files_repo'; +$location = $files_repo_path.'/'.$file['id'].'_'.$file['name']; if (!file_exists($location) || !is_readable($location) || !is_file($location)) { - throw_error(5); // ERROR + throw_error(5); + // ERROR } // All checks are fine. Download the file! header('Content-type: aplication/octet-stream;'); -header("Content-Length: " . filesize($location)); -header('Content-Disposition: attachment; filename="' . $file['name'] . '"'); +header('Content-Length: '.filesize($location)); +header('Content-Disposition: attachment; filename="'.$file['name'].'"'); readfile($location); -/// -function throw_error ($time = 15) { - sleep ($time); - $styleError = "background:url(\"../images/err.png\") no-repeat scroll 0 0 transparent; padding:4px 1px 6px 30px; color:#CC0000;"; - echo "

" . - __('Unreliable petition') . ". " . __('Please contact the administrator') . - "

"; - exit; +function throw_error($time=15) +{ + sleep($time); + + $styleError = 'background:url("../images/err.png") no-repeat scroll 0 0 transparent; padding:4px 1px 6px 30px; color:#CC0000;'; + echo "

".__('Unreliable petition').'. '.__('Please contact the administrator').'

'; + exit; } - -?> \ No newline at end of file diff --git a/pandora_console/extensions/files_repo/files_repo_list.php b/pandora_console/extensions/files_repo/files_repo_list.php index 971502d930..1d01cd1418 100644 --- a/pandora_console/extensions/files_repo/files_repo_list.php +++ b/pandora_console/extensions/files_repo/files_repo_list.php @@ -4,115 +4,116 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - global $config; -$full_extensions_dir = $config['homedir'] . "/" . EXTENSIONS_DIR . "/"; -require_once ($full_extensions_dir . - "files_repo/functions_files_repo.php"); +$full_extensions_dir = $config['homedir'].'/'.EXTENSIONS_DIR.'/'; +require_once $full_extensions_dir.'files_repo/functions_files_repo.php'; $offset = (int) get_parameter('offset'); -$filter = array(); +$filter = []; $filter['limit'] = $config['block_size']; $filter['offset'] = $offset; -$filter['order'] = array('field' => 'id', 'order' => 'DESC'); +$filter['order'] = [ + 'field' => 'id', + 'order' => 'DESC', +]; $files = files_repo_get_files($filter); if (!empty($files)) { - - if (!isset($manage)) { - $manage = false; - } - - // Pagination - if ($manage) { - $url = ui_get_full_url("index.php?sec=godmode/extensions&sec2=extensions/files_repo"); - } - else { - $url = ui_get_full_url("index.php?sec=extensions&sec2=extensions/files_repo"); - } - $total_files = files_repo_get_files(false, true); - ui_pagination($total_files, $url, $offset); - - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox data'; - $table->style = array(); - $table->style[1] = "max-width: 200px;"; - $table->style[2] = "text-align: center;"; - $table->style[3] = "text-align: center;"; - $table->style[4] = "text-align: center;"; - $table->head = array(); - $table->head[0] = __("Name"); - $table->head[1] = __("Description"); - $table->head[2] = __("Size"); - $table->head[3] = __("Last modification"); - $table->head[4] = ""; - $table->data = array(); - - foreach ($files as $file_id => $file) { - $data = array(); - - // Prepare the filename for the get_file.php script - $document_root = str_replace("\\", "/", io_safe_output($_SERVER['DOCUMENT_ROOT'])); - $file['location'] = str_replace("\\", "/", io_safe_output($file['location'])); - $relative_path = str_replace($document_root, '', $file['location']); - $file_path = base64_encode($relative_path); - $hash = md5($relative_path . $config['dbpass']); - $url = ui_get_full_url("include/get_file.php?file=$file_path&hash=$hash"); - $date_format = ($config['date_format']) ? io_safe_output($config['date_format']) : 'F j, Y - H:m'; - - $data[0] = "" . $file['name'] . ""; // Name - $data[1] = ui_print_truncate_text($file['description'], 'description', true, true); // Description - $data[2] = ui_format_filesize($file['size']); // Size - $data[3] = date($date_format, $file['mtime']); // Last modification - - // Public URL - $data[4] = ""; - if (!empty($file['hash'])) { - $public_url = ui_get_full_url(EXTENSIONS_DIR . "/files_repo/files_repo_get_file.php?file=" . $file['hash']); - $message = __('Copy to clipboard') . ": Ctrl+C -> Enter"; - $action = "window.prompt('$message', '$public_url');"; - $data[4] .= ""; - $data[4] .= html_print_image('images/world.png', true, array('title' => __('Public link'))); // Public link image - $data[4] .= " "; - } - - $data[4] .= ""; - $data[4] .= html_print_image('images/download.png', true, array('title' => __('Download'))); // Download image - $data[4] .= ""; - - if ($manage) { - - $config_url = ui_get_full_url("index.php?sec=godmode/extensions&sec2=extensions/files_repo&file_id=$file_id"); - $data[4] .= " "; - $data[4] .= html_print_image('images/config.png', true, array('title' => __('Edit'))); // Edit image - $data[4] .= ""; - - $delete_url = ui_get_full_url("index.php?sec=godmode/extensions&sec2=extensions/files_repo&delete=1&file_id=$file_id"); - $data[4] .= " "; - $data[4] .= html_print_image('images/cross.png', true, array('title' => __('Delete'))); // Delete image - $data[4] .= ""; - } - $table->data[] = $data; - } - html_print_table($table); - -} -else { - ui_print_info_message(__('No items')); -} + if (!isset($manage)) { + $manage = false; + } -?> \ No newline at end of file + // Pagination + if ($manage) { + $url = ui_get_full_url('index.php?sec=godmode/extensions&sec2=extensions/files_repo'); + } else { + $url = ui_get_full_url('index.php?sec=extensions&sec2=extensions/files_repo'); + } + + $total_files = files_repo_get_files(false, true); + ui_pagination($total_files, $url, $offset); + + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox data'; + $table->style = []; + $table->style[1] = 'max-width: 200px;'; + $table->style[2] = 'text-align: center;'; + $table->style[3] = 'text-align: center;'; + $table->style[4] = 'text-align: center;'; + $table->head = []; + $table->head[0] = __('Name'); + $table->head[1] = __('Description'); + $table->head[2] = __('Size'); + $table->head[3] = __('Last modification'); + $table->head[4] = ''; + $table->data = []; + + foreach ($files as $file_id => $file) { + $data = []; + + // Prepare the filename for the get_file.php script + $document_root = str_replace('\\', '/', io_safe_output($_SERVER['DOCUMENT_ROOT'])); + $file['location'] = str_replace('\\', '/', io_safe_output($file['location'])); + $relative_path = str_replace($document_root, '', $file['location']); + $file_path = base64_encode($relative_path); + $hash = md5($relative_path.$config['dbpass']); + $url = ui_get_full_url("include/get_file.php?file=$file_path&hash=$hash"); + $date_format = ($config['date_format']) ? io_safe_output($config['date_format']) : 'F j, Y - H:m'; + + $data[0] = "".$file['name'].''; + // Name + $data[1] = ui_print_truncate_text($file['description'], 'description', true, true); + // Description + $data[2] = ui_format_filesize($file['size']); + // Size + $data[3] = date($date_format, $file['mtime']); + // Last modification + // Public URL + $data[4] = ''; + if (!empty($file['hash'])) { + $public_url = ui_get_full_url(EXTENSIONS_DIR.'/files_repo/files_repo_get_file.php?file='.$file['hash']); + $message = __('Copy to clipboard').': Ctrl+C -> Enter'; + $action = "window.prompt('$message', '$public_url');"; + $data[4] .= ""; + $data[4] .= html_print_image('images/world.png', true, ['title' => __('Public link')]); + // Public link image + $data[4] .= ' '; + } + + $data[4] .= ""; + $data[4] .= html_print_image('images/download.png', true, ['title' => __('Download')]); + // Download image + $data[4] .= ''; + + if ($manage) { + $config_url = ui_get_full_url("index.php?sec=godmode/extensions&sec2=extensions/files_repo&file_id=$file_id"); + $data[4] .= " "; + $data[4] .= html_print_image('images/config.png', true, ['title' => __('Edit')]); + // Edit image + $data[4] .= ''; + + $delete_url = ui_get_full_url("index.php?sec=godmode/extensions&sec2=extensions/files_repo&delete=1&file_id=$file_id"); + $data[4] .= " "; + $data[4] .= html_print_image('images/cross.png', true, ['title' => __('Delete')]); + // Delete image + $data[4] .= ''; + } + + $table->data[] = $data; + } + + html_print_table($table); +} else { + ui_print_info_message(__('No items')); +} diff --git a/pandora_console/extensions/files_repo/functions_files_repo.php b/pandora_console/extensions/files_repo/functions_files_repo.php index 2f736c5b90..3d9bdccd38 100644 --- a/pandora_console/extensions/files_repo/functions_files_repo.php +++ b/pandora_console/extensions/files_repo/functions_files_repo.php @@ -4,300 +4,321 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function files_repo_check_directory($print_messages=false) +{ + global $config; + $attachment_path = io_safe_output($config['attachment_store']); + $files_repo_path = $attachment_path.'/files_repo'; -function files_repo_check_directory ($print_messages = false) { - global $config; + $result = false; + $messages = ''; - $attachment_path = io_safe_output($config['attachment_store']); - $files_repo_path = $attachment_path."/files_repo"; + // attachment/ check + if (!is_writable($attachment_path)) { + $messages .= ui_print_error_message( + [ + 'message' => __('Attachment directory is not writable by HTTP Server').''.'

'.sprinf(__('Please check that the web server has write rights on the %s directory'), $attachment_path), + 'no_close' => true, + 'force_style' => 'color: #000000 !important', + ], + '', + true + ); + } else { + // attachment/agent_packages/ check + if (!file_exists($files_repo_path) || !is_writable($files_repo_path)) { + // Create the directoty if not exist + if (!file_exists($files_repo_path)) { + mkdir($files_repo_path); + } - $result = false; - $messages = ""; + if (!is_writable($files_repo_path)) { + $messages .= ui_print_error_message( + [ + 'message' => __('Attachment directory is not writable by HTTP Server').''.'

'.sprintf(__('Please check that the web server has write rights on the %s directory'), $attachment_path), + 'no_close' => true, + 'force_style' => 'color: #000000 !important', + ], + '', + true + ); + } else { + $result = true; + } + } else { + $result = true; + } + } - // attachment/ check - if (!is_writable($attachment_path)) { - $messages .= ui_print_error_message(array('message' => __('Attachment directory is not writable by HTTP Server') - .''.'

'.sprinf(__('Please check that the web server has write rights on the %s directory'), $attachment_path), - 'no_close' => true, 'force_style' => 'color: #000000 !important'), '', true); - } else { - // attachment/agent_packages/ check - if (!file_exists($files_repo_path) || !is_writable($files_repo_path)) { - // Create the directoty if not exist - if (!file_exists($files_repo_path)) { - mkdir($files_repo_path); - } - if (!is_writable($files_repo_path)) { - $messages .= ui_print_error_message(array('message' => __('Attachment directory is not writable by HTTP Server') - .''.'

'.sprintf(__('Please check that the web server has write rights on the %s directory'), $attachment_path), - 'no_close' => true, 'force_style' => 'color: #000000 !important'), '', true); - } else { - $result = true; - } - } else { - $result = true; - } - } + if ($print_messages) { + echo $messages; + } - if ($print_messages) { - echo $messages; - } - return $result; + return $result; } -function files_repo_check_file_acl ($file_id, $user_id = false, $file_groups = false, $user_groups = false) { - global $config; - $result = false; - if (!$user_id) { - $user_id = $config['id_user']; - } - if (is_user_admin($user_id)) { - return true; - } - if (!$file_groups) { - $file_groups = files_repo_get_file_groups($file_id); - if (empty($file_groups)) { - $file_groups = array(); - } - } +function files_repo_check_file_acl($file_id, $user_id=false, $file_groups=false, $user_groups=false) +{ + global $config; - if (in_array(0, $file_groups)) { - return true; - } + $result = false; + if (!$user_id) { + $user_id = $config['id_user']; + } - if (!$user_groups) { - $user_groups = users_get_groups ($user_id, false, true); - if (empty($user_groups)) { - $user_groups = array(); - } - } + if (is_user_admin($user_id)) { + return true; + } - foreach ($file_groups as $group_id) { - // $user_groups has the id in the array keys - if (in_array($group_id, $user_groups)) { - $result = true; - break; - } - } - - return $result; + if (!$file_groups) { + $file_groups = files_repo_get_file_groups($file_id); + if (empty($file_groups)) { + $file_groups = []; + } + } + + if (in_array(0, $file_groups)) { + return true; + } + + if (!$user_groups) { + $user_groups = users_get_groups($user_id, false, true); + if (empty($user_groups)) { + $user_groups = []; + } + } + + foreach ($file_groups as $group_id) { + // $user_groups has the id in the array keys + if (in_array($group_id, $user_groups)) { + $result = true; + break; + } + } + + return $result; } -function files_repo_get_file_groups ($file_id) { - $groups = array(); - $filter = array('id_file' => $file_id); - $result = db_get_all_rows_filter("tfiles_repo_group", $filter, "id_group"); +function files_repo_get_file_groups($file_id) +{ + $groups = []; + $filter = ['id_file' => $file_id]; + $result = db_get_all_rows_filter('tfiles_repo_group', $filter, 'id_group'); - if (!empty($result)) { - foreach ($result as $key => $value) { - $groups[] = $value['id_group']; - } - } + if (!empty($result)) { + foreach ($result as $key => $value) { + $groups[] = $value['id_group']; + } + } - return $groups; + return $groups; } -function files_repo_get_user_groups ($user_id) { - $groups = array(); - $filter = array('id_usuario' => $user_id); - $result = db_get_all_rows_filter("tusuario_perfil", $filter, "id_grupo"); +function files_repo_get_user_groups($user_id) +{ + $groups = []; + $filter = ['id_usuario' => $user_id]; + $result = db_get_all_rows_filter('tusuario_perfil', $filter, 'id_grupo'); - if (!empty($result)) { - foreach ($result as $key => $value) { - $groups[] = $value['id_grupo']; - } - } + if (!empty($result)) { + foreach ($result as $key => $value) { + $groups[] = $value['id_grupo']; + } + } - return $groups; + return $groups; } -function files_repo_get_files ($filter = false, $count = false) { - global $config; - - // Don't use the realpath for the download links! - $files_repo_path = io_safe_output($config['attachment_store'])."/files_repo"; - - $sql = "SELECT * + +function files_repo_get_files($filter=false, $count=false) +{ + global $config; + + // Don't use the realpath for the download links! + $files_repo_path = io_safe_output($config['attachment_store']).'/files_repo'; + + $sql = 'SELECT * FROM tfiles_repo - " . db_format_array_where_clause_sql($filter, "AND", "WHERE"); - $files = db_get_all_rows_sql($sql); - - if ($files === false) - $files = array(); - - $user_groups = files_repo_get_user_groups($config['id_user']); - - $files_data = array(); - foreach ($files as $file) { - - $file_groups = files_repo_get_file_groups($file['id']); - $permission = files_repo_check_file_acl ($file['id'], $config['id_user'], $file_groups, $user_groups); - if (!$permission) { - continue; - } - - $data = array(); - $data['name'] = $file['name']; - $data['description'] = $file['description']; - $data['location'] = $files_repo_path . "/" . $file['id']."_".$data['name']; - // Size in bytes - $data['size'] = filesize($data['location']); - // Last modification time in unix timestamp - $data['mtime'] = filemtime($data['location']); - $data['groups'] = $file_groups; - $data['hash'] = $file['hash']; - $files_data[$file['id']] = $data; - } - - if ($count) { - $files_data = count($files_data); - } - - return $files_data; + '.db_format_array_where_clause_sql($filter, 'AND', 'WHERE'); + $files = db_get_all_rows_sql($sql); + + if ($files === false) { + $files = []; + } + + $user_groups = files_repo_get_user_groups($config['id_user']); + + $files_data = []; + foreach ($files as $file) { + $file_groups = files_repo_get_file_groups($file['id']); + $permission = files_repo_check_file_acl($file['id'], $config['id_user'], $file_groups, $user_groups); + if (!$permission) { + continue; + } + + $data = []; + $data['name'] = $file['name']; + $data['description'] = $file['description']; + $data['location'] = $files_repo_path.'/'.$file['id'].'_'.$data['name']; + // Size in bytes + $data['size'] = filesize($data['location']); + // Last modification time in unix timestamp + $data['mtime'] = filemtime($data['location']); + $data['groups'] = $file_groups; + $data['hash'] = $file['hash']; + $files_data[$file['id']] = $data; + } + + if ($count) { + $files_data = count($files_data); + } + + return $files_data; } -function files_repo_add_file ($file_input_name = "upfile", $description = "", $groups = array(), $public = false) { - global $config; - $attachment_path = io_safe_output($config['attachment_store']); - $files_repo_path = $attachment_path."/"."files_repo"; +function files_repo_add_file($file_input_name='upfile', $description='', $groups=[], $public=false) +{ + global $config; - $result = array(); - $result["status"] = false; - $result["message"] = ""; + $attachment_path = io_safe_output($config['attachment_store']); + $files_repo_path = $attachment_path.'/'.'files_repo'; - $upload_status = get_file_upload_status($file_input_name); - $upload_result = translate_file_upload_status($upload_status); + $result = []; + $result['status'] = false; + $result['message'] = ''; - if ($upload_result === true) { - $filename = $_FILES[$file_input_name]['name']; - // Replace conflictive characters - $filename = str_replace (array(" ", "=", "?", "&"), "_", $filename); - $filename = filter_var($filename, FILTER_SANITIZE_URL); - // The filename should not be larger than 200 characters - if (mb_strlen($filename, "UTF-8") > 200) { - $filename = mb_substr($filename, 0, 200, "UTF-8"); - } + $upload_status = get_file_upload_status($file_input_name); + $upload_result = translate_file_upload_status($upload_status); - $hash = ""; - if ($public) { - $hash = md5(time() . $config['dbpass']); - $hash = mb_substr($hash, 0, 8, "UTF-8"); - } + if ($upload_result === true) { + $filename = $_FILES[$file_input_name]['name']; + // Replace conflictive characters + $filename = str_replace([' ', '=', '?', '&'], '_', $filename); + $filename = filter_var($filename, FILTER_SANITIZE_URL); + // The filename should not be larger than 200 characters + if (mb_strlen($filename, 'UTF-8') > 200) { + $filename = mb_substr($filename, 0, 200, 'UTF-8'); + } - $values = array( - 'name' => $filename, - 'description' => $description, - 'hash' => $hash - ); - $file_id = db_process_sql_insert('tfiles_repo', $values); + $hash = ''; + if ($public) { + $hash = md5(time().$config['dbpass']); + $hash = mb_substr($hash, 0, 8, 'UTF-8'); + } - if ($file_id) { - - $file_tmp = $_FILES[$file_input_name]['tmp_name']; - $destination = $files_repo_path."/".$file_id."_".$filename; - - if (move_uploaded_file($file_tmp, $destination)) { + $values = [ + 'name' => $filename, + 'description' => $description, + 'hash' => $hash, + ]; + $file_id = db_process_sql_insert('tfiles_repo', $values); - if (is_array($groups) && !empty($groups)) { - db_process_sql_delete('tfiles_repo_group', array('id_file' => $file_id)); - foreach ($groups as $group) { - $values = array( - 'id_file' => $file_id, - 'id_group' => $group - ); - db_process_sql_insert('tfiles_repo_group', $values); - } - } - - $result["status"] = true; - } else { - db_process_sql_delete('tfiles_repo', array('id' => $file_id)); - unlink ($file_tmp); - $result["message"] = __('The file could not be copied'); - } - - } else { - $result["message"] = __('There was an error creating the file'); - } - } else { - $result["message"] = $upload_result; - } + if ($file_id) { + $file_tmp = $_FILES[$file_input_name]['tmp_name']; + $destination = $files_repo_path.'/'.$file_id.'_'.$filename; - return $result; + if (move_uploaded_file($file_tmp, $destination)) { + if (is_array($groups) && !empty($groups)) { + db_process_sql_delete('tfiles_repo_group', ['id_file' => $file_id]); + foreach ($groups as $group) { + $values = [ + 'id_file' => $file_id, + 'id_group' => $group, + ]; + db_process_sql_insert('tfiles_repo_group', $values); + } + } + + $result['status'] = true; + } else { + db_process_sql_delete('tfiles_repo', ['id' => $file_id]); + unlink($file_tmp); + $result['message'] = __('The file could not be copied'); + } + } else { + $result['message'] = __('There was an error creating the file'); + } + } else { + $result['message'] = $upload_result; + } + + return $result; } -function files_repo_update_file ($file_id, $description = "", $groups = array(), $public = false) { - global $config; - $result = array(); - $result["status"] = false; - $result["message"] = ""; +function files_repo_update_file($file_id, $description='', $groups=[], $public=false) +{ + global $config; - $hash = ""; - if ($public) { - $hash = md5(time() . $config['dbpass']); - $hash = mb_substr($hash, 0, 8, "UTF-8"); - } + $result = []; + $result['status'] = false; + $result['message'] = ''; - $values = array( - 'description' => $description, - 'hash' => $hash - ); - $filter = array('id' => $file_id); - $res = db_process_sql_update('tfiles_repo', $values, $filter); - if ($res !== false) { - if (is_array($groups) && !empty($groups)) { - db_process_sql_delete('tfiles_repo_group', array('id_file' => $file_id)); - foreach ($groups as $group) { - $values = array( - 'id_file' => $file_id, - 'id_group' => $group - ); - db_process_sql_insert('tfiles_repo_group', $values); - } - } - $result["status"] = true; - } else { - $result["message"] = __('There was an error updating the file'); - } + $hash = ''; + if ($public) { + $hash = md5(time().$config['dbpass']); + $hash = mb_substr($hash, 0, 8, 'UTF-8'); + } - return $result; + $values = [ + 'description' => $description, + 'hash' => $hash, + ]; + $filter = ['id' => $file_id]; + $res = db_process_sql_update('tfiles_repo', $values, $filter); + if ($res !== false) { + if (is_array($groups) && !empty($groups)) { + db_process_sql_delete('tfiles_repo_group', ['id_file' => $file_id]); + foreach ($groups as $group) { + $values = [ + 'id_file' => $file_id, + 'id_group' => $group, + ]; + db_process_sql_insert('tfiles_repo_group', $values); + } + } + + $result['status'] = true; + } else { + $result['message'] = __('There was an error updating the file'); + } + + return $result; } -function files_repo_delete_file ($file_id) { - global $config; - $result = -1; +function files_repo_delete_file($file_id) +{ + global $config; - $filename = db_get_value("name", "tfiles_repo", "id", $file_id); + $result = -1; - if ($filename) { - $attachment_path = io_safe_output($config['attachment_store']); - $files_repo_path = $attachment_path."/files_repo"; - $location = $files_repo_path."/".$file_id."_".$filename; + $filename = db_get_value('name', 'tfiles_repo', 'id', $file_id); - if (file_exists($location)) { - $result = false; - if (unlink($location)) { - $result = (bool) db_process_sql_delete('tfiles_repo', array('id' => $file_id)); - } - } - } - - return $result; + if ($filename) { + $attachment_path = io_safe_output($config['attachment_store']); + $files_repo_path = $attachment_path.'/files_repo'; + $location = $files_repo_path.'/'.$file_id.'_'.$filename; + + if (file_exists($location)) { + $result = false; + if (unlink($location)) { + $result = (bool) db_process_sql_delete('tfiles_repo', ['id' => $file_id]); + } + } + } + + return $result; } - -?> \ No newline at end of file diff --git a/pandora_console/extensions/insert_data.php b/pandora_console/extensions/insert_data.php index b930462fe5..36a4d73cc1 100644 --- a/pandora_console/extensions/insert_data.php +++ b/pandora_console/extensions/insert_data.php @@ -4,28 +4,26 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -include_once($config['homedir'] . "/include/functions_agents.php"); -include_once($config['homedir'] . "/include/functions_modules.php"); -include_once($config['homedir'] . "/include/functions.php"); +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions.php'; -function createXMLData($agent, $agentModule, $time, $data) { - global $config; - - $xmlTemplate = " - + +function createXMLData($agent, $agentModule, $time, $data) +{ + global $config; + + $xmlTemplate = " + @@ -33,228 +31,241 @@ function createXMLData($agent, $agentModule, $time, $data) { "; - - $xml = sprintf( - $xmlTemplate, - io_safe_output(get_os_name($agent['id_os'])), - io_safe_output($agent['os_version']), - $agent['intervalo'], - io_safe_output($agent['agent_version']), - $time, - io_safe_output($agent['nombre']), - io_safe_output($agentModule['nombre']), - io_safe_output($agentModule['descripcion']), - modules_get_type_name($agentModule['id_tipo_modulo']), - $data - ); - - $file_name = $config["remote_config"] . "/" . io_safe_output($agent["alias"]) . "." . strtotime($time) . ".data"; - return (bool) @file_put_contents($file_name, $xml); + + $xml = sprintf( + $xmlTemplate, + io_safe_output(get_os_name($agent['id_os'])), + io_safe_output($agent['os_version']), + $agent['intervalo'], + io_safe_output($agent['agent_version']), + $time, + io_safe_output($agent['nombre']), + io_safe_output($agentModule['nombre']), + io_safe_output($agentModule['descripcion']), + modules_get_type_name($agentModule['id_tipo_modulo']), + $data + ); + + $file_name = $config['remote_config'].'/'.io_safe_output($agent['alias']).'.'.strtotime($time).'.data'; + return (bool) @file_put_contents($file_name, $xml); } -function mainInsertData() { - global $config; - - ui_print_page_header (__("Insert data"), "images/extensions.png", false, "", true, ""); - - if (! check_acl ($config['id_user'], 0, "AW") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; - } - - $save = (bool) get_parameter("save"); - $agent_id = (int) get_parameter("agent_id"); - $agent_name = (string) get_parameter("agent_name"); - - $id_agent_module = (int) get_parameter("id_agent_module"); - $data = (string) get_parameter('data'); - $date = (string) get_parameter('date', date(DATE_FORMAT)); - $time = (string) get_parameter('time', date(TIME_FORMAT)); - if (isset($_FILES['csv'])) { - if ($_FILES['csv']['error'] != 4) { - $csv = $_FILES['csv']; - } - else { - $csv = false; - } - } - else { - $csv = false; - } - - - if ($save) { - if (!check_acl($config['id_user'], agents_get_agent_group($agent_id), "AW")) { - ui_print_error_message(__('You haven\'t privileges for insert data in the agent.')); - } - else { - $agent = db_get_row_filter('tagente', array('id_agente' => $agent_id)); - $agentModule = db_get_row_filter('tagente_modulo', array('id_agente_modulo' => $id_agent_module)); - - $done = 0; - $errors = 0; - if ($csv !== false) { - $file = file($csv['tmp_name']); - foreach ($file as $line) { - $tokens = explode(';', $line); - - $utimestamp = strtotime(trim($tokens[0])) - get_fixed_offset(); - $timestamp = date(DATE_FORMAT . " " . TIME_FORMAT, $utimestamp); - $result = createXMLData($agent, $agentModule, $timestamp, trim($tokens[1])); - - if ($result) { - $done++; - } - else { - $errors++; - } - } - } - else { - $utimestamp = strtotime($date . " " . $time) - get_fixed_offset(); - $timestamp = date(DATE_FORMAT . " " . TIME_FORMAT, $utimestamp); - $result = createXMLData($agent, $agentModule, $timestamp, $data); - if ($result) { - $done++; - } - else { - $errors++; - } - } - } - - if ($errors > 0) { - $msg = sprintf(__('Can\'t save agent (%s), module (%s) data xml.'), $agent['alias'], $agentModule['nombre']); - if ($errors > 1) { - $msg .= " ($errors)"; - } - ui_print_error_message($msg); - } - if ($done > 0) { - $msg = sprintf(__('Save agent (%s), module (%s) data xml.'), $agent['alias'], $agentModule['nombre']); - if ($done > 1) { - $msg .= " ($done)"; - } - ui_print_success_message($msg); - } - } - - echo '

'; - echo sprintf(__("Please check that the directory \"%s\" is writeable by the apache user.

The CSV file format is date;value<newline>date;value<newline>... The date in CSV is in format Y/m/d H:i:s."), - $config['remote_config']); - echo '
'; - - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox filters'; - $table->style = array(); - $table->style[0] = 'font-weight: bolder;'; - - $table->data = array(); - - $table->data[0][0] = __('Agent'); - $params = array(); - $params['return'] = true; - $params['show_helptip'] = true; - $params['input_name'] = 'agent_name'; - $params['value'] = $agent_name; - $params['javascript_is_function_select'] = true; - $params['javascript_name_function_select'] = 'custom_select_function'; - $params['javascript_code_function_select'] = ''; - $params['use_hidden_input_idagent'] = true; - $params['print_hidden_input_idagent'] = true; - $params['hidden_input_idagent_id'] = 'hidden-autocomplete_id_agent'; - $params['hidden_input_idagent_name'] = 'agent_id'; - $params['hidden_input_idagent_value'] = $agent_id; - - $table->data[0][1] = ui_print_agent_autocomplete_input($params); - - $table->data[1][0] = __('Module'); - $modules = array (); - if ($agent_id){ - $modules = agents_get_modules ($agent_id, false, array("delete_pending" => 0)); - } - $table->data[1][1] = html_print_select ($modules, 'id_agent_module', $id_agent_module, true, - __('Select'), 0, true, false, true, '', empty($agent_id)); - $table->data[2][0] = __('Data'); - $table->data[2][1] = html_print_input_text('data', $data, __('Data'), 40, 60, true); - $table->data[3][0] = __('Date'); - $table->data[3][1] = html_print_input_text ('date', $date, '', 11, 11, true).' '; - $table->data[3][1] .= html_print_input_text ('time', $time, '', 7, 7, true); - $table->data[4][0] = __('CSV'); - $table->data[4][1] = html_print_input_file('csv', true); - - echo "
"; - - html_print_table($table); - - echo "
"; - html_print_input_hidden('save', 1); - html_print_submit_button(__('Save'), 'submit', ($id_agent === ''), 'class="sub next"'); - echo "
"; - - echo "
"; - - ui_require_css_file ('datepicker'); - ui_include_time_picker(); - ui_require_jquery_file("ui.datepicker-" . get_user_language(), "include/javascript/i18n/"); -?> +function mainInsertData() +{ + global $config; + + ui_print_page_header(__('Insert data'), 'images/extensions.png', false, '', true, ''); + + if (! check_acl($config['id_user'], 0, 'AW') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; + } + + $save = (bool) get_parameter('save'); + $agent_id = (int) get_parameter('agent_id'); + $agent_name = (string) get_parameter('agent_name'); + + $id_agent_module = (int) get_parameter('id_agent_module'); + $data = (string) get_parameter('data'); + $date = (string) get_parameter('date', date(DATE_FORMAT)); + $time = (string) get_parameter('time', date(TIME_FORMAT)); + if (isset($_FILES['csv'])) { + if ($_FILES['csv']['error'] != 4) { + $csv = $_FILES['csv']; + } else { + $csv = false; + } + } else { + $csv = false; + } + + if ($save) { + if (!check_acl($config['id_user'], agents_get_agent_group($agent_id), 'AW')) { + ui_print_error_message(__('You haven\'t privileges for insert data in the agent.')); + } else { + $agent = db_get_row_filter('tagente', ['id_agente' => $agent_id]); + $agentModule = db_get_row_filter('tagente_modulo', ['id_agente_modulo' => $id_agent_module]); + + $done = 0; + $errors = 0; + if ($csv !== false) { + $file = file($csv['tmp_name']); + foreach ($file as $line) { + $tokens = explode(';', $line); + + $utimestamp = (strtotime(trim($tokens[0])) - get_fixed_offset()); + $timestamp = date(DATE_FORMAT.' '.TIME_FORMAT, $utimestamp); + $result = createXMLData($agent, $agentModule, $timestamp, trim($tokens[1])); + + if ($result) { + $done++; + } else { + $errors++; + } + } + } else { + $utimestamp = (strtotime($date.' '.$time) - get_fixed_offset()); + $timestamp = date(DATE_FORMAT.' '.TIME_FORMAT, $utimestamp); + $result = createXMLData($agent, $agentModule, $timestamp, $data); + + if ($result) { + $done++; + } else { + $errors++; + } + } + } + + if ($errors > 0) { + $msg = sprintf(__('Can\'t save agent (%s), module (%s) data xml.'), $agent['alias'], $agentModule['nombre']); + if ($errors > 1) { + $msg .= " ($errors)"; + } + + ui_print_error_message($msg); + } + + if ($done > 0) { + $msg = sprintf(__('Save agent (%s), module (%s) data xml.'), $agent['alias'], $agentModule['nombre']); + if ($done > 1) { + $msg .= " ($done)"; + } + + ui_print_success_message($msg); + } + } + + echo '
'; + echo sprintf( + __('Please check that the directory "%s" is writeable by the apache user.

The CSV file format is date;value<newline>date;value<newline>... The date in CSV is in format Y/m/d H:i:s.'), + $config['remote_config'] + ); + echo '
'; + + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox filters'; + $table->style = []; + $table->style[0] = 'font-weight: bolder;'; + + $table->data = []; + + $table->data[0][0] = __('Agent'); + $params = []; + $params['return'] = true; + $params['show_helptip'] = true; + $params['input_name'] = 'agent_name'; + $params['value'] = $agent_name; + $params['javascript_is_function_select'] = true; + $params['javascript_name_function_select'] = 'custom_select_function'; + $params['javascript_code_function_select'] = ''; + $params['use_hidden_input_idagent'] = true; + $params['print_hidden_input_idagent'] = true; + $params['hidden_input_idagent_id'] = 'hidden-autocomplete_id_agent'; + $params['hidden_input_idagent_name'] = 'agent_id'; + $params['hidden_input_idagent_value'] = $agent_id; + + $table->data[0][1] = ui_print_agent_autocomplete_input($params); + + $table->data[1][0] = __('Module'); + $modules = []; + if ($agent_id) { + $modules = agents_get_modules($agent_id, false, ['delete_pending' => 0]); + } + + $table->data[1][1] = html_print_select( + $modules, + 'id_agent_module', + $id_agent_module, + true, + __('Select'), + 0, + true, + false, + true, + '', + empty($agent_id) + ); + $table->data[2][0] = __('Data'); + $table->data[2][1] = html_print_input_text('data', $data, __('Data'), 40, 60, true); + $table->data[3][0] = __('Date'); + $table->data[3][1] = html_print_input_text('date', $date, '', 11, 11, true).' '; + $table->data[3][1] .= html_print_input_text('time', $time, '', 7, 7, true); + $table->data[4][0] = __('CSV'); + $table->data[4][1] = html_print_input_file('csv', true); + + echo "
"; + + html_print_table($table); + + echo "
"; + html_print_input_hidden('save', 1); + html_print_submit_button(__('Save'), 'submit', ($id_agent === ''), 'class="sub next"'); + echo '
'; + + echo '
'; + + ui_require_css_file('datepicker'); + ui_include_time_picker(); + ui_require_jquery_file('ui.datepicker-'.get_user_language(), 'include/javascript/i18n/'); + ?> - +extensions_add_godmode_menu_option(__('Insert Data'), 'AW', 'gagente', null, 'v1r1'); + diff --git a/pandora_console/extensions/matrix_events/ajax.php b/pandora_console/extensions/matrix_events/ajax.php index 8e94e396f5..be2e5949cc 100644 --- a/pandora_console/extensions/matrix_events/ajax.php +++ b/pandora_console/extensions/matrix_events/ajax.php @@ -4,65 +4,61 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; if (is_ajax()) { + if (! check_acl($config['id_user'], 0, 'ER')) { + db_pandora_audit('ACL Violation', 'Trying to access event viewer'); + return; + } - if (! check_acl ($config["id_user"], 0, "ER")) { - db_pandora_audit("ACL Violation", "Trying to access event viewer"); - return; - } + $get_last_events = (bool) get_parameter('get_last_events'); + if ($get_last_events) { + include_once 'include/functions_io.php'; + include_once 'include/functions_tags.php'; - $get_last_events = (bool) get_parameter("get_last_events"); - if ($get_last_events) { - - require_once ('include/functions_io.php'); - require_once ('include/functions_tags.php'); + $limit = (int) get_parameter('limit', 5); - $limit = (int) get_parameter("limit", 5); + $tags_condition = tags_get_acl_tags($config['id_user'], 0, 'ER', 'event_condition', 'AND'); - $tags_condition = tags_get_acl_tags($config['id_user'], 0, 'ER', 'event_condition', 'AND'); - - $filter = "estado <> 1 $tags_condition"; + $filter = "estado <> 1 $tags_condition"; - $sql = sprintf ("SELECT id_agente, evento, utimestamp + $sql = sprintf( + 'SELECT id_agente, evento, utimestamp FROM tevento LEFT JOIN tagent_secondary_group ON tevento.id_agente = tagent_secondary_group.id_agent WHERE %s - ORDER BY utimestamp DESC LIMIT %d", - $filter, $limit); - - $result = db_get_all_rows_sql ($sql); + ORDER BY utimestamp DESC LIMIT %d', + $filter, + $limit + ); - $events = array(); - if (! empty($result)) { - foreach ($result as $key => $value) { - $event = array(); - $event['agent'] = (empty($value['id_agente'])) ? "System" : agents_get_name($value['id_agente']); - $event['text'] = io_safe_output($value['evento']); - $event['date'] = date(io_safe_output($config['date_format']), $value['utimestamp']); - $events[] = $event; - } - } else { - sleep(5); - } + $result = db_get_all_rows_sql($sql); - echo json_encode($events); - return; - } + $events = []; + if (! empty($result)) { + foreach ($result as $key => $value) { + $event = []; + $event['agent'] = (empty($value['id_agente'])) ? 'System' : agents_get_name($value['id_agente']); + $event['text'] = io_safe_output($value['evento']); + $event['date'] = date(io_safe_output($config['date_format']), $value['utimestamp']); + $events[] = $event; + } + } else { + sleep(5); + } - return; + echo json_encode($events); + return; + } + + return; } - -?> \ No newline at end of file diff --git a/pandora_console/extensions/module_groups.php b/pandora_console/extensions/module_groups.php index b7eca3b3e9..1a505538ed 100644 --- a/pandora_console/extensions/module_groups.php +++ b/pandora_console/extensions/module_groups.php @@ -4,101 +4,128 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Load global vars - global $config; -check_login (); +check_login(); -if (is_ajax ()) { - $get_info_alert_module_group = (bool)get_parameter('get_info_alert_module_group'); +if (is_ajax()) { + $get_info_alert_module_group = (bool) get_parameter('get_info_alert_module_group'); - if ($get_info_alert_module_group) { - $send_tooltip = json_decode(io_safe_output(get_parameter('send_tooltip')), true); - echo "

    " . __('Counters Module') . "

    "; - echo "
  • " . __('Alerts_Fired') . ": " . $send_tooltip['alerts_module_count'] . "
  • "; - echo "
  • " . __('Critical') . ": " . $send_tooltip['critical_module_count'] . "
  • "; - echo "
  • " . __('warning') . ": " . $send_tooltip['warning_module_count'] . "
  • "; - echo "
  • " . __('Unknown') . ": " . $send_tooltip['unknown_module_count'] . "
  • "; - echo "
  • " . __('OK') . ": " . $send_tooltip['normal_module_count'] . "
  • "; - echo "
  • " . __('Not_init') . ": " . $send_tooltip['notInit_module_count'] . "
"; - } + if ($get_info_alert_module_group) { + $send_tooltip = json_decode(io_safe_output(get_parameter('send_tooltip')), true); + echo "

    ".__('Counters Module').'

    '; + echo "
  • ".__('Alerts_Fired').': '.$send_tooltip['alerts_module_count'].'
  • '; + echo "
  • ".__('Critical').': '.$send_tooltip['critical_module_count'].'
  • '; + echo "
  • ".__('warning').': '.$send_tooltip['warning_module_count'].'
  • '; + echo "
  • ".__('Unknown').': '.$send_tooltip['unknown_module_count'].'
  • '; + echo "
  • ".__('OK').': '.$send_tooltip['normal_module_count'].'
  • '; + echo "
  • ".__('Not_init').': '.$send_tooltip['notInit_module_count'].'
'; + } } + /** * The main function of module groups and the enter point to * execute the code. */ -function mainModuleGroups() { - global $config; +function mainModuleGroups() +{ + global $config; - require_once($config['homedir'] . "/include/class/TreeGroup.class.php"); - require_once($config['homedir'] . "/include/functions_groupview.php"); + include_once $config['homedir'].'/include/class/TreeGroup.class.php'; + include_once $config['homedir'].'/include/functions_groupview.php'; - $tree_group = new TreeGroup("group", "group"); - $tree_group->setPropagateCounters(false); - $tree_group->setDisplayAllGroups(true); - $tree_group->setFilter( array( - 'searchAgent' => '', - 'statusAgent' => AGENT_STATUS_ALL, - 'searchModule' => '', - 'statusModule' => -1, - 'groupID' => 0, - 'tagID' => 0, - 'show_not_init_agents' => 1, - 'show_not_init_modules' => 1 - )); - $info = $tree_group->getArray(); - $info = groupview_plain_groups($info); - $counter = count($info); - $offset = get_parameter('offset', 0); - $groups_view = $is_not_paginated - ? $info - : array_slice($info, $offset, $config['block_size']); - $agents_counters = array_reduce($groups_view, function($carry, $item){ - $carry[$item['id']] = $item; - return $carry; - }, array()); + $tree_group = new TreeGroup('group', 'group'); + $tree_group->setPropagateCounters(false); + $tree_group->setDisplayAllGroups(true); + $tree_group->setFilter( + [ + 'searchAgent' => '', + 'statusAgent' => AGENT_STATUS_ALL, + 'searchModule' => '', + 'statusModule' => -1, + 'groupID' => 0, + 'tagID' => 0, + 'show_not_init_agents' => 1, + 'show_not_init_modules' => 1, + ] + ); + $info = $tree_group->getArray(); + $info = groupview_plain_groups($info); + $counter = count($info); + $offset = get_parameter('offset', 0); + $agent_group_search = get_parameter('agent_group_search', ''); + $module_group_search = get_parameter('module_group_search', ''); - $ids_array = array_keys($agents_counters); + $info = array_filter( + $info, + function ($v, $k) use ($agent_group_search) { + return preg_match("/$agent_group_search/i", $v['name']); + }, + ARRAY_FILTER_USE_BOTH + ); - $ids_group = implode(',', $ids_array); + if (!empty($info)) { + $groups_view = $is_not_paginated ? $info : array_slice($info, $offset, $config['block_size']); + $agents_counters = array_reduce( + $groups_view, + function ($carry, $item) { + $carry[$item['id']] = $item; + return $carry; + }, + [] + ); - $condition_critical = modules_get_state_condition(AGENT_MODULE_STATUS_CRITICAL_ALERT); - $condition_warning = modules_get_state_condition(AGENT_MODULE_STATUS_WARNING_ALERT); - $condition_unknown = modules_get_state_condition(AGENT_MODULE_STATUS_UNKNOWN); - $condition_not_init = modules_get_state_condition(AGENT_MODULE_STATUS_NO_DATA); - $condition_normal = modules_get_state_condition(AGENT_MODULE_STATUS_NORMAL); + $ids_array = array_keys($agents_counters); - $array_for_defect = array(); - $array_module_group = array(); - $array_data = array(); + $ids_group = implode(',', $ids_array); + } else { + $ids_group = -1; + } - $sql = "SELECT id_mg, `name` FROM tmodule_group"; - $array_mod= db_get_all_rows_sql($sql); + $condition_critical = modules_get_state_condition(AGENT_MODULE_STATUS_CRITICAL_ALERT); + $condition_warning = modules_get_state_condition(AGENT_MODULE_STATUS_WARNING_ALERT); + $condition_unknown = modules_get_state_condition(AGENT_MODULE_STATUS_UNKNOWN); + $condition_not_init = modules_get_state_condition(AGENT_MODULE_STATUS_NO_DATA); + $condition_normal = modules_get_state_condition(AGENT_MODULE_STATUS_NORMAL); - foreach ($array_mod as $key => $value) { - $array_module_group[$value['id_mg']] = $value['name']; - } - $array_module_group[0] = 'Nothing'; - foreach ($agents_counters as $key => $value) { - $array_for_defect[$key]['gm'] = $array_module_group; - $array_for_defect[$key]['data']['name'] = $value['name']; - $array_for_defect[$key]['data']['parent'] = $value['parent']; - $array_for_defect[$key]['data']['icon'] = $value['icon']; - } + $array_for_defect = []; + $array_module_group = []; + $array_data = []; -$sql = - "SELECT SUM(IF(tae.alert_fired <> 0, 1, 0)) AS alerts_module_count, + $sql = 'SELECT id_mg, `name` FROM tmodule_group'; + $array_mod = db_get_all_rows_sql($sql); + + foreach ($array_mod as $key => $value) { + $array_module_group[$value['id_mg']] = $value['name']; + } + + $array_module_group[0] = 'Nothing'; + + $array_module_group = array_filter( + $array_module_group, + function ($v, $k) use ($module_group_search) { + return preg_match("/$module_group_search/i", $v); + }, + ARRAY_FILTER_USE_BOTH + ); + + foreach ($agents_counters as $key => $value) { + $array_for_defect[$key]['gm'] = $array_module_group; + $array_for_defect[$key]['data']['name'] = $value['name']; + $array_for_defect[$key]['data']['parent'] = $value['parent']; + $array_for_defect[$key]['data']['icon'] = $value['icon']; + } + + $sql = "SELECT SUM(IF(tae.alert_fired <> 0, 1, 0)) AS alerts_module_count, SUM(IF($condition_warning, 1, 0)) AS warning_module_count, SUM(IF($condition_unknown, 1, 0)) AS unknown_module_count, SUM(IF($condition_not_init, 1, 0)) AS notInit_module_count, @@ -159,127 +186,145 @@ $sql = ON tae.id_module_group = tmg.id_mg GROUP BY tae.g, tmg.id_mg"; - $array_data_prev = db_get_all_rows_sql($sql); + $array_data_prev = db_get_all_rows_sql($sql); - foreach ($array_data_prev as $key => $value) { - $array_data[$value['id_grupo']][$value['id_mg']] = $value; - } + foreach ($array_data_prev as $key => $value) { + $array_data[$value['id_grupo']][$value['id_mg']] = $value; + } - ui_print_page_header (__("Combined table of agent group and module group"), "images/module_group.png", false, "", false, ''); + ui_print_page_header(__('Combined table of agent group and module group'), 'images/module_group.png', false, '', false, ''); - if(count($array_for_defect) > 0){ - $table = new StdClass(); - $table->style[0] = 'color: #ffffff; background-color: #373737; font-weight: bolder; padding-right: 10px; min-width: 230px;'; - $table->width = '100%'; + echo " + "; + echo ""; - $head[0] = __('Groups'); - $headstyle[0] = "width: 20%; font-weight: bolder;"; - foreach ($array_module_group as $key => $value) { - $headstyle[] = "min-width: 60px;max-width: 5%;text-align:center; color: #ffffff; background-color: #373737; font-weight: bolder;"; - $head[] = ui_print_truncate_text($value, GENERIC_SIZE_TEXT, true, true, true, '…', 'color:#FFF'); - } + echo '
'; + echo __('Search by agent group').' '; + html_print_input_text('agent_group_search', $agent_group_search); - $i = 0; - foreach ($array_for_defect as $key => $value) { - $deep = groups_get_group_deep($key); - $data[$i][0] = $deep . ui_print_truncate_text($value['data']['name'], GENERIC_SIZE_TEXT, true, true, true, '…', 'color:#FFF'); - $j = 1; - if(isset($array_data[$key])){ - foreach ($value['gm'] as $k => $v) { - if(isset($array_data[$key][$k])){ - $send_tooltip = json_encode($array_data[$key][$k]); - $rel = "ajax.php?page=extensions/module_groups&get_info_alert_module_group=1&send_tooltip=" . $send_tooltip; - $url = "index.php?sec=estado&sec2=operation/agentes/status_monitor&status=-1&ag_group=" . $key . "&modulegroup=" . $k; + echo ''; + echo __('Search by module group').' '; + html_print_input_text('module_group_search', $module_group_search); - if ($array_data[$key][$k]['alerts_module_count'] != 0) { - $color = '#FFA631'; //Orange when the cell for this model group and agent has at least one alert fired. - } - else if ($array_data[$key][$k]['critical_module_count'] != 0) { - $color = '#FC4444'; //Red when the cell for this model group and agent has at least one module in critical state and the rest in any state. - } - elseif ($array_data[$key][$k]['warning_module_count'] != 0) { - $color = '#FAD403'; //Yellow when the cell for this model group and agent has at least one in warning state and the rest in green state. - } - elseif ($array_data[$key][$k]['unknown_module_count'] != 0) { - $color = '#B2B2B2 '; //Grey when the cell for this model group and agent has at least one module in unknown state and the rest in any state. - } - elseif ($array_data[$key][$k]['normal_module_count'] != 0) { - $color = '#80BA27'; //Green when the cell for this model group and agent has OK state all modules. - } - elseif ($array_data[$key][$k]['notInit_module_count'] != 0) { - $color = '#5BB6E5'; // Blue when the cell for this module group and all modules have not init value. - } + echo ''; + echo ""; + echo ''; + echo ''; + echo '
'; - $data[$i][$j] ="
"; - $data[$i][$j] .= ""; - $data[$i][$j] .= $array_data[$key][$k]['total_count']; - $data[$i][$j] .= "
"; - } - else{ - $data[$i][$j] ="
"; - $data[$i][$j] .= 0; - $data[$i][$j] .= "
"; - } - $j++; - } - } - else{ - foreach ($value['gm'] as $k => $v) { - $data[$i][$j] ="
"; - $data[$i][$j] .= 0; - $data[$i][$j] .= "
"; - $j++; - } - } - $i++; - } + if (true) { + $table = new StdClass(); + $table->style[0] = 'color: #ffffff; background-color: #373737; font-weight: bolder; padding-right: 10px; min-width: 230px;'; + $table->width = '100%'; - $table->head = $head; - $table->headstyle = $headstyle; - $table->data = $data; + $head[0] = __('Groups'); + $headstyle[0] = 'width: 20%; font-weight: bolder;'; + foreach ($array_module_group as $key => $value) { + $headstyle[] = 'min-width: 60px;max-width: 5%;text-align:center; color: #ffffff; background-color: #373737; font-weight: bolder;'; + $head[] = ui_print_truncate_text($value, GENERIC_SIZE_TEXT, true, true, true, '…', 'color:#FFF'); + } - ui_pagination($counter); + $i = 0; + foreach ($array_for_defect as $key => $value) { + $deep = groups_get_group_deep($key); + $data[$i][0] = $deep.ui_print_truncate_text($value['data']['name'], GENERIC_SIZE_TEXT, true, true, true, '…', 'color:#FFF'); + $j = 1; + if (isset($array_data[$key])) { + foreach ($value['gm'] as $k => $v) { + if (isset($array_data[$key][$k])) { + $send_tooltip = json_encode($array_data[$key][$k]); + $rel = 'ajax.php?page=extensions/module_groups&get_info_alert_module_group=1&send_tooltip='.$send_tooltip; + $url = 'index.php?sec=estado&sec2=operation/agentes/status_monitor&status=-1&ag_group='.$key.'&modulegroup='.$k; - echo "
"; - html_print_table($table); - echo "
"; + if ($array_data[$key][$k]['alerts_module_count'] != 0) { + $color = '#FFA631'; + // Orange when the cell for this model group and agent has at least one alert fired. + } else if ($array_data[$key][$k]['critical_module_count'] != 0) { + $color = '#FC4444'; + // Red when the cell for this model group and agent has at least one module in critical state and the rest in any state. + } else if ($array_data[$key][$k]['warning_module_count'] != 0) { + $color = '#FAD403'; + // Yellow when the cell for this model group and agent has at least one in warning state and the rest in green state. + } else if ($array_data[$key][$k]['unknown_module_count'] != 0) { + $color = '#B2B2B2 '; + // Grey when the cell for this model group and agent has at least one module in unknown state and the rest in any state. + } else if ($array_data[$key][$k]['normal_module_count'] != 0) { + $color = '#80BA27'; + // Green when the cell for this model group and agent has OK state all modules. + } else if ($array_data[$key][$k]['notInit_module_count'] != 0) { + $color = '#5BB6E5'; + // Blue when the cell for this module group and all modules have not init value. + } - ui_pagination($counter); + $data[$i][$j] = "
"; + $data[$i][$j] .= ""; + $data[$i][$j] .= $array_data[$key][$k]['total_count']; + $data[$i][$j] .= '
'; + } else { + $data[$i][$j] = "
"; + $data[$i][$j] .= 0; + $data[$i][$j] .= '
'; + } - echo "
"; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo "
" . __('Legend') . "
" . __("Orange cell when the module group and agent have at least one alarm fired.") . "
" . __("Red cell when the module group and agent have at least one module in critical status and the others in any status") . "
" . __("Yellow cell when the module group and agent have at least one in warning status and the others in grey or green status") . "
" . __("Grey cell when the module group and agent have at least one in unknown status and the others in green status") . "
" . __("Green cell when the module group and agent have all modules in OK status") . "
" .__("Blue cell when the module group and agent have all modules in not init status.") . "
"; - echo "
"; + $j++; + } + } else { + foreach ($value['gm'] as $k => $v) { + $data[$i][$j] = "
"; + $data[$i][$j] .= 0; + $data[$i][$j] .= '
'; + $j++; + } + } - } - else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __("This table shows in columns the modules group and in rows agents group. The cell shows all modules") )); - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined groups or module groups') )); - } + $i++; + } - ui_require_css_file('cluetip'); - ui_require_jquery_file('cluetip'); - ?> - - head = $head; + $table->headstyle = $headstyle; + $table->data = $data; + + ui_pagination($counter); + + echo "
"; + html_print_table($table); + echo '
'; + + ui_pagination($counter); + + echo "
"; + echo ''; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo '
".__('Legend').'
".__('Orange cell when the module group and agent have at least one alarm fired.').'
".__('Red cell when the module group and agent have at least one module in critical status and the others in any status').'
".__('Yellow cell when the module group and agent have at least one in warning status and the others in grey or green status').'
".__('Grey cell when the module group and agent have at least one in unknown status and the others in green status').'
".__('Green cell when the module group and agent have all modules in OK status').'
".__('Blue cell when the module group and agent have all modules in not init status.').'
'; + echo '
'; + } else { + ui_print_info_message(['no_close' => true, 'message' => __('This table shows in columns the modules group and in rows agents group. The cell shows all modules') ]); + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined groups or module groups') ]); + } + + ui_require_css_file('cluetip', 'include/styles/js/'); + ui_require_jquery_file('cluetip'); + ?> + + diff --git a/pandora_console/extensions/net_tools.php b/pandora_console/extensions/net_tools.php index a223f6aa96..e6ec05977b 100644 --- a/pandora_console/extensions/net_tools.php +++ b/pandora_console/extensions/net_tools.php @@ -4,99 +4,108 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -$id_agente = get_parameter ("id_agente"); +$id_agente = get_parameter('id_agente'); // This extension is usefull only if the agent has associated IP $address = agents_get_address($id_agente); if (!empty($address) || empty($id_agente)) { - extensions_add_opemode_tab_agent ('network_tools','Network Tools','extensions/net_tools/nettool.png',"main_net_tools", "v1r1", 'AW'); + extensions_add_opemode_tab_agent('network_tools', 'Network Tools', 'extensions/net_tools/nettool.png', 'main_net_tools', 'v1r1', 'AW'); } -function whereis_the_command ($command) { - global $config; - - if (isset($config['network_tools_config'])) { - $network_tools_config = json_decode($config['network_tools_config'], true); - $traceroute_path = $network_tools_config['traceroute_path']; - $ping_path = $network_tools_config['ping_path']; - $nmap_path = $network_tools_config['nmap_path']; - $dig_path = $network_tools_config['dig_path']; - $snmpget_path = $network_tools_config['snmpget_path']; - - switch ($command) { - case 'traceroute': - if (!empty($traceroute_path)) - return $traceroute_path; - break; - case 'ping': - if (!empty($ping_path)) - return $ping_path; - break; - case 'nmap': - if (!empty($nmap_path)) - return $nmap_path; - break; - case 'dig': - if (!empty($dig_path)) - return $dig_path; - break; - case 'snmpget': - if (!empty($snmpget_path)) - return $snmpget_path; - break; - } - } - - - - ob_start(); - system('whereis '. $command); - $output = ob_get_clean(); - $result = explode(':', $output); - $result = trim($result[1]); - - if ( empty($result)) { - return NULL; - } - - $result = explode(' ', $result); - $fullpath = trim($result[0]); - - if (! file_exists($fullpath)) { - return NULL; - } - - return $fullpath; + +function whereis_the_command($command) +{ + global $config; + + if (isset($config['network_tools_config'])) { + $network_tools_config = json_decode($config['network_tools_config'], true); + $traceroute_path = $network_tools_config['traceroute_path']; + $ping_path = $network_tools_config['ping_path']; + $nmap_path = $network_tools_config['nmap_path']; + $dig_path = $network_tools_config['dig_path']; + $snmpget_path = $network_tools_config['snmpget_path']; + + switch ($command) { + case 'traceroute': + if (!empty($traceroute_path)) { + return $traceroute_path; + } + break; + + case 'ping': + if (!empty($ping_path)) { + return $ping_path; + } + break; + + case 'nmap': + if (!empty($nmap_path)) { + return $nmap_path; + } + break; + + case 'dig': + if (!empty($dig_path)) { + return $dig_path; + } + break; + + case 'snmpget': + if (!empty($snmpget_path)) { + return $snmpget_path; + } + break; + } + } + + ob_start(); + system('whereis '.$command); + $output = ob_get_clean(); + $result = explode(':', $output); + $result = trim($result[1]); + + if (empty($result)) { + return null; + } + + $result = explode(' ', $result); + $fullpath = trim($result[0]); + + if (! file_exists($fullpath)) { + return null; + } + + return $fullpath; } -function main_net_tools () { - - $id_agente = get_parameter ("id_agente"); - $principal_ip = db_get_sql ("SELECT direccion FROM tagente WHERE id_agente = $id_agente"); - - $list_address = db_get_all_rows_sql ("select id_a from taddress_agent where id_agent = " . $id_agente); - foreach ($list_address as $address) { - $ids []= join(",",$address); - } - $ids_address = implode(",",$ids); - $ips = db_get_all_rows_sql ("select ip from taddress where id_a in (" . $ids_address . ")"); - - if ($ips == "") { - echo "
" . __('The agent hasn\'t got IP') . "
"; - return; - } - echo " + +function main_net_tools() +{ + $id_agente = get_parameter('id_agente'); + $principal_ip = db_get_sql("SELECT direccion FROM tagente WHERE id_agente = $id_agente"); + + $list_address = db_get_all_rows_sql('select id_a from taddress_agent where id_agent = '.$id_agente); + foreach ($list_address as $address) { + $ids[] = join(',', $address); + } + + $ids_address = implode(',', $ids); + $ips = db_get_all_rows_sql('select ip from taddress where id_a in ('.$ids_address.')'); + + if ($ips == '') { + echo "
".__('The agent hasn\'t got IP').'
'; + return; + } + + echo " "; - - echo "
"; - echo "
"; - echo ""; - echo ""; - echo ""; - echo ""; - echo "
"; - echo __("Operation"); - ui_print_help_tip( - __('You can set the command path in the menu Administration -> Extensions -> Config Network Tools')); - echo ""; - echo ""; - echo ""; - echo __("IP address"); - echo ""; - echo ""; - echo ""; - echo __("SNMP Community") . " "; - echo ""; - echo ""; - echo ""; - echo "
"; - echo "
"; - - - $operation = get_parameter ("operation", 0); - $community = get_parameter ("community", "public"); - $ip = get_parameter("select_ips"); - if(!validate_address($ip)){ - ui_print_error_message(__('The ip or dns name entered cannot be resolved')); - } - else{ - switch($operation) { - case 1: - $traceroute = whereis_the_command ('traceroute'); - if (empty($traceroute)) { - ui_print_error_message(__('Traceroute executable does not exist.')); - } - else { - echo "

".__("Traceroute to "). $ip. "

"; - echo "
";
-					echo system ("$traceroute $ip");
-					echo "
"; - } - break; - case 2: - $ping = whereis_the_command ('ping'); - if (empty($ping)) { - ui_print_error_message(__('Ping executable does not exist.')); - } - else { - echo "

" . __("Ping to %s", $ip) . "

"; - echo "
";
-					echo system ("$ping -c 5 $ip");
-					echo "
"; - } - break; - case 4: - $nmap = whereis_the_command ('nmap'); - if (empty($nmap)) { - ui_print_error_message(__('Nmap executable does not exist.')); - } - else { - echo "

".__("Basic TCP Scan on "). $ip. "

"; - echo "
";
-					echo system ("$nmap -F $ip");
-					echo "
"; - } - break; - case 5: - echo "

".__("Domain and IP information for "). $ip. "

"; - - $dig = whereis_the_command ('dig'); - if (empty($dig)) { - ui_print_error_message(__('Dig executable does not exist.')); - } - else { - echo "
";
-					echo system ("dig $ip");
-					echo "
"; - } - - $whois = whereis_the_command ('whois'); - if (empty($whois)) { - ui_print_error_message(__('Whois executable does not exist.')); - } - else { - echo "
";
-					echo system ("whois $ip");
-					echo "
"; - } - break; - case 3: - echo "

".__("SNMP information for "). $ip. "

"; - - $snmpget = whereis_the_command ('snmpget'); - if (empty($snmpget)) { - ui_print_error_message(__('SNMPget executable does not exist.')); - } - else { - echo "

" . __("Uptime") . "

"; - echo "
";
-					echo exec ("$snmpget -Ounv -v1 -c $community $ip .1.3.6.1.2.1.1.3.0 ");
-					echo "
"; - echo "

" . __("Device info") . "

"; - echo "
";
-					
-					echo system ("$snmpget -Ounv -v1 -c $community $ip .1.3.6.1.2.1.1.1.0 ");
-					echo "
"; - - echo "

Interface Information

"; - echo ""; - echo "
".__("Interface"); - echo "".__("Status"); - - $int_max = exec ("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.1.0 "); - - for ($ax=0; $ax < $int_max; $ax++) { - $interface = exec ("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.2.1.2.$ax "); - $estado = exec ("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.2.1.8.$ax "); - echo "
$interface$estado"; - } - echo "
"; - } - break; - } - } - - echo "
"; + echo '
'; + echo "
"; + echo ""; + echo ''; + echo ''; + echo "'; + echo '
'; + echo __('Operation'); + ui_print_help_tip( + __('You can set the command path in the menu Administration -> Extensions -> Config Network Tools') + ); + echo ''; + echo "'; + echo ''; + echo __('IP address'); + echo ''; + echo "'; + echo '"; + echo __('SNMP Community').' '; + echo ""; + echo ''; + echo ""; + echo '
'; + echo '
'; + + $operation = get_parameter('operation', 0); + $community = get_parameter('community', 'public'); + $ip = get_parameter('select_ips'); + + if (!validate_address($ip)) { + ui_print_error_message(__('The ip or dns name entered cannot be resolved')); + } else { + switch ($operation) { + case 1: + $traceroute = whereis_the_command('traceroute'); + if (empty($traceroute)) { + ui_print_error_message(__('Traceroute executable does not exist.')); + } else { + echo '

'.__('Traceroute to ').$ip.'

'; + echo '
';
+                    echo system("$traceroute $ip");
+                    echo '
'; + } + break; + + case 2: + $ping = whereis_the_command('ping'); + if (empty($ping)) { + ui_print_error_message(__('Ping executable does not exist.')); + } else { + echo '

'.__('Ping to %s', $ip).'

'; + echo '
';
+                    echo system("$ping -c 5 $ip");
+                    echo '
'; + } + break; + + case 4: + $nmap = whereis_the_command('nmap'); + if (empty($nmap)) { + ui_print_error_message(__('Nmap executable does not exist.')); + } else { + echo '

'.__('Basic TCP Scan on ').$ip.'

'; + echo '
';
+                    echo system("$nmap -F $ip");
+                    echo '
'; + } + break; + + case 5: + echo '

'.__('Domain and IP information for ').$ip.'

'; + + $dig = whereis_the_command('dig'); + if (empty($dig)) { + ui_print_error_message(__('Dig executable does not exist.')); + } else { + echo '
';
+                    echo system("dig $ip");
+                    echo '
'; + } + + $whois = whereis_the_command('whois'); + if (empty($whois)) { + ui_print_error_message(__('Whois executable does not exist.')); + } else { + echo '
';
+                    echo system("whois $ip");
+                    echo '
'; + } + break; + + case 3: + echo '

'.__('SNMP information for ').$ip.'

'; + + $snmpget = whereis_the_command('snmpget'); + if (empty($snmpget)) { + ui_print_error_message(__('SNMPget executable does not exist.')); + } else { + echo '

'.__('Uptime').'

'; + echo '
';
+                    echo exec("$snmpget -Ounv -v1 -c $community $ip .1.3.6.1.2.1.1.3.0 ");
+                    echo '
'; + echo '

'.__('Device info').'

'; + echo '
';
+
+                    echo system("$snmpget -Ounv -v1 -c $community $ip .1.3.6.1.2.1.1.1.0 ");
+                    echo '
'; + + echo '

Interface Information

'; + echo ''; + echo '
'.__('Interface'); + echo ''.__('Status'); + + $int_max = exec("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.1.0 "); + + for ($ax = 0; $ax < $int_max; $ax++) { + $interface = exec("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.2.1.2.$ax "); + $estado = exec("$snmpget -Oqunv -v1 -c $community $ip .1.3.6.1.2.1.2.2.1.8.$ax "); + echo "
$interface$estado"; + } + + echo '
'; + } + break; + } + } + + echo '
'; } -function godmode_net_tools() { - global $config; - - check_login(); - - if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Profile Management"); - require ("general/noaccess.php"); - return; - } - - ui_print_page_header (__('Config Network Tools')); - - $update_traceroute = (bool)get_parameter('update_traceroute', 0); - - $traceroute_path = (string)get_parameter('traceroute_path', ''); - $ping_path = (string)get_parameter('ping_path', ''); - $nmap_path = (string)get_parameter('nmap_path', ''); - $dig_path = (string)get_parameter('dig_path', ''); - $snmpget_path = (string)get_parameter('snmpget_path', ''); - - - if ($update_traceroute) { - $network_tools_config = array(); - $network_tools_config['traceroute_path'] = $traceroute_path; - $network_tools_config['ping_path'] = $ping_path; - $network_tools_config['nmap_path'] = $nmap_path; - $network_tools_config['dig_path'] = $dig_path; - $network_tools_config['snmpget_path'] = $snmpget_path; - - $result = config_update_value('network_tools_config', json_encode($network_tools_config)); - - ui_print_result_message($result, __('Set the paths.'), - __('Set the paths.')); - } - else { - - if (isset($config['network_tools_config'])) { - $network_tools_config_output = io_safe_output($config['network_tools_config']); - $network_tools_config = json_decode($network_tools_config_output, true); - $traceroute_path = $network_tools_config['traceroute_path']; - $ping_path = $network_tools_config['ping_path']; - $nmap_path = $network_tools_config['nmap_path']; - $dig_path = $network_tools_config['dig_path']; - $snmpget_path = $network_tools_config['snmpget_path']; - } - } - - $table = null; - $table->width = "100%"; - - $table->data = array(); - - $table->data[0][0] = __("Traceroute path"); - $table->data[0][0] .= ui_print_help_tip(__('If empty, %s will search the traceroute system.', get_product_name()), true); - $table->data[0][1] = html_print_input_text('traceroute_path', $traceroute_path, '', 40, 255, true); - - $table->data[1][0] = __("Ping path"); - $table->data[1][0] .= ui_print_help_tip(__('If empty, %s will search the ping system.', get_product_name()), true); - $table->data[1][1] = html_print_input_text('ping_path', $ping_path, '', 40, 255, true); - - $table->data[2][0] = __("Nmap path"); - $table->data[2][0] .= ui_print_help_tip(__('If empty, %s will search the nmap system.', get_product_name()), true); - $table->data[2][1] = html_print_input_text('nmap_path', $nmap_path, '', 40, 255, true); - - $table->data[3][0] = __("Dig path"); - $table->data[3][0] .= ui_print_help_tip(__('If empty, %s will search the dig system', get_product_name()), true); - $table->data[3][1] = html_print_input_text('dig_path', $dig_path, '', 40, 255, true); - - $table->data[4][0] = __("Snmpget path"); - $table->data[4][0] .= ui_print_help_tip(__('If empty, %s will search the snmpget system.', get_product_name()), true); - $table->data[4][1] = html_print_input_text('snmpget_path', $snmpget_path, '', 40, 255, true); - - echo '
'; - echo "
"; - echo "" . __('Options') . ""; - html_print_input_hidden('update_traceroute', 1); - html_print_table($table); - echo "
"; - - echo '
'; - html_print_submit_button (__('Update'), 'update_button', false, 'class="sub upd"'); - echo '
'; - echo '
'; + +function godmode_net_tools() +{ + global $config; + + check_login(); + + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Profile Management' + ); + include 'general/noaccess.php'; + return; + } + + ui_print_page_header(__('Config Network Tools')); + + $update_traceroute = (bool) get_parameter('update_traceroute', 0); + + $traceroute_path = (string) get_parameter('traceroute_path', ''); + $ping_path = (string) get_parameter('ping_path', ''); + $nmap_path = (string) get_parameter('nmap_path', ''); + $dig_path = (string) get_parameter('dig_path', ''); + $snmpget_path = (string) get_parameter('snmpget_path', ''); + + if ($update_traceroute) { + $network_tools_config = []; + $network_tools_config['traceroute_path'] = $traceroute_path; + $network_tools_config['ping_path'] = $ping_path; + $network_tools_config['nmap_path'] = $nmap_path; + $network_tools_config['dig_path'] = $dig_path; + $network_tools_config['snmpget_path'] = $snmpget_path; + + $result = config_update_value('network_tools_config', json_encode($network_tools_config)); + + ui_print_result_message( + $result, + __('Set the paths.'), + __('Set the paths.') + ); + } else { + if (isset($config['network_tools_config'])) { + $network_tools_config_output = io_safe_output($config['network_tools_config']); + $network_tools_config = json_decode($network_tools_config_output, true); + $traceroute_path = $network_tools_config['traceroute_path']; + $ping_path = $network_tools_config['ping_path']; + $nmap_path = $network_tools_config['nmap_path']; + $dig_path = $network_tools_config['dig_path']; + $snmpget_path = $network_tools_config['snmpget_path']; + } + } + + $table = null; + $table->width = '100%'; + + $table->data = []; + + $table->data[0][0] = __('Traceroute path'); + $table->data[0][0] .= ui_print_help_tip(__('If empty, %s will search the traceroute system.', get_product_name()), true); + $table->data[0][1] = html_print_input_text('traceroute_path', $traceroute_path, '', 40, 255, true); + + $table->data[1][0] = __('Ping path'); + $table->data[1][0] .= ui_print_help_tip(__('If empty, %s will search the ping system.', get_product_name()), true); + $table->data[1][1] = html_print_input_text('ping_path', $ping_path, '', 40, 255, true); + + $table->data[2][0] = __('Nmap path'); + $table->data[2][0] .= ui_print_help_tip(__('If empty, %s will search the nmap system.', get_product_name()), true); + $table->data[2][1] = html_print_input_text('nmap_path', $nmap_path, '', 40, 255, true); + + $table->data[3][0] = __('Dig path'); + $table->data[3][0] .= ui_print_help_tip(__('If empty, %s will search the dig system', get_product_name()), true); + $table->data[3][1] = html_print_input_text('dig_path', $dig_path, '', 40, 255, true); + + $table->data[4][0] = __('Snmpget path'); + $table->data[4][0] .= ui_print_help_tip(__('If empty, %s will search the snmpget system.', get_product_name()), true); + $table->data[4][1] = html_print_input_text('snmpget_path', $snmpget_path, '', 40, 255, true); + + echo '
'; + echo '
'; + echo ''.__('Options').''; + html_print_input_hidden('update_traceroute', 1); + html_print_table($table); + echo '
'; + + echo '
'; + html_print_submit_button(__('Update'), 'update_button', false, 'class="sub upd"'); + echo '
'; + echo '
'; } -extensions_add_godmode_menu_option (__('Config Network Tools'), 'PM'); -extensions_add_godmode_function ('godmode_net_tools'); -?> + +extensions_add_godmode_menu_option(__('Config Network Tools'), 'PM'); +extensions_add_godmode_function('godmode_net_tools'); diff --git a/pandora_console/extensions/pandora_logs.php b/pandora_console/extensions/pandora_logs.php index 71cf847fa5..bd8b1cfda7 100644 --- a/pandora_console/extensions/pandora_logs.php +++ b/pandora_console/extensions/pandora_logs.php @@ -4,83 +4,76 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function view_logfile($file_name) +{ + global $config; -function view_logfile ($file_name) { - global $config; - - $memory_limit = ini_get("memory_limit"); - - if (strstr($memory_limit, "M") !== false) { - $memory_limit = str_replace("M", "", $memory_limit); - $memory_limit = $memory_limit * 1024 * 1024; - - //Arbitrary size for the PHP program - $memory_limit = $memory_limit - (8 * 1024 * 1024); - } - - - - if (!file_exists($file_name)) { - ui_print_error_message(__("Cannot find file") . "(" . $file_name . ")"); - } - else { - $file_size = filesize($file_name); - - if ($memory_limit < $file_size) { - echo "

$file_name (" . __("File is too large than PHP memory allocated in the system.") . ")

"; - echo "

" . __("The preview file is imposible.") . "

"; - } - else if ($file_size > ($config['max_log_size'] * 1000)) { - $data = file_get_contents ($file_name, false, NULL, $file_size - ($config['max_log_size'] * 1000)); - echo "

$file_name (".format_numeric(filesize ($file_name)/1024)." KB)

"; - echo "

"; - } - else { - $data = file_get_contents ($file_name); - echo "

$file_name (".format_numeric(filesize ($file_name)/1024)." KB)

"; - echo "

"; - } - } + $memory_limit = ini_get('memory_limit'); + + if (strstr($memory_limit, 'M') !== false) { + $memory_limit = str_replace('M', '', $memory_limit); + $memory_limit = ($memory_limit * 1024 * 1024); + + // Arbitrary size for the PHP program + $memory_limit = ($memory_limit - (8 * 1024 * 1024)); + } + + if (!file_exists($file_name)) { + ui_print_error_message(__('Cannot find file').'('.$file_name.')'); + } else { + $file_size = filesize($file_name); + + if ($memory_limit < $file_size) { + echo "

$file_name (".__('File is too large than PHP memory allocated in the system.').')

'; + echo '

'.__('The preview file is imposible.').'

'; + } else if ($file_size > ($config['max_log_size'] * 1000)) { + $data = file_get_contents($file_name, false, null, ($file_size - ($config['max_log_size'] * 1000))); + echo "

$file_name (".format_numeric(filesize($file_name) / 1024).' KB)

'; + echo "

'; + } else { + $data = file_get_contents($file_name); + echo "

$file_name (".format_numeric(filesize($file_name) / 1024).' KB)

'; + echo "

'; + } + } } -function pandoralogs_extension_main () { - global $config; - - if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; - } - - ui_print_page_header (__("System logfile viewer"), "images/extensions.png", false, "", true, "" ); - - echo "

" . __('Use this tool to view your %s logfiles directly on the console', get_product_name()) . "

"; +function pandoralogs_extension_main() +{ + global $config; - echo "

" . __('You can choose the amount of information shown in general setup (Log size limit in system logs viewer extension), ' . $config['max_log_size'] * 1000 . 'B at the moment') . "

"; - - $logs_directory = (!empty($config["server_log_dir"])) ? io_safe_output($config["server_log_dir"]) : "/var/log/pandora"; + if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; + } - view_logfile ($config["homedir"]."/pandora_console.log"); - view_logfile ($logs_directory."/pandora_server.log"); - view_logfile ($logs_directory."/pandora_server.error"); + ui_print_page_header(__('System logfile viewer'), 'images/extensions.png', false, '', true, ''); + + echo '

'.__('Use this tool to view your %s logfiles directly on the console', get_product_name()).'

'; + + echo '

'.__('You can choose the amount of information shown in general setup (Log size limit in system logs viewer extension), '.($config['max_log_size'] * 1000).'B at the moment').'

'; + + $logs_directory = (!empty($config['server_log_dir'])) ? io_safe_output($config['server_log_dir']) : '/var/log/pandora'; + + view_logfile($config['homedir'].'/pandora_console.log'); + view_logfile($logs_directory.'/pandora_server.log'); + view_logfile($logs_directory.'/pandora_server.error'); } -extensions_add_godmode_menu_option (__('System logfiles'), 'PM','', null, "v1r1"); + +extensions_add_godmode_menu_option(__('System logfiles'), 'PM', '', null, 'v1r1'); extensions_add_godmode_function('pandoralogs_extension_main'); - -?> \ No newline at end of file diff --git a/pandora_console/extensions/plugin_registration.php b/pandora_console/extensions/plugin_registration.php index 3efa7ff183..ef08e34bae 100644 --- a/pandora_console/extensions/plugin_registration.php +++ b/pandora_console/extensions/plugin_registration.php @@ -4,434 +4,415 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function pluginreg_extension_main() +{ + global $config; -function pluginreg_extension_main () { - global $config; + check_login(); - check_login(); - - if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; - } - ui_require_css_file ('firts_task'); - ui_print_page_header (__('Plugin registration'), "images/extensions.png", false, "", true, "" ); - - echo '
+ if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; + } + + ui_require_css_file('firts_task'); + ui_print_page_header(__('Plugin registration'), 'images/extensions.png', false, '', true, ''); + + echo '
'; - echo html_print_image("images/firts_task/icono_grande_import.png", true, array("title" => __("Plugin Registration") )); - echo '
'; - echo '
'; - echo '

' . __("Plugin registration") . '

'; - echo '

' . - __("This extension makes registering server plugins an easier task. + echo html_print_image('images/firts_task/icono_grande_import.png', true, ['title' => __('Plugin Registration') ]); + echo '

'; + echo '
'; + echo '

'.__('Plugin registration').'

'; + echo '

'.__( + "This extension makes registering server plugins an easier task. Here you can upload a server plugin in .pspz zipped format. Please refer to the official documentation on how to obtain and use Server Plugins. -

You can get more plugins in our Public Resource Library ") . '

'; - // Upload form - echo "
"; - echo ''; - echo "
"; - echo ""; - echo "
"; - echo '
'; - echo '
'; +

You can get more plugins in our Public Resource Library " + ).'

'; + // Upload form + echo "
"; + echo ''; + echo "
"; + echo ""; + echo '
'; + echo '
'; + echo ''; - - $zip = null; - $upload = false; - if (isset($_FILES['plugin_upload'])) { - $config["plugin_store"] = $config["attachment_store"] . "/plugin"; - - $name_file = $_FILES['plugin_upload']['name']; - - $zip = zip_open($_FILES['plugin_upload']['tmp_name']); - $upload = true; - } - - if ($zip) { - while ($zip_entry = zip_read($zip)) { - if (zip_entry_open($zip, $zip_entry, "r")) { - if (zip_entry_name($zip_entry) == "plugin_definition.ini") { - $basepath = $config["attachment_store"]; - } - else { - $basepath = $config["plugin_store"]; - } - $filename = $basepath . "/". zip_entry_name($zip_entry); - $fp = fopen($filename, 'w'); - $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); - fwrite($fp, $buf); - fclose($fp); - chmod ($filename, 0755); - zip_entry_close($zip_entry); - } - } - zip_close($zip); - } - - if ($upload) { - // Parse with sections - if (! $ini_array = parse_ini_file($config["attachment_store"] . "/plugin_definition.ini", true)) { - echo "

".__("Cannot load INI file")."

"; - } - else { - - $version = preg_replace("/.*[.]/", "", $name_file); - - $exec_path = $config["plugin_store"] . "/" . $ini_array["plugin_definition"]["filename"]; - - $file_exec_path = $exec_path; - - if (isset($ini_array["plugin_definition"]["execution_command"]) - && ($ini_array["plugin_definition"]["execution_command"] != "")) { - - $exec_path = $ini_array["plugin_definition"]["execution_command"] . " " . $config["plugin_store"] . "/" . $ini_array["plugin_definition"]["filename"]; - } - - if (isset($ini_array["plugin_definition"]["execution_postcommand"]) - && ($ini_array["plugin_definition"]["execution_postcommand"] != "")) { - - $exec_path = $exec_path . " " .$ini_array["plugin_definition"]["execution_postcommand"]; - } - - if (!file_exists($file_exec_path)) { - echo "

".__("Plugin exec not found. Aborting!")."

"; - unlink ($config["attachment_store"] . "/plugin_definition.ini"); - } - else { - // Verify if a plugin with the same name is already registered - - $sql0 = "SELECT COUNT(*) + $zip = null; + $upload = false; + if (isset($_FILES['plugin_upload'])) { + $config['plugin_store'] = $config['attachment_store'].'/plugin'; + + $name_file = $_FILES['plugin_upload']['name']; + + $zip = zip_open($_FILES['plugin_upload']['tmp_name']); + $upload = true; + } + + if ($zip) { + while ($zip_entry = zip_read($zip)) { + if (zip_entry_open($zip, $zip_entry, 'r')) { + if (zip_entry_name($zip_entry) == 'plugin_definition.ini') { + $basepath = $config['attachment_store']; + } else { + $basepath = $config['plugin_store']; + } + + $filename = $basepath.'/'.zip_entry_name($zip_entry); + $fp = fopen($filename, 'w'); + $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); + fwrite($fp, $buf); + fclose($fp); + chmod($filename, 0755); + zip_entry_close($zip_entry); + } + } + + zip_close($zip); + } + + if ($upload) { + // Parse with sections + if (! $ini_array = parse_ini_file($config['attachment_store'].'/plugin_definition.ini', true)) { + echo '

'.__('Cannot load INI file').'

'; + } else { + $version = preg_replace('/.*[.]/', '', $name_file); + + $exec_path = $config['plugin_store'].'/'.$ini_array['plugin_definition']['filename']; + + $file_exec_path = $exec_path; + + if (isset($ini_array['plugin_definition']['execution_command']) + && ($ini_array['plugin_definition']['execution_command'] != '') + ) { + $exec_path = $ini_array['plugin_definition']['execution_command'].' '.$config['plugin_store'].'/'.$ini_array['plugin_definition']['filename']; + } + + if (isset($ini_array['plugin_definition']['execution_postcommand']) + && ($ini_array['plugin_definition']['execution_postcommand'] != '') + ) { + $exec_path = $exec_path.' '.$ini_array['plugin_definition']['execution_postcommand']; + } + + if (!file_exists($file_exec_path)) { + echo '

'.__('Plugin exec not found. Aborting!').'

'; + unlink($config['attachment_store'].'/plugin_definition.ini'); + } else { + // Verify if a plugin with the same name is already registered + $sql0 = "SELECT COUNT(*) FROM tplugin - WHERE name = '" . io_safe_input ($ini_array["plugin_definition"]["name"]) . "'"; - $result = db_get_sql ($sql0); - - - if ($result> 0) { - echo "

".__("Plugin already registered. Aborting!")."

"; - unlink ($config["attachment_store"] . "/plugin_definition.ini"); - } - else { - - $values = array( - 'name' => io_safe_input ($ini_array["plugin_definition"]["name"]), - 'description' => io_safe_input ($ini_array["plugin_definition"]["description"]), - 'max_timeout' => $ini_array["plugin_definition"]["timeout"], - 'execute' => io_safe_input ($exec_path), - 'net_dst_opt' => $ini_array["plugin_definition"]["ip_opt"], - 'net_port_opt' => $ini_array["plugin_definition"]["port_opt"], - 'user_opt' => $ini_array["plugin_definition"]["user_opt"], - 'pass_opt' => $ini_array["plugin_definition"]["pass_opt"], - 'parameters' => $ini_array["plugin_definition"]["parameters"], - 'plugin_type' => $ini_array["plugin_definition"]["plugin_type"]); - - - switch ($version) { - case 'pspz': - // Fixed the static parameters - // for - // the dinamic parameters of pandoras 5 - - $total_macros = 0; - $macros = array(); - - if (!isset($values['parameters'])) - $values['parameters'] = ""; - - if ($values['net_dst_opt'] != "") { - $total_macros++; - - $macro = array(); - $macro['macro'] = '_field' . $total_macros . '_'; - $macro['desc'] = 'Target IP from net'; - $macro['help'] = ''; - $macro['value'] = ''; - - $values['parameters'] .= - $values['net_dst_opt'] . ' _field' . $total_macros . '_ '; - - $macros[(string)$total_macros] = $macro; - } - - if ($values['ip_opt'] != "") { - $total_macros++; - - $macro = array(); - $macro['macro'] = '_field' . $total_macros . '_'; - $macro['desc'] = 'Target IP'; - $macro['help'] = ''; - $macro['value'] = ''; - - $values['parameters'] .= - $values['ip_opt'] . ' _field' . $total_macros . '_ '; - - $macros[(string)$total_macros] = $macro; - } - - if ($values['net_port_opt'] != "") { - $total_macros++; - - $macro = array(); - $macro['macro'] = '_field' . $total_macros . '_'; - $macro['desc'] = 'Port from net'; - $macro['help'] = ''; - $macro['value'] = ''; - - $values['parameters'] .= - $values['net_port_opt'] . ' _field' . $total_macros . '_ '; - - $macros[(string)$total_macros] = $macro; - } - - if ($values['port_opt'] != "") { - $total_macros++; - - $macro = array(); - $macro['macro'] = '_field' . $total_macros . '_'; - $macro['desc'] = 'Port'; - $macro['help'] = ''; - $macro['value'] = ''; - - $values['parameters'] .= - $values['port_opt'] . ' _field' . $total_macros . '_ '; - - $macros[(string)$total_macros] = $macro; - } - - if ($values['user_opt'] != "") { - $total_macros++; - - $macro = array(); - $macro['macro'] = '_field' . $total_macros . '_'; - $macro['desc'] = 'Username'; - $macro['help'] = ''; - $macro['value'] = ''; - - $values['parameters'] .= - $values['user_opt'] . ' _field' . $total_macros . '_ '; - - $macros[(string)$total_macros] = $macro; - } - - if ($values['pass_opt'] != "") { - $total_macros++; - - $macro = array(); - $macro['macro'] = '_field' . $total_macros . '_'; - $macro['desc'] = 'Password'; - $macro['help'] = ''; - $macro['value'] = ''; - - $values['parameters'] .= - $values['pass_opt'] . ' _field' . $total_macros . '_ '; - - $macros[(string)$total_macros] = $macro; - } - - // A last parameter is defined always to - // add the old "Plug-in parameters" in the - // side of the module - $total_macros++; - - $macro = array(); - $macro['macro'] = '_field' . $total_macros . '_'; - $macro['desc'] = 'Plug-in Parameters'; - $macro['help'] = ''; - $macro['value'] = ''; - - $values['parameters'] .= - ' _field' . $total_macros . '_'; - - $macros[(string)$total_macros] = $macro; - - break; - case 'pspz2': - // Fill the macros field. - $total_macros = - $ini_array["plugin_definition"]["total_macros_provided"]; - - $macros = array(); - for ($it_macros = 1; $it_macros <= $total_macros; $it_macros++) { - $label = "macro_" . $it_macros; - - $macro = array(); - - $macro['macro'] = '_field' . $it_macros . '_'; - $macro['hide'] = - $ini_array[$label]['hide']; - $macro['desc'] = io_safe_input( - $ini_array[$label]['description']); - $macro['help'] = io_safe_input( - $ini_array[$label]['help']); - $macro['value'] = io_safe_input( - $ini_array[$label]['value']); - - $macros[(string)$it_macros] = $macro; - } - break; - } - - if (!empty($macros)) { - $values['macros'] = json_encode($macros); - } - - $create_id = db_process_sql_insert('tplugin', $values); - - if (empty($create_id)) { - ui_print_error_message( - __('Plug-in Remote Registered unsuccessfull')); - ui_print_info_message( - __('Please check the syntax of file "plugin_definition.ini"')); - } - else { - for ($ax = 1; $ax <= $ini_array["plugin_definition"]["total_modules_provided"]; $ax++) { - $label = "module" . $ax; - - $plugin_user = ""; - if (isset($ini_array[$label]["plugin_user"])) - $plugin_user = $ini_array[$label]["plugin_user"]; - $plugin_pass = ""; - if (isset($ini_array[$label]["plugin_pass"])) - $plugin_pass = $ini_array[$label]["plugin_pass"]; - $plugin_parameter = ""; - if (isset($ini_array[$label]["plugin_parameter"])) - $plugin_parameter = $ini_array[$label]["plugin_parameter"]; - $unit = ""; - if (isset($ini_array[$label]["unit"])) - $unit = $ini_array[$label]["unit"]; - - $values = array( - 'name' => io_safe_input ($ini_array[$label]["name"]), - 'description' => io_safe_input ($ini_array[$label]["description"]), - 'id_group' => $ini_array[$label]["id_group"], - 'type' => $ini_array[$label]["type"], - 'max' => isset($ini_array[$label]["max"]) ? $ini_array[$label]["max"] : '', - 'min' => isset($ini_array[$label]["min"]) ? $ini_array[$label]["min"] : '', - 'module_interval' => isset($ini_array[$label]["module_interval"]) ? $ini_array[$label]["module_interval"] : '', - 'id_module_group' => $ini_array[$label]["id_module_group"], - 'id_modulo' => $ini_array[$label]["id_modulo"], - 'plugin_user' => io_safe_input ($plugin_user), - 'plugin_pass' => io_safe_input ($plugin_pass), - 'plugin_parameter' => io_safe_input ($plugin_parameter), - 'unit' => io_safe_input ($unit), - 'max_timeout' => isset($ini_array[$label]["max_timeout"]) ? $ini_array[$label]["max_timeout"] : '', - 'history_data' => isset($ini_array[$label]["history_data"]) ? $ini_array[$label]["history_data"] : '', - 'dynamic_interval' => isset($ini_array[$label]["dynamic_interval"]) ? $ini_array[$label]["dynamic_interval"] : '', - 'dynamic_min' => isset($ini_array[$label]["dynamic_min"]) ? $ini_array[$label]["dynamic_min"] : '', - 'dynamic_max' => isset($ini_array[$label]["dynamic_max"]) ? $ini_array[$label]["dynamic_max"] : '', - 'dynamic_two_tailed' => isset($ini_array[$label]["dynamic_two_tailed"]) ? $ini_array[$label]["dynamic_two_tailed"] : '', - 'min_warning' => isset($ini_array[$label]["min_warning"]) ? $ini_array[$label]["min_warning"] : '', - 'max_warning' => isset($ini_array[$label]["max_warning"]) ? $ini_array[$label]["max_warning"] : '', - 'str_warning' => isset($ini_array[$label]["str_warning"]) ? $ini_array[$label]["str_warning"] : '', - 'min_critical' => isset($ini_array[$label]["min_critical"]) ? $ini_array[$label]["min_critical"] : '', - 'max_critical' => isset($ini_array[$label]["max_critical"]) ? $ini_array[$label]["max_critical"] : '', - 'str_critical' => isset($ini_array[$label]["str_critical"]) ? $ini_array[$label]["str_critical"] : '', - 'min_ff_event' => isset($ini_array[$label]["min_ff_event"]) ? $ini_array[$label]["min_ff_event"] : '', - 'tcp_port' => isset($ini_array[$label]["tcp_port"]) ? $ini_array[$label]["tcp_port"] : '', - 'id_plugin' => $create_id); - - $macros_component = $macros; - - switch ($version) { - case 'pspz': - // Fixed the static parameters - // for - // the dinamic parameters of pandoras 5 - - foreach ($macros_component as $key => $macro) { - if ($macro['desc'] == 'Target IP from net') { - if (!empty($values['ip_target'])) { - $macros_component[$key]['value'] = - io_safe_input($values['ip_target']); - } - } - if ($macro['desc'] == 'Target IP') { - if (!empty($values['ip_target'])) { - $macros_component[$key]['value'] = - io_safe_input($values['ip_target']); - } - } - else if ($macro['desc'] == 'Port from net') { - if (!empty($values['tcp_port'])) { - $macros_component[$key]['value'] = - io_safe_input($values['tcp_port']); - } - } - else if ($macro['desc'] == 'Port') { - if (!empty($values['tcp_port'])) { - $macros_component[$key]['value'] = - io_safe_input($values['tcp_port']); - } - } - else if ($macro['desc'] == 'Username') { - if (!empty($values['plugin_user'])) { - $macros_component[$key]['value'] = - io_safe_input($values['plugin_user']); - } - } - else if ($macro['desc'] == 'Password') { - if (!empty($values['plugin_pass'])) { - $macros_component[$key]['value'] = - io_safe_input($values['plugin_pass']); - } - } - else if ($macro['desc'] == 'Plug-in Parameters') { - if (!empty($values['plugin_parameter'])) { - $macros_component[$key]['value'] = - io_safe_input($values['plugin_parameter']); - } - } - } - break; - case 'pspz2': - if ($total_macros > 0) { - for ($it_macros = 1; $it_macros <= $total_macros; $it_macros++) { - $macro = "macro_" . $it_macros . "_value"; - - // Set the value or use the default - if (isset($ini_array[$label][$macro])) { - $macros_component[(string)$it_macros]['value'] = - io_safe_input($ini_array[$label][$macro]); - } - } - } - break; - } - - if (!empty($macros_component)) { - $values['macros'] = json_encode($macros_component); - } - - db_process_sql_insert('tnetwork_component', $values); - - echo "

" . - __("Module plugin registered") . " : " . $ini_array[$label]["name"] . - "

"; - } - - echo "

" . - __("Plugin") . " " . $ini_array["plugin_definition"]["name"] . " " . __("Registered successfully") . - "

"; - } - unlink ($config["attachment_store"] . "/plugin_definition.ini"); - } - } - } - } + WHERE name = '".io_safe_input($ini_array['plugin_definition']['name'])."'"; + $result = db_get_sql($sql0); + + if ($result > 0) { + echo '

'.__('Plugin already registered. Aborting!').'

'; + unlink($config['attachment_store'].'/plugin_definition.ini'); + } else { + $values = [ + 'name' => io_safe_input($ini_array['plugin_definition']['name']), + 'description' => io_safe_input($ini_array['plugin_definition']['description']), + 'max_timeout' => $ini_array['plugin_definition']['timeout'], + 'execute' => io_safe_input($exec_path), + 'net_dst_opt' => $ini_array['plugin_definition']['ip_opt'], + 'net_port_opt' => $ini_array['plugin_definition']['port_opt'], + 'user_opt' => $ini_array['plugin_definition']['user_opt'], + 'pass_opt' => $ini_array['plugin_definition']['pass_opt'], + 'parameters' => $ini_array['plugin_definition']['parameters'], + 'plugin_type' => $ini_array['plugin_definition']['plugin_type'], + ]; + + switch ($version) { + case 'pspz': + // Fixed the static parameters + // for + // the dinamic parameters of pandoras 5 + $total_macros = 0; + $macros = []; + + if (!isset($values['parameters'])) { + $values['parameters'] = ''; + } + + if ($values['net_dst_opt'] != '') { + $total_macros++; + + $macro = []; + $macro['macro'] = '_field'.$total_macros.'_'; + $macro['desc'] = 'Target IP from net'; + $macro['help'] = ''; + $macro['value'] = ''; + + $values['parameters'] .= $values['net_dst_opt'].' _field'.$total_macros.'_ '; + + $macros[(string) $total_macros] = $macro; + } + + if ($values['ip_opt'] != '') { + $total_macros++; + + $macro = []; + $macro['macro'] = '_field'.$total_macros.'_'; + $macro['desc'] = 'Target IP'; + $macro['help'] = ''; + $macro['value'] = ''; + + $values['parameters'] .= $values['ip_opt'].' _field'.$total_macros.'_ '; + + $macros[(string) $total_macros] = $macro; + } + + if ($values['net_port_opt'] != '') { + $total_macros++; + + $macro = []; + $macro['macro'] = '_field'.$total_macros.'_'; + $macro['desc'] = 'Port from net'; + $macro['help'] = ''; + $macro['value'] = ''; + + $values['parameters'] .= $values['net_port_opt'].' _field'.$total_macros.'_ '; + + $macros[(string) $total_macros] = $macro; + } + + if ($values['port_opt'] != '') { + $total_macros++; + + $macro = []; + $macro['macro'] = '_field'.$total_macros.'_'; + $macro['desc'] = 'Port'; + $macro['help'] = ''; + $macro['value'] = ''; + + $values['parameters'] .= $values['port_opt'].' _field'.$total_macros.'_ '; + + $macros[(string) $total_macros] = $macro; + } + + if ($values['user_opt'] != '') { + $total_macros++; + + $macro = []; + $macro['macro'] = '_field'.$total_macros.'_'; + $macro['desc'] = 'Username'; + $macro['help'] = ''; + $macro['value'] = ''; + + $values['parameters'] .= $values['user_opt'].' _field'.$total_macros.'_ '; + + $macros[(string) $total_macros] = $macro; + } + + if ($values['pass_opt'] != '') { + $total_macros++; + + $macro = []; + $macro['macro'] = '_field'.$total_macros.'_'; + $macro['desc'] = 'Password'; + $macro['help'] = ''; + $macro['value'] = ''; + + $values['parameters'] .= $values['pass_opt'].' _field'.$total_macros.'_ '; + + $macros[(string) $total_macros] = $macro; + } + + // A last parameter is defined always to + // add the old "Plug-in parameters" in the + // side of the module + $total_macros++; + + $macro = []; + $macro['macro'] = '_field'.$total_macros.'_'; + $macro['desc'] = 'Plug-in Parameters'; + $macro['help'] = ''; + $macro['value'] = ''; + + $values['parameters'] .= ' _field'.$total_macros.'_'; + + $macros[(string) $total_macros] = $macro; + + break; + + case 'pspz2': + // Fill the macros field. + $total_macros = $ini_array['plugin_definition']['total_macros_provided']; + + $macros = []; + for ($it_macros = 1; $it_macros <= $total_macros; $it_macros++) { + $label = 'macro_'.$it_macros; + + $macro = []; + + $macro['macro'] = '_field'.$it_macros.'_'; + $macro['hide'] = $ini_array[$label]['hide']; + $macro['desc'] = io_safe_input( + $ini_array[$label]['description'] + ); + $macro['help'] = io_safe_input( + $ini_array[$label]['help'] + ); + $macro['value'] = io_safe_input( + $ini_array[$label]['value'] + ); + + $macros[(string) $it_macros] = $macro; + } + break; + } + + if (!empty($macros)) { + $values['macros'] = json_encode($macros); + } + + $create_id = db_process_sql_insert('tplugin', $values); + + if (empty($create_id)) { + ui_print_error_message( + __('Plug-in Remote Registered unsuccessfull') + ); + ui_print_info_message( + __('Please check the syntax of file "plugin_definition.ini"') + ); + } else { + for ($ax = 1; $ax <= $ini_array['plugin_definition']['total_modules_provided']; $ax++) { + $label = 'module'.$ax; + + $plugin_user = ''; + if (isset($ini_array[$label]['plugin_user'])) { + $plugin_user = $ini_array[$label]['plugin_user']; + } + + $plugin_pass = ''; + if (isset($ini_array[$label]['plugin_pass'])) { + $plugin_pass = $ini_array[$label]['plugin_pass']; + } + + $plugin_parameter = ''; + if (isset($ini_array[$label]['plugin_parameter'])) { + $plugin_parameter = $ini_array[$label]['plugin_parameter']; + } + + $unit = ''; + if (isset($ini_array[$label]['unit'])) { + $unit = $ini_array[$label]['unit']; + } + + $values = [ + 'name' => io_safe_input($ini_array[$label]['name']), + 'description' => io_safe_input($ini_array[$label]['description']), + 'id_group' => $ini_array[$label]['id_group'], + 'type' => $ini_array[$label]['type'], + 'max' => isset($ini_array[$label]['max']) ? $ini_array[$label]['max'] : '', + 'min' => isset($ini_array[$label]['min']) ? $ini_array[$label]['min'] : '', + 'module_interval' => isset($ini_array[$label]['module_interval']) ? $ini_array[$label]['module_interval'] : '', + 'id_module_group' => $ini_array[$label]['id_module_group'], + 'id_modulo' => $ini_array[$label]['id_modulo'], + 'plugin_user' => io_safe_input($plugin_user), + 'plugin_pass' => io_safe_input($plugin_pass), + 'plugin_parameter' => io_safe_input($plugin_parameter), + 'unit' => io_safe_input($unit), + 'max_timeout' => isset($ini_array[$label]['max_timeout']) ? $ini_array[$label]['max_timeout'] : '', + 'history_data' => isset($ini_array[$label]['history_data']) ? $ini_array[$label]['history_data'] : '', + 'dynamic_interval' => isset($ini_array[$label]['dynamic_interval']) ? $ini_array[$label]['dynamic_interval'] : '', + 'dynamic_min' => isset($ini_array[$label]['dynamic_min']) ? $ini_array[$label]['dynamic_min'] : '', + 'dynamic_max' => isset($ini_array[$label]['dynamic_max']) ? $ini_array[$label]['dynamic_max'] : '', + 'dynamic_two_tailed' => isset($ini_array[$label]['dynamic_two_tailed']) ? $ini_array[$label]['dynamic_two_tailed'] : '', + 'min_warning' => isset($ini_array[$label]['min_warning']) ? $ini_array[$label]['min_warning'] : '', + 'max_warning' => isset($ini_array[$label]['max_warning']) ? $ini_array[$label]['max_warning'] : '', + 'str_warning' => isset($ini_array[$label]['str_warning']) ? $ini_array[$label]['str_warning'] : '', + 'min_critical' => isset($ini_array[$label]['min_critical']) ? $ini_array[$label]['min_critical'] : '', + 'max_critical' => isset($ini_array[$label]['max_critical']) ? $ini_array[$label]['max_critical'] : '', + 'str_critical' => isset($ini_array[$label]['str_critical']) ? $ini_array[$label]['str_critical'] : '', + 'min_ff_event' => isset($ini_array[$label]['min_ff_event']) ? $ini_array[$label]['min_ff_event'] : '', + 'tcp_port' => isset($ini_array[$label]['tcp_port']) ? $ini_array[$label]['tcp_port'] : '', + 'id_plugin' => $create_id, + ]; + + $macros_component = $macros; + + switch ($version) { + case 'pspz': + // Fixed the static parameters + // for + // the dinamic parameters of pandoras 5 + foreach ($macros_component as $key => $macro) { + if ($macro['desc'] == 'Target IP from net') { + if (!empty($values['ip_target'])) { + $macros_component[$key]['value'] = io_safe_input($values['ip_target']); + } + } + + if ($macro['desc'] == 'Target IP') { + if (!empty($values['ip_target'])) { + $macros_component[$key]['value'] = io_safe_input($values['ip_target']); + } + } else if ($macro['desc'] == 'Port from net') { + if (!empty($values['tcp_port'])) { + $macros_component[$key]['value'] = io_safe_input($values['tcp_port']); + } + } else if ($macro['desc'] == 'Port') { + if (!empty($values['tcp_port'])) { + $macros_component[$key]['value'] = io_safe_input($values['tcp_port']); + } + } else if ($macro['desc'] == 'Username') { + if (!empty($values['plugin_user'])) { + $macros_component[$key]['value'] = io_safe_input($values['plugin_user']); + } + } else if ($macro['desc'] == 'Password') { + if (!empty($values['plugin_pass'])) { + $macros_component[$key]['value'] = io_safe_input($values['plugin_pass']); + } + } else if ($macro['desc'] == 'Plug-in Parameters') { + if (!empty($values['plugin_parameter'])) { + $macros_component[$key]['value'] = io_safe_input($values['plugin_parameter']); + } + } + } + break; + + case 'pspz2': + if ($total_macros > 0) { + for ($it_macros = 1; $it_macros <= $total_macros; $it_macros++) { + $macro = 'macro_'.$it_macros.'_value'; + + // Set the value or use the default + if (isset($ini_array[$label][$macro])) { + $macros_component[(string) $it_macros]['value'] = io_safe_input($ini_array[$label][$macro]); + } + } + } + break; + } + + if (!empty($macros_component)) { + $values['macros'] = json_encode($macros_component); + } + + db_process_sql_insert('tnetwork_component', $values); + + echo '

'.__('Module plugin registered').' : '.$ini_array[$label]['name'].'

'; + } + + echo '

'.__('Plugin').' '.$ini_array['plugin_definition']['name'].' '.__('Registered successfully').'

'; + } + + unlink($config['attachment_store'].'/plugin_definition.ini'); + } + } + } + } } -extensions_add_godmode_menu_option (__('Register plugin'), 'PM','gservers', null, "v1r1"); -extensions_add_godmode_function('pluginreg_extension_main'); -?> +extensions_add_godmode_menu_option(__('Register plugin'), 'PM', 'gservers', null, 'v1r1'); +extensions_add_godmode_function('pluginreg_extension_main'); diff --git a/pandora_console/extensions/realtime_graphs.php b/pandora_console/extensions/realtime_graphs.php index 5f6bca2c93..09d66abf0c 100644 --- a/pandora_console/extensions/realtime_graphs.php +++ b/pandora_console/extensions/realtime_graphs.php @@ -4,191 +4,204 @@ // ================================================== // Copyright (c) 2005-2014 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -include_once($config['homedir'] . '/include/graphs/fgraph.php'); -include_once($config['homedir'] . '/include/functions_snmp_browser.php'); +require_once $config['homedir'].'/include/graphs/fgraph.php'; +require_once $config['homedir'].'/include/functions_snmp_browser.php'; -function pandora_realtime_graphs () { - global $config; - check_login (); - $id_network = get_parameter('id_network', 0); - $action = get_parameter('action', 'list'); +function pandora_realtime_graphs() +{ + global $config; + check_login(); - $onheader = array(); + $id_network = get_parameter('id_network', 0); + $action = get_parameter('action', 'list'); - $hide_header = get_parameter('hide_header', 0); - if (!$hide_header) { - ui_print_page_header (__("Realtime graphs"), "images/extensions.png", false, "", false, $onheader); - } + $onheader = []; - $chart[time()]['graph'] = '0'; - $interactive_graph = true; - $color = array(); - $legend = ''; - $long_index = array(); - $no_data_image = ''; + $hide_header = get_parameter('hide_header', 0); + if (!$hide_header) { + ui_print_page_header(__('Realtime graphs'), 'images/extensions.png', false, '', false, $onheader); + } - $canvas = '
'; - $canvas .= '
'; + $chart[time()]['graph'] = '0'; + $interactive_graph = true; + $color = []; + $legend = ''; + $long_index = []; + $no_data_image = ''; - $width = 800; - $height = 300; + $canvas = '
'; + $canvas .= '
'; - $data_array['realtime']['data'][0][0] = time() - 10; - $data_array['realtime']['data'][0][1] = 0; - $data_array['realtime']['data'][1][0] = time(); - $data_array['realtime']['data'][1][1] = 0; - $data_array['realtime']['color'] = 'green'; + $width = 800; + $height = 300; - $params =array( - 'agent_module_id' => false, - 'period' => 300, - 'width' => $width, - 'height' => $height, - 'unit' => $unit, - 'only_image' => $only_image, - 'homeurl' => $homeurl, - 'type_graph' => 'area', - 'font' => $config['fontpath'], - 'font-size' => $config['font_size'], - 'array_data_create' => $data_array, - 'show_legend' => false, - 'show_menu' => false - ); + $data_array['realtime']['data'][0][0] = (time() - 10); + $data_array['realtime']['data'][0][1] = 0; + $data_array['realtime']['data'][1][0] = time(); + $data_array['realtime']['data'][1][1] = 0; + $data_array['realtime']['color'] = 'green'; - $canvas .= grafico_modulo_sparse($params); + $params = [ + 'agent_module_id' => false, + 'period' => 300, + 'width' => $width, + 'height' => $height, + 'unit' => $unit, + 'only_image' => $only_image, + 'homeurl' => $homeurl, + 'type_graph' => 'area', + 'font' => $config['fontpath'], + 'font-size' => $config['font_size'], + 'array_data_create' => $data_array, + 'show_legend' => false, + 'show_menu' => false, + ]; - $canvas .= '
'; - echo $canvas; + $canvas .= grafico_modulo_sparse($params); - $table->width = '100%'; - $table->id = 'table-form'; - $table->class = 'databox filters'; - $table->style = array (); - $table->cellpadding = '0'; - $table->cellspacing = '0'; - $table->style['graph'] = 'font-weight: bold;'; - $table->style['refresh'] = 'font-weight: bold;'; - $table->style['incremental'] = 'font-weight: bold;'; - $table->style['reset'] = 'font-weight: bold;'; - $table->style['snmp_address'] = 'font-weight: bold;'; - $table->style['snmp_community'] = 'font-weight: bold;'; - $table->style['snmp_oid'] = 'font-weight: bold;'; - $table->style['snmp_oid'] = 'font-weight: bold;'; - $table->data = array (); + $canvas .= '
'; + echo $canvas; - $graph_fields['cpu_load'] = __('%s Server CPU', get_product_name()); - $graph_fields['pending_packets'] = __('Pending packages from %s Server', get_product_name()); - $graph_fields['disk_io_wait'] = __('%s Server Disk IO Wait', get_product_name()); - $graph_fields['apache_load'] = __('%s Server Apache load', get_product_name()); - $graph_fields['mysql_load'] = __('%s Server MySQL load', get_product_name()); - $graph_fields['server_load'] = __('%s Server load', get_product_name()); - $graph_fields['snmp_interface'] = __('SNMP Interface throughput'); + $table->width = '100%'; + $table->id = 'table-form'; + $table->class = 'databox filters'; + $table->style = []; + $table->cellpadding = '0'; + $table->cellspacing = '0'; + $table->style['graph'] = 'font-weight: bold;'; + $table->style['refresh'] = 'font-weight: bold;'; + $table->style['incremental'] = 'font-weight: bold;'; + $table->style['reset'] = 'font-weight: bold;'; + $table->style['snmp_address'] = 'font-weight: bold;'; + $table->style['snmp_community'] = 'font-weight: bold;'; + $table->style['snmp_oid'] = 'font-weight: bold;'; + $table->style['snmp_oid'] = 'font-weight: bold;'; + $table->data = []; - $graph = get_parameter('graph', 'cpu_load'); - $refresh = get_parameter('refresh', '1000'); + $graph_fields['cpu_load'] = __('%s Server CPU', get_product_name()); + $graph_fields['pending_packets'] = __('Pending packages from %s Server', get_product_name()); + $graph_fields['disk_io_wait'] = __('%s Server Disk IO Wait', get_product_name()); + $graph_fields['apache_load'] = __('%s Server Apache load', get_product_name()); + $graph_fields['mysql_load'] = __('%s Server MySQL load', get_product_name()); + $graph_fields['server_load'] = __('%s Server load', get_product_name()); + $graph_fields['snmp_interface'] = __('SNMP Interface throughput'); - if ($graph != 'snmp_module') { - $data['graph'] = __('Graph') . '  ' . html_print_select ($graph_fields, 'graph', $graph, '', '', 0, true); - } + $graph = get_parameter('graph', 'cpu_load'); + $refresh = get_parameter('refresh', '1000'); - $refresh_fields[1000] = human_time_description_raw(1, true, 'large'); - $refresh_fields[5000] = human_time_description_raw(5, true, 'large'); - $refresh_fields[10000] = human_time_description_raw(10, true, 'large'); - $refresh_fields[30000] = human_time_description_raw(30, true, 'large'); + if ($graph != 'snmp_module') { + $data['graph'] = __('Graph').'  '.html_print_select($graph_fields, 'graph', $graph, '', '', 0, true); + } - if ($graph == 'snmp_module') { - $agent_alias = io_safe_output(get_parameter('agent_alias', '')) ; - $module_name = io_safe_output(get_parameter('module_name', '')) ; - $module_incremental = get_parameter ('incremental', 0); - $data['module_info'] = "$agent_alias: $module_name"; + $refresh_fields[1000] = human_time_description_raw(1, true, 'large'); + $refresh_fields[5000] = human_time_description_raw(5, true, 'large'); + $refresh_fields[10000] = human_time_description_raw(10, true, 'large'); + $refresh_fields[30000] = human_time_description_raw(30, true, 'large'); - // Append all the hidden in this cell - $data['module_info'] .= html_print_input_hidden ('incremental', $module_incremental, true); - $data['module_info'] .= html_print_select ( - array('snmp_module' => '-'), 'graph', 'snmp_module', '', '', 0, true, false, true, '', false, 'display: none;' - ); - } - $data['refresh'] = __('Refresh interval') . '  ' . html_print_select ($refresh_fields, 'refresh', $refresh, '', '', 0, true); - if ($graph != 'snmp_module') { - $data['incremental'] = __('Incremental') . '  ' . html_print_checkbox ('incremental', 1, 0, true); - } - $data['reset'] = html_print_button(__('Clear graph'), 'reset', false, 'javascript:realtimeGraphs.clearGraph();', 'class="sub delete" style="margin-top:0px;"', true); - $table->data[] = $data; + if ($graph == 'snmp_module') { + $agent_alias = io_safe_output(get_parameter('agent_alias', '')); + $module_name = io_safe_output(get_parameter('module_name', '')); + $module_incremental = get_parameter('incremental', 0); + $data['module_info'] = "$agent_alias: $module_name"; - if ($graph == 'snmp_interface' || $graph == 'snmp_module') { - $snmp_address = get_parameter('snmp_address', ''); - $snmp_community = get_parameter('snmp_community', ''); - $snmp_oid = get_parameter('snmp_oid', ''); - $snmp_ver = get_parameter('snmp_ver', ''); + // Append all the hidden in this cell + $data['module_info'] .= html_print_input_hidden('incremental', $module_incremental, true); + $data['module_info'] .= html_print_select( + ['snmp_module' => '-'], + 'graph', + 'snmp_module', + '', + '', + 0, + true, + false, + true, + '', + false, + 'display: none;' + ); + } - $data = array(); + $data['refresh'] = __('Refresh interval').'  '.html_print_select($refresh_fields, 'refresh', $refresh, '', '', 0, true); + if ($graph != 'snmp_module') { + $data['incremental'] = __('Incremental').'  '.html_print_checkbox('incremental', 1, 0, true); + } - $data['snmp_address'] = __('Target IP') . '  ' . html_print_input_text ('ip_target', $snmp_address, '', 50, 255, true); - $table->colspan[1]['snmp_address'] = 2; + $data['reset'] = html_print_button(__('Clear graph'), 'reset', false, 'javascript:realtimeGraphs.clearGraph();', 'class="sub delete" style="margin-top:0px;"', true); + $table->data[] = $data; - $data['snmp_community'] = __('Community') . '  ' . html_print_input_text ('snmp_community', $snmp_community, '', 50, 255, true); - $table->colspan[1]['snmp_community'] = 2; + if ($graph == 'snmp_interface' || $graph == 'snmp_module') { + $snmp_address = get_parameter('snmp_address', ''); + $snmp_community = get_parameter('snmp_community', ''); + $snmp_oid = get_parameter('snmp_oid', ''); + $snmp_ver = get_parameter('snmp_ver', ''); - $table->data[] = $data; + $data = []; - $snmp_versions = array(); - $snmp_versions['1'] = '1'; - $snmp_versions['2'] = '2'; - $snmp_versions['2c'] = '2c'; + $data['snmp_address'] = __('Target IP').'  '.html_print_input_text('ip_target', $snmp_address, '', 50, 255, true); + $table->colspan[1]['snmp_address'] = 2; - $data = array(); - $data['snmp_oid'] = __('OID') . '  ' . html_print_input_text ('snmp_oid', $snmp_oid, '', 100, 255, true); - $table->colspan[2]['snmp_oid'] = 2; + $data['snmp_community'] = __('Community').'  '.html_print_input_text('snmp_community', $snmp_community, '', 50, 255, true); + $table->colspan[1]['snmp_community'] = 2; - $data['snmp_ver'] = __('Version') . '  ' . html_print_select ($snmp_versions, 'snmp_version', $snmp_ver, '', '', 0, true); - $data['snmp_ver'] .= '  ' . html_print_button (__('SNMP walk'), 'snmp_walk', false, 'javascript:realtimeGraphs.snmpBrowserWindow();', 'class="sub next"', true); - $table->colspan[2]['snmp_ver'] = 2; + $table->data[] = $data; - $table->data[] = $data; + $snmp_versions = []; + $snmp_versions['1'] = '1'; + $snmp_versions['2'] = '2'; + $snmp_versions['2c'] = '2c'; - // Hide some options in snmp_module graphs - if ($graph == 'snmp_module') { - $table->rowstyle[1] = "display: none;"; - $table->rowstyle[2] = "display: none;"; - } - snmp_browser_print_container (false, '100%', '60%', 'none'); - } + $data = []; + $data['snmp_oid'] = __('OID').'  '.html_print_input_text('snmp_oid', $snmp_oid, '', 100, 255, true); + $table->colspan[2]['snmp_oid'] = 2; - // Print the relative path to AJAX calls: - html_print_input_hidden('rel_path', get_parameter('rel_path', '')); + $data['snmp_ver'] = __('Version').'  '.html_print_select($snmp_versions, 'snmp_version', $snmp_ver, '', '', 0, true); + $data['snmp_ver'] .= '  '.html_print_button(__('SNMP walk'), 'snmp_walk', false, 'javascript:realtimeGraphs.snmpBrowserWindow();', 'class="sub next"', true); + $table->colspan[2]['snmp_ver'] = 2; - // Print the form - echo '
'; - html_print_table($table); - echo '
'; + $table->data[] = $data; - // Define a custom action to save the OID selected in the SNMP browser to the form - html_print_input_hidden ('custom_action', urlencode (base64_encode(' ')), false); - html_print_input_hidden ('incremental_base', '0'); + // Hide some options in snmp_module graphs + if ($graph == 'snmp_module') { + $table->rowstyle[1] = 'display: none;'; + $table->rowstyle[2] = 'display: none;'; + } - echo ''; - echo ''; - echo ''; + snmp_browser_print_container(false, '100%', '60%', 'none'); + } - // Store servers timezone offset to be retrieved from js - set_js_value('timezone_offset', date('Z', time())); + // Print the relative path to AJAX calls: + html_print_input_hidden('rel_path', get_parameter('rel_path', '')); + + // Print the form + echo '
'; + html_print_table($table); + echo '
'; + + // Define a custom action to save the OID selected in the SNMP browser to the form + html_print_input_hidden('custom_action', urlencode(base64_encode(' ')), false); + html_print_input_hidden('incremental_base', '0'); + + echo ''; + echo ''; + echo ''; + + // Store servers timezone offset to be retrieved from js + set_js_value('timezone_offset', date('Z', time())); } -extensions_add_operation_menu_option (__('Realtime graphs'), "estado", null, "v1r1","view"); -extensions_add_main_function ('pandora_realtime_graphs'); -$db = NULL; -?> +extensions_add_operation_menu_option(__('Realtime graphs'), 'estado', null, 'v1r1', 'view'); +extensions_add_main_function('pandora_realtime_graphs'); + +$db = null; diff --git a/pandora_console/extensions/realtime_graphs/ajax.php b/pandora_console/extensions/realtime_graphs/ajax.php index caea2bda86..73d3c20748 100644 --- a/pandora_console/extensions/realtime_graphs/ajax.php +++ b/pandora_console/extensions/realtime_graphs/ajax.php @@ -4,101 +4,111 @@ // ================================================== // Copyright (c) 2005-2014 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -require_once ('../../include/functions_html.php'); +require_once '../../include/functions_html.php'; $graph = $_POST['graph']; $graph_title = $_POST['graph_title']; $refresh = $_POST['refresh']; $os = strtolower(PHP_OS); - if (substr($os, 0, 3) === 'win') { - $os = 'windows'; +if (substr($os, 0, 3) === 'win') { + $os = 'windows'; } -switch($graph) { - case 'cpu_load': - if ( $os == 'windows') - $data = exec('wmic cpu get loadpercentage|find /I /V "Loadpercentage" | findstr /r "[0-9]" '); - else - $data = exec("top -bn 2 -d 0.01 | grep '^Cpu' | tail -n 1 | awk '{ print $2+$4+$6 }'"); - break; - case 'pending_packets': - $data = exec("ls /var/spool/pandora/data_in/*.data | wc -l"); - break; - case 'disk_io_wait': - if ( $os == 'windows') - $data = exec("vmstat 1 3 | tail -1 | awk '{ print $16 }'"); - else - $data = exec("vmstat 1 3 | tail -1 | awk '{ print $16 }'"); - break; - case 'mysql_load': - if ( $os == 'windows') - $data = exec('(FOR /F "skip=2 tokens=2 delims=\," %P IN (\'typeperf "\\Process(mysqld)\\% processor time" -sc 1\') DO @echo %P)|find /V /I "..."'); - else - $data = exec("ps aux | grep mysqld | grep -v safe | grep -v grep | awk '{ print $3 }'"); - break; - case 'apache_load': - if ( $os == 'windows') - $data = exec('(FOR /F "skip=2 tokens=2 delims=\," %P IN (\'typeperf "\\Process(httpd)\\% processor time" -sc 1\') DO @echo %P)|find /V /I "..."'); - else - $data = exec("ps aux | grep apache2 | grep -v safe | grep -v grep | awk '{ sum+=$3 } END { print sum }'"); - break; - case 'server_load': - if ( $os == 'windows') - $data = exec('(FOR /F "skip=2 tokens=2 delims=\," %P IN (\'typeperf "\\Process(pandora_server)\\% processor time" -sc 1\') DO @echo %P)|find /V /I "..."'); - else - $data = exec("ps aux | grep pandora_server | grep -v grep | awk '{ print $3 }'"); - break; - case 'snmp_interface': - case 'snmp_module': - $snmp_address = $_POST['snmp_address']; - $snmp_community = $_POST['snmp_community']; - $snmp_ver = $_POST['snmp_ver']; - $snmp_oid = $_POST['snmp_oid']; - - if (empty($snmp_address) || empty($snmp_oid)) { - $data = 0; - } - else { - $data = get_snmpwalk($snmp_address, $snmp_ver, $snmp_community, '', '', '', '', '', '', 0, $snmp_oid); - $data_index = array_keys($data); - $graph_title = $data_index[0]; - if (!empty($data)) { - $data_array = explode(' ', reset($data)); - if (count($data_array) > 1) { - $data = $data_array[1]; - } - // Redefine boolean data - switch ($data) { - case "up(1)": - $data = 1; - break; - case "down(0)": - $data = 0; - break; - } - } - } - break; - default: - $data = 0; + +switch ($graph) { + case 'cpu_load': + if ($os == 'windows') { + $data = exec('wmic cpu get loadpercentage|find /I /V "Loadpercentage" | findstr /r "[0-9]" '); + } else { + $data = exec("top -bn 2 -d 0.01 | grep '^Cpu' | tail -n 1 | awk '{ print $2+$4+$6 }'"); + } + break; + + case 'pending_packets': + $data = exec('ls /var/spool/pandora/data_in/*.data | wc -l'); + break; + + case 'disk_io_wait': + if ($os == 'windows') { + $data = exec("vmstat 1 3 | tail -1 | awk '{ print $16 }'"); + } else { + $data = exec("vmstat 1 3 | tail -1 | awk '{ print $16 }'"); + } + break; + + case 'mysql_load': + if ($os == 'windows') { + $data = exec('(FOR /F "skip=2 tokens=2 delims=\," %P IN (\'typeperf "\\Process(mysqld)\\% processor time" -sc 1\') DO @echo %P)|find /V /I "..."'); + } else { + $data = exec("ps aux | grep mysqld | grep -v safe | grep -v grep | awk '{ print $3 }'"); + } + break; + + case 'apache_load': + if ($os == 'windows') { + $data = exec('(FOR /F "skip=2 tokens=2 delims=\," %P IN (\'typeperf "\\Process(httpd)\\% processor time" -sc 1\') DO @echo %P)|find /V /I "..."'); + } else { + $data = exec("ps aux | grep apache2 | grep -v safe | grep -v grep | awk '{ sum+=$3 } END { print sum }'"); + } + break; + + case 'server_load': + if ($os == 'windows') { + $data = exec('(FOR /F "skip=2 tokens=2 delims=\," %P IN (\'typeperf "\\Process(pandora_server)\\% processor time" -sc 1\') DO @echo %P)|find /V /I "..."'); + } else { + $data = exec("ps aux | grep pandora_server | grep -v grep | awk '{ print $3 }'"); + } + break; + + case 'snmp_interface': + case 'snmp_module': + $snmp_address = $_POST['snmp_address']; + $snmp_community = $_POST['snmp_community']; + $snmp_ver = $_POST['snmp_ver']; + $snmp_oid = $_POST['snmp_oid']; + + if (empty($snmp_address) || empty($snmp_oid)) { + $data = 0; + } else { + $data = get_snmpwalk($snmp_address, $snmp_ver, $snmp_community, '', '', '', '', '', '', 0, $snmp_oid); + $data_index = array_keys($data); + $graph_title = $data_index[0]; + if (!empty($data)) { + $data_array = explode(' ', reset($data)); + if (count($data_array) > 1) { + $data = $data_array[1]; + } + + // Redefine boolean data + switch ($data) { + case 'up(1)': + $data = 1; + break; + + case 'down(0)': + $data = 0; + break; + } + } + } + break; + + default: + $data = 0; } if (empty($data)) { - $data = 0; + $data = 0; } echo '{ - "label": "' . $graph_title . '", - "data": [["' . time() . '", ' . $data . ']] + "label": "'.$graph_title.'", + "data": [["'.time().'", '.$data.']] }'; -?> diff --git a/pandora_console/extensions/realtime_graphs/realtime_graphs.css b/pandora_console/extensions/realtime_graphs/realtime_graphs.css index e5a1f8a2bb..ab6c94e238 100644 --- a/pandora_console/extensions/realtime_graphs/realtime_graphs.css +++ b/pandora_console/extensions/realtime_graphs/realtime_graphs.css @@ -1,15 +1,15 @@ #chartLegend { - width: 100%; - position: relative; - height: 30px; + width: 100%; + position: relative; + height: 30px; } #chartLegend table { - position: absolute; - right: 0px; + position: absolute; + right: 0px; } #graph_container { - width: 800px; - margin: 20px auto !important; + width: 800px; + margin: 20px auto !important; } diff --git a/pandora_console/extensions/realtime_graphs/realtime_graphs.js b/pandora_console/extensions/realtime_graphs/realtime_graphs.js index 34da7b1704..7140d245d4 100644 --- a/pandora_console/extensions/realtime_graphs/realtime_graphs.js +++ b/pandora_console/extensions/realtime_graphs/realtime_graphs.js @@ -1,207 +1,218 @@ -(function () { - var numberOfPoints = 100; - var refresh = parseInt($('#refresh').val()); - var incremental = $('#checkbox-incremental').is(':checked') || $('#hidden-incremental').val() == 1; - var lastIncVal = null; - var intervalRef = null; - var currentXHR = null; +(function() { + var numberOfPoints = 100; + var refresh = parseInt($("#refresh").val()); + var incremental = + $("#checkbox-incremental").is(":checked") || + $("#hidden-incremental").val() == 1; + var lastIncVal = null; + var intervalRef = null; + var currentXHR = null; - var plot; - var plotOptions = { - legend: { container: $("#chartLegend") }, - xaxis: { - tickFormatter: function (timestamp, axis) { - var date = new Date(timestamp * 1000); - - var server_timezone_offset = get_php_value('timezone_offset'); - var local_timezone_offset = date.getTimezoneOffset()*60*-1; - - if (server_timezone_offset != local_timezone_offset) { - // If timezone of server and client is different, adjust the time to the server - date = new Date((timestamp + (server_timezone_offset - local_timezone_offset)) * 1000); - } - - var hours = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()); - var minutes = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()); - var seconds = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()); - var formattedTime = hours + ':' + minutes + ':' + seconds; - return formattedTime; - } - }, - yaxis: { - tickFormatter: function (value, axis) { - return shortNumber(value); - } - }, - series: { - lines: { - lineWidth: 2, - fill: true - } - }, - colors: ['#6db431'] - }; + var plot; + var plotOptions = { + legend: { container: $("#chartLegend") }, + xaxis: { + tickFormatter: function(timestamp, axis) { + var date = new Date(timestamp * 1000); - function updatePlot (data) { - plot = $.plot($('.graph'), data, plotOptions); - } + var server_timezone_offset = get_php_value("timezone_offset"); + var local_timezone_offset = date.getTimezoneOffset() * 60 * -1; - function requestData () { - var rel_path = $("#hidden-rel_path").val(); + if (server_timezone_offset != local_timezone_offset) { + // If timezone of server and client is different, adjust the time to the server + date = new Date( + (timestamp + (server_timezone_offset - local_timezone_offset)) * + 1000 + ); + } - currentXHR = $.ajax({ - url: rel_path + "extensions/realtime_graphs/ajax.php", - type: "POST", - dataType: "json", - data: { - graph: $('#graph :selected').val(), - graph_title: $('#graph :selected').html(), - snmp_community: $('#text-snmp_community').val(), - snmp_oid: $('#text-snmp_oid').val(), - snmp_ver: $('#snmp_version :selected').val(), - snmp_address: $('#text-ip_target').val(), - refresh: refresh - }, - success: function (serie) { - var timestamp = serie.data[0][0]; - var data = plot.getData(); - - if (incremental) { - var currentVal = serie.data[0][1]; - // Try to avoid the first value, cause we need at least two values to get the increment - serie.data[0][1] = lastIncVal == null ? 0 : currentVal - lastIncVal; - // Incremental is always positive - if (serie.data[0][1] < 0) serie.data[0][1] = 0; - // Store the current value to use it into the next request - lastIncVal = currentVal; - } - - if (data.length === 0) { - for (i = 0; i < numberOfPoints; i++) { - var step = i * (refresh / 1000); - serie.data.unshift([timestamp - step, 0]); - } - - serie = [serie]; - updatePlot(serie); - return; - } + var hours = + date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); + var minutes = + date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); + var seconds = + date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); + var formattedTime = hours + ":" + minutes + ":" + seconds; + return formattedTime; + } + }, + yaxis: { + tickFormatter: function(value, axis) { + return shortNumber(roundToTwo(value)); + } + }, + series: { + lines: { + lineWidth: 2, + fill: true + } + }, + colors: ["#6db431"] + }; - data[0].label = serie.label; - if (data[0].data.length >= numberOfPoints) { - data[0].data.shift(); - } - - data[0].data.push(serie.data[0]); - updatePlot(data); - } - }); - } - - function startDataPooling () { - intervalRef = window.setInterval(requestData, refresh); - } + function updatePlot(data) { + plot = $.plot($(".graph"), data, plotOptions); + } - function resetDataPooling () { - if (currentXHR !== null) currentXHR.abort(); - // Stop and start the interval - window.clearInterval(intervalRef); - startDataPooling(); - } + function requestData() { + var rel_path = $("#hidden-rel_path").val(); - function clearGraph () { - var data = plot.getData(); - if (data.length === 0) return; + currentXHR = $.ajax({ + url: rel_path + "extensions/realtime_graphs/ajax.php", + type: "POST", + dataType: "json", + data: { + graph: $("#graph :selected").val(), + graph_title: $("#graph :selected").html(), + snmp_community: $("#text-snmp_community").val(), + snmp_oid: $("#text-snmp_oid").val(), + snmp_ver: $("#snmp_version :selected").val(), + snmp_address: $("#text-ip_target").val(), + refresh: refresh + }, + success: function(serie) { + var timestamp = serie.data[0][0]; + var data = plot.getData(); - for (i = 0; i < data[0].data.length; i ++) { - data[0].data[i][1] = 0; - } - if (incremental) lastIncVal = null; - - updatePlot(data); + if (incremental) { + var currentVal = serie.data[0][1]; + // Try to avoid the first value, cause we need at least two values to get the increment + serie.data[0][1] = lastIncVal == null ? 0 : currentVal - lastIncVal; + // Incremental is always positive + if (serie.data[0][1] < 0) serie.data[0][1] = 0; + // Store the current value to use it into the next request + lastIncVal = currentVal; + } - resetDataPooling(); - } + if (data.length === 0) { + for (i = 0; i < numberOfPoints; i++) { + var step = i * (refresh / 1000); + serie.data.unshift([timestamp - step, 0]); + } - // Set the form OID to the value selected in the SNMP browser - function setOID () { - if ($('#snmp_browser_version').val() == '3') { - $('#text-snmp_oid').val($('#table1-0-1').text()); - } else { - $('#text-snmp_oid').val($('#snmp_selected_oid').text()); - } - - // Close the SNMP browser - $('.ui-dialog-titlebar-close').trigger('click'); - } + serie = [serie]; + updatePlot(serie); + return; + } - // Show the SNMP browser window - function snmpBrowserWindow () { - - // Keep elements in the form and the SNMP browser synced - $('#text-target_ip').val($('#text-ip_target').val()); - $('#text-community').val($('#text-snmp_community').val()); - $('#snmp_browser_version').val($('#snmp_version').val()); - $('#snmp3_browser_auth_user').val($('#snmp3_auth_user').val()); - $('#snmp3_browser_security_level').val($('#snmp3_security_level').val()); - $('#snmp3_browser_auth_method').val($('#snmp3_auth_method').val()); - $('#snmp3_browser_auth_pass').val($('#snmp3_auth_pass').val()); - $('#snmp3_browser_privacy_method').val($('#snmp3_privacy_method').val()); - $('#snmp3_browser_privacy_pass').val($('#snmp3_privacy_pass').val()); - - $("#snmp_browser_container").show().dialog ({ - title: '', - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: "black" - }, - width: 920, - height: 500 - }); - } + data[0].label = serie.label; + if (data[0].data.length >= numberOfPoints) { + data[0].data.shift(); + } - function shortNumber (number) { - if (Math.round(number) != number) return number; - number = Number.parseInt(number); - if (Number.isNaN(number)) return number; + data[0].data.push(serie.data[0]); + updatePlot(data); + } + }); + } - var shorts = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"]; - var pos = 0; + function startDataPooling() { + intervalRef = window.setInterval(requestData, refresh); + } - while (number >= 1000 || number <= -1000) { - pos++; - number = number / 1000; - } + function resetDataPooling() { + if (currentXHR !== null) currentXHR.abort(); + // Stop and start the interval + window.clearInterval(intervalRef); + startDataPooling(); + } - return number + " " + shorts[pos]; - } + function clearGraph() { + var data = plot.getData(); + if (data.length === 0) return; - $('#graph').change(function() { - $('form#realgraph').submit(); - }); + for (i = 0; i < data[0].data.length; i++) { + data[0].data[i][1] = 0; + } + if (incremental) lastIncVal = null; - $('#refresh').change(function () { - refresh = parseInt($('#refresh').val()); - resetDataPooling(); - }); + updatePlot(data); - $('#checkbox-incremental').change(function() { - incremental = $('#checkbox-incremental').is(':checked'); - clearGraph(); - }); + resetDataPooling(); + } - updatePlot([]); - requestData(); - startDataPooling(); + // Set the form OID to the value selected in the SNMP browser + function setOID() { + if ($("#snmp_browser_version").val() == "3") { + $("#text-snmp_oid").val($("#table1-0-1").text()); + } else { + $("#text-snmp_oid").val($("#snmp_selected_oid").text()); + } - // Expose this functions - window.realtimeGraphs = { - clearGraph: clearGraph, - setOID: setOID, - snmpBrowserWindow: snmpBrowserWindow - } + // Close the SNMP browser + $(".ui-dialog-titlebar-close").trigger("click"); + } -})(); \ No newline at end of file + // Show the SNMP browser window + function snmpBrowserWindow() { + // Keep elements in the form and the SNMP browser synced + $("#text-target_ip").val($("#text-ip_target").val()); + $("#text-community").val($("#text-snmp_community").val()); + $("#snmp_browser_version").val($("#snmp_version").val()); + $("#snmp3_browser_auth_user").val($("#snmp3_auth_user").val()); + $("#snmp3_browser_security_level").val($("#snmp3_security_level").val()); + $("#snmp3_browser_auth_method").val($("#snmp3_auth_method").val()); + $("#snmp3_browser_auth_pass").val($("#snmp3_auth_pass").val()); + $("#snmp3_browser_privacy_method").val($("#snmp3_privacy_method").val()); + $("#snmp3_browser_privacy_pass").val($("#snmp3_privacy_pass").val()); + + $("#snmp_browser_container") + .show() + .dialog({ + title: "", + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 920, + height: 500 + }); + } + + function shortNumber(number) { + if (Math.round(number) != number) return number; + number = Number.parseInt(number); + if (Number.isNaN(number)) return number; + + var shorts = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"]; + var pos = 0; + + while (number >= 1000 || number <= -1000) { + pos++; + number = number / 1000; + } + + return number + " " + shorts[pos]; + } + function roundToTwo(num) { + return +(Math.round(num + "e+2") + "e-2"); + } + + $("#graph").change(function() { + $("form#realgraph").submit(); + }); + + $("#refresh").change(function() { + refresh = parseInt($("#refresh").val()); + resetDataPooling(); + }); + + $("#checkbox-incremental").change(function() { + incremental = $("#checkbox-incremental").is(":checked"); + clearGraph(); + }); + + updatePlot([]); + requestData(); + startDataPooling(); + + // Expose this functions + window.realtimeGraphs = { + clearGraph: clearGraph, + setOID: setOID, + snmpBrowserWindow: snmpBrowserWindow + }; +})(); diff --git a/pandora_console/extensions/resource_exportation.php b/pandora_console/extensions/resource_exportation.php index 092b90b3f3..f8731f8a5b 100755 --- a/pandora_console/extensions/resource_exportation.php +++ b/pandora_console/extensions/resource_exportation.php @@ -4,402 +4,466 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - if (isset($_GET['get_ptr'])) { - if ($_GET['get_ptr'] == 1) { + if ($_GET['get_ptr'] == 1) { + $ownDir = dirname(__FILE__).'/'; + $ownDir = str_replace('\\', '/', $ownDir); - $ownDir = dirname(__FILE__) . '/'; - $ownDir = str_replace("\\", "/", $ownDir); + // Don't start a session before this import. + // The session is configured and started inside the config process. + include_once $ownDir.'../include/config.php'; - // Don't start a session before this import. - // The session is configured and started inside the config process. - require_once ($ownDir.'../include/config.php'); + // Login check + if (!isset($_SESSION['id_usuario'])) { + $config['id_user'] = null; + } else { + $config['id_user'] = $_SESSION['id_usuario']; + } - // Login check - if (!isset($_SESSION["id_usuario"])) { - $config['id_user'] = null; - } - else { - $config['id_user'] = $_SESSION["id_usuario"]; - } - - - if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; - } - - $hook_enterprise = enterprise_include ('extensions/resource_exportation/functions.php'); - - header("Content-type: binary"); - header("Content-Disposition: attachment; filename=\"".get_name_xml_resource($hook_enterprise)) . "\""; - header("Pragma: no-cache"); - header("Expires: 0"); - - output_xml_resource($hook_enterprise); - } -} -else { - extensions_add_godmode_menu_option (__('Resource exportation'), 'PM','gagente','', "v1r1"); - extensions_add_godmode_function('resource_exportation_extension_main'); + + if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; + } + + $hook_enterprise = enterprise_include('extensions/resource_exportation/functions.php'); + + header('Content-type: binary'); + header('Content-Disposition: attachment; filename="'.get_name_xml_resource($hook_enterprise)).'"'; + header('Pragma: no-cache'); + header('Expires: 0'); + + output_xml_resource($hook_enterprise); + } +} else { + extensions_add_godmode_menu_option(__('Resource exportation'), 'PM', 'gagente', '', 'v1r1'); + extensions_add_godmode_function('resource_exportation_extension_main'); } -function output_xml_resource($hook_enterprise) { - global $config; - - $type = get_parameter('type'); - $id = (int)get_parameter('id'); - - switch ($type) { - case 'report': - output_xml_report($id); - break; - case 'visual_console': - output_xml_visual_console($id); - break; - default: - if ($hook_enterprise === true) { - $include_agents = get_parameter('include_agents', 0); - return enterprise_output_xml_resource($type, $id, $include_agents); - } - break; - } + +function output_xml_resource($hook_enterprise) +{ + global $config; + + $type = get_parameter('type'); + $id = (int) get_parameter('id'); + + switch ($type) { + case 'report': + output_xml_report($id); + break; + + case 'visual_console': + output_xml_visual_console($id); + break; + + default: + if ($hook_enterprise === true) { + $include_agents = get_parameter('include_agents', 0); + return enterprise_output_xml_resource($type, $id, $include_agents); + } + break; + } } -function output_xml_report($id) { - global $config; - - require_once ($config['homedir'].'/include/functions_agents.php'); - - $report = db_get_row('treport', 'id_report', $id); - - echo '' . "\n"; - echo "\n"; - echo "\n"; - if (isset($report['description'])) - echo "\n"; - $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $report['id_group']); - echo "\n"; - $items = db_get_all_rows_field_filter('treport_content', 'id_report', $report['id_report']); - foreach ($items as $item) { - echo "\n"; - echo "" . io_safe_output($item['type']) . "\n"; - echo "" . io_safe_output($item['description']) . "\n"; - echo "" . io_safe_output($item['period']) . "\n"; - if ($item['id_agent'] != 0) { - $agent = db_get_value ("alias","tagente","id_agente",$item['id_agent']); - } - if ($item['id_agent_module'] != 0) { - $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $item['id_agent_module']); - $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $item['id_agent_module']); - $agent = db_get_value ("alias","tagente","id_agente",$item['id_agent']); - - echo "\n"; - } - if (isset($agent)) - echo "\n"; - $agent = null; - switch (io_safe_output($item['type'])) { - case 1: - case 'simple_graph': - break; - case 'simple_baseline_graph': - break; - case 2: - case 'custom_graph': - case 'automatic_custom_graph': - $graph = db_get_value('name', 'tgraph', 'id_graph', $item['id_gs']); - echo "\n"; - break; - case 3: - case 'SLA': - echo "" . $item['only_display_wrong'] . "\n"; - echo "" . $item['monday'] . "\n"; - echo "" . $item['tuesday'] . "\n"; - echo "" . $item['wednesday'] . "\n"; - echo "" . $item['thursday'] . "\n"; - echo "" . $item['friday'] . "\n"; - echo "" . $item['saturday'] . "\n"; - echo "" . $item['sunday'] . "\n"; - echo "" . $item['time_from'] . "\n"; - echo "" . $item['time_to'] . "\n"; - - $slas = db_get_all_rows_field_filter('treport_content_sla_combined', 'id_report_content', $item['id_rc']); - if ($slas === false) $slas = array(); - - foreach ($slas as $sla) { - $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $sla['id_agent_module']); - $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $sla['id_agent_module']); - $agent = db_get_value ("alias","tagente","id_agente",$item['id_agent']); - echo ""; - echo "\n"; - echo "\n"; - echo "" . $sla['sla_max'] . "\n"; - echo "" . $sla['sla_min'] . "\n"; - echo "" . $sla['sla_limit'] . "\n"; - echo ""; - } - break; - case 6: - case 'monitor_report': - break; - case 7: - case 'avg_value': - break; - case 8: - case 'max_value': - break; - case 9: - case 'min_value': - break; - case 10: - case 'sumatory': - break; - case 'agent_detailed_event': - case 'event_report_agent': - break; - case 'text': - echo "\n"; - break; - case 'sql': - echo "\n"; - if (!empty($item['external_source'])) { - echo "\n"; - } - else { - $sql = db_get_value('sql', 'treport_custom_sql', 'id', $item['treport_custom_sql_id']); - echo "" . io_safe_output($sql) . "\n"; - } - break; - case 'sql_graph_pie': - case 'sql_graph_vbar': - case 'sql_graph_hbar': - echo "" . io_safe_output($item['header_definition']) . "\n"; - if (!empty($item['external_source'])) { - echo "" . io_safe_output($item['external_source']) . "\n"; - } - else { - $sql = db_get_value('sql', 'treport_custom_sql', 'id', $item['treport_custom_sql_id']); - echo "" . io_safe_output($sql) . "\n"; - } - break; - case 'event_report_group': - $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $item['id_agent']); - echo "\n"; - break; - case 'event_report_module': - break; - case 'alert_report_module': - break; - case 'alert_report_agent': - break; - case 'alert_report_group': - break; - case 'url': - echo ""; - break; - case 'database_serialized': - echo ""; - echo ""; - echo ""; - break; - case 'TTRT': - break; - case 'TTO': - break; - case 'MTBF': - break; - case 'MTTR': - break; - } - echo "\n"; - } - echo "\n"; + +function output_xml_report($id) +{ + global $config; + + include_once $config['homedir'].'/include/functions_agents.php'; + + $report = db_get_row('treport', 'id_report', $id); + + echo ''."\n"; + echo "\n"; + echo '\n"; + if (isset($report['description'])) { + echo '\n"; + } + + $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $report['id_group']); + echo '\n"; + $items = db_get_all_rows_field_filter('treport_content', 'id_report', $report['id_report']); + foreach ($items as $item) { + echo "\n"; + echo ''.io_safe_output($item['type'])."\n"; + echo ''.io_safe_output($item['description'])."\n"; + echo ''.io_safe_output($item['period'])."\n"; + if ($item['id_agent'] != 0) { + $agent = db_get_value('alias', 'tagente', 'id_agente', $item['id_agent']); + } + + if ($item['id_agent_module'] != 0) { + $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $item['id_agent_module']); + $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $item['id_agent_module']); + $agent = db_get_value('alias', 'tagente', 'id_agente', $item['id_agent']); + + echo '\n"; + } + + if (isset($agent)) { + echo '\n"; + } + + $agent = null; + switch (io_safe_output($item['type'])) { + case 1: + case 'simple_graph': + break; + + case 'simple_baseline_graph': + break; + + case 2: + case 'custom_graph': + case 'automatic_custom_graph': + $graph = db_get_value('name', 'tgraph', 'id_graph', $item['id_gs']); + echo '\n"; + break; + + case 3: + case 'SLA': + echo ''.$item['only_display_wrong']."\n"; + echo ''.$item['monday']."\n"; + echo ''.$item['tuesday']."\n"; + echo ''.$item['wednesday']."\n"; + echo ''.$item['thursday']."\n"; + echo ''.$item['friday']."\n"; + echo ''.$item['saturday']."\n"; + echo ''.$item['sunday']."\n"; + echo ''.$item['time_from']."\n"; + echo ''.$item['time_to']."\n"; + + $slas = db_get_all_rows_field_filter('treport_content_sla_combined', 'id_report_content', $item['id_rc']); + if ($slas === false) { + $slas = []; + } + + foreach ($slas as $sla) { + $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $sla['id_agent_module']); + $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $sla['id_agent_module']); + $agent = db_get_value('alias', 'tagente', 'id_agente', $item['id_agent']); + echo ''; + echo '\n"; + echo '\n"; + echo ''.$sla['sla_max']."\n"; + echo ''.$sla['sla_min']."\n"; + echo ''.$sla['sla_limit']."\n"; + echo ''; + } + break; + + case 6: + case 'monitor_report': + break; + + case 7: + case 'avg_value': + break; + + case 8: + case 'max_value': + break; + + case 9: + case 'min_value': + break; + + case 10: + case 'sumatory': + break; + + case 'agent_detailed_event': + case 'event_report_agent': + break; + + case 'text': + echo '\n"; + break; + + case 'sql': + echo '\n"; + if (!empty($item['external_source'])) { + echo '\n"; + } else { + $sql = db_get_value('sql', 'treport_custom_sql', 'id', $item['treport_custom_sql_id']); + echo ''.io_safe_output($sql)."\n"; + } + break; + + case 'sql_graph_pie': + case 'sql_graph_vbar': + case 'sql_graph_hbar': + echo ''.io_safe_output($item['header_definition'])."\n"; + if (!empty($item['external_source'])) { + echo ''.io_safe_output($item['external_source'])."\n"; + } else { + $sql = db_get_value('sql', 'treport_custom_sql', 'id', $item['treport_custom_sql_id']); + echo ''.io_safe_output($sql)."\n"; + } + break; + + case 'event_report_group': + $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $item['id_agent']); + echo '\n"; + break; + + case 'event_report_module': + break; + + case 'alert_report_module': + break; + + case 'alert_report_agent': + break; + + case 'alert_report_group': + break; + + case 'url': + echo ''; + break; + + case 'database_serialized': + echo ''; + echo ''; + echo ''; + break; + + case 'TTRT': + break; + + case 'TTO': + break; + + case 'MTBF': + break; + + case 'MTTR': + break; + } + + echo "\n"; + } + + echo "\n"; } -function output_xml_visual_console($id) { - $visual_map = db_get_row('tlayout', 'id', $id); - - echo '' . "\n"; - echo "\n"; - echo "\n"; - if ($visual_map['id_group'] != 0) { - $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $visual_map['id_group']); - echo "\n"; - } - echo "\n"; - echo "" . io_safe_output($visual_map['height']) . "\n"; - echo "" . io_safe_output($visual_map['width']) . "\n"; - $items = db_get_all_rows_field_filter('tlayout_data', 'id_layout', $visual_map['id']); - if ($items === false) $items = array(); - foreach ($items as $item) { - echo "\n"; - echo "" . $item['id'] . "\n"; //OLD ID USE FOR parent item - $agent = ''; - if ($item['id_agent'] != 0) { - $agent = db_get_value ("nombre","tagente","id_agente",$item['id_agent']); - } - if (!empty($item['label'])) { - echo "\n"; - } - echo "" . $item['pos_x'] . "\n"; - echo "" . $item['pos_y'] . "\n"; - echo "" . $item['type'] . "\n"; - if ($item['width'] != 0) { - echo "" . $item['width'] . "\n"; - } - if ($item['height'] != 0) { - echo "" . $item['height'] . "\n"; - } - if (!empty($item['image'])) { - echo "" . $item['image'] . "\n"; - } - if ($item['period'] != 0) { - echo "" . $item['period'] . "\n"; - } - if (isset($item['id_agente_modulo'])) { - if ($item['id_agente_modulo'] != 0) { - $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $item['id_agente_modulo']); - $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $item['id_agente_modulo']); - $agent = db_get_value ("nombre","tagente","id_agente",$id_agent); - - echo "\n"; - } - } - if (!empty($agent)) { - echo "\n"; - } - if ($item['id_layout_linked'] != 0) { - echo "" . $item['id_layout_linked'] . "\n"; - } - if ($item['parent_item'] != 0) { - echo "" . $item['parent_item'] . "\n"; - } - if (!empty($item['clock_animation'])) { - echo "" . $item['clock_animation'] . "\n"; - } - if (!empty($item['fill_color'])) { - echo "" . $item['fill_color'] . "\n"; - } - if (!empty($item['type_graph'])) { - echo "" . $item['type_graph'] . "\n"; - } - if (!empty($item['time_format'])) { - echo "" . $item['time_format'] . "\n"; - } - if (!empty($item['timezone'])) { - echo "" . $item['timezone'] . "\n"; - } - if (!empty($item['border_width'])) { - echo "" . $item['border_width'] . "\n"; - } - if (!empty($item['border_color'])) { - echo "" . $item['border_color'] . "\n"; - } - echo "\n"; - } - echo "\n"; + +function output_xml_visual_console($id) +{ + $visual_map = db_get_row('tlayout', 'id', $id); + + echo ''."\n"; + echo "\n"; + echo '\n"; + if ($visual_map['id_group'] != 0) { + $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $visual_map['id_group']); + echo '\n"; + } + + echo '\n"; + echo ''.io_safe_output($visual_map['height'])."\n"; + echo ''.io_safe_output($visual_map['width'])."\n"; + $items = db_get_all_rows_field_filter('tlayout_data', 'id_layout', $visual_map['id']); + if ($items === false) { + $items = []; + } + + foreach ($items as $item) { + echo "\n"; + echo ''.$item['id']."\n"; + // OLD ID USE FOR parent item + $agent = ''; + if ($item['id_agent'] != 0) { + $agent = db_get_value('nombre', 'tagente', 'id_agente', $item['id_agent']); + } + + if (!empty($item['label'])) { + echo '\n"; + } + + echo ''.$item['pos_x']."\n"; + echo ''.$item['pos_y']."\n"; + echo ''.$item['type']."\n"; + if ($item['width'] != 0) { + echo ''.$item['width']."\n"; + } + + if ($item['height'] != 0) { + echo ''.$item['height']."\n"; + } + + if (!empty($item['image'])) { + echo ''.$item['image']."\n"; + } + + if ($item['period'] != 0) { + echo ''.$item['period']."\n"; + } + + if (isset($item['id_agente_modulo'])) { + if ($item['id_agente_modulo'] != 0) { + $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $item['id_agente_modulo']); + $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $item['id_agente_modulo']); + $agent = db_get_value('nombre', 'tagente', 'id_agente', $id_agent); + + echo '\n"; + } + } + + if (!empty($agent)) { + echo '\n"; + } + + if ($item['id_layout_linked'] != 0) { + echo ''.$item['id_layout_linked']."\n"; + } + + if ($item['parent_item'] != 0) { + echo ''.$item['parent_item']."\n"; + } + + if (!empty($item['clock_animation'])) { + echo ''.$item['clock_animation']."\n"; + } + + if (!empty($item['fill_color'])) { + echo ''.$item['fill_color']."\n"; + } + + if (!empty($item['type_graph'])) { + echo ''.$item['type_graph']."\n"; + } + + if (!empty($item['time_format'])) { + echo ''.$item['time_format']."\n"; + } + + if (!empty($item['timezone'])) { + echo ''.$item['timezone']."\n"; + } + + if (!empty($item['border_width'])) { + echo ''.$item['border_width']."\n"; + } + + if (!empty($item['border_color'])) { + echo ''.$item['border_color']."\n"; + } + + echo "\n"; + } + + echo "\n"; } -function get_name_xml_resource($hook_enterprise) { - global $config; - - $type = get_parameter('type'); - $id = (int)get_parameter('id'); - - switch ($type) { - case 'report': - $name = db_get_value('name', 'treport', 'id_report', $id); - break; - case 'visual_console': - $name = db_get_value('name', 'tlayout', 'id', $id); - break; - default: - if ($hook_enterprise === true) - return enterprise_get_name_xml_resource($type, $id); - break; - } - - $file = $name . ".ptr"; - - return $file; + +function get_name_xml_resource($hook_enterprise) +{ + global $config; + + $type = get_parameter('type'); + $id = (int) get_parameter('id'); + + switch ($type) { + case 'report': + $name = db_get_value('name', 'treport', 'id_report', $id); + break; + + case 'visual_console': + $name = db_get_value('name', 'tlayout', 'id', $id); + break; + + default: + if ($hook_enterprise === true) { + return enterprise_get_name_xml_resource($type, $id); + } + break; + } + + $file = $name.'.ptr'; + + return $file; } -function get_xml_resource() { - global $config; - - $hook_enterprise = enterprise_include ('extensions/resource_exportation/functions.php'); + +function get_xml_resource() +{ + global $config; + + $hook_enterprise = enterprise_include('extensions/resource_exportation/functions.php'); } -function resource_exportation_extension_main() { - global $config; - - check_login(); - - if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; - } - - $hook_enterprise = enterprise_include ('extensions/resource_exportation/functions.php'); - ui_print_page_header (__('Resource exportation'), "images/extensions.png", false, "", true, "" ); - - echo "
"; - echo __("This extension makes exportation of resource template more easy.") . - " " . - __("You can export resource templates in .ptr format."); - echo "
"; - - echo "

"; - - $table = null; - $table->width = '100%'; - $table->style[0] = 'width: 30%;'; - $table->style[1] = 'width: 10%;'; - $table->class = "databox filters"; - $table->data[0][0] = __('Report'); - $table->data[0][1] = html_print_select_from_sql('SELECT id_report, name FROM treport', 'report', '', '', '', 0, true); - $table->data[0][2] = html_print_button(__('Export'), '', false, 'export_to_ptr(\'report\');', 'class="sub config"', true); - $table->data[1][0] = __('Visual console'); - $table->data[1][1] = html_print_select_from_sql('SELECT id, name FROM tlayout', 'visual_console', '', '', '', 0, true); - $table->data[1][2] = html_print_button(__('Export'), '', false, 'export_to_ptr(\'visual_console\');', 'class="sub config"', true); - - if ($hook_enterprise === true) - add_rows_for_enterprise($table->data); - - html_print_table($table); - - ?> - - '; + echo __('This extension makes exportation of resource template more easy.').' '.__('You can export resource templates in .ptr format.'); + echo ''; + + echo '

'; + + $table = null; + $table->width = '100%'; + $table->style[0] = 'width: 30%;'; + $table->style[1] = 'width: 10%;'; + $table->class = 'databox filters'; + $table->data[0][0] = __('Report'); + $table->data[0][1] = html_print_select_from_sql('SELECT id_report, name FROM treport', 'report', '', '', '', 0, true); + $table->data[0][2] = html_print_button(__('Export'), '', false, 'export_to_ptr(\'report\');', 'class="sub config"', true); + $table->data[1][0] = __('Visual console'); + $table->data[1][1] = html_print_select_from_sql('SELECT id, name FROM tlayout', 'visual_console', '', '', '', 0, true); + $table->data[1][2] = html_print_button(__('Export'), '', false, 'export_to_ptr(\'visual_console\');', 'class="sub config"', true); + + if ($hook_enterprise === true) { + add_rows_for_enterprise($table->data); + } + + html_print_table($table); + + ?> + + + diff --git a/pandora_console/extensions/resource_registration.php b/pandora_console/extensions/resource_registration.php index 61542dee66..92d106d153 100755 --- a/pandora_console/extensions/resource_registration.php +++ b/pandora_console/extensions/resource_registration.php @@ -4,917 +4,1069 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -//Remember the hard-coded values +// Remember the hard-coded values /* --- id_modulo now uses tmodule --- --------------------------- --- 1 - Data server modules (agent related modules) --- 2 - Network server modules --- 4 - Plugin server --- 5 - Predictive server --- 6 - WMI server --- 7 - WEB Server (enteprise) + -- id_modulo now uses tmodule + -- --------------------------- + -- 1 - Data server modules (agent related modules) + -- 2 - Network server modules + -- 4 - Plugin server + -- 5 - Predictive server + -- 6 - WMI server + -- 7 - WEB Server (enteprise) -In the xml is the tag "module_source" + In the xml is the tag "module_source" */ -require_once ($config['homedir'].'/include/functions_agents.php'); +require_once $config['homedir'].'/include/functions_agents.php'; enterprise_include_once('include/functions_local_components.php'); -function insert_item_report($report_id, $values) { - foreach ($report_id as $id => $name) { - $values['id_report'] = $id; - $result = (bool)db_process_sql_insert('treport_content', $values); - - ui_print_result_message($result, - sprintf(__("Success add '%s' item in report '%s'."), $values['type'], $name), - sprintf(__("Error create '%s' item in report '%s'."), $values['type'], $name)); - } + +function insert_item_report($report_id, $values) +{ + foreach ($report_id as $id => $name) { + $values['id_report'] = $id; + $result = (bool) db_process_sql_insert('treport_content', $values); + + ui_print_result_message( + $result, + sprintf(__("Success add '%s' item in report '%s'."), $values['type'], $name), + sprintf(__("Error create '%s' item in report '%s'."), $values['type'], $name) + ); + } } -function process_upload_xml_report($xml, $group_filter = 0) { - foreach ($xml->xpath('/report') as $reportElement) { - - $values = array(); - - if (isset($reportElement->name)) { - $values['name'] = $reportElement->name; - - $posible_name = $values['name']; - $exist = true; - $loops = 30; //Loops to exit or tries - while ($exist && $loops > 0) { - $exist = (bool)db_get_row_filter('treport', array('name' => io_safe_input($posible_name))); - - if ($exist) { - $loops--; - $posible_name = $values['name'] . " (" . (30 - $loops) . ")"; - } - } - - if ($exist) { - ui_print_error_message( - sprintf( - __("Error create '%s' report, the name exist and there aren't free name."), - $reportElement->name)); - break; - } - else if ($loops != 30) { - ui_print_error_message( - sprintf( - __("Warning create '%s' report, the name exist, the report have a name %s."), - $reportElement->name, $posible_name)); - } - - $values['name'] = io_safe_input($posible_name); - } - else { - ui_print_error_message(__("Error the report haven't name.")); - break; - } - - $id_group = db_get_value('id_grupo', 'tgrupo', 'nombre', $reportElement->group); - if ($id_group === false) { - ui_print_error_message(__("Error the report haven't group.")); - break; - } - - if (isset($reportElement->description)) - $values['description'] = $reportElement->description; - - $id_report = db_process_sql_insert ('treport', $values); - - ui_print_result_message($id_report, - sprintf(__("Success create '%s' report."), $posible_name), - sprintf(__("Error create '%s' report."), $posible_name)); - - if ($id_report) { - db_pandora_audit("Report management", "Create report " . $id_report, false, false); - } - else { - db_pandora_audit("Report management", "Fail to create report", false, false); - break; - } - - foreach ($reportElement->item as $item) { - $item = (array)$item; - - $values = array(); - $values['id_report'] = $id_report; - if (isset($item['description'])) - $values['description'] = io_safe_input($item['description']); - if (isset($item['period'])) - $values['period'] = io_safe_input($item['period']); - if (isset($item['type'])) - $values['type'] = io_safe_input($item['type']); - - $agents_item= array(); - if (isset($item['agent'])) { - $agents = agents_get_agents(array('id_grupo' => $group_filter), - array('id_agente', 'nombre')); - - $agent_clean = str_replace(array('[', ']'), '', $item['agent']); - $regular_expresion = ($agent_clean != $item['agent']); - - foreach ($agents as $agent) { - if ($regular_expresion) { - if ((bool)preg_match("/" . $agent_clean . "/", io_safe_output($agent['nombre']))) { - $agents_item[$agent['id_agente']]['name'] = $agent['nombre']; - } - } - else { - if ($agent_clean == io_safe_output($agent['nombre'])) { - $agents_item[$agent['id_agente']]['name'] = $agent['nombre']; - } - } - } - } - if (isset($item['module'])) { - $module_clean = str_replace(array('[', ']'), '', $item['module']); - $regular_expresion = ($module_clean != $item['module']); - - foreach ($agents_item as $id => $agent) { - $modules = db_get_all_rows_filter('tagente_modulo', - array('id_agente' => $id), array('id_agente_modulo', 'nombre')); - - $agents_item[$id]['modules'] = array(); - - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool)preg_match("/" . $module_clean . "/", io_safe_output($module['nombre']))) { - $agents_item[$id]['modules'][$module['id_agente_modulo']]['name'] = - $module['nombre']; - } - } - else { - if ($module_clean == io_safe_output($module['nombre'])) { - $agents_item[$id]['modules'][$module['id_agente_modulo']]['name'] = - $module['nombre']; - } - } - } - } - } - - switch ($item['type']) { - case 1: - case 'simple_graph': - break; - case 'simple_baseline_graph': - break; - case 2: - case 'custom_graph': - case 'automatic_custom_graph': - $group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($item['graph'])); - $values['id_gs'] = $group; - break; - case 3: - case 'SLA': - if (isset($item['only_display_wrong'])) - $values['only_display_wrong'] = (string)$item['only_display_wrong']; - if (isset($item['monday'])) - $values['monday'] = (string)$item['monday']; - if (isset($item['tuesday'])) - $values['tuesday'] = (string)$item['tuesday']; - if (isset($item['wednesday'])) - $values['wednesday'] = (string)$item['wednesday']; - if (isset($item['thursday'])) - $values['thursday'] = (string)$item['thursday']; - if (isset($item['friday'])) - $values['friday'] = (string)$item['friday']; - if (isset($item['saturday'])) - $values['saturday'] = (string)$item['saturday']; - if (isset($item['sunday'])) - $values['sunday'] = (string)$item['sunday']; - if (isset($item['time_from'])) - $values['time_from'] = (string)$item['time_from']; - if (isset($item['time_to'])) - $values['time_to'] = (string)$item['time_to']; - - $slas = array(); - if (!isset($item['sla'])) { - $item['sla'] = array(); - } - foreach ($item['sla'] as $sla_xml) { - if (isset($sla_xml->agent)) { - $agents = agents_get_agents(array('id_grupo' => $group_filter), array('id_agente', 'nombre')); - - $agent_clean = str_replace(array('[', ']'), '', $sla_xml->agent); - $regular_expresion = ($agent_clean != $sla_xml->agent); - - foreach ($agents as $agent) { - $id_agent = false; - if ($regular_expresion) { - if ((bool)preg_match("/" . $agent_clean . "/", io_safe_output($agent['nombre']))) { - $id_agent = $agent['id_agente']; - } - else { - if ($agent_clean == io_safe_output($agent['nombre'])) { - $id_agent = $agent['id_agente']; - } - } - } - - if ($id_agent) { - if (isset($sla_xml->module)) { - $module_clean = str_replace(array('[', ']'), '', $sla_xml->module); - $regular_expresion = ($module_clean != $sla_xml->module); - - $modules = db_get_all_rows_filter('tagente_modulo', - array('id_agente' => $id_agent), array('id_agente_modulo', 'nombre')); - - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool)preg_match("/" . $module_clean . "/", io_safe_output($module['nombre']))) { - $slas[] = array( - 'id_agent_module' => $module['id_agente_modulo'], - 'sla_max' => (string)$sla_xml->sla_max, - 'sla_min' => (string)$sla_xml->sla_min, - 'sla_limit' => (string)$sla_xml->sla_limit - ); - } - } - else { - if ($module_clean == io_safe_output($module['nombre'])) { - $slas[] = array( - 'id_agent_module' => $module['id_agente_modulo'], - 'sla_max' => (string)$sla_xml->sla_max, - 'sla_min' => (string)$sla_xml->sla_min, - 'sla_limit' => (string)$sla_xml->sla_limit - ); - } - } - } - } - } - } - } - } - break; - case 6: - case 'monitor_report': - break; - case 7: - case 'avg_value': - break; - case 8: - case 'max_value': - break; - case 9: - case 'min_value': - break; - case 10: - case 'sumatory': - break; - case 'agent_detailed_event': - case 'event_report_agent': - break; - case 'text': - $values['text'] = io_safe_input($item['text']); - break; - case 'sql': - $values['header_definition'] = io_safe_input($item['header_definition']); - $values['external_source'] = io_safe_input($item['sql']); - break; - case 'sql_graph_pie': - case 'sql_graph_vbar': - case 'sql_graph_hbar': - $values['header_definition'] = io_safe_input($item['header_definition']); - $values['external_source'] = io_safe_input($item['sql']); - break; - case 'event_report_group': - $values['id_agent'] = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($item->group)); - break; - case 'event_report_module': - break; - case 'alert_report_module': - break; - case 'alert_report_agent': - break; - case 'alert_report_group': - break; - case 'url': - $values["external_source"] = io_safe_input($item['url']); - break; - case 'database_serialized': - $values['header_definition'] = io_safe_input($item['header_definition']); - $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)) { - $id_content = db_process_sql_insert ('treport_content', $values); - ui_print_result_message($id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type'])); - - if ($item['type'] == 'SLA') { - foreach ($slas as $sla) { - $sla['id_report_content'] = $id_content; - $result = db_process_sql_insert ('treport_content_sla_combined', $sla); - ui_print_result_message($result, - sprintf(__("Success add '%s' SLA."), $sla['id_agent_module']), - sprintf(__("Error add '%s' SLA."), $sla['id_agent_module'])); - - } - - } - } - else { - foreach ($agents_item as $id_agent => $agent) { - if (empty($agent['modules'])) { - $values['id_agent'] = $id_agent; - $id_content = db_process_sql_insert ('treport_content', $values); - ui_print_result_message($id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type'])); - } - else { - foreach ($agent['modules'] as $id_module => $module) { - $values['id_agent_module'] = $id_module; - $values['id_agent'] = $id_agent; - - $id_content = db_process_sql_insert ('treport_content', $values); - ui_print_result_message($id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type'])); - } - } - } - } - } - } + +function process_upload_xml_report($xml, $group_filter=0) +{ + foreach ($xml->xpath('/report') as $reportElement) { + $values = []; + + if (isset($reportElement->name)) { + $values['name'] = $reportElement->name; + + $posible_name = $values['name']; + $exist = true; + $loops = 30; + // Loops to exit or tries + while ($exist && $loops > 0) { + $exist = (bool) db_get_row_filter('treport', ['name' => io_safe_input($posible_name)]); + + if ($exist) { + $loops--; + $posible_name = $values['name'].' ('.(30 - $loops).')'; + } + } + + if ($exist) { + ui_print_error_message( + sprintf( + __("Error create '%s' report, the name exist and there aren't free name."), + $reportElement->name + ) + ); + break; + } else if ($loops != 30) { + ui_print_error_message( + sprintf( + __("Warning create '%s' report, the name exist, the report have a name %s."), + $reportElement->name, + $posible_name + ) + ); + } + + $values['name'] = io_safe_input($posible_name); + } else { + ui_print_error_message(__("Error the report haven't name.")); + break; + } + + $id_group = db_get_value('id_grupo', 'tgrupo', 'nombre', $reportElement->group); + if ($id_group === false) { + ui_print_error_message(__("Error the report haven't group.")); + break; + } + + if (isset($reportElement->description)) { + $values['description'] = $reportElement->description; + } + + $id_report = db_process_sql_insert('treport', $values); + + ui_print_result_message( + $id_report, + sprintf(__("Success create '%s' report."), $posible_name), + sprintf(__("Error create '%s' report."), $posible_name) + ); + + if ($id_report) { + db_pandora_audit('Report management', 'Create report '.$id_report, false, false); + } else { + db_pandora_audit('Report management', 'Fail to create report', false, false); + break; + } + + foreach ($reportElement->item as $item) { + $item = (array) $item; + + $values = []; + $values['id_report'] = $id_report; + if (isset($item['description'])) { + $values['description'] = io_safe_input($item['description']); + } + + if (isset($item['period'])) { + $values['period'] = io_safe_input($item['period']); + } + + if (isset($item['type'])) { + $values['type'] = io_safe_input($item['type']); + } + + $agents_item = []; + if (isset($item['agent'])) { + $agents = agents_get_agents( + ['id_grupo' => $group_filter], + [ + 'id_agente', + 'nombre', + ] + ); + + $agent_clean = str_replace(['[', ']'], '', $item['agent']); + $regular_expresion = ($agent_clean != $item['agent']); + + foreach ($agents as $agent) { + if ($regular_expresion) { + if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent['nombre']))) { + $agents_item[$agent['id_agente']]['name'] = $agent['nombre']; + } + } else { + if ($agent_clean == io_safe_output($agent['nombre'])) { + $agents_item[$agent['id_agente']]['name'] = $agent['nombre']; + } + } + } + } + + if (isset($item['module'])) { + $module_clean = str_replace(['[', ']'], '', $item['module']); + $regular_expresion = ($module_clean != $item['module']); + + foreach ($agents_item as $id => $agent) { + $modules = db_get_all_rows_filter( + 'tagente_modulo', + ['id_agente' => $id], + [ + 'id_agente_modulo', + 'nombre', + ] + ); + + $agents_item[$id]['modules'] = []; + + foreach ($modules as $module) { + if ($regular_expresion) { + if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { + $agents_item[$id]['modules'][$module['id_agente_modulo']]['name'] = $module['nombre']; + } + } else { + if ($module_clean == io_safe_output($module['nombre'])) { + $agents_item[$id]['modules'][$module['id_agente_modulo']]['name'] = $module['nombre']; + } + } + } + } + } + + switch ($item['type']) { + case 1: + case 'simple_graph': + break; + + case 'simple_baseline_graph': + break; + + case 2: + case 'custom_graph': + case 'automatic_custom_graph': + $group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($item['graph'])); + $values['id_gs'] = $group; + break; + + case 3: + case 'SLA': + if (isset($item['only_display_wrong'])) { + $values['only_display_wrong'] = (string) $item['only_display_wrong']; + } + + if (isset($item['monday'])) { + $values['monday'] = (string) $item['monday']; + } + + if (isset($item['tuesday'])) { + $values['tuesday'] = (string) $item['tuesday']; + } + + if (isset($item['wednesday'])) { + $values['wednesday'] = (string) $item['wednesday']; + } + + if (isset($item['thursday'])) { + $values['thursday'] = (string) $item['thursday']; + } + + if (isset($item['friday'])) { + $values['friday'] = (string) $item['friday']; + } + + if (isset($item['saturday'])) { + $values['saturday'] = (string) $item['saturday']; + } + + if (isset($item['sunday'])) { + $values['sunday'] = (string) $item['sunday']; + } + + if (isset($item['time_from'])) { + $values['time_from'] = (string) $item['time_from']; + } + + if (isset($item['time_to'])) { + $values['time_to'] = (string) $item['time_to']; + } + + $slas = []; + if (!isset($item['sla'])) { + $item['sla'] = []; + } + + foreach ($item['sla'] as $sla_xml) { + if (isset($sla_xml->agent)) { + $agents = agents_get_agents(['id_grupo' => $group_filter], ['id_agente', 'nombre']); + + $agent_clean = str_replace(['[', ']'], '', $sla_xml->agent); + $regular_expresion = ($agent_clean != $sla_xml->agent); + + foreach ($agents as $agent) { + $id_agent = false; + if ($regular_expresion) { + if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent['nombre']))) { + $id_agent = $agent['id_agente']; + } else { + if ($agent_clean == io_safe_output($agent['nombre'])) { + $id_agent = $agent['id_agente']; + } + } + } + + if ($id_agent) { + if (isset($sla_xml->module)) { + $module_clean = str_replace(['[', ']'], '', $sla_xml->module); + $regular_expresion = ($module_clean != $sla_xml->module); + + $modules = db_get_all_rows_filter( + 'tagente_modulo', + ['id_agente' => $id_agent], + [ + 'id_agente_modulo', + 'nombre', + ] + ); + + foreach ($modules as $module) { + if ($regular_expresion) { + if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { + $slas[] = [ + 'id_agent_module' => $module['id_agente_modulo'], + 'sla_max' => (string) $sla_xml->sla_max, + 'sla_min' => (string) $sla_xml->sla_min, + 'sla_limit' => (string) $sla_xml->sla_limit, + ]; + } + } else { + if ($module_clean == io_safe_output($module['nombre'])) { + $slas[] = [ + 'id_agent_module' => $module['id_agente_modulo'], + 'sla_max' => (string) $sla_xml->sla_max, + 'sla_min' => (string) $sla_xml->sla_min, + 'sla_limit' => (string) $sla_xml->sla_limit, + ]; + } + } + } + } + } + } + } + } + break; + + case 6: + case 'monitor_report': + break; + + case 7: + case 'avg_value': + break; + + case 8: + case 'max_value': + break; + + case 9: + case 'min_value': + break; + + case 10: + case 'sumatory': + break; + + case 'agent_detailed_event': + case 'event_report_agent': + break; + + case 'text': + $values['text'] = io_safe_input($item['text']); + break; + + case 'sql': + $values['header_definition'] = io_safe_input($item['header_definition']); + $values['external_source'] = io_safe_input($item['sql']); + break; + + case 'sql_graph_pie': + case 'sql_graph_vbar': + case 'sql_graph_hbar': + $values['header_definition'] = io_safe_input($item['header_definition']); + $values['external_source'] = io_safe_input($item['sql']); + break; + + case 'event_report_group': + $values['id_agent'] = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($item->group)); + break; + + case 'event_report_module': + break; + + case 'alert_report_module': + break; + + case 'alert_report_agent': + break; + + case 'alert_report_group': + break; + + case 'url': + $values['external_source'] = io_safe_input($item['url']); + break; + + case 'database_serialized': + $values['header_definition'] = io_safe_input($item['header_definition']); + $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)) { + $id_content = db_process_sql_insert('treport_content', $values); + ui_print_result_message( + $id_content, + sprintf(__("Success add '%s' content."), $values['type']), + sprintf(__("Error add '%s' action."), $values['type']) + ); + + if ($item['type'] == 'SLA') { + foreach ($slas as $sla) { + $sla['id_report_content'] = $id_content; + $result = db_process_sql_insert('treport_content_sla_combined', $sla); + ui_print_result_message( + $result, + sprintf(__("Success add '%s' SLA."), $sla['id_agent_module']), + sprintf(__("Error add '%s' SLA."), $sla['id_agent_module']) + ); + } + } + } else { + foreach ($agents_item as $id_agent => $agent) { + if (empty($agent['modules'])) { + $values['id_agent'] = $id_agent; + $id_content = db_process_sql_insert('treport_content', $values); + ui_print_result_message( + $id_content, + sprintf(__("Success add '%s' content."), $values['type']), + sprintf(__("Error add '%s' action."), $values['type']) + ); + } else { + foreach ($agent['modules'] as $id_module => $module) { + $values['id_agent_module'] = $id_module; + $values['id_agent'] = $id_agent; + + $id_content = db_process_sql_insert('treport_content', $values); + ui_print_result_message( + $id_content, + sprintf(__("Success add '%s' content."), $values['type']), + sprintf(__("Error add '%s' action."), $values['type']) + ); + } + } + } + } + } + } } -function process_upload_xml_visualmap($xml, $filter_group = 0) { - global $config; - - foreach ($xml->xpath('/visual_map') as $visual_map) { - if (isset($visual_map->name)) { - $values['name'] = (string)$visual_map->name; - } - else { - ui_print_error_message( - __("Error create '%s' visual map, lost tag name.")); - break; - } - - $values['id_group'] = 0; - if (isset($visual_map->group)) { - $id_group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($visual_map->group)); - if ($id_group !== false) $values['id_group'] = $id_group; - } - - if (isset($visual_map->background)) - $values['background'] = (string)$visual_map->background; - - $values['width'] = 0; - if (isset($visual_map->width)) - $values['width'] = (string)$visual_map->width; - - $values['height'] = 0; - if (isset($visual_map->height)) - $values['height'] = (string)$visual_map->height; - - $posible_name = $values['name']; - $exist = true; - $loops = 30; //Loops to exit or tries - while ($exist && $loops > 0) { - $exist = (bool)db_get_row_filter('tlayout', array('name' => io_safe_input($posible_name))); - - if ($exist) { - $loops--; - $posible_name = $values['name'] . " (" . (30 - $loops) . ")"; - } - } - - if ($exist) { - ui_print_error_message( - sprintf( - __("Error create '%s' visual map, the name exist and there aren't free name."), - $values['name'])); - continue; - } - else if ($loops != 30) { - ui_print_error_message( - sprintf( - __("Warning create '%s' visual map, the name exist, the report have a name %s."), - $values['name'], $posible_name)); - } - - $values['name'] = io_safe_input($posible_name); - $id_visual_map = db_process_sql_insert('tlayout', $values); - - ui_print_result_message((bool)$id_visual_map, - sprintf(__("Success create '%s' visual map."), $posible_name), - sprintf(__("Error create '%s' visual map."), $posible_name)); - - if ($id_visual_map !== false) { - db_pandora_audit('CREATE VISUAL CONSOLE', $id_visual_map, $config['id_user']); - } - else { - break; - } - - $relation_other_ids = array(); - - foreach ($visual_map->item as $item) { - $no_agents = true; - - if (isset($item->agent)) { - $agent_clean = str_replace(array('[', ']'), '', $item->agent); - $regular_expresion = ($agent_clean != $item->agent); - - $agents = agents_get_agents(array('id_grupo' => $filter_group), array('id_agente', 'nombre')); - if ($agents === false) $agents = array(); - $temp = array(); - foreach ($agents as $agent) { - $temp[$agent['id_agente']] = $agent['nombre']; - } - $agents = $temp; - - $agents_in_item = array(); - foreach ($agents as $id => $agent) { - if ($regular_expresion) { - if ((bool)preg_match("/" . $agent_clean . "/", io_safe_output($agent))) { - $agents_in_item[$id]['name'] = $agent; - $no_agents = false; - } - } - else { - if ($agent_clean == io_safe_output($agent)) { - $agents_in_item[$id]['name'] = $agent; - $no_agents = false; - break; - } - } - } - } - - $no_modules = true; - if (isset($item->module)) { - $module_clean = str_replace(array('[', ']'), '', $item->module); - $regular_expresion = ($module_clean != $item->module); - - foreach ($agents_in_item as $id => $agent) { - $modules = db_get_all_rows_filter('tagente_modulo', - array('id_agente' => $id), array('id_agente_modulo', 'nombre')); - - $modules_in_item = array(); - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool)preg_match("/" . $module_clean . "/", io_safe_output($module['nombre']))) { - $modules_in_item[$module['id_agente_modulo']] = $module['nombre']; - $no_modules = false; - } - } - else { - if ($module_clean == io_safe_output($module['nombre'])) { - $modules_in_item[$module['id_agente_modulo']] = $module['nombre']; - $no_modules = false; - break; - } - } - } - - $agents_in_item[$id]['modules'] = $modules_in_item; - } - } - - $values = array(); - - $values['id_layout'] = $id_visual_map; - if (isset($item->label)) - $values['label'] = io_safe_input($item->label); - if (isset($item->x)) - $values['pos_x'] = (string)$item->x; - if (isset($item->y)) - $values['pos_y'] = (string)$item->y; - if (isset($item->height)) - $values['height'] = (string)$item->height; - if (isset($item->width)) - $values['width'] = (string)$item->width; - if (isset($item->image)) - $values['image'] = (string)$item->image; - if (isset($item->period)) - $values['period'] = (string)$item->period; - if (isset($item->parent_item)) { - //Hack for link the items use the OTHER_ID - // and have too OTHER_ID - // then $relation_other_ids[OTHER_ID] have the item_id in DB. - $values['parent_item'] = (string)$relation_other_ids[(string)$item->parent_item]; - } - if (isset($item->map_linked)) - $values['id_layout_linked'] = (string)$item->map_linked; - if (isset($item->type)) - $values['type'] = (string)$item->type; - - if (isset($item->clock_animation)) { - $values['clock_animation'] = (string)$item->clock_animation; - } - - if (isset($item->fill_color)) { - $values['fill_color'] = (string)$item->fill_color; - } - - if (isset($item->type_graph)) { - $values['type_graph'] = (string)$item->type_graph; - } - - if (isset($item->time_format)) { - $values['time_format'] = (string)$item->time_format; - } - - if (isset($item->timezone)) { - $values['timezone'] = (string)$item->timezone; - } - - if (isset($item->border_width)) { - $values['border_width'] = (string)$item->border_width; - } - - if (isset($item->border_color)) { - $values['border_color'] = (string)$item->border_color; - } - - if ($no_agents) { - $id_item = db_process_sql_insert('tlayout_data', $values); - - ui_print_result_message((bool)$id_item, - sprintf(__("Success create item type '%d' visual map."), $values['type']), - sprintf(__("Error create item type '%d' visual map."), $values['type'])); - - if ($id_item !== false) { - db_pandora_audit('CREATE ITEM VISUAL CONSOLE', $values['id_layout'] . " - " . $id_item, $config['id_user']); - } - } - else { - foreach ($agents_in_item as $id => $agent) { - if ($no_modules) { - $values['id_agent'] = $id; - - $id_item = db_process_sql_insert('tlayout_data', $values); - - if (isset($item->other_id)) { - $relation_other_ids[(string)$item->other_id] = $id_item; - } - - ui_print_result_message((bool)$id_item, - sprintf(__("Success create item for agent '%s' visual map."), $agent['name']), - sprintf(__("Error create item for agent '%s' visual map."), $agent['name'])); - - if ($id_item !== false) { - db_pandora_audit('CREATE ITEM VISUAL CONSOLE', $values['id_layout'] . " - " . $id_item, $config['id_user']); - } - } - else { - foreach ($agent['modules'] as $id_module => $module) { - $values['id_agent'] = $id; - $values['id_agente_modulo'] = $id_module; - - db_process_sql_insert('tlayout_data', $values); - - ui_print_result_message((bool)$id_item, - sprintf(__("Success create item for agent '%s' visual map."), $agent['name']), - sprintf(__("Error create item for agent '%s' visual map."), $agent['name'])); - - if ($id_item !== false) { - db_pandora_audit('CREATE ITEM VISUAL CONSOLE', $values['id_layout'] . " - " . $id_item, $config['id_user']); - } - } - } - } - } - } - } + +function process_upload_xml_visualmap($xml, $filter_group=0) +{ + global $config; + + foreach ($xml->xpath('/visual_map') as $visual_map) { + if (isset($visual_map->name)) { + $values['name'] = (string) $visual_map->name; + } else { + ui_print_error_message( + __("Error create '%s' visual map, lost tag name.") + ); + break; + } + + $values['id_group'] = 0; + if (isset($visual_map->group)) { + $id_group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($visual_map->group)); + if ($id_group !== false) { + $values['id_group'] = $id_group; + } + } + + if (isset($visual_map->background)) { + $values['background'] = (string) $visual_map->background; + } + + $values['width'] = 0; + if (isset($visual_map->width)) { + $values['width'] = (string) $visual_map->width; + } + + $values['height'] = 0; + if (isset($visual_map->height)) { + $values['height'] = (string) $visual_map->height; + } + + $posible_name = $values['name']; + $exist = true; + $loops = 30; + // Loops to exit or tries + while ($exist && $loops > 0) { + $exist = (bool) db_get_row_filter('tlayout', ['name' => io_safe_input($posible_name)]); + + if ($exist) { + $loops--; + $posible_name = $values['name'].' ('.(30 - $loops).')'; + } + } + + if ($exist) { + ui_print_error_message( + sprintf( + __("Error create '%s' visual map, the name exist and there aren't free name."), + $values['name'] + ) + ); + continue; + } else if ($loops != 30) { + ui_print_error_message( + sprintf( + __("Warning create '%s' visual map, the name exist, the report have a name %s."), + $values['name'], + $posible_name + ) + ); + } + + $values['name'] = io_safe_input($posible_name); + $id_visual_map = db_process_sql_insert('tlayout', $values); + + ui_print_result_message( + (bool) $id_visual_map, + sprintf(__("Success create '%s' visual map."), $posible_name), + sprintf(__("Error create '%s' visual map."), $posible_name) + ); + + if ($id_visual_map !== false) { + db_pandora_audit('CREATE VISUAL CONSOLE', $id_visual_map, $config['id_user']); + } else { + break; + } + + $relation_other_ids = []; + + foreach ($visual_map->item as $item) { + $no_agents = true; + + if (isset($item->agent)) { + $agent_clean = str_replace(['[', ']'], '', $item->agent); + $regular_expresion = ($agent_clean != $item->agent); + + $agents = agents_get_agents(['id_grupo' => $filter_group], ['id_agente', 'nombre']); + if ($agents === false) { + $agents = []; + } + + $temp = []; + foreach ($agents as $agent) { + $temp[$agent['id_agente']] = $agent['nombre']; + } + + $agents = $temp; + + $agents_in_item = []; + foreach ($agents as $id => $agent) { + if ($regular_expresion) { + if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent))) { + $agents_in_item[$id]['name'] = $agent; + $no_agents = false; + } + } else { + if ($agent_clean == io_safe_output($agent)) { + $agents_in_item[$id]['name'] = $agent; + $no_agents = false; + break; + } + } + } + } + + $no_modules = true; + if (isset($item->module)) { + $module_clean = str_replace(['[', ']'], '', $item->module); + $regular_expresion = ($module_clean != $item->module); + + foreach ($agents_in_item as $id => $agent) { + $modules = db_get_all_rows_filter( + 'tagente_modulo', + ['id_agente' => $id], + [ + 'id_agente_modulo', + 'nombre', + ] + ); + + $modules_in_item = []; + foreach ($modules as $module) { + if ($regular_expresion) { + if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { + $modules_in_item[$module['id_agente_modulo']] = $module['nombre']; + $no_modules = false; + } + } else { + if ($module_clean == io_safe_output($module['nombre'])) { + $modules_in_item[$module['id_agente_modulo']] = $module['nombre']; + $no_modules = false; + break; + } + } + } + + $agents_in_item[$id]['modules'] = $modules_in_item; + } + } + + $values = []; + + $values['id_layout'] = $id_visual_map; + if (isset($item->label)) { + $values['label'] = io_safe_input($item->label); + } + + if (isset($item->x)) { + $values['pos_x'] = (string) $item->x; + } + + if (isset($item->y)) { + $values['pos_y'] = (string) $item->y; + } + + if (isset($item->height)) { + $values['height'] = (string) $item->height; + } + + if (isset($item->width)) { + $values['width'] = (string) $item->width; + } + + if (isset($item->image)) { + $values['image'] = (string) $item->image; + } + + if (isset($item->period)) { + $values['period'] = (string) $item->period; + } + + if (isset($item->parent_item)) { + // Hack for link the items use the OTHER_ID + // and have too OTHER_ID + // then $relation_other_ids[OTHER_ID] have the item_id in DB. + $values['parent_item'] = (string) $relation_other_ids[(string) $item->parent_item]; + } + + if (isset($item->map_linked)) { + $values['id_layout_linked'] = (string) $item->map_linked; + } + + if (isset($item->type)) { + $values['type'] = (string) $item->type; + } + + if (isset($item->clock_animation)) { + $values['clock_animation'] = (string) $item->clock_animation; + } + + if (isset($item->fill_color)) { + $values['fill_color'] = (string) $item->fill_color; + } + + if (isset($item->type_graph)) { + $values['type_graph'] = (string) $item->type_graph; + } + + if (isset($item->time_format)) { + $values['time_format'] = (string) $item->time_format; + } + + if (isset($item->timezone)) { + $values['timezone'] = (string) $item->timezone; + } + + if (isset($item->border_width)) { + $values['border_width'] = (string) $item->border_width; + } + + if (isset($item->border_color)) { + $values['border_color'] = (string) $item->border_color; + } + + if ($no_agents) { + $id_item = db_process_sql_insert('tlayout_data', $values); + + ui_print_result_message( + (bool) $id_item, + sprintf(__("Success create item type '%d' visual map."), $values['type']), + sprintf(__("Error create item type '%d' visual map."), $values['type']) + ); + + if ($id_item !== false) { + db_pandora_audit('CREATE ITEM VISUAL CONSOLE', $values['id_layout'].' - '.$id_item, $config['id_user']); + } + } else { + foreach ($agents_in_item as $id => $agent) { + if ($no_modules) { + $values['id_agent'] = $id; + + $id_item = db_process_sql_insert('tlayout_data', $values); + + if (isset($item->other_id)) { + $relation_other_ids[(string) $item->other_id] = $id_item; + } + + ui_print_result_message( + (bool) $id_item, + sprintf(__("Success create item for agent '%s' visual map."), $agent['name']), + sprintf(__("Error create item for agent '%s' visual map."), $agent['name']) + ); + + if ($id_item !== false) { + db_pandora_audit('CREATE ITEM VISUAL CONSOLE', $values['id_layout'].' - '.$id_item, $config['id_user']); + } + } else { + foreach ($agent['modules'] as $id_module => $module) { + $values['id_agent'] = $id; + $values['id_agente_modulo'] = $id_module; + + db_process_sql_insert('tlayout_data', $values); + + ui_print_result_message( + (bool) $id_item, + sprintf(__("Success create item for agent '%s' visual map."), $agent['name']), + sprintf(__("Error create item for agent '%s' visual map."), $agent['name']) + ); + + if ($id_item !== false) { + db_pandora_audit('CREATE ITEM VISUAL CONSOLE', $values['id_layout'].' - '.$id_item, $config['id_user']); + } + } + } + } + } + } + } } -function process_upload_xml_component($xml) { - //Extract components - $components = array(); - foreach ($xml->xpath('/component') as $componentElement) { - $name = io_safe_input((string)$componentElement->name); - $id_os = (int)$componentElement->id_os; - $os_version = io_safe_input((string)$componentElement->os_version); - $data = io_safe_input((string)$componentElement->data); - $type = (int)$componentElement->type; - $group = (int)$componentElement->group; - $description = io_safe_input((string)$componentElement->description); - $module_interval = (int)$componentElement->module_interval; - $max = (float)$componentElement->max; - $min = (float)$componentElement->min; - $tcp_send = io_safe_input((string)$componentElement->tcp_send); - $tcp_rcv_text = io_safe_input((string)$componentElement->tcp_rcv_text); - $tcp_port = (int)$componentElement->tcp_port; - $snmp_oid = io_safe_input((string)$componentElement->snmp_oid); - $snmp_community = io_safe_input((string)$componentElement->snmp_community); - $id_module_group = (int)$componentElement->id_module_group; - $module_source = (int)$componentElement->module_source; - $plugin = (int)$componentElement->plugin; - $plugin_username = io_safe_input((string)$componentElement->plugin_username); - $plugin_password = io_safe_input((string)$componentElement->plugin_password); - $plugin_parameters = io_safe_input((string)$componentElement->plugin_parameters); - $max_timeout = (int)$componentElement->max_timeout; - $max_retries = (int)$componentElement->max_retries; - $historical_data = (int)$componentElement->historical_data; - $dynamic_interval = (int)$componentElement->dynamic_interval; - $dynamic_min = (int)$componentElement->dynamic_min; - $dynamic_max = (int)$componentElement->dynamic_max; - $dynamic_two_tailed = (int)$componentElement->dynamic_two_tailed; - $min_war = (float)$componentElement->min_war; - $max_war = (float)$componentElement->max_war; - $str_war = (string)$componentElement->str_war; - $min_cri = (float)$componentElement->min_cri; - $max_cri = (float)$componentElement->max_cri; - $str_cri = (string)$componentElement->str_cri; - $ff_treshold = (int)$componentElement->ff_treshold; - $snmp_version = (int)$componentElement->snmp_version; - $auth_user = io_safe_input((string)$componentElement->auth_user); - $auth_password = io_safe_input((string)$componentElement->auth_password); - $auth_method = io_safe_input((string)$componentElement->auth_method); - $privacy_method = io_safe_input((string)$componentElement->privacy_method); - $privacy_pass = io_safe_input((string)$componentElement->privacy_pass); - $security_level = io_safe_input((string)$componentElement->security_level); - $wmi_query = io_safe_input((string)$componentElement->wmi_query); - $key_string = io_safe_input((string)$componentElement->key_string); - $field_number = (int)$componentElement->field_number; - $namespace = io_safe_input((string)$componentElement->namespace); - $wmi_user = io_safe_input((string)$componentElement->wmi_user); - $wmi_password = io_safe_input((string)$componentElement->wmi_password); - $post_process = io_safe_input((float)$componentElement->post_process); - - $idComponent = false; - switch ((int)$componentElement->module_source) { - case 1: //Local component - $values = array('description' => $description, - 'id_network_component_group' => $group, - 'os_version' => $os_version); - $return = enterprise_hook('local_components_create_local_component', array($name, $data, $id_os, $values)); - if ($return !== ENTERPRISE_NOT_HOOK) { - $idComponent = $return; - } - break; - case 2: //Network component - - //for modules - //15 = remote_snmp, 16 = remote_snmp_inc, - //17 = remote_snmp_string, 18 = remote_snmp_proc - $custom_string_1 = ''; - $custom_string_2 = ''; - $custom_string_3 = ''; - if ($type >= 15 && $type <= 18) { - // New support for snmp v3 - $tcp_send = $snmp_version; - $plugin_user = $auth_user; - $plugin_pass = $auth_password; - $plugin_parameters = $auth_method; - $custom_string_1 = $privacy_method; - $custom_string_2 = $privacy_pass; - $custom_string_3 = $security_level; - } - - $idComponent = network_components_create_network_component ($name, - $type, $group, - array ('description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $tcp_send, - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $tcp_port, - 'snmp_oid' => $snmp_oid, - 'snmp_community' => $snmp_community, - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $plugin_username, - 'plugin_pass' => $plugin_password, - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process)); - if ((bool)$idComponent) { - $components[] = $idComponent; - } - break; - case 4: //Plugin component - $idComponent = network_components_create_network_component ($name, - $type, $group, - array ('description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $tcp_send, - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $tcp_port, - 'snmp_oid' => $snmp_oid, - 'snmp_community' => $snmp_community, - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $plugin_username, - 'plugin_pass' => $plugin_password, - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process)); - if ((bool)$idComponent) { - $components[] = $idComponent; - } - break; - case 5: //Prediction component - break; - case 6: //WMI component - $idComponent = network_components_create_network_component ($name, - $type, $group, - array ('description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $namespace, //work around - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $field_number, //work around - 'snmp_oid' => $wmi_query, //work around - 'snmp_community' => $key_string, //work around - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $wmi_user, //work around - 'plugin_pass' => $wmi_password, //work around - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process)); - if ((bool)$idComponent) { - $components[] = $idComponent; - } - break; - case 7: //Web component - break; - } - - ui_print_result_message((bool)$idComponent, sprintf(__("Success create '%s' component."), $name), - sprintf(__("Error create '%s' component."), $name)); - } - - //Extract the template - $templateElement = $xml->xpath('//template'); - if (!empty($templateElement)) { - $templateElement = $templateElement[0]; - - $templateName = (string)$templateElement->name; - $templateDescription = (string)$templateElement->description; - - $idTemplate = db_process_sql_insert('tnetwork_profile', array('name' => $templateName, 'description' => $templateDescription)); - - $result = false; - if ((bool)$idTemplate) { - foreach ($components as $idComponent) { - db_process_sql_insert("tnetwork_profile_component", array('id_nc' => $idComponent, 'id_np' => $idTemplate)); - } - } - } + +function process_upload_xml_component($xml) +{ + // Extract components + $components = []; + foreach ($xml->xpath('/component') as $componentElement) { + $name = io_safe_input((string) $componentElement->name); + $id_os = (int) $componentElement->id_os; + $os_version = io_safe_input((string) $componentElement->os_version); + $data = io_safe_input((string) $componentElement->data); + $type = (int) $componentElement->type; + $group = (int) $componentElement->group; + $description = io_safe_input((string) $componentElement->description); + $module_interval = (int) $componentElement->module_interval; + $max = (float) $componentElement->max; + $min = (float) $componentElement->min; + $tcp_send = io_safe_input((string) $componentElement->tcp_send); + $tcp_rcv_text = io_safe_input((string) $componentElement->tcp_rcv_text); + $tcp_port = (int) $componentElement->tcp_port; + $snmp_oid = io_safe_input((string) $componentElement->snmp_oid); + $snmp_community = io_safe_input((string) $componentElement->snmp_community); + $id_module_group = (int) $componentElement->id_module_group; + $module_source = (int) $componentElement->module_source; + $plugin = (int) $componentElement->plugin; + $plugin_username = io_safe_input((string) $componentElement->plugin_username); + $plugin_password = io_safe_input((string) $componentElement->plugin_password); + $plugin_parameters = io_safe_input((string) $componentElement->plugin_parameters); + $max_timeout = (int) $componentElement->max_timeout; + $max_retries = (int) $componentElement->max_retries; + $historical_data = (int) $componentElement->historical_data; + $dynamic_interval = (int) $componentElement->dynamic_interval; + $dynamic_min = (int) $componentElement->dynamic_min; + $dynamic_max = (int) $componentElement->dynamic_max; + $dynamic_two_tailed = (int) $componentElement->dynamic_two_tailed; + $min_war = (float) $componentElement->min_war; + $max_war = (float) $componentElement->max_war; + $str_war = (string) $componentElement->str_war; + $min_cri = (float) $componentElement->min_cri; + $max_cri = (float) $componentElement->max_cri; + $str_cri = (string) $componentElement->str_cri; + $ff_treshold = (int) $componentElement->ff_treshold; + $snmp_version = (int) $componentElement->snmp_version; + $auth_user = io_safe_input((string) $componentElement->auth_user); + $auth_password = io_safe_input((string) $componentElement->auth_password); + $auth_method = io_safe_input((string) $componentElement->auth_method); + $privacy_method = io_safe_input((string) $componentElement->privacy_method); + $privacy_pass = io_safe_input((string) $componentElement->privacy_pass); + $security_level = io_safe_input((string) $componentElement->security_level); + $wmi_query = io_safe_input((string) $componentElement->wmi_query); + $key_string = io_safe_input((string) $componentElement->key_string); + $field_number = (int) $componentElement->field_number; + $namespace = io_safe_input((string) $componentElement->namespace); + $wmi_user = io_safe_input((string) $componentElement->wmi_user); + $wmi_password = io_safe_input((string) $componentElement->wmi_password); + $post_process = io_safe_input((float) $componentElement->post_process); + + $idComponent = false; + switch ((int) $componentElement->module_source) { + case 1: + // Local component + $values = [ + 'description' => $description, + 'id_network_component_group' => $group, + 'os_version' => $os_version, + ]; + $return = enterprise_hook('local_components_create_local_component', [$name, $data, $id_os, $values]); + if ($return !== ENTERPRISE_NOT_HOOK) { + $idComponent = $return; + } + break; + + case 2: + // Network component + // for modules + // 15 = remote_snmp, 16 = remote_snmp_inc, + // 17 = remote_snmp_string, 18 = remote_snmp_proc + $custom_string_1 = ''; + $custom_string_2 = ''; + $custom_string_3 = ''; + if ($type >= 15 && $type <= 18) { + // New support for snmp v3 + $tcp_send = $snmp_version; + $plugin_user = $auth_user; + $plugin_pass = $auth_password; + $plugin_parameters = $auth_method; + $custom_string_1 = $privacy_method; + $custom_string_2 = $privacy_pass; + $custom_string_3 = $security_level; + } + + $idComponent = network_components_create_network_component( + $name, + $type, + $group, + [ + 'description' => $description, + 'module_interval' => $module_interval, + 'max' => $max, + 'min' => $min, + 'tcp_send' => $tcp_send, + 'tcp_rcv' => $tcp_rcv_text, + 'tcp_port' => $tcp_port, + 'snmp_oid' => $snmp_oid, + 'snmp_community' => $snmp_community, + 'id_module_group' => $id_module_group, + 'id_modulo' => $module_source, + 'id_plugin' => $plugin, + 'plugin_user' => $plugin_username, + 'plugin_pass' => $plugin_password, + 'plugin_parameter' => $plugin_parameters, + 'max_timeout' => $max_timeout, + 'max_retries' => $max_retries, + 'history_data' => $historical_data, + 'dynamic_interval' => $dynamic_interval, + 'dynamic_min' => $dynamic_min, + 'dynamic_max' => $dynamic_max, + 'dynamic_two_tailed' => $dynamic_two_tailed, + 'min_warning' => $min_war, + 'max_warning' => $max_war, + 'str_warning' => $str_war, + 'min_critical' => $min_cri, + 'max_critical' => $max_cri, + 'str_critical' => $str_cri, + 'min_ff_event' => $ff_treshold, + 'custom_string_1' => $custom_string_1, + 'custom_string_2' => $custom_string_2, + 'custom_string_3' => $custom_string_3, + 'post_process' => $post_process, + ] + ); + if ((bool) $idComponent) { + $components[] = $idComponent; + } + break; + + case 4: + // Plugin component + $idComponent = network_components_create_network_component( + $name, + $type, + $group, + [ + 'description' => $description, + 'module_interval' => $module_interval, + 'max' => $max, + 'min' => $min, + 'tcp_send' => $tcp_send, + 'tcp_rcv' => $tcp_rcv_text, + 'tcp_port' => $tcp_port, + 'snmp_oid' => $snmp_oid, + 'snmp_community' => $snmp_community, + 'id_module_group' => $id_module_group, + 'id_modulo' => $module_source, + 'id_plugin' => $plugin, + 'plugin_user' => $plugin_username, + 'plugin_pass' => $plugin_password, + 'plugin_parameter' => $plugin_parameters, + 'max_timeout' => $max_timeout, + 'max_retries' => $max_retries, + 'history_data' => $historical_data, + 'dynamic_interval' => $dynamic_interval, + 'dynamic_min' => $dynamic_min, + 'dynamic_max' => $dynamic_max, + 'dynamic_two_tailed' => $dynamic_two_tailed, + 'min_warning' => $min_war, + 'max_warning' => $max_war, + 'str_warning' => $str_war, + 'min_critical' => $min_cri, + 'max_critical' => $max_cri, + 'str_critical' => $str_cri, + 'min_ff_event' => $ff_treshold, + 'custom_string_1' => $custom_string_1, + 'custom_string_2' => $custom_string_2, + 'custom_string_3' => $custom_string_3, + 'post_process' => $post_process, + ] + ); + if ((bool) $idComponent) { + $components[] = $idComponent; + } + break; + + case 5: + // Prediction component + break; + + case 6: + // WMI component + $idComponent = network_components_create_network_component( + $name, + $type, + $group, + [ + 'description' => $description, + 'module_interval' => $module_interval, + 'max' => $max, + 'min' => $min, + 'tcp_send' => $namespace, + // work around + 'tcp_rcv' => $tcp_rcv_text, + 'tcp_port' => $field_number, + // work around + 'snmp_oid' => $wmi_query, + // work around + 'snmp_community' => $key_string, + // work around + 'id_module_group' => $id_module_group, + 'id_modulo' => $module_source, + 'id_plugin' => $plugin, + 'plugin_user' => $wmi_user, + // work around + 'plugin_pass' => $wmi_password, + // work around + 'plugin_parameter' => $plugin_parameters, + 'max_timeout' => $max_timeout, + 'max_retries' => $max_retries, + 'history_data' => $historical_data, + 'dynamic_interval' => $dynamic_interval, + 'dynamic_min' => $dynamic_min, + 'dynamic_max' => $dynamic_max, + 'dynamic_two_tailed' => $dynamic_two_tailed, + 'min_warning' => $min_war, + 'max_warning' => $max_war, + 'str_warning' => $str_war, + 'min_critical' => $min_cri, + 'max_critical' => $max_cri, + 'str_critical' => $str_cri, + 'min_ff_event' => $ff_treshold, + 'custom_string_1' => $custom_string_1, + 'custom_string_2' => $custom_string_2, + 'custom_string_3' => $custom_string_3, + 'post_process' => $post_process, + ] + ); + if ((bool) $idComponent) { + $components[] = $idComponent; + } + break; + + case 7: + // Web component + break; + } + + ui_print_result_message( + (bool) $idComponent, + sprintf(__("Success create '%s' component."), $name), + sprintf(__("Error create '%s' component."), $name) + ); + } + + // Extract the template + $templateElement = $xml->xpath('//template'); + if (!empty($templateElement)) { + $templateElement = $templateElement[0]; + + $templateName = (string) $templateElement->name; + $templateDescription = (string) $templateElement->description; + + $idTemplate = db_process_sql_insert('tnetwork_profile', ['name' => $templateName, 'description' => $templateDescription]); + + $result = false; + if ((bool) $idTemplate) { + foreach ($components as $idComponent) { + db_process_sql_insert('tnetwork_profile_component', ['id_nc' => $idComponent, 'id_np' => $idTemplate]); + } + } + } } -function process_upload_xml($xml) { - $hook_enterprise = enterprise_include ('extensions/resource_registration/functions.php'); - - //Extract component - process_upload_xml_component($xml); - - $group_filter = get_parameter('group'); - - //Extract visual map - process_upload_xml_visualmap($xml, $group_filter); - - - //Extract policies - if ($hook_enterprise === true) - process_upload_xml_policy($xml, $group_filter); - - - //Extract reports - process_upload_xml_report($xml, $group_filter); + +function process_upload_xml($xml) +{ + $hook_enterprise = enterprise_include('extensions/resource_registration/functions.php'); + + // Extract component + process_upload_xml_component($xml); + + $group_filter = get_parameter('group'); + + // Extract visual map + process_upload_xml_visualmap($xml, $group_filter); + + // Extract policies + if ($hook_enterprise === true) { + process_upload_xml_policy($xml, $group_filter); + } + + // Extract reports + process_upload_xml_report($xml, $group_filter); } -function resource_registration_extension_main() { - global $config; - - if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; - } - - require_once($config['homedir'] . '/include/functions_network_components.php'); - require_once($config['homedir'] . '/include/functions_db.php'); - enterprise_include_once('include/functions_local_components.php'); - - ui_print_page_header (__('Resource registration'), "images/extensions.png", false, "", true, "" ); - - if (!extension_loaded("libxml")) { - ui_print_error_message(_("Error, please install the PHP libXML in the system.")); - - return; - } - - echo "
"; - echo __("This extension makes registering resource templates easier.") . " " . - __("Here you can upload a resource template in .ptr format.") . " " . - __("Please refer to our documentation for more information on how to obtain and use %s resources.", get_product_name()) . " " . - "

" . - __("You can get more resurces in our Public Resource Library") - ; - echo "
"; - - echo "

"; - - // Upload form - echo "
"; - echo ''; - echo ""; - echo ""; - echo ""; - echo ""; - echo "
"; - echo "" . __('Group filter: ') . ""; - html_print_select_groups(false, "AW", true, 'group'); - echo ""; - echo "
"; - echo "
"; - - if (!isset ($_FILES['resource_upload']['tmp_name'])) { - return; - } - $xml = simplexml_load_file($_FILES['resource_upload']['tmp_name'], NULL, LIBXML_NOCDATA); - - process_upload_xml($xml); + +function resource_registration_extension_main() +{ + global $config; + + if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; + } + + include_once $config['homedir'].'/include/functions_network_components.php'; + include_once $config['homedir'].'/include/functions_db.php'; + enterprise_include_once('include/functions_local_components.php'); + + ui_print_page_header(__('Resource registration'), 'images/extensions.png', false, '', true, ''); + + if (!extension_loaded('libxml')) { + ui_print_error_message(_('Error, please install the PHP libXML in the system.')); + + return; + } + + echo '
'; + echo __('This extension makes registering resource templates easier.').' '.__('Here you can upload a resource template in .ptr format.').' '.__('Please refer to our documentation for more information on how to obtain and use %s resources.', get_product_name()).' '.'

'.__("You can get more resurces in our Public Resource Library"); + echo '
'; + + echo '

'; + + // Upload form + echo "
"; + echo ''; + echo ''; + echo "'; + echo ''; + echo "'; + echo '
"; + echo ''.__('Group filter: ').''; + html_print_select_groups(false, 'AW', true, 'group'); + echo '"; + echo '
'; + echo '
'; + + if (!isset($_FILES['resource_upload']['tmp_name'])) { + return; + } + + $xml = simplexml_load_file($_FILES['resource_upload']['tmp_name'], null, LIBXML_NOCDATA); + + process_upload_xml($xml); } -extensions_add_godmode_menu_option (__('Resource registration'), 'PM','gagente','', "v1r1"); + +extensions_add_godmode_menu_option(__('Resource registration'), 'PM', 'gagente', '', 'v1r1'); extensions_add_godmode_function('resource_registration_extension_main'); -?> diff --git a/pandora_console/extensions/users_connected.php b/pandora_console/extensions/users_connected.php index 02a4fecf15..562d757a20 100644 --- a/pandora_console/extensions/users_connected.php +++ b/pandora_console/extensions/users_connected.php @@ -4,125 +4,138 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -function users_extension_main() { - users_extension_main_god(false); +function users_extension_main() +{ + users_extension_main_god(false); } -function users_extension_main_god ($god = true) { - global $config; - - if (isset($config["id_user"])) { - if (!check_acl ($config["id_user"], 0, "UM")) { - return; - } - } - - if ($god) { - $image = "images/gm_users.png"; - } - else { - $image = "images/op_workspace.png"; - } - - // Header - ui_print_page_header (__("Users connected"), $image, false, "", $god); - - // Get user conected last 5 minutes - switch ($config["dbtype"]) { - case "mysql": - $sql = "SELECT id_user, last_connect + +function users_extension_main_god($god=true) +{ + global $config; + + if (isset($config['id_user'])) { + if (!check_acl($config['id_user'], 0, 'UM')) { + return; + } + } + + if ($god) { + $image = 'images/gm_users.png'; + } else { + $image = 'images/op_workspace.png'; + } + + // Header + ui_print_page_header(__('Users connected'), $image, false, '', $god); + + // Get user conected last 5 minutes + switch ($config['dbtype']) { + case 'mysql': + $sql = 'SELECT id_user, last_connect FROM tusuario - WHERE last_connect > (UNIX_TIMESTAMP(NOW()) - " . SECONDS_5MINUTES . ") - ORDER BY last_connect DESC"; - break; - case "postgresql": - $sql = "SELECT id_user, last_connect + WHERE last_connect > (UNIX_TIMESTAMP(NOW()) - '.SECONDS_5MINUTES.') + ORDER BY last_connect DESC'; + break; + + case 'postgresql': + $sql = "SELECT id_user, last_connect FROM tusuario - WHERE last_connect > (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - " . SECONDS_5MINUTES . ") - ORDER BY last_connect DESC"; - break; - case "oracle": - $sql = "SELECT id_user, last_connect + WHERE last_connect > (ceil(date_part('epoch', CURRENT_TIMESTAMP)) - ".SECONDS_5MINUTES.') + ORDER BY last_connect DESC'; + break; + + case 'oracle': + $sql = "SELECT id_user, last_connect FROM tusuario - WHERE last_connect > (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) - " . SECONDS_5MINUTES . ") - ORDER BY last_connect DESC"; - break; - } - - $rows = db_get_all_rows_sql ($sql); - - if (empty ($rows)) { - $rows = array (); - echo "
".__('No other users connected')."
"; - } - else { - $table->cellpadding = 4; - $table->cellspacing = 4; - $table->width = '100%'; - $table->class = "databox data"; - $table->size = array (); - $table->data = array (); - $table->head = array (); - - $table->head[0] = __('User'); - $table->head[1] = __('IP'); - $table->head[2] = __('Date'); - - $rowPair = true; - $iterator = 0; - - // Get data - foreach ($rows as $row) { - // Get ip_origin of the last login of the user - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $ip_origin = db_get_value_sql(sprintf("SELECT ip_origen + WHERE last_connect > (ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) - '.SECONDS_5MINUTES.') + ORDER BY last_connect DESC'; + break; + } + + $rows = db_get_all_rows_sql($sql); + + if (empty($rows)) { + $rows = []; + echo "
".__('No other users connected').'
'; + } else { + $table->cellpadding = 4; + $table->cellspacing = 4; + $table->width = '100%'; + $table->class = 'databox data'; + $table->size = []; + $table->data = []; + $table->head = []; + + $table->head[0] = __('User'); + $table->head[1] = __('IP'); + $table->head[2] = __('Date'); + + $rowPair = true; + $iterator = 0; + + // Get data + foreach ($rows as $row) { + // Get ip_origin of the last login of the user + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $ip_origin = db_get_value_sql( + sprintf( + "SELECT ip_origen FROM tsesion WHERE id_usuario = '%s' - AND descripcion = '" . io_safe_input('Logged in') . "' - ORDER BY fecha DESC",$row["id_user"])); - break; - case "oracle": - $ip_origin = db_get_value_sql(sprintf("SELECT ip_origen + AND descripcion = '".io_safe_input('Logged in')."' + ORDER BY fecha DESC", + $row['id_user'] + ) + ); + break; + + case 'oracle': + $ip_origin = db_get_value_sql( + sprintf( + "SELECT ip_origen FROM tsesion WHERE id_usuario = '%s' - AND to_char(descripcion) = '" . io_safe_input('Logged in') . "' - ORDER BY fecha DESC",$row["id_user"])); - break; - } - - if ($rowPair) - $table->rowclass[$iterator] = 'rowPair'; - else - $table->rowclass[$iterator] = 'rowOdd'; - $rowPair = !$rowPair; - $iterator++; - - $data = array (); - $data[0] = ''.$row["id_user"].''; - $data[1] = $ip_origin; - $data[2] = date($config["date_format"], $row['last_connect']); - array_push ($table->data, $data); - } - - html_print_table ($table); - } + AND to_char(descripcion) = '".io_safe_input('Logged in')."' + ORDER BY fecha DESC", + $row['id_user'] + ) + ); + break; + } + + if ($rowPair) { + $table->rowclass[$iterator] = 'rowPair'; + } else { + $table->rowclass[$iterator] = 'rowOdd'; + } + + $rowPair = !$rowPair; + $iterator++; + + $data = []; + $data[0] = ''.$row['id_user'].''; + $data[1] = $ip_origin; + $data[2] = date($config['date_format'], $row['last_connect']); + array_push($table->data, $data); + } + + html_print_table($table); + } } -extensions_add_godmode_menu_option (__('Users connected'), 'UM','gusuarios',"users/icon.png", "v1r1"); -extensions_add_operation_menu_option(__('Users connected'), 'workspace',"users/icon.png", "v1r1", '', "UM"); + + +extensions_add_godmode_menu_option(__('Users connected'), 'UM', 'gusuarios', 'users/icon.png', 'v1r1'); +extensions_add_operation_menu_option(__('Users connected'), 'workspace', 'users/icon.png', 'v1r1', '', 'UM'); extensions_add_godmode_function('users_extension_main_god'); extensions_add_main_function('users_extension_main'); - -?> diff --git a/pandora_console/extras/mr/23.sql b/pandora_console/extras/mr/23.sql index a602023e3b..98ef4f5747 100644 --- a/pandora_console/extras/mr/23.sql +++ b/pandora_console/extras/mr/23.sql @@ -6,4 +6,6 @@ ALTER TABLE `tagent_custom_fields_filter` ADD COLUMN `module_status` varchar(600 ALTER TABLE `tagent_custom_fields_filter` ADD COLUMN `recursion` int(1) unsigned default '0'; +ALTER TABLE `tevent_rule` ADD COLUMN `group_recursion` INT(1) unsigned default 0; + COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/mr/24.sql b/pandora_console/extras/mr/24.sql new file mode 100644 index 0000000000..f93d9c6e6e --- /dev/null +++ b/pandora_console/extras/mr/24.sql @@ -0,0 +1,5 @@ +START TRANSACTION; + +ALTER TABLE `treport` ADD COLUMN `orientation` varchar(25) NOT NULL default 'vertical'; + +COMMIT; diff --git a/pandora_console/extras/pandora_diag.php b/pandora_console/extras/pandora_diag.php index 29e83182fe..4a0b32de81 100644 --- a/pandora_console/extras/pandora_diag.php +++ b/pandora_console/extras/pandora_diag.php @@ -1,10 +1,10 @@ @@ -15,7 +15,6 @@ $(document).ready(function(){ // ============================================ // Copyright (c) 2010 Artica Soluciones Tecnologicas, http://www.artica.es // Please see http://pandora.sourceforge.net for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -23,27 +22,27 @@ $(document).ready(function(){ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, 'PM')) { - db_pandora_audit("ACL Violation", "Trying to change License settings"); - include ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit('ACL Violation', 'Trying to change License settings'); + include 'general/noaccess.php'; + return; } -$update_settings = (bool) get_parameter_post ('update_settings'); +$update_settings = (bool) get_parameter_post('update_settings'); if ($update_settings) { - foreach ($_POST['keys'] as $key => $value) { - db_process_sql_update( - 'tupdate_settings', - array(db_escape_key_identifier('value') => $value), - array(db_escape_key_identifier('key') => $key)); - } - - ui_print_success_message(__('License updated')); + foreach ($_POST['keys'] as $key => $value) { + db_process_sql_update( + 'tupdate_settings', + [db_escape_key_identifier('value') => $value], + [db_escape_key_identifier('key') => $key] + ); + } + + ui_print_success_message(__('License updated')); } ui_require_javascript_file_enterprise('load_enterprise'); @@ -54,185 +53,235 @@ $rows = db_get_all_rows_in_table('tupdate_settings'); $settings = new StdClass; foreach ($rows as $row) { - $settings->{$row['key']} = $row['value']; + $settings->{$row['key']} = $row['value']; } echo ''; -function render_info ($table) { - global $console_mode; - - $info = db_get_sql ("SELECT COUNT(*) FROM $table"); - render_row ($info,"DB Table $table"); -} -function render_info_data ($query, $label) { - global $console_mode; - - $info = db_get_sql ($query); - render_row ($info, $label); -} +function render_info($table) +{ + global $console_mode; -function render_row ($data, $label) { - global $console_mode; - - if ($console_mode == 1) { - echo $label; - echo "|"; - echo $data; - echo "\n"; - } - else { - echo ""; - echo "
" . $label; - echo "
"; - echo "
" . $data; - echo "
"; - echo ""; - } -} - -function get_value_sum($arr){ - foreach($arr as $clave){ - foreach($clave as $valor){ - $result += $valor; - } - } - return $result; -} - -function execution_time(){ - $times = db_get_all_rows_sql("SELECT datos FROM tagente_datos WHERE id_agente_modulo = 29 ORDER BY utimestamp DESC LIMIT 2"); - if($times[0]['datos'] > $times[1]['datos'] * 1.2) - return "Warning Status   The execution time could be degrading. For a more extensive information of this data consult the Execution Time graph"; - else - return "Normal Status   The execution time is correct. For a more extensive information of this data consult the Execution Time graph"; + $info = db_get_sql("SELECT COUNT(*) FROM $table"); + render_row($info, "DB Table $table"); } -function get_logs_size($file){ - $file_name = '/var'. $file .''; - $size_server_log = filesize($file_name); - return $size_server_log; +function render_info_data($query, $label) +{ + global $console_mode; + + $info = db_get_sql($query); + render_row($info, $label); +} + + +function render_row($data, $label) +{ + global $console_mode; + + if ($console_mode == 1) { + echo $label; + echo '|'; + echo $data; + echo "\n"; + } else { + echo ''; + echo "
".$label; + echo '
'; + echo "
".$data; + echo '
'; + echo ''; + } +} + + +function get_value_sum($arr) +{ + foreach ($arr as $clave) { + foreach ($clave as $valor) { + $result += $valor; + } + } + + return $result; +} + + +function execution_time() +{ + $times = db_get_all_rows_sql('SELECT datos FROM tagente_datos WHERE id_agente_modulo = 29 ORDER BY utimestamp DESC LIMIT 2'); + if ($times[0]['datos'] > ($times[1]['datos'] * 1.2)) { + return "Warning Status   The execution time could be degrading. For a more extensive information of this data consult the Execution Time graph"; + } else { + return "Normal Status   The execution time is correct. For a more extensive information of this data consult the Execution Time graph"; + } +} + + +function get_logs_size($file) +{ + $file_name = '/var'.$file.''; + $size_server_log = filesize($file_name); + return $size_server_log; } -function get_status_logs($path){ - $status_server_log = ""; - $size_server_log = get_logs_size($path); - if ($size_server_log <= 10240){ - $status_server_log = "Normal Status   You have less than 10 MB of logs"; - }else{ - $status_server_log = "Warning Status   You have more than 10 MB of logs"; - } - return $status_server_log; -} -function percentage_modules_per_agent(){ - $status_average_modules = ""; - $total_agents = db_get_value_sql ('SELECT count(*) FROM tagente'); - $total_modules = db_get_value_sql ('SELECT count(*) FROM tagente_modulo'); - $average_modules_per_agent = $total_modules / $total_agents; - if($average_modules_per_agent <= 40){ - $status_average_modules = "Normal Status   The average of modules per agent is less than 40 percent"; - }else{ - $status_average_modules = "Warning Status  The average of modules per agent is more than 40 percent. You can have performance problems"; - } -return $status_average_modules; + +function get_status_logs($path) +{ + $status_server_log = ''; + $size_server_log = get_logs_size($path); + if ($size_server_log <= 10240) { + $status_server_log = "Normal Status   You have less than 10 MB of logs"; + } else { + $status_server_log = "Warning Status   You have more than 10 MB of logs"; + } + + return $status_server_log; } -function license_capacity(){ - $license = enterprise_hook('license_get_info'); - $license_limit = $license['limit']; - $status_license_capacity = ""; - $current_count = db_get_value_sql ('SELECT count(*) FROM tagente'); - if ($current_count > $license_limit * 90 /100){ - $status_license_capacity = "Warning Status   The license capacity is more than 90 percent"; - }else{ - $status_license_capacity = "Normal Status   The license capacity is less than 90 percent"; - } - return $status_license_capacity; + +function percentage_modules_per_agent() +{ + $status_average_modules = ''; + $total_agents = db_get_value_sql('SELECT count(*) FROM tagente'); + $total_modules = db_get_value_sql('SELECT count(*) FROM tagente_modulo'); + $average_modules_per_agent = ($total_modules / $total_agents); + if ($average_modules_per_agent <= 40) { + $status_average_modules = "Normal Status   The average of modules per agent is less than 40 percent"; + } else { + $status_average_modules = "Warning Status  The average of modules per agent is more than 40 percent. You can have performance problems"; + } + + return $status_average_modules; } -function status_license_params($license_param){ - $status_license_par =""; - if ($license_param <=0) - $status_license_par = "OFF"; - else - $status_license_par = "ON"; - return $status_license_par; -} -function interval_average_of_network_modules(){ - $total_network_modules = db_get_value_sql ("SELECT count(*) FROM tagente_modulo WHERE id_tipo_modulo BETWEEN 6 AND 18"); - $total_module_interval_time = db_get_value_sql ("SELECT SUM(module_interval) FROM tagente_modulo WHERE id_tipo_modulo BETWEEN 6 AND 18"); - $average_time= (int) $total_module_interval_time / $total_network_modules; - - if($average_time < 180 ){ - $status_average_modules = "Warning Status   The system has a lot of load and a very fine configuration is required"; - }else{ - $status_average_modules = "Normal Status   The system has an acceptable charge"; - } - if ($average_time == 0) - $status_average_modules = "Normal Status   The system has no load"; - return $status_average_modules; + +function license_capacity() +{ + $license = enterprise_hook('license_get_info'); + $license_limit = $license['limit']; + $status_license_capacity = ''; + $current_count = db_get_value_sql('SELECT count(*) FROM tagente'); + if ($current_count > ($license_limit * 90 / 100)) { + $status_license_capacity = "Warning Status   The license capacity is more than 90 percent"; + } else { + $status_license_capacity = "Normal Status   The license capacity is less than 90 percent"; + } + + return $status_license_capacity; } -$attachment_total_files = count(glob($config['homedir']."/attachment/{*.*}",GLOB_BRACE)); -function files_attachment_folder($total_files){ - if($total_files <= 700){ - $status_total_files = "Normal Status   The attachment folder has less than 700 files."; - }else{ - $status_total_files = "Warning Status   The attachment folder has more than 700 files."; - } - return $status_total_files; +function status_license_params($license_param) +{ + $status_license_par = ''; + if ($license_param <= 0) { + $status_license_par = 'OFF'; + } else { + $status_license_par = 'ON'; + } + + return $status_license_par; } + +function interval_average_of_network_modules() +{ + $total_network_modules = db_get_value_sql('SELECT count(*) FROM tagente_modulo WHERE id_tipo_modulo BETWEEN 6 AND 18'); + $total_module_interval_time = db_get_value_sql('SELECT SUM(module_interval) FROM tagente_modulo WHERE id_tipo_modulo BETWEEN 6 AND 18'); + $average_time = ((int) $total_module_interval_time / $total_network_modules); + + if ($average_time < 180) { + $status_average_modules = "Warning Status   The system has a lot of load and a very fine configuration is required"; + } else { + $status_average_modules = "Normal Status   The system has an acceptable charge"; + } + + if ($average_time == 0) { + $status_average_modules = "Normal Status   The system has no load"; + } + + return $status_average_modules; +} + + +$attachment_total_files = count(glob($config['homedir'].'/attachment/{*.*}', GLOB_BRACE)); + + +function files_attachment_folder($total_files) +{ + if ($total_files <= 700) { + $status_total_files = "Normal Status   The attachment folder has less than 700 files."; + } else { + $status_total_files = "Warning Status   The attachment folder has more than 700 files."; + } + + return $status_total_files; +} + + $tagente_datos_size = db_get_value_sql('SELECT COUNT(*) FROM tagente_datos'); -function status_tagente_datos($tagente_datos_size){ - if ($tagente_datos_size <=3000000){ - $tagente_datos_size = "Normal Status   The tagente_datos table has an acceptable amount of data."; - }else{ - $tagente_datos_size = "Warning Status   The tagente_datos table has too much data. A historical database is recommended."; - } - return $tagente_datos_size; + +function status_tagente_datos($tagente_datos_size) +{ + if ($tagente_datos_size <= 3000000) { + $tagente_datos_size = "Normal Status   The tagente_datos table has an acceptable amount of data."; + } else { + $tagente_datos_size = "Warning Status   The tagente_datos table has too much data. A historical database is recommended."; + } + + return $tagente_datos_size; } -function status_values($val_rec, $val){ - if ($val_rec <= $val) - return $val . " (Min. Recommended Value " . $val_rec. ")"; - else - return $val . " (Min. Recommended Value " . $val_rec. ") Warning Status"; + +function status_values($val_rec, $val) +{ + if ($val_rec <= $val) { + return $val." (Min. Recommended Value ".$val_rec.')'; + } else { + return $val." (Min. Recommended Value ".$val_rec.") Warning Status"; + } } -$tables_fragmentation=db_get_sql ("SELECT (data_free/(index_length+data_length)) -as frag_ratio from information_schema.tables where DATA_FREE > 0 and table_name='tagente_datos' and table_schema='pandora'"); -$db_size=db_get_all_rows_sql("SELECT table_schema, + +$tables_fragmentation = db_get_sql( + "SELECT (data_free/(index_length+data_length)) +as frag_ratio from information_schema.tables where DATA_FREE > 0 and table_name='tagente_datos' and table_schema='pandora'" +); +$db_size = db_get_all_rows_sql( + 'SELECT table_schema, ROUND(SUM(data_length+index_length)/1024/1024,3) FROM information_schema.TABLES -GROUP BY table_schema;" +GROUP BY table_schema;' ); -if(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN'){ - $total_server_threads = shell_exec("ps -T aux | grep pandora_server | grep -v grep | wc -l"); - $percentage_threads_ram = shell_exec("ps axo pmem,cmd | grep pandora_server | awk '{sum+=$1} END {print sum}'"); - $percentage_threads_cpu = shell_exec("ps axo pcpu,cmd | grep pandora_server | awk '{sum+=$1} END {print sum}'"); - $innodb_buffer_pool_size_min_rec_value = shell_exec("cat /proc/meminfo | grep -i total | head -1 | awk '{print $(NF-1)*0.4/1024}'"); +if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { + $total_server_threads = shell_exec('ps -T aux | grep pandora_server | grep -v grep | wc -l'); + $percentage_threads_ram = shell_exec("ps axo pmem,cmd | grep pandora_server | awk '{sum+=$1} END {print sum}'"); + $percentage_threads_cpu = shell_exec("ps axo pcpu,cmd | grep pandora_server | awk '{sum+=$1} END {print sum}'"); + $innodb_buffer_pool_size_min_rec_value = shell_exec("cat /proc/meminfo | grep -i total | head -1 | awk '{print $(NF-1)*0.4/1024}'"); } -$path_server_logs ="/log/pandora/pandora_server.log"; -$path_console_logs ="/www/html/pandora_console/pandora_console.log"; -$innodb_log_file_size_min_rec_value = "64M"; -$innodb_log_buffer_size_min_rec_value = "16M"; + +$path_server_logs = '/log/pandora/pandora_server.log'; +$path_console_logs = '/www/html/pandora_console/pandora_console.log'; +$innodb_log_file_size_min_rec_value = '64M'; +$innodb_log_buffer_size_min_rec_value = '16M'; $innodb_flush_log_at_trx_commit_min_rec_value = 0; -$query_cache_limit_min_rec_value = 2; +$query_cache_limit_min_rec_value = 2; $max_allowed_packet_min_rec_value = 32; $innodb_buffer_pool_size_min_rec_value = shell_exec("cat /proc/meminfo | grep -i total | head -1 | awk '{print $(NF-1)*0.4/1024}'"); $sort_buffer_size_min_rec_value = 32; $join_buffer_size_min_rec_value = 265; -$query_cache_type_min_rec_value = "ON"; +$query_cache_type_min_rec_value = 'ON'; $query_cache_size_min_rec_value = 24; $innodb_lock_wait_timeout_max_rec_value = 120; $tables_fragmentation_max_rec_value = 10; @@ -245,24 +294,30 @@ $read_rnd_buffer_size_min_rec_value = 32; $query_cache_min_res_unit_min_rec_value = 2; $innodb_file_per_table_min_rec_value = 0; -function status_fragmentation_tables($tables_fragmentation_max_rec_value, $tables_fragmentation){ - $status_tables_frag = ""; - if($tables_fragmentation > $tables_fragmentation_max_rec_value) - $status_tables_frag = "Warning Status   The fragmentation tables is higher than recommended. You should defragment them."; - else - $status_tables_frag = "Normal Status   The fragmentation tables is correct."; - return $status_tables_frag; + +function status_fragmentation_tables($tables_fragmentation_max_rec_value, $tables_fragmentation) +{ + $status_tables_frag = ''; + if ($tables_fragmentation > $tables_fragmentation_max_rec_value) { + $status_tables_frag = "Warning Status   The fragmentation tables is higher than recommended. You should defragment them."; + } else { + $status_tables_frag = "Normal Status   The fragmentation tables is correct."; + } + + return $status_tables_frag; } + $console_mode = 1; -if (!isset($argc)) - $console_mode = 0; - +if (!isset($argc)) { + $console_mode = 0; +} + if ($console_mode == 1) { - echo "\nPandora FMS PHP diagnostic tool v3.2 (c) Artica ST 2009-2010 \n"; - - if ($argc == 1 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) { - echo "\nThis command line script gives information about Pandora FMS database. + echo "\nPandora FMS PHP diagnostic tool v3.2 (c) Artica ST 2009-2010 \n"; + + if ($argc == 1 || in_array($argv[1], ['--help', '-help', '-h', '-?'])) { + echo "\nThis command line script gives information about Pandora FMS database. This program only can be executed from console, and need a parameter, the full path to Pandora FMS 'config.php' file. @@ -273,377 +328,461 @@ full path to Pandora FMS 'config.php' file. php pandora_diag.php /var/www/pandora_console "; - exit; - } - if (preg_match ('/[^a-zA-Z0-9_\/\.]|(\/\/)|(\.\.)/', $argv[1])) { - echo "Invalid path: $argv[1]. Always use absolute paths."; - exit; - } - include $argv[1]."/include/config.php"; -} -else { - if (file_exists("../include/config.php")) - include "../include/config.php"; - - // Not from console, this is a web session - if ((!isset($config["id_user"])) OR (!check_acl ($config["id_user"], 0, "PM"))) { - echo "

You don't have privileges to use diagnostic tool

"; - echo "

Please login with an administrator account before try to use this tool

"; - exit; - } + exit; + } - // Header - ui_print_page_header (__('Pandora FMS Diagnostic tool'), "", false, "", true); + if (preg_match('/[^a-zA-Z0-9_\/\.]|(\/\/)|(\.\.)/', $argv[1])) { + echo "Invalid path: $argv[1]. Always use absolute paths."; + exit; + } - echo ""; - echo ""; + include $argv[1].'/include/config.php'; +} else { + if (file_exists('../include/config.php')) { + include '../include/config.php'; + } + + // Not from console, this is a web session + if ((!isset($config['id_user'])) or (!check_acl($config['id_user'], 0, 'PM'))) { + echo "

You don't have privileges to use diagnostic tool

"; + echo '

Please login with an administrator account before try to use this tool

'; + exit; + } + + // Header + ui_print_page_header(__('Pandora FMS Diagnostic tool'), '', false, '', true); + + echo "
".__("Pandora status info")."
"; + echo "'; } -render_row ($build_version, "Pandora FMS Build"); -render_row ($pandora_version, "Pandora FMS Version"); -render_info_data ("SELECT value FROM tconfig where token ='MR'","Minor Release"); -render_row ($config["homedir"], "Homedir"); -render_row ($config["homeurl"], "HomeUrl"); -render_info_data ("SELECT `value` +render_row($build_version, 'Pandora FMS Build'); +render_row($pandora_version, 'Pandora FMS Version'); +render_info_data("SELECT value FROM tconfig where token ='MR'", 'Minor Release'); +render_row($config['homedir'], 'Homedir'); +render_row($config['homeurl'], 'HomeUrl'); +render_info_data( + "SELECT `value` FROM tconfig - WHERE `token` = 'enterprise_installed'", "Enterprise installed"); - - $full_key = db_get_sql("SELECT value + WHERE `token` = 'enterprise_installed'", + 'Enterprise installed' +); + + $full_key = db_get_sql( + "SELECT value FROM tupdate_settings - WHERE `key` = 'customer_key'"); - - $compressed_key = substr($full_key, 0,5).'...'.substr($full_key, -5); - - render_row ($compressed_key,"Update Key"); - - render_info_data ("SELECT value + WHERE `key` = 'customer_key'" + ); + + $compressed_key = substr($full_key, 0, 5).'...'.substr($full_key, -5); + + render_row($compressed_key, 'Update Key'); + + render_info_data( + "SELECT value FROM tupdate_settings - WHERE `key` = 'updating_code_path'", "Updating code path"); - - render_info_data ("SELECT value + WHERE `key` = 'updating_code_path'", + 'Updating code path' + ); + + render_info_data( + "SELECT value FROM tupdate_settings - WHERE `key` = 'current_update'", "Current Update #"); + WHERE `key` = 'current_update'", + 'Current Update #' + ); -echo ""; + echo "'; -render_row (phpversion(), "PHP Version"); + render_row(phpversion(), 'PHP Version'); -render_row (ini_get('max_execution_time')." seconds", "PHP Max execution time"); + render_row(ini_get('max_execution_time').' seconds', 'PHP Max execution time'); -render_row (ini_get('max_input_time')." seconds", "PHP Max input time"); + render_row(ini_get('max_input_time').' seconds', 'PHP Max input time'); -render_row (ini_get('memory_limit'), "PHP Memory limit"); + render_row(ini_get('memory_limit'), 'PHP Memory limit'); -render_row (ini_get('session.cookie_lifetime'), "Session cookie lifetime"); + render_row(ini_get('session.cookie_lifetime'), 'Session cookie lifetime'); -echo ""; + echo "'; -render_info_data ("SELECT COUNT(*) FROM tagente","Total agents"); -render_info_data ("SELECT COUNT(*) FROM tagente_modulo","Total modules"); -render_info_data ("SELECT COUNT(*) FROM tgrupo","Total groups"); -render_info_data ("SELECT COUNT(*) FROM tagente_datos","Total module data records"); -// render_info_data ("SELECT COUNT(*) FROM tagente_datos_string","Total module string data records"); -// render_info_data ("SELECT COUNT(*) FROM tagente_datos_log4x","Total module log4x data records"); -render_info_data ("SELECT COUNT(*) FROM tagent_access","Total agent access record"); -// render_info ("tagente_estado"); -// render_info ("talert_template_modules"); -render_info_data ("SELECT COUNT(*) FROM tevento","Total events"); + render_info_data('SELECT COUNT(*) FROM tagente', 'Total agents'); + render_info_data('SELECT COUNT(*) FROM tagente_modulo', 'Total modules'); + render_info_data('SELECT COUNT(*) FROM tgrupo', 'Total groups'); + render_info_data('SELECT COUNT(*) FROM tagente_datos', 'Total module data records'); + // render_info_data ("SELECT COUNT(*) FROM tagente_datos_string","Total module string data records"); + // render_info_data ("SELECT COUNT(*) FROM tagente_datos_log4x","Total module log4x data records"); + render_info_data('SELECT COUNT(*) FROM tagent_access', 'Total agent access record'); + // render_info ("tagente_estado"); + // render_info ("talert_template_modules"); + render_info_data('SELECT COUNT(*) FROM tevento', 'Total events'); -if($config['enterprise_installed']) -render_info_data ("SELECT COUNT(*) FROM ttrap","Total traps"); -render_info_data ("SELECT COUNT(*) FROM tusuario","Total users"); -render_info_data ("SELECT COUNT(*) FROM tsesion","Total sessions"); + if ($config['enterprise_installed']) { + render_info_data('SELECT COUNT(*) FROM ttrap', 'Total traps'); + } -echo ""; + render_info_data('SELECT COUNT(*) FROM tusuario', 'Total users'); + render_info_data('SELECT COUNT(*) FROM tsesion', 'Total sessions'); -render_info_data ("SELECT COUNT( DISTINCT tagente.id_agente) + echo "'; + + render_info_data( + 'SELECT COUNT( DISTINCT tagente.id_agente) FROM tagente_estado, tagente, tagente_modulo WHERE tagente.disabled = 0 AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_modulo.disabled = 0 AND tagente_estado.id_agente = tagente.id_agente - AND tagente_estado.estado = 3","Total unknown agents"); - -render_info_data ("SELECT COUNT(tagente_estado.estado) + AND tagente_estado.estado = 3', + 'Total unknown agents' + ); + + render_info_data( + 'SELECT COUNT(tagente_estado.estado) FROM tagente_estado - WHERE tagente_estado.estado = 4","Total not-init modules"); + WHERE tagente_estado.estado = 4', + 'Total not-init modules' + ); -$last_run_difference = ''; + $last_run_difference = ''; -$diferencia = time() - date ( - db_get_sql ("SELECT `value` + $diferencia = (time() - date( + db_get_sql( + "SELECT `value` FROM tconfig - WHERE `token` = 'db_maintance'")); + WHERE `token` = 'db_maintance'" + ) + )); -$last_run_difference_months = 0; -$last_run_difference_weeks = 0; -$last_run_difference_days = 0; -$last_run_difference_minutos = 0; -$last_run_difference_seconds = 0; + $last_run_difference_months = 0; + $last_run_difference_weeks = 0; + $last_run_difference_days = 0; + $last_run_difference_minutos = 0; + $last_run_difference_seconds = 0; -while($diferencia >= 2419200){ - $diferencia -= 2419200; - $last_run_difference_months++; -} + while ($diferencia >= 2419200) { + $diferencia -= 2419200; + $last_run_difference_months++; + } -while($diferencia >= 604800){ - $diferencia -= 604800; - $last_run_difference_weeks++; -} + while ($diferencia >= 604800) { + $diferencia -= 604800; + $last_run_difference_weeks++; + } -while($diferencia >= 86400){ - $diferencia -= 86400; - $last_run_difference_days++; -} + while ($diferencia >= 86400) { + $diferencia -= 86400; + $last_run_difference_days++; + } -while($diferencia >= 3600){ - $diferencia -= 3600; - $last_run_difference_hours++; -} + while ($diferencia >= 3600) { + $diferencia -= 3600; + $last_run_difference_hours++; + } -while($diferencia >= 60){ - $diferencia -= 60; - $last_run_difference_minutes++; -} + while ($diferencia >= 60) { + $diferencia -= 60; + $last_run_difference_minutes++; + } -$last_run_difference_seconds = $diferencia; + $last_run_difference_seconds = $diferencia; -if($last_run_difference_months > 0){ - $last_run_difference .= $last_run_difference_months.'month/s '; -} + if ($last_run_difference_months > 0) { + $last_run_difference .= $last_run_difference_months.'month/s '; + } -if ($last_run_difference_weeks > 0) { - $last_run_difference .= $last_run_difference_weeks.' week/s '; -} + if ($last_run_difference_weeks > 0) { + $last_run_difference .= $last_run_difference_weeks.' week/s '; + } -if ($last_run_difference_days > 0) { - $last_run_difference .= $last_run_difference_days.' day/s '; -} + if ($last_run_difference_days > 0) { + $last_run_difference .= $last_run_difference_days.' day/s '; + } -if ($last_run_difference_hours > 0) { - $last_run_difference .= $last_run_difference_hours.' hour/s '; -} + if ($last_run_difference_hours > 0) { + $last_run_difference .= $last_run_difference_hours.' hour/s '; + } -if ($last_run_difference_minutes > 0) { - $last_run_difference .= $last_run_difference_minutes.' minute/s '; -} + if ($last_run_difference_minutes > 0) { + $last_run_difference .= $last_run_difference_minutes.' minute/s '; + } -$last_run_difference .= $last_run_difference_seconds.' second/s ago'; - -render_row ( date ("Y/m/d H:i:s", -db_get_sql ("SELECT `value` + $last_run_difference .= $last_run_difference_seconds.' second/s ago'; + + render_row( + date( + 'Y/m/d H:i:s', + db_get_sql( + "SELECT `value` FROM tconfig - WHERE `token` = 'db_maintance'")).' ('.$last_run_difference.')'.' *', "PandoraDB Last run"); + WHERE `token` = 'db_maintance'" + ) + ).' ('.$last_run_difference.')'.' *', + 'PandoraDB Last run' + ); -echo ""; + echo "'; -switch ($config["dbtype"]) { - case "mysql": - render_info_data ("SELECT `value` + switch ($config['dbtype']) { + case 'mysql': + render_info_data( + "SELECT `value` FROM tconfig - WHERE `token` = 'db_scheme_first_version'", "DB Schema Version (first installed)"); - render_info_data ("SELECT `value` + WHERE `token` = 'db_scheme_first_version'", + 'DB Schema Version (first installed)' + ); + render_info_data( + "SELECT `value` FROM tconfig - WHERE `token` = 'db_scheme_version'", "DB Schema Version (actual)"); - render_info_data ("SELECT `value` + WHERE `token` = 'db_scheme_version'", + 'DB Schema Version (actual)' + ); + render_info_data( + "SELECT `value` FROM tconfig - WHERE `token` = 'db_scheme_build'", "DB Schema Build"); + WHERE `token` = 'db_scheme_build'", + 'DB Schema Build' + ); - render_row(get_value_sum($db_size) . "M", "DB Size"); - - - if(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN'){ - - echo ""; - - $output = 'cat /proc/cpuinfo | grep "model name" | tail -1 | cut -f 2 -d ":"'; - $output2 = 'cat /proc/cpuinfo | grep "processor" | wc -l'; - - render_row(exec($output).' x '.exec($output2),'CPU'); - - $output = 'cat /proc/meminfo | grep "MemTotal"'; - - render_row(exec($output),'RAM'); - - } - - break; - case "postgresql": - render_info_data ("SELECT \"value\" + render_row(get_value_sum($db_size).'M', 'DB Size'); + + + if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { + echo "'; + + $output = 'cat /proc/cpuinfo | grep "model name" | tail -1 | cut -f 2 -d ":"'; + $output2 = 'cat /proc/cpuinfo | grep "processor" | wc -l'; + + render_row(exec($output).' x '.exec($output2), 'CPU'); + + $output = 'cat /proc/meminfo | grep "MemTotal"'; + + render_row(exec($output), 'RAM'); + } + break; + + case 'postgresql': + render_info_data( + "SELECT \"value\" FROM tconfig - WHERE \"token\" = 'db_scheme_version'", "DB Schema Version"); - render_info_data ("SELECT \"value\" + WHERE \"token\" = 'db_scheme_version'", + 'DB Schema Version' + ); + render_info_data( + "SELECT \"value\" FROM tconfig - WHERE \"token\" = 'db_scheme_build'", "DB Schema Build"); - render_info_data ("SELECT \"value\" + WHERE \"token\" = 'db_scheme_build'", + 'DB Schema Build' + ); + render_info_data( + "SELECT \"value\" FROM tconfig - WHERE \"token\" = 'enterprise_installed'", "Enterprise installed"); - render_row ( date ("Y/m/d H:i:s", - db_get_sql ("SELECT \"value\" - FROM tconfig WHERE \"token\" = 'db_maintance'")), "PandoraDB Last run"); - - render_info_data ("SELECT value + WHERE \"token\" = 'enterprise_installed'", + 'Enterprise installed' + ); + render_row( + date( + 'Y/m/d H:i:s', + db_get_sql( + "SELECT \"value\" + FROM tconfig WHERE \"token\" = 'db_maintance'" + ) + ), + 'PandoraDB Last run' + ); + + render_info_data( + "SELECT value FROM tupdate_settings - WHERE \"key\" = 'customer_key';", "Update Key"); - render_info_data ("SELECT value + WHERE \"key\" = 'customer_key';", + 'Update Key' + ); + render_info_data( + "SELECT value FROM tupdate_settings - WHERE \"key\" = 'updating_code_path'", "Updating code path"); - render_info_data ("SELECT value + WHERE \"key\" = 'updating_code_path'", + 'Updating code path' + ); + render_info_data( + "SELECT value FROM tupdate_settings - WHERE \"key\" = 'current_update'", "Current Update #"); - break; - case "oracle": - render_info_data ("SELECT value + WHERE \"key\" = 'current_update'", + 'Current Update #' + ); + break; + + case 'oracle': + render_info_data( + "SELECT value FROM tconfig - WHERE token = 'db_scheme_version'", "DB Schema Version"); - render_info_data ("SELECT value + WHERE token = 'db_scheme_version'", + 'DB Schema Version' + ); + render_info_data( + "SELECT value FROM tconfig - WHERE token = 'db_scheme_build'", "DB Schema Build"); - render_info_data ("SELECT value + WHERE token = 'db_scheme_build'", + 'DB Schema Build' + ); + render_info_data( + "SELECT value FROM tconfig - WHERE token = 'enterprise_installed'", "Enterprise installed"); - render_row (db_get_sql ("SELECT value + WHERE token = 'enterprise_installed'", + 'Enterprise installed' + ); + render_row( + db_get_sql( + "SELECT value FROM tconfig - WHERE token = 'db_maintance'"), "PandoraDB Last run"); + WHERE token = 'db_maintance'" + ), + 'PandoraDB Last run' + ); - render_info_data ("SELECT " . db_escape_key_identifier('value') . - " FROM tupdate_settings - WHERE \"key\" = 'customer_key'", "Update Key"); - render_info_data ("SELECT " . db_escape_key_identifier('value') . - " FROM tupdate_settings - WHERE \"key\" = 'updating_code_path'", "Updating code path"); - render_info_data ("SELECT " . db_escape_key_identifier('value') . - " FROM tupdate_settings - WHERE \"key\" = 'current_update'", "Current Update #"); - break; -} -$innodb_log_file_size =db_get_value_sql ("SELECT @@innodb_log_file_size")/1048576; -$innodb_log_buffer_size =db_get_value_sql("SELECT @@innodb_log_buffer_size")/1048576; -$innodb_flush_log_at_trx_commit =db_get_value_sql("SELECT @@innodb_flush_log_at_trx_commit"); -$max_allowed_packet =db_get_value_sql("SELECT @@max_allowed_packet")/1048576; -$innodb_buffer_pool_size = db_get_value_sql("SELECT @@innodb_buffer_pool_size")/1024; -$sort_buffer_size =number_format(db_get_value_sql("SELECT @@sort_buffer_size")/1024, 2); -$join_buffer_size =db_get_value_sql("SELECT @@join_buffer_size")/1024; -$query_cache_type =db_get_value_sql("SELECT @@query_cache_type"); -$query_cache_size =db_get_value_sql("SELECT @@query_cache_size")/1048576; -$query_cache_limit =db_get_value_sql("SELECT @@query_cache_limit")/1048576; -$innodb_lock_wait_timeout =db_get_value_sql("SELECT @@innodb_lock_wait_timeout"); -$thread_cache_size =db_get_value_sql("SELECT @@thread_cache_size"); -$thread_stack =db_get_value_sql("SELECT @@thread_stack")/1024; -$max_connections =db_get_value_sql("SELECT @@max_connections"); -$key_buffer_size =db_get_value_sql("SELECT @@key_buffer_size")/1024; -$read_buffer_size =db_get_value_sql("SELECT @@read_buffer_size")/1024; -$read_rnd_buffer_size =db_get_value_sql("SELECT @@read_rnd_buffer_size")/1024; -$query_cache_min_res_unit =db_get_value_sql("SELECT @@query_cache_min_res_unit")/1024; -$innodb_file_per_table = db_get_value_sql("SELECT @@innodb_file_per_table"); -echo ""; + render_info_data( + 'SELECT '.db_escape_key_identifier('value')." FROM tupdate_settings + WHERE \"key\" = 'customer_key'", + 'Update Key' + ); + render_info_data( + 'SELECT '.db_escape_key_identifier('value')." FROM tupdate_settings + WHERE \"key\" = 'updating_code_path'", + 'Updating code path' + ); + render_info_data( + 'SELECT '.db_escape_key_identifier('value')." FROM tupdate_settings + WHERE \"key\" = 'current_update'", + 'Current Update #' + ); + break; + } -render_row(status_values($innodb_log_file_size_min_rec_value,$innodb_log_file_size),'InnoDB log file size ', 'InnoDB log file size '); -render_row(status_values($innodb_log_buffer_size_min_rec_value,$innodb_log_buffer_size),'InnoDB log buffer size ', 'InnoDB log buffer size '); -render_row(status_values($innodb_flush_log_at_trx_commit_min_rec_value,$innodb_flush_log_at_trx_commit), 'InnoDB flush log at trx-commit ','InnoDB flush log at trx-commit '); -render_row(status_values($max_allowed_packet_min_rec_value,$max_allowed_packet), 'Maximun allowed packet ','Maximun allowed packet '); -render_row(status_values($innodb_buffer_pool_size_min_rec_value,$innodb_buffer_pool_size), 'InnoDB buffer pool size ','InnoDB buffer pool size '); -render_row(status_values($sort_buffer_size_min_rec_value,$sort_buffer_size), 'Sort buffer size ','Sort buffer size '); -render_row(status_values($join_buffer_size_min_rec_value,$join_buffer_size), 'Join buffer size ','Join buffer size '); -render_row(status_values($query_cache_type_min_rec_value,$query_cache_type), 'Query cache type ', 'Query cache type '); -render_row(status_values($query_cache_size_min_rec_value,$query_cache_size), 'Query cache size ','Query cache size '); -render_row(status_values($query_cache_limit_min_rec_value,$query_cache_limit), 'Query cache limit ','Query cache limit '); -render_row(status_values($innodb_lock_wait_timeout_max_rec_value,$innodb_lock_wait_timeout), 'InnoDB lock wait timeout ','InnoDB lock wait timeout '); -render_row(status_values($thread_cache_size_max_rec_value,$thread_cache_size), 'Thread cache size ','Thread cache size '); -render_row(status_values($thread_stack_min_rec_value,$thread_stack), 'Thread stack ','Thread stack '); -render_row(status_values($max_connections_max_rec_value,$max_connections), 'Maximum connections ','Maximun connections '); -render_row(status_values($key_buffer_size_min_rec_value,$key_buffer_size), 'Key buffer size ','Key buffer size '); -render_row(status_values($read_buffer_size_min_rec_value,$read_buffer_size), 'Read buffer size ','Read buffer size '); -render_row(status_values($read_rnd_buffer_size_min_rec_value,$read_rnd_buffer_size), 'Read rnd-buffer size ','Read rnd-buffer size '); -render_row(status_values($query_cache_min_res_unit_min_rec_value,$query_cache_min_res_unit), 'Query cache min-res-unit ','Query cache min-res-unit '); -render_row(status_values($innodb_file_per_table_min_rec_value,$innodb_file_per_table), 'InnoDB file per table ','InnoDB file per table '); -echo ""; + $innodb_log_file_size = (db_get_value_sql('SELECT @@innodb_log_file_size') / 1048576); + $innodb_log_buffer_size = (db_get_value_sql('SELECT @@innodb_log_buffer_size') / 1048576); + $innodb_flush_log_at_trx_commit = db_get_value_sql('SELECT @@innodb_flush_log_at_trx_commit'); + $max_allowed_packet = (db_get_value_sql('SELECT @@max_allowed_packet') / 1048576); + $innodb_buffer_pool_size = (db_get_value_sql('SELECT @@innodb_buffer_pool_size') / 1024); + $sort_buffer_size = number_format((db_get_value_sql('SELECT @@sort_buffer_size') / 1024), 2); + $join_buffer_size = (db_get_value_sql('SELECT @@join_buffer_size') / 1024); + $query_cache_type = db_get_value_sql('SELECT @@query_cache_type'); + $query_cache_size = (db_get_value_sql('SELECT @@query_cache_size') / 1048576); + $query_cache_limit = (db_get_value_sql('SELECT @@query_cache_limit') / 1048576); + $innodb_lock_wait_timeout = db_get_value_sql('SELECT @@innodb_lock_wait_timeout'); + $thread_cache_size = db_get_value_sql('SELECT @@thread_cache_size'); + $thread_stack = (db_get_value_sql('SELECT @@thread_stack') / 1024); + $max_connections = db_get_value_sql('SELECT @@max_connections'); + $key_buffer_size = (db_get_value_sql('SELECT @@key_buffer_size') / 1024); + $read_buffer_size = (db_get_value_sql('SELECT @@read_buffer_size') / 1024); + $read_rnd_buffer_size = (db_get_value_sql('SELECT @@read_rnd_buffer_size') / 1024); + $query_cache_min_res_unit = (db_get_value_sql('SELECT @@query_cache_min_res_unit') / 1024); + $innodb_file_per_table = db_get_value_sql('SELECT @@innodb_file_per_table'); + echo "'; + + render_row(status_values($innodb_log_file_size_min_rec_value, $innodb_log_file_size), 'InnoDB log file size ', 'InnoDB log file size '); + render_row(status_values($innodb_log_buffer_size_min_rec_value, $innodb_log_buffer_size), 'InnoDB log buffer size ', 'InnoDB log buffer size '); + render_row(status_values($innodb_flush_log_at_trx_commit_min_rec_value, $innodb_flush_log_at_trx_commit), 'InnoDB flush log at trx-commit ', 'InnoDB flush log at trx-commit '); + render_row(status_values($max_allowed_packet_min_rec_value, $max_allowed_packet), 'Maximun allowed packet ', 'Maximun allowed packet '); + render_row(status_values($innodb_buffer_pool_size_min_rec_value, $innodb_buffer_pool_size), 'InnoDB buffer pool size ', 'InnoDB buffer pool size '); + render_row(status_values($sort_buffer_size_min_rec_value, $sort_buffer_size), 'Sort buffer size ', 'Sort buffer size '); + render_row(status_values($join_buffer_size_min_rec_value, $join_buffer_size), 'Join buffer size ', 'Join buffer size '); + render_row(status_values($query_cache_type_min_rec_value, $query_cache_type), 'Query cache type ', 'Query cache type '); + render_row(status_values($query_cache_size_min_rec_value, $query_cache_size), 'Query cache size ', 'Query cache size '); + render_row(status_values($query_cache_limit_min_rec_value, $query_cache_limit), 'Query cache limit ', 'Query cache limit '); + render_row(status_values($innodb_lock_wait_timeout_max_rec_value, $innodb_lock_wait_timeout), 'InnoDB lock wait timeout ', 'InnoDB lock wait timeout '); + render_row(status_values($thread_cache_size_max_rec_value, $thread_cache_size), 'Thread cache size ', 'Thread cache size '); + render_row(status_values($thread_stack_min_rec_value, $thread_stack), 'Thread stack ', 'Thread stack '); + render_row(status_values($max_connections_max_rec_value, $max_connections), 'Maximum connections ', 'Maximun connections '); + render_row(status_values($key_buffer_size_min_rec_value, $key_buffer_size), 'Key buffer size ', 'Key buffer size '); + render_row(status_values($read_buffer_size_min_rec_value, $read_buffer_size), 'Read buffer size ', 'Read buffer size '); + render_row(status_values($read_rnd_buffer_size_min_rec_value, $read_rnd_buffer_size), 'Read rnd-buffer size ', 'Read rnd-buffer size '); + render_row(status_values($query_cache_min_res_unit_min_rec_value, $query_cache_min_res_unit), 'Query cache min-res-unit ', 'Query cache min-res-unit '); + render_row(status_values($innodb_file_per_table_min_rec_value, $innodb_file_per_table), 'InnoDB file per table ', 'InnoDB file per table '); + echo "'; -render_row ($tables_fragmentation_max_rec_value . "%", "Tables fragmentation (maximum recommended value)"); -render_row (number_format($tables_fragmentation, 2) . "%", "Tables fragmentation (current value)"); -render_row (status_fragmentation_tables($tables_fragmentation_max_rec_value, $tables_fragmentation), "Status fragmentation tables"); + render_row($tables_fragmentation_max_rec_value.'%', 'Tables fragmentation (maximum recommended value)'); + render_row(number_format($tables_fragmentation, 2).'%', 'Tables fragmentation (current value)'); + render_row(status_fragmentation_tables($tables_fragmentation_max_rec_value, $tables_fragmentation), 'Status fragmentation tables'); -echo ""; + echo "'; -render_row(number_format(get_logs_size($path_server_logs)/1024, 2) . "M", 'Size server logs (current value)'); -render_row(get_status_logs($path_server_logs),'Status server logs'); -render_row(number_format(get_logs_size($path_console_logs)/1024, 2) . "M", 'Size console logs (current value)'); -render_row(get_status_logs($path_console_logs),'Status console logs'); + render_row(number_format((get_logs_size($path_server_logs) / 1024), 2).'M', 'Size server logs (current value)'); + render_row(get_status_logs($path_server_logs), 'Status server logs'); + render_row(number_format((get_logs_size($path_console_logs) / 1024), 2).'M', 'Size console logs (current value)'); + render_row(get_status_logs($path_console_logs), 'Status console logs'); -echo ""; + echo "'; -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['limit'] . ' agents','Platform Limit'); -render_row( $license['count'] . ' agents','Current Platform Count'); -render_row( $license['count_enabled']. ' agents','Current Platform Count (enabled: items)'); -render_row( $license['count_disabled']. ' agents','Current Platform Count (disabled: items)'); -render_row( $license['license_mode'],'License Mode'); -render_row( status_license_params($license['nms']) , 'Network Management System'); -render_row( status_license_params($license['dhpm']) , 'Satellite'); -render_row( $license['licensed_to'], 'Licensed to'); -render_row( license_capacity(), "Status of agents capacity"); -render_row(percentage_modules_per_agent(), "Status of average modules per agent"); -render_row(interval_average_of_network_modules(), "Interval average of the network modules"); + 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['limit'].' agents', 'Platform Limit'); + render_row($license['count'].' agents', 'Current Platform Count'); + render_row($license['count_enabled'].' agents', 'Current Platform Count (enabled: items)'); + render_row($license['count_disabled'].' agents', 'Current Platform Count (disabled: items)'); + render_row($license['license_mode'], 'License Mode'); + render_row(status_license_params($license['nms']), 'Network Management System'); + render_row(status_license_params($license['dhpm']), 'Satellite'); + render_row($license['licensed_to'], 'Licensed to'); + render_row(license_capacity(), 'Status of agents capacity'); + render_row(percentage_modules_per_agent(), 'Status of average modules per agent'); + render_row(interval_average_of_network_modules(), 'Interval average of the network modules'); -echo ""; + echo "'; -render_row($attachment_total_files, "Total files in the attachment folder"); -render_row(files_attachment_folder($attachment_total_files), "Status of the attachment folder"); + render_row($attachment_total_files, 'Total files in the attachment folder'); + render_row(files_attachment_folder($attachment_total_files), 'Status of the attachment folder'); -echo ""; + echo "'; -render_row($tagente_datos_size, "Total data in the tagente_datos table"); -render_row(status_tagente_datos($tagente_datos_size), "Status of the tagente_datos table"); -render_row(execution_time(), "Degradation of the execution time when executing a count"); + render_row($tagente_datos_size, 'Total data in the tagente_datos table'); + render_row(status_tagente_datos($tagente_datos_size), 'Status of the tagente_datos table'); + render_row(execution_time(), 'Degradation of the execution time when executing a count'); -echo ""; + echo "'; -render_row($total_server_threads, "Total server threads"); -render_row($percentage_threads_ram . "%", "Percentage of threads used by the RAM"); -render_row($percentage_threads_cpu . "%", "Percentage of threads used by the CPU"); + render_row($total_server_threads, 'Total server threads'); + render_row($percentage_threads_ram.'%', 'Percentage of threads used by the RAM'); + render_row($percentage_threads_cpu.'%', 'Percentage of threads used by the CPU'); -echo ""; + echo "'; -$server_name = db_get_value_sql("SELECT name FROM tserver WHERE master = 1"); -$agent_id= db_get_value_sql ("SELECT id_agente FROM tagente WHERE nombre = '$server_name'"); + $server_name = db_get_value_sql('SELECT name FROM tserver WHERE master = 1'); + $agent_id = db_get_value_sql("SELECT id_agente FROM tagente WHERE nombre = '$server_name'"); - $id_modules = agents_get_modules($agent_id); + $id_modules = agents_get_modules($agent_id); - $id_modules = array ( - modules_get_agentmodule_id('Agents_Unknown',$agent_id), - modules_get_agentmodule_id('Database Maintenance',$agent_id), - modules_get_agentmodule_id('FreeDisk_SpoolDir',$agent_id), - modules_get_agentmodule_id('Free_RAM',$agent_id), - modules_get_agentmodule_id('Queued_Modules',$agent_id), - modules_get_agentmodule_id('Status',$agent_id), - modules_get_agentmodule_id('System_Load_AVG',$agent_id), - modules_get_agentmodule_id('Execution_time',$agent_id) - ); + $id_modules = [ + modules_get_agentmodule_id('Agents_Unknown', $agent_id), + modules_get_agentmodule_id('Database Maintenance', $agent_id), + modules_get_agentmodule_id('FreeDisk_SpoolDir', $agent_id), + modules_get_agentmodule_id('Free_RAM', $agent_id), + modules_get_agentmodule_id('Queued_Modules', $agent_id), + modules_get_agentmodule_id('Status', $agent_id), + modules_get_agentmodule_id('System_Load_AVG', $agent_id), + modules_get_agentmodule_id('Execution_time', $agent_id), + ]; - foreach ($id_modules as $id_module){ - $params =array( - 'agent_module_id' => $id_module['id_agente_modulo'], - 'period' => SECONDS_1MONTH, - 'date' => time() , - 'height' => '150' - ); - render_row(grafico_modulo_sparse ($params),"Graph of the " . $id_module['nombre']." module."); - } -if ($console_mode == 0) { - echo "
".__('Pandora status info').'
".__("PHP setup")."
".__('PHP setup').'
".__("Database size stats")."
".__('Database size stats').'
".__("Database sanity")."
".__('Database sanity').'
".__("Database status info")."
".__('Database status info').'
".__("System info")."
".__('System info').'
".__("MySQL Performance metrics")."
".__("Tables fragmentation in the PandoraFMS database")."
".__('MySQL Performance metrics').'
".__('Tables fragmentation in the PandoraFMS database').'
".__(" PandoraFMS logs dates")."
".__(' PandoraFMS logs dates').'
".__(" PandoraFMS Licence Information")."
".__(' PandoraFMS Licence Information').'
".__(" Status of the attachment folder")."
".__(' Status of the attachment folder').'
".__(" Information from the tagente_datos table")."
".__(' Information from the tagente_datos table').'
".__(" Pandora FMS server threads")."
".__(' Pandora FMS server threads').'
".__(" Graphs modules that represent the self-monitoring system")."
".__(' Graphs modules that represent the self-monitoring system').'
"; -} + foreach ($id_modules as $id_module) { + $params = [ + 'agent_module_id' => $id_module['id_agente_modulo'], + 'period' => SECONDS_1MONTH, + 'date' => time(), + 'height' => '150', + ]; + render_row(grafico_modulo_sparse($params), 'Graph of the '.$id_module['nombre'].' module.'); + } -echo "
"; + if ($console_mode == 0) { + echo ''; + } -echo "".__('(*) Please check your Pandora Server setup and be sure that database maintenance daemon is running. It\' very important to -keep up-to-date database to get the best performance and results in Pandora')."


"; + echo "
"; - - -?> \ No newline at end of file + echo ''.__( + '(*) Please check your Pandora Server setup and be sure that database maintenance daemon is running. It\' very important to +keep up-to-date database to get the best performance and results in Pandora' + ).'


'; 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 5b98fdbec0..bedb9927cd 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 @@ -48,8 +48,6 @@ CREATE TABLE IF NOT EXISTS `tlocal_component` ( `dynamic_interval` int(4) unsigned default '0', `dynamic_max` int(4) default '0', `dynamic_min` int(4) default '0', - `dynamic_next` bigint(20) NOT NULL default '0', - `dynamic_two_tailed` tinyint(1) unsigned default '0', `prediction_sample_window` int(10) default 0, `prediction_samples` int(4) default 0, `prediction_threshold` int(4) default 0, @@ -58,6 +56,9 @@ CREATE TABLE IF NOT EXISTS `tlocal_component` ( ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +ALTER TABLE `tlocal_component` ADD COLUMN `dynamic_next` bigint(20) NOT NULL default '0'; +ALTER TABLE `tlocal_component` ADD COLUMN `dynamic_two_tailed` tinyint(1) unsigned default '0'; + -- ----------------------------------------------------- -- Table `tpolicy_modules` -- ----------------------------------------------------- @@ -125,8 +126,6 @@ CREATE TABLE IF NOT EXISTS `tpolicy_modules` ( `dynamic_interval` int(4) unsigned default '0', `dynamic_max` int(4) default '0', `dynamic_min` int(4) default '0', - `dynamic_next` bigint(20) NOT NULL default '0', - `dynamic_two_tailed` tinyint(1) unsigned default '0', `prediction_sample_window` int(10) default 0, `prediction_samples` int(4) default 0, `prediction_threshold` int(4) default 0, @@ -135,6 +134,9 @@ CREATE TABLE IF NOT EXISTS `tpolicy_modules` ( UNIQUE (`id_policy`, `name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +ALTER TABLE `tpolicy_modules` ADD COLUMN `dynamic_next` bigint(20) NOT NULL default '0'; +ALTER TABLE `tpolicy_modules` ADD COLUMN `dynamic_two_tailed` tinyint(1) unsigned default '0'; + -- --------------------------------------------------------------------- -- Table `tpolicies` -- --------------------------------------------------------------------- @@ -181,6 +183,9 @@ CREATE TABLE IF NOT EXISTS `tpolicy_agents` ( UNIQUE (`id_policy`, `id_agent`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +ALTER TABLE `tpolicy_agents` ADD COLUMN `id_node` int(10) NOT NULL DEFAULT '0'; +ALTER TABLE `tpolicy_agents` ADD UNIQUE(`id_policy`, `id_agent`, `id_node`); + -- ----------------------------------------------------- -- Table `tpolicy_groups` -- ----------------------------------------------------- @@ -292,6 +297,8 @@ CREATE TABLE IF NOT EXISTS `tagent_module_inventory` ( ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +ALTER TABLE `tagent_module_inventory` ADD COLUMN `custom_fields` MEDIUMBLOB NOT NULL; + -- --------------------------------------------------------------------- -- Table `tpolicy_modules_inventory` -- --------------------------------------------------------------------- @@ -310,6 +317,8 @@ CREATE TABLE IF NOT EXISTS `tpolicy_modules_inventory` ( ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +ALTER TABLE `tpolicy_modules_inventory` ADD COLUMN `custom_fields` MEDIUMBLOB NOT NULL; + -- ----------------------------------------------------- -- Table `tagente_datos_inventory` -- ----------------------------------------------------- @@ -341,18 +350,13 @@ CREATE TABLE IF NOT EXISTS `ttrap_custom_values` ( -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `tmetaconsole_setup` ( `id` int(10) NOT NULL auto_increment primary key, - `server_name` text, - `server_url` text, - `dbuser` text, - `dbpass` text, - `dbhost` text, - `dbport` text, - `dbname` text, - `meta_dbuser` text, - `meta_dbpass` text, - `meta_dbhost` text, - `meta_dbport` text, - `meta_dbname` text, + `server_name` text default '', + `server_url` text default '', + `dbuser` text default '', + `dbpass` text default '', + `dbhost` text default '', + `dbport` text default '', + `dbname` text default '', `auth_token` text default '', `id_group` int(10) unsigned NOT NULL default 0, `api_password` text NOT NULL, @@ -362,6 +366,12 @@ CREATE TABLE IF NOT EXISTS `tmetaconsole_setup` ( COMMENT = 'Table to store metaconsole sources' DEFAULT CHARSET=utf8; +ALTER TABLE tmetaconsole_setup ADD COLUMN `meta_dbuser` text; +ALTER TABLE tmetaconsole_setup ADD COLUMN `meta_dbpass` text; +ALTER TABLE tmetaconsole_setup ADD COLUMN `meta_dbhost` text; +ALTER TABLE tmetaconsole_setup ADD COLUMN `meta_dbport` text; +ALTER TABLE tmetaconsole_setup ADD COLUMN `meta_dbname` text; + -- --------------------------------------------------------------------- -- Table `tprofile_view` -- --------------------------------------------------------------------- @@ -400,7 +410,7 @@ CREATE TABLE IF NOT EXISTS `tservice` ( `id_template_alert_warning` int(10) unsigned NOT NULL default 0, `id_template_alert_critical` int(10) unsigned NOT NULL default 0, `id_template_alert_unknown` int(10) unsigned NOT NULL default 0, - `id_template_alert_critical_sla` int(10) unsigned NOT NULL default 0 + `id_template_alert_critical_sla` int(10) unsigned NOT NULL default 0, PRIMARY KEY (`id`) ) ENGINE=InnoDB COMMENT = 'Table to define services to monitor' @@ -548,6 +558,8 @@ CREATE TABLE IF NOT EXISTS `tevent_rule` ( KEY `idx_id_event_alert` (`id_event_alert`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +ALTER TABLE `tevent_rule` ADD COLUMN `group_recursion` INT(1) unsigned default 0; + -- ----------------------------------------------------- -- Table `tevent_alert` -- ----------------------------------------------------- @@ -744,14 +756,15 @@ CREATE TABLE IF NOT EXISTS `treport_content_template` ( `module_names` TEXT, `module_free_text` TEXT, `each_agent` tinyint(1) default 1, - `historical_db` tinyint(1) UNSIGNED NOT NULL default 0, - `lapse_calc` tinyint(1) UNSIGNED NOT NULL default '0', - `lapse` int(11) UNSIGNED NOT NULL default '300', - `visual_format` tinyint(1) UNSIGNED NOT NULL default '0', - `hide_no_data` tinyint(1) default 0, PRIMARY KEY(`id_rc`) ) ENGINE = InnoDB DEFAULT CHARSET=utf8; +ALTER TABLE treport_content_template ADD COLUMN `historical_db` tinyint(1) NOT NULL DEFAULT '0'; +ALTER TABLE treport_content_template ADD COLUMN `lapse_calc` tinyint(1) default '0'; +ALTER TABLE treport_content_template ADD COLUMN `lapse` int(11) default '300'; +ALTER TABLE treport_content_template ADD COLUMN `visual_format` tinyint(1) default '0'; +ALTER TABLE treport_content_template ADD COLUMN `hide_no_data` tinyint(1) default '0'; + -- ----------------------------------------------------- -- Table `treport_content_sla_com_temp` (treport_content_sla_combined_template) -- ----------------------------------------------------- @@ -860,6 +873,9 @@ CREATE TABLE IF NOT EXISTS `tmetaconsole_event` ( -- Criticity: 5 - Minor -- Criticity: 6 - Major +ALTER TABLE `tmetaconsole_event` ADD COLUMN `data` double(22,5) default NULL; +ALTER TABLE `tmetaconsole_event` ADD COLUMN `module_status` int(4) NOT NULL default '0'; + -- --------------------------------------------------------------------- -- Table `tmetaconsole_event_history` -- --------------------------------------------------------------------- @@ -905,6 +921,8 @@ CREATE TABLE IF NOT EXISTS `tmetaconsole_event_history` ( -- Criticity: 5 - Minor -- Criticity: 6 - Major +ALTER TABLE `tmetaconsole_event_history` ADD COLUMN `data` double(22,5) default NULL; +ALTER TABLE `tmetaconsole_event_history` ADD COLUMN `module_status` int(4) NOT NULL default '0'; -- --------------------------------------------------------------------- -- Table `textension_translate_string` -- --------------------------------------------------------------------- @@ -957,12 +975,10 @@ CREATE TABLE IF NOT EXISTS `tmetaconsole_agent` ( `agent_version` varchar(100) default '', `ultimo_contacto_remoto` datetime default '1970-01-01 00:00:00', `disabled` tinyint(2) NOT NULL default '0', - `remote` tinyint(1) NOT NULL default '0', `id_parent` int(10) unsigned default '0', `custom_id` varchar(255) default '', `server_name` varchar(100) default '', `cascade_protection` tinyint(2) NOT NULL default '0', - `cascade_protection_module` int(10) unsigned default '0', `timezone_offset` TINYINT(2) NULL DEFAULT '0' COMMENT 'number of hours of diference with the server timezone' , `icon_path` VARCHAR(127) NULL DEFAULT NULL COMMENT 'path in the server to the image of the icon representing the agent' , `update_gis_data` TINYINT(1) NOT NULL DEFAULT '1' COMMENT 'set it to one to update the position data (altitude, longitude, latitude) when getting information from the agent or to 0 to keep the last value and do not update it' , @@ -977,8 +993,6 @@ CREATE TABLE IF NOT EXISTS `tmetaconsole_agent` ( `fired_count` bigint(20) NOT NULL default '0', `update_module_count` tinyint(1) NOT NULL default '0', `update_alert_count` tinyint(1) NOT NULL default '0', - `transactional_agent` tinyint(1) NOT NULL default '0', - `alias` varchar(600) BINARY NOT NULL default '', PRIMARY KEY (`id_agente`), KEY `nombre` (`nombre`(255)), KEY `direccion` (`direccion`), @@ -987,6 +1001,11 @@ CREATE TABLE IF NOT EXISTS `tmetaconsole_agent` ( FOREIGN KEY (`id_tmetaconsole_setup`) REFERENCES tmetaconsole_setup(`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +ALTER TABLE tmetaconsole_agent ADD COLUMN `remote` tinyint(1) NOT NULL default '0'; +ALTER TABLE tmetaconsole_agent ADD COLUMN `cascade_protection_module` int(10) default '0'; +ALTER TABLE tmetaconsole_agent ADD COLUMN `transactional_agent` tinyint(1) NOT NULL default '0'; +ALTER TABLE tmetaconsole_agent ADD COLUMN `alias` VARCHAR(600) not null DEFAULT ''; + -- --------------------------------------------------------------------- -- Table `ttransaction` -- --------------------------------------------------------------------- @@ -1180,13 +1199,13 @@ 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', 23); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('MR', 24); 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', '730'); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('current_package_enterprise', '731'); -- --------------------------------------------------------------------- -- Table `tconfig_os` @@ -1305,6 +1324,10 @@ ALTER TABLE tlayout_data ADD COLUMN `clock_animation` varchar(60) NOT NULL defau ALTER TABLE tlayout_data ADD COLUMN `time_format` varchar(60) NOT NULL default "time"; ALTER TABLE tlayout_data ADD COLUMN `timezone` varchar(60) NOT NULL default "Europe/Madrid"; ALTER TABLE tlayout_data ADD COLUMN `show_last_value` tinyint(1) UNSIGNED NULL default '0'; +ALTER TABLE `tlayout_data` ADD COLUMN `linked_layout_status_type` ENUM ('default', 'weight', 'service') DEFAULT 'default'; +ALTER TABLE `tlayout_data` ADD COLUMN `linked_layout_status_as_service_warning` FLOAT(20, 3) NOT NULL default 0; +ALTER TABLE `tlayout_data` ADD COLUMN `linked_layout_status_as_service_critical` FLOAT(20, 3) NOT NULL default 0; +ALTER TABLE `tlayout_data` ADD COLUMN `linked_layout_node_id` INT(10) NOT NULL default 0; -- --------------------------------------------------------------------- -- Table `tagent_custom_fields` @@ -1358,26 +1381,15 @@ ALTER TABLE treport_content ADD COLUMN `recursion` tinyint(1) default NULL; -- --------------------------------------------------------------------- ALTER TABLE tmodule_relationship ADD COLUMN `id_server` varchar(100) NOT NULL DEFAULT ''; --- Table `tlocal_component` --- --------------------------------------------------------------------- -ALTER TABLE tlocal_component ADD COLUMN `dynamic_next` bigint(20) NOT NULL default '0'; -ALTER TABLE tlocal_component ADD COLUMN `dynamic_two_tailed` tinyint(1) unsigned default '0'; - -- --------------------------------------------------------------------- -- Table `tpolicy_module` -- --------------------------------------------------------------------- ALTER TABLE tpolicy_modules ADD COLUMN `ip_target`varchar(100) default ''; -ALTER TABLE tpolicy_modules ADD COLUMN `dynamic_next` bigint(20) NOT NULL default '0'; -ALTER TABLE tpolicy_modules ADD COLUMN `dynamic_two_tailed` tinyint(1) unsigned default '0'; ALTER TABLE `tpolicy_modules` ADD COLUMN `cps` int NOT NULL DEFAULT 0; -- --------------------------------------------------------------------- -- Table `tmetaconsole_agent` -- --------------------------------------------------------------------- -ALTER TABLE tmetaconsole_agent ADD COLUMN `remote` tinyint(1) NOT NULL default '0'; -ALTER TABLE tmetaconsole_agent ADD COLUMN `cascade_protection_module` int(10) default '0'; -ALTER TABLE tmetaconsole_agent ADD COLUMN `transactional_agent` tinyint(1) NOT NULL default '0'; -ALTER TABLE tmetaconsole_agent ADD COLUMN `alias` VARCHAR(600) not null DEFAULT ''; ALTER TABLE tmetaconsole_agent ADD COLUMN `alias_as_name` int(2) unsigned default '0'; ALTER TABLE tmetaconsole_agent ADD COLUMN `safe_mode_module` int(10) unsigned NOT NULL default '0'; ALTER TABLE `tmetaconsole_agent` ADD COLUMN `cps` int NOT NULL default 0; @@ -1542,6 +1554,8 @@ ALTER TABLE `tdashboard` ADD COLUMN `cells_slideshow` TINYINT(1) NOT NULL defaul -- --------------------------------------------------------------------- -- Table `tsnmp_filter` -- --------------------------------------------------------------------- +ALTER TABLE tsnmp_filter ADD unified_filters_id int(10) NOT NULL DEFAULT 0; + SELECT max(unified_filters_id) INTO @max FROM tsnmp_filter; UPDATE tsnmp_filter tsf,(SELECT @max:= @max) m SET tsf.unified_filters_id = @max:= @max + 1 where tsf.unified_filters_id=0; @@ -1732,7 +1746,7 @@ CREATE TABLE IF NOT EXISTS `tautoconfig_actions` ( -- --------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS `tlayout_template` ( `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, - `name` varchar(50) NOT NULL, + `name` varchar(600) NOT NULL, `id_group` INTEGER UNSIGNED NOT NULL, `background` varchar(200) NOT NULL, `height` INTEGER UNSIGNED NOT NULL default 0, @@ -1778,11 +1792,15 @@ CREATE TABLE IF NOT EXISTS `tlayout_template_data` ( `clock_animation` varchar(60) NOT NULL default "analogic_1", `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', + `linked_layout_status_type` ENUM ('default', 'weight', 'service') DEFAULT 'default', + `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, PRIMARY KEY(`id`), FOREIGN KEY (`id_layout_template`) REFERENCES tlayout_template(`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB DEFAULT CHARSET=utf8; -ALTER TABLE tlayout_template_data ADD COLUMN `show_last_value` tinyint(1) UNSIGNED NULL default '0'; -- --------------------------------------------------------------------- -- Table `tlog_graph_models` -- --------------------------------------------------------------------- @@ -1804,6 +1822,7 @@ INSERT INTO tlog_graph_models VALUES (1, 'Apache log model', -- ----------------------------------------------------- ALTER TABLE `treport` ADD COLUMN `hidden` tinyint(1) NOT NULL DEFAULT 0; +ALTER TABLE `treport` ADD COLUMN `orientation` varchar(25) NOT NULL default 'vertical'; ALTER TABLE `trecon_task` ADD COLUMN `snmp_version` varchar(5) NOT NULL default '1'; ALTER TABLE `trecon_task` ADD COLUMN `snmp_auth_user` varchar(255) NOT NULL default ''; @@ -1824,11 +1843,28 @@ CREATE TABLE IF NOT EXISTS `tagent_custom_fields_filter` ( `id_custom_fields_data` varchar(600) default '', `id_status` varchar(600) default '', `module_search` varchar(600) default '', + `module_status` varchar(600) default '', + `recursion` int(1) unsigned default '0', + `group_search` int(10) unsigned default '0', PRIMARY KEY(`id`) ) ENGINE = InnoDB DEFAULT CHARSET=utf8; -ALTER TABLE `tagent_custom_fields_filter` ADD COLUMN `module_status` varchar(600) default ''; +-- --------------------------------------------------------------------- +-- Table `tevento` +-- --------------------------------------------------------------------- +ALTER TABLE `tevento` ADD COLUMN `data` double(22,5) default NULL; -ALTER TABLE `tagent_custom_fields_filter` ADD COLUMN `recursion` int(1) unsigned default '0'; +ALTER TABLE `tevento` ADD COLUMN `module_status` int(4) NOT NULL default '0'; -ALTER TABLE `tagent_custom_fields_filter` ADD COLUMN `group_search` int(10) unsigned default '0'; +-- ----------------------------------------------------- +-- Table `tgis_map_layer_groups` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `tgis_map_layer_groups` ( + `layer_id` INT NOT NULL, + `group_id` MEDIUMINT(4) UNSIGNED NOT NULL, + `agent_id` INT(10) UNSIGNED NOT NULL COMMENT 'Used to link the position to the group', + PRIMARY KEY (`layer_id`, `group_id`), + FOREIGN KEY (`layer_id`) REFERENCES `tgis_map_layer` (`id_tmap_layer`) ON DELETE CASCADE, + FOREIGN KEY (`group_id`) REFERENCES `tgrupo` (`id_grupo`) ON DELETE CASCADE, + FOREIGN KEY (`agent_id`) REFERENCES `tagente` (`id_agente`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/pandora_console/extras/sample_login.php b/pandora_console/extras/sample_login.php index 5cdd919e17..776a4915fd 100644 --- a/pandora_console/extras/sample_login.php +++ b/pandora_console/extras/sample_login.php @@ -1,15 +1,15 @@ "; echo '
'; echo ''; -echo ''; +echo ''; echo ''; echo '
'; diff --git a/pandora_console/general/alert_enterprise.php b/pandora_console/general/alert_enterprise.php index c319b3910d..69a09d2998 100644 --- a/pandora_console/general/alert_enterprise.php +++ b/pandora_console/general/alert_enterprise.php @@ -1,183 +1,190 @@ "; -if($tipo=='noaccess'){ - echo "You don't have access to this page"; -} -elseif(!enterprise_installed()){ - echo "Community version"; -} -else{ - echo "Enterprise version"; -} + if ($tipo == 'noaccess') { + echo "You don't have access to this page"; + } else if (!enterprise_installed()) { + echo 'Community version'; + } else { + echo 'Enterprise version'; + } -echo " + echo "
- + echo "'>
"; -switch ($tipo) { - - case "helpmodal": - - echo __("This is the online help for %s console. This help is -in best cases- just a brief contextual help, not intented to teach you how to use %s. Official documentation of %s is about 900 pages, and you probably don't need to read it entirely, but sure, you should download it and take a look.

+ switch ($tipo) { + case 'helpmodal': + + echo __( + "This is the online help for %s console. This help is -in best cases- just a brief contextual help, not intented to teach you how to use %s. Official documentation of %s is about 900 pages, and you probably don't need to read it entirely, but sure, you should download it and take a look.

Download the official documentation", - get_product_name(), get_product_name(), get_product_name(), $config['custom_docs_url']); - - break; - - case "noaccess": - - echo __('Access to this page is restricted to authorized users only, please contact system administrator if you need assistance.

+ get_product_name(), + get_product_name(), + get_product_name(), + $config['custom_docs_url'] + ); + + break; + + case 'noaccess': + + echo __( + 'Access to this page is restricted to authorized users only, please contact system administrator if you need assistance.

Please know that all attempts to access this page are recorded in security logs of %s System Database.', - get_product_name()); - - break; - - case "infomodal": - - if($open){ + get_product_name() + ); - echo - '

' . - __('The Update Manager client is included on %s. It helps system administrators update their %s automatically, since the Update Manager retrieves new modules, new plugins and new features (even full migrations tools for future versions) automatically.', get_product_name(), get_product_name()) . - '

' . - '

' . - __('OpenSource version updates are automated packages generated each week. These updates come WITHOUT ANY warranty or support. If your system is corrupted or a feature stops working properly, you will need to recover a backup by yourself.') . - '

' . - '

' . - __('The Enterprise version comes with a different update system, with fully tested, professionally-supported packages, and our support team is there to help you in case of problems or queries. Update Manager is another feature present in the Enterprise version and not included in the OpenSource version. There are lots of advanced business-oriented features contained in %s Enterprise Edition. For more information visit pandorafms.com', get_product_name()) . - '

' - ; - - }else{ - - echo - '

' . - __('The new Update Manager client is included on %s. It helps system administrators update their %s automatically, since the Update Manager retrieves new modules, new plugins and new features (even full migrations tools for future versions) automatically.', get_product_name(), get_product_name()) . - '

' . - '

' . - __('The Update Manager is one of the most advanced features on the %s Enterprise Edition. For more information visit http://pandorafms.com.', get_product_name()) . - '

' . - '

' . - __('Update Manager sends anonymous information about %s usage (number of agents and modules running). To disable it, please remove the remote server address from the Update Manager plugin setup.', get_product_name()) . - '

' - ; + break; + + case 'infomodal': + + if ($open) { + echo '

'.__('The Update Manager client is included on %s. It helps system administrators update their %s automatically, since the Update Manager retrieves new modules, new plugins and new features (even full migrations tools for future versions) automatically.', get_product_name(), get_product_name()).'

'.'

'.__('OpenSource version updates are automated packages generated each week. These updates come WITHOUT ANY warranty or support. If your system is corrupted or a feature stops working properly, you will need to recover a backup by yourself.').'

'.'

'.__('The Enterprise version comes with a different update system, with fully tested, professionally-supported packages, and our support team is there to help you in case of problems or queries. Update Manager is another feature present in the Enterprise version and not included in the OpenSource version. There are lots of advanced business-oriented features contained in %s Enterprise Edition. For more information visit pandorafms.com', get_product_name()).'

'; + } else { + echo '

'.__('The new Update Manager client is included on %s. It helps system administrators update their %s automatically, since the Update Manager retrieves new modules, new plugins and new features (even full migrations tools for future versions) automatically.', get_product_name(), get_product_name()).'

'.'

'.__('The Update Manager is one of the most advanced features on the %s Enterprise Edition. For more information visit http://pandorafms.com.', get_product_name()).'

'.'

'.__('Update Manager sends anonymous information about %s usage (number of agents and modules running). To disable it, please remove the remote server address from the Update Manager plugin setup.', get_product_name()).'

'; + } + break; + + case 'modulemodal': + echo __( + "The community version doesn't have the ability to define your own library of local modules, or distribute it to remote agents. You need to make those changes individually on each agent which is possible by using external tools and time and effort. Nor can it distribute local plugins, or have access to the library of enterprise plugins to monitor applications such as VMWare, RHEV or Informix between others. The Enterprise version will have all this, plus the ability to distribute and manage your own local modules on your systems, individually or through policies. +



* Todos los logotipos pertenecen a marcas registradas" + ); + break; + + case 'massivemodal': + echo __("Do you want to consolidate all your system monitoring? Do you have many systems, making it difficult to manage them in a comprehensive manner? Would you like to deploy monitoring, alerts and even local plugins with a single click? %s Enterprise Policies are exactly what you need; you'll save time, effort and annoyances. More information pandorafms.com", get_product_name()); + break; + + case 'eventsmodal': + echo __('%s Enterprise also features event correlation. Through correlation you can generate realtime alerts and / or new events based on logical rules. This allows you to automate troubleshooting. If you know the value of working with events, event correlation will take you to a new level.', get_product_name()); + break; + + case 'reportingmodal': + echo __('Report generating on the Enterprise version is also more powerful: it has wizards, you can schedule emails in PDF to be sent according to the schedule you decide, and it has a template system to create personalized reports quickly for each of your customers. It will even allow your customers to generate their own reports from templates created by you. If reports are key to your business, %s Enterprise version is for you.', get_product_name()); + break; + + case 'visualmodal': + echo __('These options are only effective on the Enterprise version.'); + break; + + case 'updatemodal': + echo __('WARNING: You are just one click away from an automated update. This may result in a damaged system, including loss of data and operativity. Check you have a recent backup. OpenSource updates are automatically created packages, and there is no WARRANTY or SUPPORT. If you need professional support and warranty, please upgrade to Enterprise Version.'); + break; + + case 'agentsmodal': + echo __('This system is heavily loaded. OpenSource version could get a lot more agents but fine tuning requires knowledge and time. Checkout the Enterprise Version for a professional supported system.'); + break; + + case 'monitorcheckmodal': + echo __('This system has too many modules per agent. OpenSource version could manage thousands of modules, but is not recommended to have more than 40 modules per agent. This configuration has B/A modules per agent. Checkout the Enterprise Version for a professional supported system.'); + break; + + case 'remotemodulesmodal': + echo __('Too much remote modules has been detected on this system. OpenSource version could manage thousands of modules, but performance is limited on high amount of SNMP or ICMP request. Checkout the Enterprise Version for a professional supported system with improved capacity on network monitoring, including distributed servers.'); + break; + + case 'monitoreventsmodal': + echo __('This system has too much events in the database. Checkout database purge options. Checkout the Enterprise Version for a professional supported system.'); + break; + + case 'alertagentmodal': + echo __('You have defined a high number of alerts, this may cause you performance problems in the future. In the Enterprise version, you can use event correlation alerts to simplify the alerting system and have easier administration and increased performance.'); + break; + + default: + break; } - - break; - case "modulemodal": - echo __("The community version doesn't have the ability to define your own library of local modules, or distribute it to remote agents. You need to make those changes individually on each agent which is possible by using external tools and time and effort. Nor can it distribute local plugins, or have access to the library of enterprise plugins to monitor applications such as VMWare, RHEV or Informix between others. The Enterprise version will have all this, plus the ability to distribute and manage your own local modules on your systems, individually or through policies. -



* Todos los logotipos pertenecen a marcas registradas"); - break; - case "massivemodal": - echo __("Do you want to consolidate all your system monitoring? Do you have many systems, making it difficult to manage them in a comprehensive manner? Would you like to deploy monitoring, alerts and even local plugins with a single click? %s Enterprise Policies are exactly what you need; you'll save time, effort and annoyances. More information pandorafms.com", get_product_name()); - break; - case "eventsmodal": - echo __("%s Enterprise also features event correlation. Through correlation you can generate realtime alerts and / or new events based on logical rules. This allows you to automate troubleshooting. If you know the value of working with events, event correlation will take you to a new level.", get_product_name()); - break; - case "reportingmodal": - echo __("Report generating on the Enterprise version is also more powerful: it has wizards, you can schedule emails in PDF to be sent according to the schedule you decide, and it has a template system to create personalized reports quickly for each of your customers. It will even allow your customers to generate their own reports from templates created by you. If reports are key to your business, %s Enterprise version is for you.", get_product_name()); - break; - case "visualmodal": - echo __("These options are only effective on the Enterprise version."); - break; - case "updatemodal": - echo __("WARNING: You are just one click away from an automated update. This may result in a damaged system, including loss of data and operativity. Check you have a recent backup. OpenSource updates are automatically created packages, and there is no WARRANTY or SUPPORT. If you need professional support and warranty, please upgrade to Enterprise Version."); - break; - case "agentsmodal": - echo __("This system is heavily loaded. OpenSource version could get a lot more agents but fine tuning requires knowledge and time. Checkout the Enterprise Version for a professional supported system."); - break; - case "monitorcheckmodal": - echo __("This system has too many modules per agent. OpenSource version could manage thousands of modules, but is not recommended to have more than 40 modules per agent. This configuration has B/A modules per agent. Checkout the Enterprise Version for a professional supported system."); - break; - case "remotemodulesmodal": - echo __("Too much remote modules has been detected on this system. OpenSource version could manage thousands of modules, but performance is limited on high amount of SNMP or ICMP request. Checkout the Enterprise Version for a professional supported system with improved capacity on network monitoring, including distributed servers."); - break; - case "monitoreventsmodal": - echo __("This system has too much events in the database. Checkout database purge options. Checkout the Enterprise Version for a professional supported system."); - break; - case "alertagentmodal": - echo __("You have defined a high number of alerts, this may cause you performance problems in the future. In the Enterprise version, you can use event correlation alerts to simplify the alerting system and have easier administration and increased performance."); - break; - default: - break; -} -echo " + echo "
@@ -185,12 +192,11 @@ echo "
OK
"; -if($open){ -echo "
+ if ($open) { + echo "
About Enterprise
"; -} - + } } ?> diff --git a/pandora_console/general/cg_items.php b/pandora_console/general/cg_items.php index bb76299e07..0c8aaa801c 100644 --- a/pandora_console/general/cg_items.php +++ b/pandora_console/general/cg_items.php @@ -1,7 +1,4 @@ - \ No newline at end of file diff --git a/pandora_console/general/check_image_module.php b/pandora_console/general/check_image_module.php index 422b1de7ba..2e4a65bfde 100644 --- a/pandora_console/general/check_image_module.php +++ b/pandora_console/general/check_image_module.php @@ -1,9 +1,9 @@ - - diff --git a/pandora_console/general/error_screen.php b/pandora_console/general/error_screen.php index 9135170263..0cab19a203 100644 --- a/pandora_console/general/error_screen.php +++ b/pandora_console/general/error_screen.php @@ -4,31 +4,28 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -include_once("include/functions.php"); -include_once("include/functions_html.php"); -include_once("include/functions_ui.php"); -include_once("include/functions_io.php"); -include_once("include/functions_extensions.php"); +require_once 'include/functions.php'; +require_once 'include/functions_html.php'; +require_once 'include/functions_ui.php'; +require_once 'include/functions_io.php'; +require_once 'include/functions_extensions.php'; echo ''; -ob_start ('ui_process_page_head'); +ob_start('ui_process_page_head'); echo ''; -echo '' . "\n"; +echo ''."\n"; -require_once ("include/functions_themes.php"); -ob_start ('ui_process_page_body'); +require_once 'include/functions_themes.php'; +ob_start('ui_process_page_body'); // At this point, $login_screen is setted with the error type desired - -require('login_page.php'); +require 'login_page.php'; ?> diff --git a/pandora_console/general/firts_task/HA_cluster_builder.php b/pandora_console/general/firts_task/HA_cluster_builder.php index 18978db402..fa85e28381 100644 --- a/pandora_console/general/firts_task/HA_cluster_builder.php +++ b/pandora_console/general/firts_task/HA_cluster_builder.php @@ -3,87 +3,85 @@ // ================================================== // Copyright (c) 2005-2018 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access HA cluster"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access HA cluster' + ); + include 'general/noaccess.php'; + exit; } -ui_require_css_file ('firts_task'); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no HA clusters defined yet.') ) ); + true, 'message' => __('There are no HA clusters defined yet.') ]); ?>
-
- __('Clusters')));?> -
-
-

-

+ __('Clusters')]); ?> +

+
+

+

+
'; - + echo __('Click on "add new node" to start transforming your Pandora FMS DB Cluster into a Pandora FMS DB Cluster.').'

'; - - ?>

- -
"; - ?> - - -
+ ?> +

+ +
"; + ?> + + +
diff --git a/pandora_console/general/firts_task/cluster_builder.php b/pandora_console/general/firts_task/cluster_builder.php index dc1e1a3ea3..ba9d8c311a 100644 --- a/pandora_console/general/firts_task/cluster_builder.php +++ b/pandora_console/general/firts_task/cluster_builder.php @@ -4,62 +4,60 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; check_login(); -if (! check_acl ($config['id_user'], 0, "AR") && ! check_acl ($config['id_user'], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access Inventory"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AR') && ! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Inventory' + ); + include 'general/noaccess.php'; + return; } -ui_require_css_file ('firts_task'); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no clusters defined yet.') ) ); + true, 'message' => __('There are no clusters defined yet.') ]); ?>
-
- __('Clusters')));?> -
-
-

-

+ __('Clusters')]); ?> +

+
+

+

+
'; - + echo __('Depending on how they provide that service, we can find two types:').'

'; - + echo __('Clusters to balance the service load: these are active - active (A/A) mode clusters. It means that all the nodes (or machines that compose it) are working. They must be working because if one stops working, it will overload the others.').'

'; - + echo __('Clusters to guarantee service: these are active - passive (A/P) mode clusters. It means that one of the nodes (or machines that make up the cluster) will be running (primary) and another won\'t (secondary). When the primary goes down, the secondary must take over and give the service instead. Although many of the elements of this cluster are active-passive, it will also have active elements in both of them that indicate that the passive node is "online", so that in the case of a service failure in the master, the active node collects this information.'); - - ?>

- - - -
- -
- - -
+ ?> +

+ + + +
+ +
+ + +
\ No newline at end of file diff --git a/pandora_console/general/firts_task/collections.php b/pandora_console/general/firts_task/collections.php index 7d87c6afc0..269de3ba12 100755 --- a/pandora_console/general/firts_task/collections.php +++ b/pandora_console/general/firts_task/collections.php @@ -4,37 +4,39 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no collections defined yet.') ) ); ?> + true, 'message' => __('There are no collections defined yet.') ]); ?>
-
- __('Collections')));?> -
-
-

-

+ __('Collections')]); ?> +

+
+

+

-
- -
-

+ the picture below. " + ); + ?> +

+
+ +
+
diff --git a/pandora_console/general/firts_task/custom_fields.php b/pandora_console/general/firts_task/custom_fields.php index 624bcac357..da5b30f274 100644 --- a/pandora_console/general/firts_task/custom_fields.php +++ b/pandora_console/general/firts_task/custom_fields.php @@ -4,35 +4,36 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no custom fields defined yet.') ) ); + true, 'message' => __('There are no custom fields defined yet.') ]); ?>
-
- __('Custom Fields')));?> -
-
-

-

'Manage monitoring' -> 'Manage custom fields'. "); ?>

-
- -
-
+
+ __('Custom Fields')]); ?> +
+
+

+ 'Manage monitoring' -> 'Manage custom fields'. " + ); + ?> +

+
+ +
+

\ No newline at end of file diff --git a/pandora_console/general/firts_task/custom_graphs.php b/pandora_console/general/firts_task/custom_graphs.php index a951bb4966..80d64300aa 100644 --- a/pandora_console/general/firts_task/custom_graphs.php +++ b/pandora_console/general/firts_task/custom_graphs.php @@ -4,37 +4,39 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no custom graphs defined yet.') ) ); + true, 'message' => __('There are no custom graphs defined yet.') ]); ?>
-
- __('Custom Graphs')));?> -
-
-

-

+ __('Custom Graphs')]); ?> +

+
+

+

-
- -
-

+ get_product_name(), + get_product_name() + ); + ?> +

+
+ +
+
\ No newline at end of file diff --git a/pandora_console/general/firts_task/fields_manager.php b/pandora_console/general/firts_task/fields_manager.php index 0b3fc2a886..db2b3ee0c2 100755 --- a/pandora_console/general/firts_task/fields_manager.php +++ b/pandora_console/general/firts_task/fields_manager.php @@ -4,32 +4,34 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no custom fields defined yet.') ) ); ?> + true, 'message' => __('There are no custom fields defined yet.') ]); ?>
-
- __('Fields Manager')));?> -
-
-

-

'Manage monitoring' -> 'Manage custom fields'. "); ?>

-
- -
-
+
+ __('Fields Manager')]); ?> +
+
+

+ 'Manage monitoring' -> 'Manage custom fields'. " + ); + ?> +

+
+ +
+

diff --git a/pandora_console/general/firts_task/incidents.php b/pandora_console/general/firts_task/incidents.php index a694874cb3..a8acde2829 100644 --- a/pandora_console/general/firts_task/incidents.php +++ b/pandora_console/general/firts_task/incidents.php @@ -4,45 +4,48 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; global $incident_w; global $incident_m; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no incidents defined yet.') ) ); + true, 'message' => __('There are no incidents defined yet.') ]); if ($incident_w || $incident_m) { -?> + ?>
-
- __('Incidents')));?> -
-
-

-

+ __('Incidents')]); ?> +

+
+

+

-
- -
-

+ ", + get_product_name() + ); + ?> +

+
+ +
+
- + true, - 'message'=> __('There are no visual console defined yet.'))); + [ + 'no_close' => true, + 'message' => __('There are no visual console defined yet.'), + ] +); if ($vconsoles_write || $vconsoles_manage) { -?> + ?>
-
- __('Visual Console')));?> -
-
-

-

-
- - -
-
+
+ __('Visual Console')]); ?> +
+
+

+ +

+
+ + +
+

- + -true, 'message'=> __('There are no network map defined yet.') ) ); + true, 'message' => __('There are no network map defined yet.') ]); $strict_user = db_get_value('strict_acl', 'tusuario', 'id_user', $config['id_user']); $networkmap_types = networkmap_get_types($strict_user); ?>
-
- __('Network Map')));?> -
-
-

-

+ __('Network Map')]); ?> +

+
+

+ " . __("Topology Map") . " -

  • " . __("Group Map") . "
  • -
  • " . __("Radial Map (User without strict user)") . "
  • -
  • " . __("Dinamic Map") . "
  • -
  • " . __("Policy Map (Only Enterprise version)") . "
  • "; - ?>

    -
    - - - -
    -

    + ' + ); + echo '
  • '.__('Topology Map').'
  • +
  • '.__('Group Map').'
  • +
  • '.__('Radial Map (User without strict user)').'
  • +
  • '.__('Dinamic Map').'
  • +
  • '.__('Policy Map (Only Enterprise version)').'
  • '; + ?> +

    +
    + + + +
    +
    diff --git a/pandora_console/general/firts_task/planned_downtime.php b/pandora_console/general/firts_task/planned_downtime.php index e8f38d35e9..a2499bd3c1 100644 --- a/pandora_console/general/firts_task/planned_downtime.php +++ b/pandora_console/general/firts_task/planned_downtime.php @@ -4,35 +4,37 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no planned downtime defined yet.') ) ); ?> + true, 'message' => __('There are no planned downtime defined yet.') ]); ?>
    -
    - __('Planned Downtime')));?> -
    -
    -

    -

    + __('Planned Downtime')]); ?> +

    +
    +

    +

    -
    - -
    -

    + get_product_name() + ); + ?> +

    +
    + +
    +
    diff --git a/pandora_console/general/firts_task/recon_view.php b/pandora_console/general/firts_task/recon_view.php index bcb414b92d..026d0f5673 100755 --- a/pandora_console/general/firts_task/recon_view.php +++ b/pandora_console/general/firts_task/recon_view.php @@ -4,35 +4,37 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no recon task defined yet.') ) ); ?> + true, 'message' => __('There are no recon task defined yet.') ]); ?>
    -
    - __('Recon server')));?> -
    -
    -

    -

    + __('Recon server')]); ?> +

    +
    +

    + ICMP (pings), SNMP (detecting the topology of networks and their interfaces), and other customized - type. You can define your own customized recon script.'); ?>

    -
    - -
    -

    + type. You can define your own customized recon script.' + ); + ?> +

    +
    + +
    +
    diff --git a/pandora_console/general/firts_task/service_list.php b/pandora_console/general/firts_task/service_list.php index 9bb647e8b3..f3971ca786 100755 --- a/pandora_console/general/firts_task/service_list.php +++ b/pandora_console/general/firts_task/service_list.php @@ -4,42 +4,45 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; global $agent_w; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no services defined yet.') ) ); ?> + true, 'message' => __('There are no services defined yet.') ]); ?> -
    -
    - __('Services')));?> -
    -
    -

    -

    +

    + __('Services')]); ?> +
    +
    +

    +

    - -
    - -
    - -

    -
    - \ No newline at end of file + His company consists of three big departments: A management, an on-line shop and support." + ); + ?> +

    + +
    + +
    + +
    + + -true, 'message'=> __('There are no SNMP filter defined yet.') ) ); ?> + true, 'message' => __('There are no SNMP filter defined yet.') ]); ?>
    -
    - __('SNMP Filter')));?> -
    -
    -

    -

    + __('SNMP Filter')]); ?> +

    +
    +

    + 'Manage SNMP Console' and 'SNMP Filters'. - One trap which is going to run in conjunction with any of them - just the ones for the server are going to get ruled out automatically. "); ?>

    -
    - -
    -

    + One trap which is going to run in conjunction with any of them - just the ones for the server are going to get ruled out automatically. " + ); + ?> +

    +
    + +
    +
    diff --git a/pandora_console/general/firts_task/tags.php b/pandora_console/general/firts_task/tags.php index e0069e55c0..bbf77c5d2a 100755 --- a/pandora_console/general/firts_task/tags.php +++ b/pandora_console/general/firts_task/tags.php @@ -4,33 +4,35 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no tags defined yet.') ) ); ?> + true, 'message' => __('There are no tags defined yet.') ]); ?>
    -
    - __('Tags')));?> -
    -
    -

    -

    + __('Tags')]); ?> +

    +
    +

    +

    -
    - -
    -

    + A user's access can therefore be restricted to modules with certain tags." + ); + ?> +

    +
    + +
    +
    diff --git a/pandora_console/general/firts_task/transactional_list.php b/pandora_console/general/firts_task/transactional_list.php index a309c1040e..74066fe7bf 100644 --- a/pandora_console/general/firts_task/transactional_list.php +++ b/pandora_console/general/firts_task/transactional_list.php @@ -4,39 +4,43 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; global $networkmaps_write; global $networkmaps_manage; -check_login (); -ui_require_css_file ('firts_task'); +check_login(); +ui_require_css_file('firts_task'); ?> -true, 'message'=> __('There are no transactions defined yet.') ) ); + true, 'message' => __('There are no transactions defined yet.') ]); if ($networkmaps_write || $networkmaps_manage) { -?> + ?>
    -
    - __('Transactions')));?> -
    -
    -

    -

    + __('Transactions')]); ?> +

    +
    +

    +

    -
    - -
    -

    +Transaction graphs represent the different processes within our infrastructure that we use to deliver our service.' + ); + ?> +

    +
    + +
    +
    - + '; +echo ''; -include_once ($config["homedir"]."/include/functions_update_manager.php"); +require_once $config['homedir'].'/include/functions_update_manager.php'; $current_package = update_manager_get_current_package(); -if($current_package == 0){ - $build_package_version = $build_version; -} -else{ - $build_package_version = $current_package; +if ($current_package == 0) { + $build_package_version = $build_version; +} else { + $build_package_version = $current_package; } -echo sprintf(__('%s %s - Build %s - MR %s', get_product_name(), $pandora_version, $build_package_version, $config["MR"])); +echo sprintf(__('%s %s - Build %s - MR %s', get_product_name(), $pandora_version, $build_package_version, $config['MR'])); echo '
    '; -echo ''. __('Page generated at') . ' '. date($config["date_format"]); +echo ''.__('Page generated at').' '.date($config['date_format']); echo '
    ® '.get_copyright_notice().''; -if (isset ($config['debug'])) { - $cache_info = array(); - $cache_info = db_get_cached_queries(); - echo ' - Saved '.$cache_info[0].' Queries'; +if (isset($config['debug'])) { + $cache_info = []; + $cache_info = db_get_cached_queries(); + echo ' - Saved '.$cache_info[0].' Queries'; } - -?> diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index c26bed8762..846f20677b 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -4,507 +4,499 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -require_once ("include/functions_messages.php"); -require_once ('include/functions_servers.php'); +require_once 'include/functions_messages.php'; +require_once 'include/functions_servers.php'; // Check permissions - // Global errors/warnings checking. config_check(); ?> - - - + + - - + + // ======= Autorefresh code ============================= + $autorefresh_txt = ''; + $autorefresh_additional = ''; + + $ignored_params = [ + 'agent_config' => false, + 'code' => false, + ]; + + if (!isset($_GET['sec2'])) { + $_GET['sec2'] = ''; + } + + if (!isset($_GET['refr'])) { + $_GET['refr'] = null; + } + + $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '".$config['id_user']."'"); + $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); + + if ($autorefresh_list !== null && array_search($_GET['sec2'], $autorefresh_list) !== false) { + $do_refresh = true; + if ($_GET['sec2'] == 'operation/agentes/pandora_networkmap') { + if ((!isset($_GET['tab'])) || ($_GET['tab'] != 'view')) { + $do_refresh = false; + } + } + + if ($do_refresh) { + $autorefresh_img = html_print_image('images/header_refresh.png', true, ['class' => 'bot', 'alt' => 'lightning', 'title' => __('Configure autorefresh')]); + + if ($_GET['refr']) { + $autorefresh_txt .= ' ('.date('i:s', $config['refr']).')'; + } + + $ignored_params['refr'] = ''; + $values = get_refresh_time_array(); + $autorefresh_additional = ''; + unset($values); + + $autorefresh_link_open_img = ''; + + if ($_GET['refr']) { + $autorefresh_link_open_txt = ''; + } else { + $autorefresh_link_open_txt = ''; + } + + $autorefresh_link_close = ''; + } else { + $autorefresh_img = html_print_image('images/header_refresh_disabled.png', true, ['class' => 'bot autorefresh_disabled', 'alt' => 'lightning', 'title' => __('Disabled autorefresh')]); + + $ignored_params['refr'] = false; + + $autorefresh_link_open_img = ''; + $autorefresh_link_open_txt = ''; + $autorefresh_link_close = ''; + } + } else { + $autorefresh_img = html_print_image('images/header_refresh_disabled.png', true, ['class' => 'bot autorefresh_disabled', 'alt' => 'lightning', 'title' => __('Disabled autorefresh')]); + + $ignored_params['refr'] = false; + + $autorefresh_link_open_img = ''; + $autorefresh_link_open_txt = ''; + $autorefresh_link_close = ''; + } + + $table->data[0][1] = $autorefresh_link_open_img.$autorefresh_img.$autorefresh_link_close; + $table->data[0][2] = $autorefresh_link_open_txt.$autorefresh_txt.$autorefresh_link_close.$autorefresh_additional; + // ====================================================== + $check_minor_release_available = false; + $pandora_management = check_acl($config['id_user'], 0, 'PM'); + + $check_minor_release_available = db_check_minor_relase_available(); + + if ($check_minor_release_available) { + if (users_is_admin($config['id_user'])) { + if ($config['language'] == 'es') { + set_pandora_error_for_header('Hay una o mas revisiones menores en espera para ser actualizadas. '.__('Sobre actualización de revisión menor').'', 'Revisión/es menor/es disponible/s'); + } else { + set_pandora_error_for_header('There are one or more minor releases waiting for update. '.__('About minor release update').'', 'minor release/s available'); + } + } + } + + echo ''; + + if ($config['alert_cnt'] > 0) { + $maintenance_link = 'javascript:'; + $maintenance_title = __('System alerts detected - Please fix as soon as possible'); + $maintenance_class = $maintenance_id = 'show_systemalert_dialog white'; + + $maintenance_link_open_txt = ''; + $maintenance_link_open_img = ''; + $maintenance_link_close = ''; + if (!$pandora_management) { + $maintenance_img = ''; + } else { + $maintenance_img = $maintenance_link_open_img.html_print_image( + 'images/header_yellow.png', + true, + [ + 'title' => __( + 'You have %d warning(s)', + $config['alert_cnt'] + ), + 'id' => 'yougotalert', + 'class' => 'bot', + ] + ).$maintenance_link_close; + } + } else { + if (!$pandora_management) { + $maintenance_img = ''; + } else { + $maintenance_img = html_print_image('images/header_ready.png', true, ['title' => __('There are not warnings'), 'id' => 'yougotalert', 'class' => 'bot']); + } + } + + $table->data[0][3] = $maintenance_img; + + // Main help icon + if (!$config['disable_help']) { + $table->data[0][4] = ''.html_print_image( + 'images/header_help.png', + true, + [ + 'title' => __('Main help'), + 'id' => 'helpmodal', + 'class' => 'modalpopup', + ] + ).''; + } + + // Logout + $table->data[0][5] = ''; + $table->data[0][5] .= html_print_image('images/header_logout.png', true, ['alt' => __('Logout'), 'class' => 'bot', 'title' => __('Logout')]); + $table->data[0][5] .= ''; + + // User + if (is_user_admin($config['id_user']) == 1) { + $table->data[0][6] = html_print_image('images/header_user_admin.png', true, ['title' => __('Edit my user'), 'class' => 'bot', 'alt' => 'user']); + } else { + $table->data[0][6] = html_print_image('images/header_user.png', true, ['title' => __('Edit my user'), 'class' => 'bot', 'alt' => 'user']); + } + + $table->data[0][6] = ''.$table->data[0][6].''; + + $table->data[0][7] = ' ('.$config['id_user'].')'; + + // Chat messages + $table->data[0][8] = "'; + + // Messages + $msg_cnt = messages_get_count($config['id_user']); + if ($msg_cnt > 0) { + echo ''; + + $table->data[0][9] = ''; + $table->data[0][9] .= html_print_image('images/header_email.png', true, ['title' => __('You have %d unread message(s)', $msg_cnt), 'id' => 'yougotmail', 'class' => 'bot', 'style' => 'width:24px;']); + $table->data[0][9] .= ''; + } + + + + html_print_table($table); + + unset($table); + ?> + + +
    - - $logo_title, "border" => '0')); - ?> - - - id = "header_table"; - $table->class = "none"; - $table->cellpadding = 0; - $table->cellspacing = 0; - $table->head = array (); - $table->data = array (); - $table->style[0] = - $table->style['clippy'] = - $table->style[1] = - $table->style[3] = - $table->style[4] = - $table->style[5] = - $table->style[6] = - $table->style[8] = - $table->style[9] = - $table->style['qr'] = - 'width: 22px; text-align:center; height: 22px; padding-right: 9px;padding-left: 9px;'; - $table->style[7] = 'width: 20px; padding-right: 9px;'; - $table->style['searchbar'] = 'width: 180px; min-width: 180px;'; - $table->style[11] = 'padding-left: 10px; padding-right: 5px;width: 16px;'; - $table->width = "100%"; - $table->styleTable = 'margin: auto; margin-top: 0px;'; - $table->rowclass[0] = ''; - - $acl_head_search = true; - if ($config["acl_enterprise"] == 1 && !users_is_admin()) { - $acl_head_search = db_get_sql("SELECT sec FROM tusuario +
    + + $logo_title, + 'border' => '0', + ] + ); + ?> + + + id = 'header_table'; + $table->class = 'none'; + $table->cellpadding = 0; + $table->cellspacing = 0; + $table->head = []; + $table->data = []; + $table->style[0] = $table->style['clippy'] = $table->style[1] = $table->style[3] = $table->style[4] = $table->style[5] = $table->style[6] = $table->style[8] = $table->style[9] = $table->style['qr'] = 'width: 22px; text-align:center; height: 22px; padding-right: 9px;padding-left: 9px;'; + $table->style[7] = 'width: 20px; padding-right: 9px;'; + $table->style['searchbar'] = 'width: 180px; min-width: 180px;'; + $table->style[11] = 'padding-left: 10px; padding-right: 5px;width: 16px;'; + $table->width = '100%'; + $table->styleTable = 'margin: auto; margin-top: 0px;'; + $table->rowclass[0] = ''; + + $acl_head_search = true; + if ($config['acl_enterprise'] == 1 && !users_is_admin()) { + $acl_head_search = db_get_sql( + "SELECT sec FROM tusuario INNER JOIN tusuario_perfil ON tusuario.id_user = tusuario_perfil.id_usuario INNER JOIN tprofile_view ON tprofile_view.id_profile = tusuario_perfil.id_perfil - WHERE tusuario.id_user = '".$config['id_user']."' AND (sec = '*' OR sec = 'head_search')"); - } - if ($acl_head_search) { - $table->data[0][11] = ui_print_help_tip (__("Blank characters are used as AND conditions"), true); - - // Search bar - $search_bar = '
    '; - if (!isset($config['search_keywords'])) { - $search_bar .= ''; - } - else { - if (strlen($config['search_keywords']) == 0) - $search_bar .= ''; - else - $search_bar .= ''; - } - - $search_bar .= 'data[0][11] = ui_print_help_tip(__('Blank characters are used as AND conditions'), true); + + // Search bar + $search_bar = ''; + if (!isset($config['search_keywords'])) { + $search_bar .= ''; + } else { + if (strlen($config['search_keywords']) == 0) { + $search_bar .= ''; + } else { + $search_bar .= ''; + } + } + + $search_bar .= ''; - - //$search_bar .= 'onClick="javascript: document.quicksearch.submit()"'; - - $search_bar .= ""; - $search_bar .= '
    '; - - $table->data[0]['searchbar'] = $search_bar; - } - - // Servers check - $servers = array(); - $servers["all"] = (int) db_get_value ('COUNT(id_server)','tserver'); - $servers["up"] = (int) servers_check_status (); - $servers["down"] = $servers["all"] - $servers["up"]; - if ($servers["up"] == 0) { - //All Servers down or no servers at all - $servers_check_img = html_print_image("images/header_down.png", true, array("alt" => 'cross', "class" => 'bot', 'title' => __('All systems').': '.__('Down'))); - } - elseif ($servers["down"] != 0) { - //Some servers down - $servers_check_img = html_print_image("images/header_warning.png", true, array("alt" => 'error', "class" => 'bot', 'title' => $servers["down"].' '.__('servers down'))); - } - else { - //All servers up - $servers_check_img = html_print_image("images/header_ready.png", true, array("alt" => 'ok', "class" => 'bot', 'title' => __('All systems').': '.__('Ready'))); - } - unset ($servers); // Since this is the header, we don't like to trickle down variables. - - $servers_link_open = ''; - $servers_link_close = ''; - - if ($config['show_qr_code_header'] == 0){ - $show_qr_code_header = 'display: none;'; - } - else { - $show_qr_code_header = 'display: inline;'; - } - - $table->data[0]['qr'] = - ''; - - echo ""; - ?> - - data[0]['clippy'] = - '' . - html_print_image( - "images/clippy_icon.png", - true, - array("id" => 'clippy', - "class" => 'clippy', - "alt" => __('%s assistant', get_product_name()), - 'title' => __('%s assistant', get_product_name()))) . - ''; - } - - - $table->data[0][0] = $servers_link_open . - $servers_check_img . $servers_link_close; - - - - - //======= Autorefresh code ============================= - $autorefresh_txt = ''; - $autorefresh_additional = ''; - - $ignored_params = array ('agent_config' => false, 'code' => false); - - if (!isset($_GET['sec2'])) { - $_GET['sec2'] = ''; - } - if (!isset($_GET['refr'])) { - $_GET['refr'] = null; - } - - $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '" . $config['id_user'] . "'"); - $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); - - if ($autorefresh_list !== null && array_search($_GET['sec2'], $autorefresh_list) !== false) { - $do_refresh = true; - if ($_GET['sec2'] == 'operation/agentes/pandora_networkmap') { - if ((!isset($_GET['tab'])) || ($_GET['tab'] != 'view')) { - $do_refresh = false; - } - } - if ($do_refresh) { - $autorefresh_img = html_print_image("images/header_refresh.png", true, array("class" => 'bot', "alt" => 'lightning', 'title' => __('Configure autorefresh'))); - - if ($_GET['refr']) { - $autorefresh_txt .= ' ('.date ("i:s", $config["refr"]).')'; - } - - $ignored_params['refr'] = ''; - $values = get_refresh_time_array(); - $autorefresh_additional = ''; - unset ($values); - - $autorefresh_link_open_img = - ''; - - if ($_GET['refr']) { - $autorefresh_link_open_txt = - ''; - } - else { - $autorefresh_link_open_txt = ''; - } - - $autorefresh_link_close = ''; - } - else { - $autorefresh_img = html_print_image("images/header_refresh_disabled.png", true, array("class" => 'bot autorefresh_disabled', "alt" => 'lightning', 'title' => __('Disabled autorefresh'))); - - $ignored_params['refr'] = false; - - $autorefresh_link_open_img = ''; - $autorefresh_link_open_txt = ''; - $autorefresh_link_close = ''; - } - } - else { - $autorefresh_img = html_print_image("images/header_refresh_disabled.png", true, array("class" => 'bot autorefresh_disabled', "alt" => 'lightning', 'title' => __('Disabled autorefresh'))); - - $ignored_params['refr'] = false; - - $autorefresh_link_open_img = ''; - $autorefresh_link_open_txt = ''; - $autorefresh_link_close = ''; - } - - $table->data[0][1] = $autorefresh_link_open_img . $autorefresh_img . $autorefresh_link_close; - $table->data[0][2] = $autorefresh_link_open_txt . $autorefresh_txt . $autorefresh_link_close . $autorefresh_additional; - //====================================================== - - - $check_minor_release_available = false; - $pandora_management = check_acl($config['id_user'], 0, "PM"); - - $check_minor_release_available = db_check_minor_relase_available (); - - if ($check_minor_release_available) { - if (users_is_admin($config['id_user'])) { - - if($config['language'] == 'es'){ - set_pandora_error_for_header('Hay una o mas revisiones menores en espera para ser actualizadas. '.__('Sobre actualización de revisión menor').'', 'Revisión/es menor/es disponible/s'); - } - else{ - set_pandora_error_for_header('There are one or more minor releases waiting for update. '.__('About minor release update').'', 'minor release/s available'); - } - } - } - echo ''; + // $search_bar .= 'onClick="javascript: document.quicksearch.submit()"'; + $search_bar .= ""; + $search_bar .= ''; - if ($config["alert_cnt"] > 0) { - $maintenance_link = 'javascript:'; - $maintenance_title = __("System alerts detected - Please fix as soon as possible"); - $maintenance_class = $maintenance_id = 'show_systemalert_dialog white'; - - $maintenance_link_open_txt = - ''; - $maintenance_link_open_img = - ''; - $maintenance_link_close = ''; - if (!$pandora_management) { - $maintenance_img = ''; - } - else { - $maintenance_img = $maintenance_link_open_img . - html_print_image("images/header_yellow.png", - true, array( - "title" => __('You have %d warning(s)', - $config["alert_cnt"]), - "id" => "yougotalert", - "class" => "bot")) . $maintenance_link_close; - } - } - else { - if (!$pandora_management) { - $maintenance_img = ''; - } - else { - $maintenance_img = html_print_image ("images/header_ready.png", true, array ("title" => __('There are not warnings'), "id" => "yougotalert", "class" => "bot")); - } - } - - $table->data[0][3] = $maintenance_img; - - // Main help icon - if (!$config['disable_help']) { - $table->data[0][4] = - '' . - html_print_image("images/header_help.png", true, array( - "title" => __('Main help'), - "id" => "helpmodal", - "class" => "modalpopup")) . - ''; - } - - // Logout - $table->data[0][5] = ''; - $table->data[0][5] .= html_print_image("images/header_logout.png", true, array("alt" => __('Logout'), "class" => 'bot', "title" => __('Logout'))); - $table->data[0][5] .= ''; - - // User - if (is_user_admin ($config["id_user"]) == 1) - $table->data[0][6] = html_print_image("images/header_user_admin.png" , true, array("title" => __('Edit my user'), "class" => 'bot', "alt" => 'user')); - else - $table->data[0][6] = html_print_image("images/header_user.png" , true, array("title" => __('Edit my user'), "class" => 'bot', "alt" => 'user')); - - $table->data[0][6] = '' . $table->data[0][6] . ''; - - $table->data[0][7] = ' (' . $config["id_user"] . ')'; - - // Chat messages - $table->data[0][8] = ""; - - // Messages - $msg_cnt = messages_get_count ($config["id_user"]); - if ($msg_cnt > 0) { - echo ''; - - $table->data[0][9] = ''; - $table->data[0][9] .= html_print_image ("images/header_email.png", true, array ("title" => __('You have %d unread message(s)', $msg_cnt), "id" => "yougotmail", "class" => "bot", 'style' => 'width:24px;')); - $table->data[0][9] .= ''; - } + $table->data[0]['searchbar'] = $search_bar; + } + + // Servers check + $servers = []; + $servers['all'] = (int) db_get_value('COUNT(id_server)', 'tserver'); + $servers['up'] = (int) servers_check_status(); + $servers['down'] = ($servers['all'] - $servers['up']); + if ($servers['up'] == 0) { + // All Servers down or no servers at all + $servers_check_img = html_print_image('images/header_down.png', true, ['alt' => 'cross', 'class' => 'bot', 'title' => __('All systems').': '.__('Down')]); + } else if ($servers['down'] != 0) { + // Some servers down + $servers_check_img = html_print_image('images/header_warning.png', true, ['alt' => 'error', 'class' => 'bot', 'title' => $servers['down'].' '.__('servers down')]); + } else { + // All servers up + $servers_check_img = html_print_image('images/header_ready.png', true, ['alt' => 'ok', 'class' => 'bot', 'title' => __('All systems').': '.__('Ready')]); + } + + unset($servers); + // Since this is the header, we don't like to trickle down variables. + $servers_link_open = ''; + $servers_link_close = ''; + + if ($config['show_qr_code_header'] == 0) { + $show_qr_code_header = 'display: none;'; + } else { + $show_qr_code_header = 'display: inline;'; + } + + $table->data[0]['qr'] = ''; + + echo "'; + ?> + + data[0]['clippy'] = ''.html_print_image( + 'images/clippy_icon.png', + true, + [ + 'id' => 'clippy', + 'class' => 'clippy', + 'alt' => __('%s assistant', get_product_name()), + 'title' => __( + '%s assistant', + get_product_name() + ), + ] + ).''; + } + + + $table->data[0][0] = $servers_link_open.$servers_check_img.$servers_link_close; - html_print_table($table); - - unset($table); - ?> -
    diff --git a/pandora_console/general/last_message.php b/pandora_console/general/last_message.php index 01c6af40b2..f6649a8e72 100644 --- a/pandora_console/general/last_message.php +++ b/pandora_console/general/last_message.php @@ -4,11 +4,9 @@ // ================================================== // Copyright (c) 2005-2016 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the @@ -20,35 +18,36 @@ global $config; -include_once("include/functions_update_manager.php"); +require_once 'include/functions_update_manager.php'; -$message = array(); +$message = []; if (is_ajax()) { - - $message_id = get_parameter ('message_id', false); - if ($message_id === false) return false; - $message = update_manger_get_single_message ($message_id); - + $message_id = get_parameter('message_id', false); + if ($message_id === false) { + return false; + } + + $message = update_manger_get_single_message($message_id); } else { - - $message = update_manger_get_last_message (); + $message = update_manger_get_last_message(); - if ($message === false) return false; + if ($message === false) { + return false; + } - update_manger_set_read_message($message["svn_version"], 1); - update_manager_remote_read_messages ($message["svn_version"]); + update_manger_set_read_message($message['svn_version'], 1); + update_manager_remote_read_messages($message['svn_version']); } // Prints first step pandora registration -echo '
    '; - - echo '
    '; - echo io_safe_output_html($message["data"]); - echo '
    '; +echo '
    '; + + echo '
    '; + echo io_safe_output_html($message['data']); + echo '
    '; echo '
    '; ?> @@ -57,17 +56,17 @@ echo '
    '; /* */ diff --git a/pandora_console/general/license/pandora_info_ast.html b/pandora_console/general/license/pandora_info_ast.html index d7c82ff2da..98cd25040d 100644 --- a/pandora_console/general/license/pandora_info_ast.html +++ b/pandora_console/general/license/pandora_info_ast.html @@ -1,392 +1,542 @@ - - -Licencia Pública GNU - - - -

    Licencia Pública GNU

    -

    Contenido

    + + + Licencia Pública GNU + + +

    Licencia Pública GNU

    +

    Contenido

    - -
    -

    Licencia Pública GNU

    -

    -Esta es la conocida GNU Public License (GPL), versión 2 (de junio -de 1.991), que cubre la mayor parte del software de la Free Software Foundation, -y muchos más programas.

    + +
    +

    Licencia Pública GNU

    +

    + Esta es la conocida GNU Public License (GPL), versión 2 (de junio + de 1.991), que cubre la mayor parte del software de la Free Software + Foundation, y muchos más programas. +

    -

    Los autores de esta traducción son:

    - +

    Los autores de esta traducción son:

    + -
    -
    -NOTA IMPORTANTE: -

    -Esta es una traducción no oficial al español de la GNU General Public -License. No ha sido publicada por la Free Software Foundation, y no -establece legalmente las condiciones de distribución para el software -que usa la GNU GPL. Estas condiciones se establecen solamente por -el texto original, en inglés, de la GNU GPL. Sin embargo, esperamos -que esta traducción ayude a los hispanohablantes a entender mejor la -GNU GPL. -

    +

    +
    + NOTA IMPORTANTE: +

    + Esta es una traducción no oficial al español de la GNU + General Public License. No ha sido publicada por la Free Software + Foundation, y no establece legalmente las condiciones de + distribución para el software que usa la GNU GPL. Estas + condiciones se establecen solamente por el texto original, en + inglés, de la GNU GPL. Sin embargo, esperamos que esta + traducción ayude a los hispanohablantes a entender mejor la GNU + GPL. +

    +

    IMPORTANT NOTICE:

    +

    + This is an unofficial translation of the GNU General Public License into + Spanish. It was not published by the Free Software Foundation, and does + not legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, + we hope that this translation will help Spanish speakers understand the + GNU GPL better. +

    +

    +
    +
    -IMPORTANT NOTICE: -

    -This is an unofficial translation of the GNU General Public License -into Spanish. It was not published by the Free Software -Foundation, and does not legally state the distribution terms for -software that uses the GNU GPL--only the original English text of -the GNU GPL does that. However, we hope that this translation will -help Spanish speakers understand the GNU GPL better. -

    -


    -
    +

    Copyright (C) 1989, 1991 Free Software Foundation, Inc.

    +

    675 Mass Ave, Cambridge, MA 02139, EEUU

    +

    + Se permite la copia y distribución de copias literales de este + documento, pero no se permite su modificación. +

    -

    Copyright (C) 1989, 1991 Free Software Foundation, Inc. -

    675 Mass Ave, Cambridge, MA 02139, EEUU -

    Se permite la copia y distribución de copias literales de este -documento, pero no se permite su modificación. -

    +

    Preámbulo

    +

    + Las licencias que cubren la mayor parte del software están + diseñadas para quitarle a usted la libertad de compartirlo y + modificarlo. Por el contrario, la Licencia Pública General de GNU + pretende garantizarle la libertad de compartir y modificar software libre, + para asegurar que el software es libre para todos sus usuarios. Esta + Licencia Pública General se aplica a la mayor parte del software + del la Free Software Foundation y a cualquier otro programa si sus autores + se comprometen a utilizarla. (Existe otro software de la Free Software + Foundation que está cubierto por la Licencia Pública General + de GNU para Bibliotecas). Si quiere, también puede aplicarla a sus + propios programas. +

    +

    + Cuando hablamos de software libre, estamos refiriéndonos a + libertad, no a precio. Nuestras Licencias Públicas Generales + están diseñadas para asegurarnos de que tenga la libertad de + distribuir copias de software libre (y cobrar por ese servicio si quiere), + de que reciba el código fuente o que pueda conseguirlo si lo + quiere, de que pueda modificar el software o usar fragmentos de él + en nuevos programas libres, y de que sepa que puede hacer todas estas + cosas. +

    +

    + Para proteger sus derechos necesitamos algunas restricciones que prohiban + a cualquiera negarle a usted estos derechos o pedirle que renuncie a + ellos. Estas restricciones se traducen en ciertas obligaciones que le + afectan si distribuye copias del software, o si lo modifica. +

    +

    + Por ejemplo, si distribuye copias de uno de estos programas, sea + gratuitamente, o a cambio de una contraprestación, debe dar a los + receptores todos los derechos que tiene. Debe asegurarse de que ellos + también reciben, o pueden conseguir, el código fuente. Y + debe mostrarles estas condiciones de forma que conozcan sus derechos. +

    +

    Protegemos sus derechos con la combinación de dos medidas:

    +
      +
    1. Ponemos el software bajo copyright y
    2. +
    3. + le ofrecemos esta licencia, que le da permiso legal para copiar, + distribuir y/o modificar el software. +
    4. +
    +

    + También, para la protección de cada autor y la nuestra + propia, queremos asegurarnos de que todo el mundo comprende que no se + proporciona ninguna garantía para este software libre. Si el + software se modifica por cualquiera y éste a su vez lo distribuye, + queremos que sus receptores sepan que lo que tienen no es el original, de + forma que cualquier problema introducido por otros no afecte a la + reputación de los autores originales. +

    +

    + Por último, cualquier programa libre está constantemente + amenazado por patentes sobre el software. Queremos evitar el peligro de + que los redistribuidores de un programa libre obtengan patentes por su + cuenta, convirtiendo de facto el programa en propietario. Para evitar + esto, hemos dejado claro que cualquier patente debe ser pedida para el uso + libre de cualquiera, o no ser pedida. +

    +

    + Los términos exactos y las condiciones para la copia, + distribución y modificación se exponen a + continuación. +

    +

    + Términos y condiciones para la copia, distribución y + modificación +

    -

    Preámbulo

    -

    -Las licencias que cubren la mayor parte del software están diseñadas -para quitarle a usted la libertad de compartirlo y modificarlo. Por el -contrario, la Licencia Pública General de GNU pretende garantizarle -la libertad de compartir y modificar software libre, para asegurar que -el software es libre para todos sus usuarios. Esta Licencia Pública -General se aplica a la mayor parte del software del la Free Software Foundation -y a cualquier otro programa si sus autores se comprometen a utilizarla. -(Existe otro software de la Free Software Foundation que está cubierto -por la Licencia Pública General de GNU para Bibliotecas). Si quiere, -también puede aplicarla a sus propios programas.

    -

    Cuando hablamos de software libre, estamos refiriéndonos a libertad, -no a precio. Nuestras Licencias Públicas Generales están -diseñadas para asegurarnos de que tenga la libertad de distribuir -copias de software libre (y cobrar por ese servicio si quiere), de que -reciba el código fuente o que pueda conseguirlo si lo quiere, de -que pueda modificar el software o usar fragmentos de él en nuevos -programas libres, y de que sepa que puede hacer todas estas cosas. -

    Para proteger sus derechos necesitamos algunas restricciones que prohiban -a cualquiera negarle a usted estos derechos o pedirle que renuncie a ellos. -Estas restricciones se traducen en ciertas obligaciones que le afectan -si distribuye copias del software, o si lo modifica. -

    Por ejemplo, si distribuye copias de uno de estos programas, sea gratuitamente, -o a cambio de una contraprestación, debe dar a los receptores todos -los derechos que tiene. Debe asegurarse de que ellos también reciben, -o pueden conseguir, el código fuente. Y debe mostrarles estas condiciones -de forma que conozcan sus derechos. -

    Protegemos sus derechos con la combinación de dos medidas: -

      -
    1. Ponemos el software bajo copyright y -
    2. le ofrecemos esta licencia, que le da permiso legal para copiar, distribuir -y/o modificar el software.
    -

    -También, para la protección de cada autor y la nuestra propia, -queremos asegurarnos de que todo el mundo comprende que no se proporciona -ninguna garantía para este software libre. Si el software se modifica -por cualquiera y éste a su vez lo distribuye, queremos que sus receptores -sepan que lo que tienen no es el original, de forma que cualquier problema -introducido por otros no afecte a la reputación de los autores originales.

    -

    Por último, cualquier programa libre está constantemente -amenazado por patentes sobre el software. Queremos evitar el peligro de -que los redistribuidores de un programa libre obtengan patentes por su -cuenta, convirtiendo de facto el programa en propietario. Para evitar esto, -hemos dejado claro que cualquier patente debe ser pedida para el uso libre -de cualquiera, o no ser pedida. -

    Los términos exactos y las condiciones para la copia, distribución -y modificación se exponen a continuación.

    +
      +
    1. + Esta Licencia se aplica a cualquier programa u otro tipo de trabajo que + contenga una nota colocada por el tenedor del copyright diciendo que + puede ser distribuido bajo los términos de esta Licencia + Pública General. En adelante, «Programa» se + referirá a cualquier programa o trabajo que cumpla esa + condición y «trabajo basado en el Programa» se + referirá bien al Programa o a cualquier trabajo derivado de + él según la ley de copyright. Esto es, un trabajo que + contenga el programa o una proción de él, bien en forma + literal o con modificaciones y/o traducido en otro lenguaje. Por lo + tanto, la traducción está incluida sin limitaciones en el + término «modificación». Cada concesionario + (licenciatario) será denominado «usted». +

      + Cualquier otra actividad que no sea la copia, distribución o + modificación no está cubierta por esta Licencia, + está fuera de su ámbito. El acto de ejecutar el Programa + no está restringido, y los resultados del Programa están + cubiertos únicamente si sus contenidos constituyen un trabajo + basado en el Programa, independientemente de haberlo producido + mediante la ejecución del programa. El que esto se cumpla, + depende de lo que haga el programa. +

      +
    2. +
    3. + Usted puede copiar y distribuir copias literales del código + fuente del Programa, según lo has recibido, en cualquier medio, + supuesto que de forma adecuada y bien visible publique en cada copia un + anuncio de copyright adecuado y un repudio de garantía, mantenga + intactos todos los anuncios que se refieran a esta Licencia y a la + ausencia de garantía, y proporcione a cualquier otro receptor del + programa una copia de esta Licencia junto con el Programa. +

      + Puede cobrar un precio por el acto físico de transferir una + copia, y puede, según su libre albedrío, ofrecer + garantía a cambio de unos honorarios. +

      +
    4. +
    5. + Puede modificar su copia o copias del Programa o de cualquier + porción de él, formando de esta manera un trabajo basado + en el Programa, y copiar y distribuir esa modificación o trabajo + bajo los términos del apartado 1, antedicho, supuesto que + además cumpla las siguientes condiciones: +
        +
      1. + Debe hacer que los ficheros modificados lleven anuncios prominentes + indicando que los ha cambiado y la fecha de cualquier cambio. +
      2. +
      3. + Debe hacer que cualquier trabajo que distribuya o publique y que en + todo o en parte contenga o sea derivado del Programa o de cualquier + parte de él sea licenciada como un todo, sin carga alguna, a + todas las terceras partes y bajo los términos de esta + Licencia. +
      4. +
      5. + Si el programa modificado lee normalmente órdenes + interactivamente cuando es ejecutado, debe hacer que, cuando + comience su ejecución para ese uso interactivo de la forma + más habitual, muestre o escriba un mensaje que incluya un + anuncio de copyright y un anuncio de que no se ofrece ninguna + garantía (o por el contrario que sí se ofrece + garantía) y que los usuarios pueden redistribuir el programa + bajo estas condiciones, e indicando al usuario cómo ver una + copia de esta licencia. (Excepción: si el propio programa es + interactivo pero normalmente no muestra ese anuncio, no se requiere + que su trabajo basado en el Programa muestre ningún anuncio). +
      6. +
      + Estos requisitos se aplican al trabajo modificado como un todo. Si + partes identificables de ese trabajo no son derivadas del Programa, y + pueden, razonablemente, ser consideradas trabajos independientes y + separados por ellos mismos, entonces esta Licencia y sus términos + no se aplican a esas partes cuando sean distribuidas como trabajos + separados. Pero cuando distribuya esas mismas secciones como partes de + un todo que es un trabajo basado en el Programa, la distribución + del todo debe ser según los términos de esta licencia, + cuyos permisos para otros licenciatarios se extienden al todo completo, + y por lo tanto a todas y cada una de sus partes, con independencia de + quién la escribió. +

      + Por lo tanto, no es la intención de este apartado reclamar + derechos o desafiar sus derechos sobre trabajos escritos totalmente + por usted mismo. El intento es ejercer el derecho a controlar la + distribución de trabajos derivados o colectivos basados en el + Programa. +

      +

      + Además, el simple hecho de reunir un trabajo no basado en el + Programa con el Programa (o con un trabajo basado en el Programa) en + un volumen de almacenamiento o en un medio de distribución no + hace que dicho trabajo entre dentro del ámbito cubierto por + esta Licencia. +

      +
    6. +
    7. + Puede copiar y distribuir el Programa (o un trabajo basado en él, + según se especifica en el apartado 2, como código objeto o + en formato ejecutable según los términos de los apartados + 1 y 2, supuesto que además cumpla una de las siguientes + condiciones: +
        +
      1. + Acompañarlo con el código fuente completo + correspondiente, en formato electrónico, que debe ser + distribuido según se especifica en los apartados 1 y 2 de + esta Licencia en un medio habitualmente utilizado para el + intercambio de programas, o +
      2. +
      3. + Acompañarlo con una oferta por escrito, válida durante + al menos tres años, de proporcionar a cualquier tercera parte + una copia completa en formato electrónico del código + fuente correspondiente, a un coste no mayor que el de realizar + físicamente la distribución del fuente, que + será distribuido bajo las condiciones descritas en los + apartados 1 y 2 anteriores, en un medio habitualmente utilizado para + el intercambio de programas, o +
      4. +
      5. + Acompañarlo con la información que recibiste + ofreciendo distribuir el código fuente correspondiente. (Esta + opción se permite sólo para distribución no + comercial y sólo si usted recibió el programa como + código objeto o en formato ejecutable con tal oferta, de + acuerdo con el apartado b anterior). +
      6. +
      + Por código fuente de un trabajo se entiende la forma preferida + del trabajo cuando se le hacen modificaciones. Para un trabajo + ejecutable, se entiende por código fuente completo todo el + código fuente para todos los módulos que contiene, + más cualquier fichero asociado de definición de + interfaces, más los guiones utilizados para controlar la + compilación e instalación del ejecutable. Como + excepción especial el código fuente distribuido no + necesita incluir nada que sea distribuido normalmente (bien como fuente, + bien en forma binaria) con los componentes principales (compilador, + kernel y similares) del sistema operativo en el cual funciona el + ejecutable, a no ser que el propio componente acompañe al + ejecutable. +

      + Si la distribución del ejecutable o del código objeto se + hace mediante la oferta acceso para copiarlo de un cierto lugar, + entonces se considera la oferta de acceso para copiar el código + fuente del mismo lugar como distribución del código + fuente, incluso aunque terceras partes no estén forzadas a + copiar el fuente junto con el código objeto. +

      +
    8. +
    9. + No puede copiar, modificar, sublicenciar o distribuir el Programa + excepto como prevé expresamente esta Licencia. Cualquier intento + de copiar, modificar sublicenciar o distribuir el Programa de otra forma + es inválida, y hará que cesen automáticamente los + derechos que te proporciona esta Licencia. En cualquier caso, las partes + que hayan recibido copias o derechos de usted bajo esta Licencia no + cesarán en sus derechos mientras esas partes continúen + cumpliéndola. +
    10. +
    11. + No está obligado a aceptar esta licencia, ya que no la ha + firmado. Sin embargo, no hay hada más que le proporcione permiso + para modificar o distribuir el Programa o sus trabajos derivados. Estas + acciones están prohibidas por la ley si no acepta esta Licencia. + Por lo tanto, si modifica o distribuye el Programa (o cualquier trabajo + basado en el Programa), está indicando que acepta esta Licencia + para poder hacerlo, y todos sus términos y condiciones para + copiar, distribuir o modificar el Programa o trabajos basados en + él. +
    12. +
    13. + Cada vez que redistribuya el Programa (o cualquier trabajo basado en el + Programa), el receptor recibe automáticamente una licencia del + licenciatario original para copiar, distribuir o modificar el Programa, + de forma sujeta a estos términos y condiciones. No puede imponer + al receptor ninguna restricción más sobre el ejercicio de + los derechos aquí garantizados. No es usted responsable de hacer + cumplir esta licencia por terceras partes. +
    14. +
    15. + Si como consecuencia de una resolución judicial o de una + alegación de infracción de patente o por cualquier otra + razón (no limitada a asuntos relacionados con patentes) se le + imponen condiciones (ya sea por mandato judicial, por acuerdo o por + cualquier otra causa) que contradigan las condiciones de esta Licencia, + ello no le exime de cumplir las condiciones de esta Licencia. Si no + puede realizar distribuciones de forma que se satisfagan + simultáneamente sus obligaciones bajo esta licencia y cualquier + otra obligación pertinente entonces, como consecuencia, no puede + distribuir el Programa de ninguna forma. Por ejemplo, si una patente no + permite la redistribución libre de derechos de autor del Programa + por parte de todos aquellos que reciban copias directa o indirectamente + a través de usted, entonces la única forma en que + podría satisfacer tanto esa condición como esta Licencia + sería evitar completamente la distribución del Programa. +

      + Si cualquier porción de este apartado se considera + inválida o imposible de cumplir bajo cualquier circunstancia + particular ha de cumplirse el resto y la sección por entero ha + de cumplirse en cualquier otra circunstancia. +

      +

      + No es el propósito de este apartado inducirle a infringir + ninguna reivindicación de patente ni de ningún otro + derecho de propiedad o impugnar la validez de ninguna de dichas + reivindicaciones. Este apartado tiene el único propósito + de proteger la integridad del sistema de distribución de + software libre, que se realiza mediante prácticas de licencia + pública. Mucha gente ha hecho contribuciones generosas a la + gran variedad de software distribuido mediante ese sistema con la + confianza de que el sistema se aplicará consistentemente. + Será el autor/donante quien decida si quiere distribuir + software mediante cualquier otro sistema y una licencia no puede + imponer esa elección. +

      +

      + Este apartado pretende dejar completamente claro lo que se cree que es + una consecuencia del resto de esta Licencia. +

      +
    16. +
    17. + Si la distribución y/o uso de el Programa está restringida + en ciertos países, bien por patentes o por interfaces bajo + copyright, el tenedor del copyright que coloca este Programa bajo esta + Licencia puede añadir una limitación explícita de + distribución geográfica excluyendo esos países, de + forma que la distribución se permita sólo en o entre los + países no excluidos de esta manera. En ese caso, esta Licencia + incorporará la limitación como si estuviese escrita en el + cuerpo de esta Licencia. +
    18. +
    19. + La Free Software Foundation puede publicar versiones revisadas y/o + nuevas de la Licencia Pública General de tiempo en tiempo. Dichas + nuevas versiones serán similares en espíritu a la presente + versión, pero pueden ser diferentes en detalles para considerar + nuevos problemas o situaciones. +

      + Cada versión recibe un número de versión que la + distingue de otras. Si el Programa especifica un número de + versión de esta Licencia que se refiere a ella y a + «cualquier versión posterior», tienes la + opción de seguir los términos y condiciones, bien de esa + versión, bien de cualquier versión posterior publicada + por la Free Software Foundation. Si el Programa no especifica un + número de versión de esta Licencia, puedes escoger + cualquier versión publicada por la Free Software Foundation. +

      +
    20. +
    21. + Si quiere incorporar partes del Programa en otros programas libres cuyas + condiciones de distribución son diferentes, escribe al autor para + pedirle permiso. Si el software tiene copyright de la Free Software + Foundation, escribe a la Free Software Foundation: algunas veces hacemos + excepciones en estos casos. Nuestra decisión estará guiada + por el doble objetivo de de preservar la libertad de todos los derivados + de nuestro software libre y promover el que se comparta y reutilice el + software en general. +
    22. +
    -

    Términos y condiciones para la copia, -distribución y modificación

    +

    AUSENCIA DE GARANTÍA

    -
      -
    1. Esta Licencia se aplica a cualquier programa u otro tipo -de trabajo que contenga una nota colocada por el tenedor del copyright -diciendo que puede ser distribuido bajo los términos de esta Licencia -Pública General. En adelante, «Programa» se referirá -a cualquier programa o trabajo que cumpla esa condición y «trabajo -basado en el Programa» se referirá bien al Programa o a cualquier -trabajo derivado de él según la ley de copyright. Esto es, -un trabajo que contenga el programa o una proción de él, -bien en forma literal o con modificaciones y/o traducido en otro lenguaje. -Por lo tanto, la traducción está incluida sin limitaciones -en el término «modificación». Cada concesionario -(licenciatario) será denominado «usted». -

      Cualquier otra actividad que no sea la copia, distribución o -modificación no está cubierta por esta Licencia, está -fuera de su ámbito. El acto de ejecutar el Programa no está -restringido, y los resultados del Programa están cubiertos únicamente -si sus contenidos constituyen un trabajo basado en el Programa, independientemente -de haberlo producido mediante la ejecución del programa. El que -esto se cumpla, depende de lo que haga el programa. -

    2. Usted puede copiar y distribuir copias literales del código fuente -del Programa, según lo has recibido, en cualquier medio, supuesto -que de forma adecuada y bien visible publique en cada copia un anuncio -de copyright adecuado y un repudio de garantía, mantenga intactos -todos los anuncios que se refieran a esta Licencia y a la ausencia de garantía, -y proporcione a cualquier otro receptor del programa una copia de esta -Licencia junto con el Programa. -

      Puede cobrar un precio por el acto físico de transferir una copia, -y puede, según su libre albedrío, ofrecer garantía -a cambio de unos honorarios. -

    3. Puede modificar su copia o copias del Programa o de cualquier porción -de él, formando de esta manera un trabajo basado en el Programa, -y copiar y distribuir esa modificación o trabajo bajo los términos -del apartado 1, antedicho, supuesto que además cumpla las siguientes -condiciones: -
      1. Debe hacer que los ficheros modificados lleven anuncios -prominentes indicando que los ha cambiado y la fecha de cualquier cambio. -
      2. Debe hacer que cualquier trabajo que distribuya o publique y que en -todo o en parte contenga o sea derivado del Programa o de cualquier parte -de él sea licenciada como un todo, sin carga alguna, a todas las -terceras partes y bajo los términos de esta Licencia. -
      3. Si el programa modificado lee normalmente órdenes interactivamente -cuando es ejecutado, debe hacer que, cuando comience su ejecución -para ese uso interactivo de la forma más habitual, muestre o escriba -un mensaje que incluya un anuncio de copyright y un anuncio de que no se -ofrece ninguna garantía (o por el contrario que sí se ofrece -garantía) y que los usuarios pueden redistribuir el programa bajo -estas condiciones, e indicando al usuario cómo ver una copia de -esta licencia. (Excepción: si el propio programa es interactivo -pero normalmente no muestra ese anuncio, no se requiere que su trabajo -basado en el Programa muestre ningún anuncio).
      -Estos requisitos se aplican al trabajo modificado como un todo. Si partes -identificables de ese trabajo no son derivadas del Programa, y pueden, -razonablemente, ser consideradas trabajos independientes y separados por -ellos mismos, entonces esta Licencia y sus términos no se aplican -a esas partes cuando sean distribuidas como trabajos separados. Pero cuando -distribuya esas mismas secciones como partes de un todo que es un trabajo -basado en el Programa, la distribución del todo debe ser según -los términos de esta licencia, cuyos permisos para otros licenciatarios -se extienden al todo completo, y por lo tanto a todas y cada una de sus -partes, con independencia de quién la escribió. -

      Por lo tanto, no es la intención de este apartado reclamar derechos -o desafiar sus derechos sobre trabajos escritos totalmente por usted mismo. -El intento es ejercer el derecho a controlar la distribución de -trabajos derivados o colectivos basados en el Programa. -

      Además, el simple hecho de reunir un trabajo no basado en el -Programa con el Programa (o con un trabajo basado en el Programa) en un -volumen de almacenamiento o en un medio de distribución no hace -que dicho trabajo entre dentro del ámbito cubierto por esta Licencia. -

    4. Puede copiar y distribuir el Programa (o un trabajo basado en él, -según se especifica en el apartado 2, como código objeto -o en formato ejecutable según los términos de los apartados -1 y 2, supuesto que además cumpla una de las siguientes condiciones: -
      1. Acompañarlo con el código fuente completo -correspondiente, en formato electrónico, que debe ser distribuido -según se especifica en los apartados 1 y 2 de esta Licencia en un -medio habitualmente utilizado para el intercambio de programas, o -
      2. Acompañarlo con una oferta por escrito, válida durante -al menos tres años, de proporcionar a cualquier tercera parte una -copia completa en formato electrónico del código fuente correspondiente, -a un coste no mayor que el de realizar físicamente la distribución -del fuente, que será distribuido bajo las condiciones descritas -en los apartados 1 y 2 anteriores, en un medio habitualmente utilizado -para el intercambio de programas, o -
      3. Acompañarlo con la información que recibiste ofreciendo -distribuir el código fuente correspondiente. (Esta opción -se permite sólo para distribución no comercial y sólo -si usted recibió el programa como código objeto o en formato -ejecutable con tal oferta, de acuerdo con el apartado b anterior).
      -Por código fuente de un trabajo se entiende la forma preferida del -trabajo cuando se le hacen modificaciones. Para un trabajo ejecutable, -se entiende por código fuente completo todo el código fuente -para todos los módulos que contiene, más cualquier fichero -asociado de definición de interfaces, más los guiones utilizados -para controlar la compilación e instalación del ejecutable. -Como excepción especial el código fuente distribuido no necesita -incluir nada que sea distribuido normalmente (bien como fuente, bien en -forma binaria) con los componentes principales (compilador, kernel y similares) -del sistema operativo en el cual funciona el ejecutable, a no ser que el -propio componente acompañe al ejecutable. -

      Si la distribución del ejecutable o del código objeto -se hace mediante la oferta acceso para copiarlo de un cierto lugar, entonces -se considera la oferta de acceso para copiar el código fuente del -mismo lugar como distribución del código fuente, incluso -aunque terceras partes no estén forzadas a copiar el fuente junto -con el código objeto. -

    5. No puede copiar, modificar, sublicenciar o distribuir el Programa excepto -como prevé expresamente esta Licencia. Cualquier intento de copiar, -modificar sublicenciar o distribuir el Programa de otra forma es inválida, -y hará que cesen automáticamente los derechos que te proporciona -esta Licencia. En cualquier caso, las partes que hayan recibido copias -o derechos de usted bajo esta Licencia no cesarán en sus derechos -mientras esas partes continúen cumpliéndola. -
    6. No está obligado a aceptar esta licencia, ya que no la ha firmado. -Sin embargo, no hay hada más que le proporcione permiso para modificar -o distribuir el Programa o sus trabajos derivados. Estas acciones están -prohibidas por la ley si no acepta esta Licencia. Por lo tanto, si modifica -o distribuye el Programa (o cualquier trabajo basado en el Programa), está -indicando que acepta esta Licencia para poder hacerlo, y todos sus términos -y condiciones para copiar, distribuir o modificar el Programa o trabajos -basados en él. -
    7. Cada vez que redistribuya el Programa (o cualquier trabajo basado en -el Programa), el receptor recibe automáticamente una licencia del -licenciatario original para copiar, distribuir o modificar el Programa, -de forma sujeta a estos términos y condiciones. No puede imponer -al receptor ninguna restricción más sobre el ejercicio de -los derechos aquí garantizados. No es usted responsable de hacer -cumplir esta licencia por terceras partes. -
    8. Si como consecuencia de una resolución judicial o de una alegación -de infracción de patente o por cualquier otra razón (no limitada -a asuntos relacionados con patentes) se le imponen condiciones (ya sea -por mandato judicial, por acuerdo o por cualquier otra causa) que contradigan -las condiciones de esta Licencia, ello no le exime de cumplir las condiciones -de esta Licencia. Si no puede realizar distribuciones de forma que se satisfagan -simultáneamente sus obligaciones bajo esta licencia y cualquier -otra obligación pertinente entonces, como consecuencia, no puede -distribuir el Programa de ninguna forma. Por ejemplo, si una patente no -permite la redistribución libre de derechos de autor del Programa -por parte de todos aquellos que reciban copias directa o indirectamente -a través de usted, entonces la única forma en que podría -satisfacer tanto esa condición como esta Licencia sería evitar -completamente la distribución del Programa. -

      Si cualquier porción de este apartado se considera inválida -o imposible de cumplir bajo cualquier circunstancia particular ha de cumplirse -el resto y la sección por entero ha de cumplirse en cualquier otra -circunstancia. -

      No es el propósito de este apartado inducirle a infringir ninguna -reivindicación de patente ni de ningún otro derecho de propiedad -o impugnar la validez de ninguna de dichas reivindicaciones. Este apartado -tiene el único propósito de proteger la integridad del sistema -de distribución de software libre, que se realiza mediante prácticas -de licencia pública. Mucha gente ha hecho contribuciones generosas -a la gran variedad de software distribuido mediante ese sistema con la -confianza de que el sistema se aplicará consistentemente. Será -el autor/donante quien decida si quiere distribuir software mediante cualquier -otro sistema y una licencia no puede imponer esa elección. -

      Este apartado pretende dejar completamente claro lo que se cree que -es una consecuencia del resto de esta Licencia. -

    9. Si la distribución y/o uso de el Programa está restringida -en ciertos países, bien por patentes o por interfaces bajo copyright, -el tenedor del copyright que coloca este Programa bajo esta Licencia puede -añadir una limitación explícita de distribución -geográfica excluyendo esos países, de forma que la distribución -se permita sólo en o entre los países no excluidos de esta -manera. En ese caso, esta Licencia incorporará la limitación -como si estuviese escrita en el cuerpo de esta Licencia. -
    10. La Free Software Foundation puede publicar versiones revisadas y/o nuevas -de la Licencia Pública General de tiempo en tiempo. Dichas nuevas -versiones serán similares en espíritu a la presente versión, -pero pueden ser diferentes en detalles para considerar nuevos problemas -o situaciones. -

      Cada versión recibe un número de versión que la -distingue de otras. Si el Programa especifica un número de versión -de esta Licencia que se refiere a ella y a «cualquier versión -posterior», tienes la opción de seguir los términos -y condiciones, bien de esa versión, bien de cualquier versión -posterior publicada por la Free Software Foundation. Si el Programa no -especifica un número de versión de esta Licencia, puedes -escoger cualquier versión publicada por la Free Software Foundation. -

    11. Si quiere incorporar partes del Programa en otros programas libres cuyas -condiciones de distribución son diferentes, escribe al autor para -pedirle permiso. Si el software tiene copyright de la Free Software Foundation, -escribe a la Free Software Foundation: algunas veces hacemos excepciones -en estos casos. Nuestra decisión estará guiada por el doble -objetivo de de preservar la libertad de todos los derivados de nuestro -software libre y promover el que se comparta y reutilice el software en -general.
    +
      +
    1. + Como el programa se licencia libre de cargas, no se ofrece ninguna + garantía sobre el programa, en todas la extensión + permitida por la legislación aplicable. Excepto cuando se indique + de otra forma por escrito, los tenedores del copyright y/u otras partes + proporcionan el programa «tal cual», sin garantía de + ninguna clase, bien expresa o implícita, con inclusión, + pero sin limitación a las garantías mercantiles + implícitas o a la conveniencia para un propósito + particular. Cualquier riesgo referente a la calidad y prestaciones del + programa es asumido por usted. Si se probase que el Programa es + defectuoso, asume el coste de cualquier servicio, reparación o + corrección. +
    2. +
    3. + En ningún caso, salvo que lo requiera la legislación + aplicable o haya sido acordado por escrito, ningún tenedor del + copyright ni ninguna otra parte que modifique y/o redistribuya el + Programa según se permite en esta Licencia será + responsable ante usted por daños, incluyendo cualquier + daño general, especial, incidental o resultante producido por el + uso o la imposibilidad de uso del Programa (con inclusión, pero + sin limitación a la pérdida de datos o a la + generación incorrecta de datos o a pérdidas sufridas por + usted o por terceras partes o a un fallo del Programa al funcionar en + combinación con cualquier otro programa), incluso si dicho + tenedor u otra parte ha sido advertido de la posibilidad de dichos + daños. +
    4. +
    -

    AUSENCIA DE GARANTÍA

    +

    FIN DE TÉRMINOS Y CONDICIONES

    -
      -
    1. Como el programa se licencia libre de cargas, -no se ofrece ninguna garantía sobre el programa, en todas la extensión -permitida por la legislación aplicable. Excepto cuando se indique -de otra forma por escrito, los tenedores del copyright y/u otras partes -proporcionan el programa «tal cual», sin garantía de -ninguna clase, bien expresa o implícita, con inclusión, pero -sin limitación a las garantías mercantiles implícitas -o a la conveniencia para un propósito particular. Cualquier riesgo -referente a la calidad y prestaciones del programa es asumido por usted. -Si se probase que el Programa es defectuoso, asume el coste de cualquier -servicio, reparación o corrección. -
    2. En ningún caso, salvo que lo requiera la legislación aplicable -o haya sido acordado por escrito, ningún tenedor del copyright ni -ninguna otra parte que modifique y/o redistribuya el Programa según -se permite en esta Licencia será responsable ante usted por daños, -incluyendo cualquier daño general, especial, incidental o resultante -producido por el uso o la imposibilidad de uso del Programa (con inclusión, -pero sin limitación a la pérdida de datos o a la generación -incorrecta de datos o a pérdidas sufridas por usted o por terceras -partes o a un fallo del Programa al funcionar en combinación con -cualquier otro programa), incluso si dicho tenedor u otra parte ha sido -advertido de la posibilidad de dichos daños.
    - -

    FIN DE TÉRMINOS Y CONDICIONES

    - -

    Apéndice: Cómo aplicar estos -términos a sus nuevos programas.

    -

    -Si usted desarrolla un nuevo Programa, y quiere que sea del mayor uso posible -para el público en general, la mejor forma de conseguirlo es convirtiéndolo -en software libre que cualquiera pueda redistribuir y cambiar bajo estos -términos.

    -

    Para hacerlo, añada los siguientes anuncios al programa. Lo más -seguro es añadirlos al principio de cada fichero fuente para transmitir -lo más efectivamente posible la ausencia de garantía. Además -cada fichero debería tener al menos la línea de «copyright» -y un indicador a dónde puede encontrarse el anuncio completo. -

    <una línea para indicar el nombre -del programa y una rápida idea de qué hace.> -

    Copyright (C) 19aa <nombre del autor> -

    Este programa es software libre. Puede redistribuirlo y/o modificarlo -bajo los términos de la Licencia Pública General de GNU según -es publicada por la Free Software Foundation, bien de la versión -2 de dicha Licencia o bien (según su elección) de cualquier -versión posterior. -

    Este programa se distribuye con la esperanza de que sea útil, -pero SIN NINGUNA GARANTÍA, incluso sin la garantía MERCANTIL -implícita o sin garantizar la CONVENIENCIA PARA UN PROPÓSITO -PARTICULAR. Véase la Licencia Pública General de GNU para -más detalles. -

    Debería haber recibido una copia de la Licencia Pública -General junto con este programa. Si no ha sido así, escriba a la -Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, EEUU.

    -

    -Añada también información sobre cómo contactar -con usted mediante correo electrónico y postal.

    -

    Si el programa es interactivo, haga que muestre un pequeño anuncio -como el siguiente, cuando comienza a funcionar en modo interactivo: -

    Gnomovision versión 69, Copyright -(C) 19aa nombre del autor -

    Gnomovision no ofrece ABSOLUTAMENTE NINGUNA GARANTÍA. Para más -detalles escriba «show w».

    -

    -Los comandos hipotéticos «show w» y «show c» -deberían mostrar las partes adecuadas de la Licencia Pública -General. Por supuesto, los comandos que use pueden llamarse de cualquier -otra manera. Podrían incluso ser pulsaciones del ratón o -elementos de un menú (lo que sea apropiado para su programa).

    -

    También deberías conseguir que su empleador (si trabaja -como programador) o tu Universidad (si es el caso) firme un «renuncia -de copyright» para el programa, si es necesario. A continuación -se ofrece un ejemplo, altere los nombres según sea conveniente: -

    -
    -Yoyodyne, Inc. mediante este documento renuncia -a cualquier interés de derechos de copyright con respecto al programa -Gnomovision (que hace pasadas a compiladores) escrito por Pepe Programador. -

    <firma de Pepito Grillo>, 20 de diciembre de 1996 -

    Pepito Grillo, Presidente de Asuntillos Varios.

    -
    -

    -Esta Licencia Pública General no permite que incluya sus programas -en programas propietarios. Si su programa es una biblioteca de subrutinas, -puede considerar más útil el permitir el enlazado de aplicaciones -propietarias con la biblioteca. Si este es el caso, use la Licencia Pública -General de GNU para Bibliotecas en lugar de esta Licencia.

    - - \ No newline at end of file +

    + Apéndice: Cómo aplicar estos + términos a sus nuevos programas. +

    +

    + Si usted desarrolla un nuevo Programa, y quiere que sea del mayor uso + posible para el público en general, la mejor forma de conseguirlo + es convirtiéndolo en software libre que cualquiera pueda + redistribuir y cambiar bajo estos términos. +

    +

    + Para hacerlo, añada los siguientes anuncios al programa. Lo + más seguro es añadirlos al principio de cada fichero fuente + para transmitir lo más efectivamente posible la ausencia de + garantía. Además cada fichero debería tener al menos + la línea de «copyright» y un indicador a dónde + puede encontrarse el anuncio completo. +

    +
    + <una línea para indicar el nombre del programa y una + rápida idea de qué hace.> +

    Copyright (C) 19aa <nombre del autor>

    +

    + Este programa es software libre. Puede redistribuirlo y/o modificarlo + bajo los términos de la Licencia Pública General de GNU + según es publicada por la Free Software Foundation, bien de la + versión 2 de dicha Licencia o bien (según su + elección) de cualquier versión posterior. +

    +

    + Este programa se distribuye con la esperanza de que sea útil, + pero SIN NINGUNA GARANTÍA, incluso sin la garantía + MERCANTIL implícita o sin garantizar la CONVENIENCIA PARA UN + PROPÓSITO PARTICULAR. Véase la Licencia Pública + General de GNU para más detalles. +

    +

    + Debería haber recibido una copia de la Licencia Pública + General junto con este programa. Si no ha sido así, escriba a la + Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, + EEUU. +

    +
    +

    + Añada también información sobre cómo contactar + con usted mediante correo electrónico y postal. +

    +

    + Si el programa es interactivo, haga que muestre un pequeño anuncio + como el siguiente, cuando comienza a funcionar en modo interactivo: +

    +
    + Gnomovision versión 69, Copyright (C) 19aa nombre del autor +

    + Gnomovision no ofrece ABSOLUTAMENTE NINGUNA GARANTÍA. Para + más detalles escriba «show w». +

    +
    +

    + Los comandos hipotéticos «show w» y «show + c» deberían mostrar las partes adecuadas de la Licencia + Pública General. Por supuesto, los comandos que use pueden llamarse + de cualquier otra manera. Podrían incluso ser pulsaciones del + ratón o elementos de un menú (lo que sea apropiado para su + programa). +

    +

    + También deberías conseguir que su empleador (si trabaja como + programador) o tu Universidad (si es el caso) firme un «renuncia de + copyright» para el programa, si es necesario. A continuación + se ofrece un ejemplo, altere los nombres según sea conveniente: +

    +
    + Yoyodyne, Inc. mediante este documento renuncia a cualquier interés + de derechos de copyright con respecto al programa Gnomovision (que hace + pasadas a compiladores) escrito por Pepe Programador. +

    <firma de Pepito Grillo>, 20 de diciembre de 1996

    +

    Pepito Grillo, Presidente de Asuntillos Varios.

    +
    +

    + Esta Licencia Pública General no permite que incluya sus programas + en programas propietarios. Si su programa es una biblioteca de subrutinas, + puede considerar más útil el permitir el enlazado de + aplicaciones propietarias con la biblioteca. Si este es el caso, use la + Licencia Pública General de GNU para Bibliotecas en lugar de esta + Licencia. +

    + + diff --git a/pandora_console/general/license/pandora_info_ca.html b/pandora_console/general/license/pandora_info_ca.html index e2828b4237..09fbfe8411 100644 --- a/pandora_console/general/license/pandora_info_ca.html +++ b/pandora_console/general/license/pandora_info_ca.html @@ -1,348 +1,460 @@ - -Llicència Pública General de GNU - - + + Llicència Pública General de GNU + + +

    Llicència Pública General de GNU

    -

    Llicència Pública General de GNU

    +

    Advertiment

    + This is an unofficial translation of the GNU General Public License into + Catalan. It was not published by the Free Software Foundation, and does not + legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, we + hope that this translation will help Catalan speakers understand the GNU GPL + better +

    + Ve't aquí una traducció no oficial al català de la + llicència pública general (GPL) de GNU. No ha estat + publicada per la Free Software Foundation (fundació per al + programari lliure), i no defineix legalment els termes de + distribució del programari que utilitza la GPL de GNU -- + només el text original en anglès ho fa. Tot i això, + esperem que aquesta traducció ajudi els catalanoparlants a entendre + millor la GPL de GNU. +

    -

    Advertiment

    -This is an unofficial translation of the GNU General Public License into -Catalan. It was not published by the Free Software Foundation, and does -not legally state the distribution terms for software that uses the GNU -GPL--only the original English text of the GNU GPL does that. However, -we hope that this translation will help Catalan speakers understand the -GNU GPL better -

    Ve't aquí una traducció no oficial al català de -la llicència pública general (GPL) de GNU. No ha estat publicada -per la Free Software Foundation (fundació per al programari lliure), -i no defineix legalment els termes de distribució del programari -que utilitza la GPL de GNU -- només el text original en anglès -ho fa. Tot i això, esperem que aquesta traducció ajudi els -catalanoparlants a entendre millor la GPL de GNU.

    +

    Índex

    -

    Índex

    +

    -

    +

    - + - - -
    -

    -LLICÈNCIA -PÚBLICA GENERAL DE GNU

    -Versió 2, Juny de 1991 -
    Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
    +    
    +

    + LLICÈNCIA PÚBLICA GENERAL DE GNU +

    + Versió 2, Juny de 1991 +
    +Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
     59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
     
     Es permet que tothom faci còpies literals d'aquest document de
      llicència i les distribueixi, però no és permès modificar-lo.
    -
    +
    -

    Preàmbul

    -Les llicències de la major part de programari estan pensades per -prendre-us la llibertat de compartir-lo i modificar-lo. Contràriament, -la Llicència pública general de GNU pretén garantir-vos -la llibertat de compartir i modificar el programari lliure -- assegurar-se -que el programari sigui lliure per a tots els seus usuaris i usuàries. -Aquesta Llicència pública general de GNU afecta la majoria -del programari de la Free Software Foundation (fundació pel programari -lliure) i a qualsevol altre programa els autors o autores del qual decideixin -usar-la (algun altre programari de la Free Software Foundation, en canvi, -està protegit per la Llicència pública general per -a biblioteques de GNU [NdeT: aquesta llicència, la LGPL, és -la que actualment la FSF anomena Llicència pública menys -general]). També podeu aplicar-la als vostres programes. -

    Quan parlem de programari lliure (free software) ens referim a la llibertat, -no al preu [NdeT: en català no hi ha l'ambigüitat que hi ha -en anglès]. Les nostres llicències públiques generals -estan pensades per assegurar que tingueu la llibertat de distribuir còpies -del programari lliure (i cobrar per aquest servei si així ho voleu), -que rebeu el codi font o que el pugueu rebre si el voleu, que pugueu modificar -el programari o fer-ne servir parts en programes lliures nous; i que sapigueu

    -que podeu fer aquestes coses. -

    Per protegir els vostres drets, hem d'imposar restriccions que prohibeixin -a tothom denegar-vos aquests drets o demanar-vos que hi renuncieu. Aquestes -restriccions suposen algunes responsabilitats per a vós si distribuïu -còpies del programari o si el modifiqueu.

    -

    Per exemple, si distribuïu còpies d'un aquests programes, -tant si és de franc com per un preu, heu de donar als destinataris -els mateixos drets que teniu vós. Us heu d'assegurar que també -ells rebin o puguin obtenir el codi font. I els heu de fer saber aquests -termes per tal que coneguin els seus drets.

    -

    Protegim els vostres drets en dos passos: (1) Ens reservem el copyright -del programari, i (2) us oferim aquesta llicència que us dóna -permís legal per copiar, distribuir i/o modificar el programari.

    -

    A més a més, per protegir-nos i protegir l'autor o autora, -volem estar segurs que tothom entén que no hi ha cap garantia per -a aquest programari lliure. Si algú modifica el programari i el -passa, volem que els destinataris sàpiguen que el que tenen no és -l'original, per tal que qualsevol problema que haguessin pogut introduir -terceres persones no repercuteixi en la reputació de l'autor o autora -original.

    -

    Finalment, qualsevol programa lliure està constantment amenaçat -per les patents de programari. Volem evitar el perill de que els redistribuïdors -d'un programa lliure acabin obtenint llicències de patents, i de -resultes el programa esdevingui propietat exclusiva d'algú. Per -evitar-ho, he deixat clar que de qualsevol patent se n'han d'emetre llicències -per a tothom o no emetre'n cap.

    -

    Les condicions exactes per a la còpia, distribució i modificació -són les següents.

    +

    Preàmbul

    + Les llicències de la major part de programari estan pensades per + prendre-us la llibertat de compartir-lo i modificar-lo. + Contràriament, la Llicència pública general de GNU + pretén garantir-vos la llibertat de compartir i modificar el + programari lliure -- assegurar-se que el programari sigui lliure per a tots + els seus usuaris i usuàries. Aquesta Llicència pública + general de GNU afecta la majoria del programari de la Free Software + Foundation (fundació pel programari lliure) i a qualsevol altre + programa els autors o autores del qual decideixin usar-la (algun altre + programari de la Free Software Foundation, en canvi, està protegit + per la Llicència pública general per a biblioteques de GNU + [NdeT: aquesta llicència, la LGPL, és la que actualment la FSF + anomena Llicència pública menys general]). També podeu + aplicar-la als vostres programes. +

    + Quan parlem de programari lliure (free software) ens referim a la + llibertat, no al preu [NdeT: en català no hi ha l'ambigüitat + que hi ha en anglès]. Les nostres llicències + públiques generals estan pensades per assegurar que tingueu la + llibertat de distribuir còpies del programari lliure (i cobrar per + aquest servei si així ho voleu), que rebeu el codi font o que el + pugueu rebre si el voleu, que pugueu modificar el programari o fer-ne + servir parts en programes lliures nous; i que sapigueu +

    + que podeu fer aquestes coses. +

    + Per protegir els vostres drets, hem d'imposar restriccions que prohibeixin + a tothom denegar-vos aquests drets o demanar-vos que hi renuncieu. + Aquestes restriccions suposen algunes responsabilitats per a vós si + distribuïu còpies del programari o si el modifiqueu. +

    +

    + Per exemple, si distribuïu còpies d'un aquests programes, tant + si és de franc com per un preu, heu de donar als destinataris els + mateixos drets que teniu vós. Us heu d'assegurar que també + ells rebin o puguin obtenir el codi font. I els heu de fer saber aquests + termes per tal que coneguin els seus drets. +

    +

    + Protegim els vostres drets en dos passos: (1) Ens reservem el copyright + del programari, i (2) us oferim aquesta llicència que us + dóna permís legal per copiar, distribuir i/o modificar el + programari. +

    +

    + A més a més, per protegir-nos i protegir l'autor o autora, + volem estar segurs que tothom entén que no hi ha cap garantia per a + aquest programari lliure. Si algú modifica el programari i el + passa, volem que els destinataris sàpiguen que el que tenen no + és l'original, per tal que qualsevol problema que haguessin pogut + introduir terceres persones no repercuteixi en la reputació de + l'autor o autora original. +

    +

    + Finalment, qualsevol programa lliure està constantment + amenaçat per les patents de programari. Volem evitar el perill de + que els redistribuïdors d'un programa lliure acabin obtenint + llicències de patents, i de resultes el programa esdevingui + propietat exclusiva d'algú. Per evitar-ho, he deixat clar que de + qualsevol patent se n'han d'emetre llicències per a tothom o no + emetre'n cap. +

    +

    + Les condicions exactes per a la còpia, distribució i + modificació són les següents. +

    -

    TERMES -I CONDICIONS PER A LA CÒPIA, DISTRIBUCIÓ I MODIFICACIÓ

    +

    + TERMES I CONDICIONS PER A LA CÒPIA, DISTRIBUCIÓ I + MODIFICACIÓ +

    -

    -0. Aquesta llicència afecta a qualsevol programa o altra -obra que contingui un avís del posseïdor del copyright que -digui que es pot distribuir sota els termes d'aquesta llicència -pública general. D'ara endavant, el "programa" es refereix a aquest -programa o obra, i una "obra basada en el programa" voldrà dir el -programa o qualsevol obra derivada segons la llei de copyright: és -a dir una obra que contingui el programa o alguna part d'ell, ja sigui -literalment o amb modificacions o bé traduït a altres llengües. -(Per això mateix, les traduccions s'inclouen sense cap limitació -en el terme "modificació"). Ens referim a Cada beneficiari de la -llicència com a "vós".

    -

    Les activitats que no siguin còpia, distribució o modificació -no estan contemplades en aquesta llicència, queden fora del seu -àmbit. No es restringeix l'acte d'executar el programa, i la sortida -del programa queda contemplada només si el seu contingut constitueix -una obra basada en el programa (independentment de que s'hagi creat executant -el programa). Que aquest sigui el cas o no depèn de què faci -el programa.

    -

    1. Podeu copiar i distribuir còpies literals del codi -font del programa tal i com el rebeu, en qualsevol mitjà, sempre -i quan publiqueu en cada còpia, de manera adient i ben visible, -una nota de copyright i una renúncia de garantia; manteniu intactes -tots els avisos que fan referència a aquesta llicència i -a l'absència de garanties de cap mena; i lliureu a qualsevol altre -destinatari del programa una còpia d'aquesta llicència juntament -amb el programa.

    -

    Podeu cobrar un preu per l'acte físic de trametre una còpia -i podeu, si així ho voleu, oferir alguna garantia a canvi d'un preu.

    -

    2. Podeu modificar la còpia o còpies del programa -o qualsevol tros, tot fornint una obra basada en el programa, i podeu copiar -i distribuir aquestes modificacions o obres sota els termes de la Secció -1 anterior, sempre i quan també compliu les següents condicions:

    -
      -
    • -a) Heu de fer que els fitxers modificats portin indicacions ben -visibles que diguin que heu modificat els fitxers i la data de la modificació.
    • +

      + 0. Aquesta llicència afecta a qualsevol programa o altra + obra que contingui un avís del posseïdor del copyright que + digui que es pot distribuir sota els termes d'aquesta llicència + pública general. D'ara endavant, el "programa" es refereix a aquest + programa o obra, i una "obra basada en el programa" voldrà dir el + programa o qualsevol obra derivada segons la llei de copyright: és + a dir una obra que contingui el programa o alguna part d'ell, ja sigui + literalment o amb modificacions o bé traduït a altres + llengües. (Per això mateix, les traduccions s'inclouen sense + cap limitació en el terme "modificació"). Ens referim a Cada + beneficiari de la llicència com a "vós". +

      +

      + Les activitats que no siguin còpia, distribució o + modificació no estan contemplades en aquesta llicència, + queden fora del seu àmbit. No es restringeix l'acte d'executar el + programa, i la sortida del programa queda contemplada només si el + seu contingut constitueix una obra basada en el programa (independentment + de que s'hagi creat executant el programa). Que aquest sigui el cas o no + depèn de què faci el programa. +

      +

      + 1. Podeu copiar i distribuir còpies literals del codi font + del programa tal i com el rebeu, en qualsevol mitjà, sempre i quan + publiqueu en cada còpia, de manera adient i ben visible, una nota + de copyright i una renúncia de garantia; manteniu intactes tots els + avisos que fan referència a aquesta llicència i a + l'absència de garanties de cap mena; i lliureu a qualsevol altre + destinatari del programa una còpia d'aquesta llicència + juntament amb el programa. +

      +

      + Podeu cobrar un preu per l'acte físic de trametre una còpia + i podeu, si així ho voleu, oferir alguna garantia a canvi d'un + preu. +

      +

      + 2. Podeu modificar la còpia o còpies del programa o + qualsevol tros, tot fornint una obra basada en el programa, i podeu copiar + i distribuir aquestes modificacions o obres sota els termes de la + Secció 1 anterior, sempre i quan també compliu les + següents condicions: +

      +
        +
      • + a) Heu de fer que els fitxers modificats portin indicacions ben + visibles que diguin que heu modificat els fitxers i la data de la + modificació. +
      • -
      • -b) Heu d'atorgar gratuïtament a totes les terceres parts els -termes d'aquesta mateixa llicència sobre la totalitat de qualsevol -obra que distribuïu o publiqueu, que completament o en part contingui -o sigui un derivat del programa o qualsevol part d'aquest.
      • +
      • + b) Heu d'atorgar gratuïtament a totes les terceres parts els + termes d'aquesta mateixa llicència sobre la totalitat de + qualsevol obra que distribuïu o publiqueu, que completament o en + part contingui o sigui un derivat del programa o qualsevol part + d'aquest. +
      • -
      • -c) Si el programa modificat normalment llegeix instruccions interactivament -quan s'executa, heu de fer que quan s'arrenqui per a aquest ús interactiu -de la manera més habitual, imprimeixi o mostri un missatge que inclogui -una nota de copyright adient i un avís de que no hi ha garantia -(o, si de cas, que digui que la garantia l'oferiu vós mateix) i -que els usuaris poden redistribuir el programa sota aquestes condicions, -i que indiqui a l'usuari o usuària com veure una còpia d'aquesta -llicència. (Excepció: si el mateix programa és interactiu -però normalment no escriu un missatge d'aquesta mena, la vostra -obra basada en el programa tampoc cal que l'escrigui).
      • -
      -

      -Aquests requeriments afecten a l'obra modificada com un tot. Si hi ha parts -identificables que no estan derivades del programa, i es poden considerar -raonablement com a obres independents i separades en si mateixes, aleshores -aquesta llicència i els seus termes no s'apliquen a aquelles parts -quan les distribuïu com a obres separades. Però quan distribuïu -aquestes mateixes parts integrades en un tot que sigui una obra basada -en el programa, la distribució del tot s'ha de fer d'acord amb els -termes d'aquesta llicència, i els permisos atorgats a altres beneficiaris -abasten el tot sencer i, per tant, totes i cadascuna de les parts, independentment -de qui les hagi escrites.. -

      Així doncs, la intenció d'aquesta secció no és -reclamar o disputar-vos cap dret a codi que hagueu escrit del tot vós -mateix. La intenció és més aviat exercir el dret a -controlar la distribució d'obres derivades o col·lectives -basades en el programa.

      -

      A més a més, la simple agregació amb el programa -(o amb una obra basada en el programa) d'altres obres no basades en el -programa en un volum d'un mitjà d'emmagatzemament o de distribució -no posa aquestes altres obres sota l'àmbit de la llicència.

      -

      3. Podeu copiar i distribuir el programa (o una obra basada en -el programa, segons la secció 2) en forma executable o de codi objecte -d'acord amb els termes de les Seccions 1 i 2 anteriors, sempre i quan també -feu una de les coses següents: 

      -
        -
      • -a) L'acompanyeu amb el codi font complet corresponent, capaç -de ser llegit per un ordinador i en un mitjà utilitzat habitualment -per a l'intercanvi de programari; o
      • +
      • + c) Si el programa modificat normalment llegeix instruccions + interactivament quan s'executa, heu de fer que quan s'arrenqui per a + aquest ús interactiu de la manera més habitual, imprimeixi + o mostri un missatge que inclogui una nota de copyright adient i un + avís de que no hi ha garantia (o, si de cas, que digui que la + garantia l'oferiu vós mateix) i que els usuaris poden + redistribuir el programa sota aquestes condicions, i que indiqui a + l'usuari o usuària com veure una còpia d'aquesta + llicència. (Excepció: si el mateix programa és + interactiu però normalment no escriu un missatge d'aquesta mena, + la vostra obra basada en el programa tampoc cal que l'escrigui). +
      • +
      +

      + Aquests requeriments afecten a l'obra modificada com un tot. Si hi ha + parts identificables que no estan derivades del programa, i es poden + considerar raonablement com a obres independents i separades en si + mateixes, aleshores aquesta llicència i els seus termes no + s'apliquen a aquelles parts quan les distribuïu com a obres + separades. Però quan distribuïu aquestes mateixes parts + integrades en un tot que sigui una obra basada en el programa, la + distribució del tot s'ha de fer d'acord amb els termes d'aquesta + llicència, i els permisos atorgats a altres beneficiaris abasten el + tot sencer i, per tant, totes i cadascuna de les parts, independentment de + qui les hagi escrites.. +

      -
    • -b) L'acompanyeu amb un oferiment per escrit, amb validesa com a -mínim fins al cap de tres anys, de subministrar a tota tercera part, -i per un preu no superior al que us costi físicament realitzar la -distribució, el codi font complet corresponent, que es distribuirà -d'acord amb els termes de les seccions 1 i 2 anteriors en un mitjà -utilitzat habitualment per a l'intercanvi de programari; o,
    • +

      + Així doncs, la intenció d'aquesta secció no és + reclamar o disputar-vos cap dret a codi que hagueu escrit del tot + vós mateix. La intenció és més aviat exercir + el dret a controlar la distribució d'obres derivades o + col·lectives basades en el programa. +

      +

      + A més a més, la simple agregació amb el programa (o + amb una obra basada en el programa) d'altres obres no basades en el + programa en un volum d'un mitjà d'emmagatzemament o de + distribució no posa aquestes altres obres sota l'àmbit de la + llicència. +

      +

      + 3. Podeu copiar i distribuir el programa (o una obra basada en el + programa, segons la secció 2) en forma executable o de codi objecte + d'acord amb els termes de les Seccions 1 i 2 anteriors, sempre i quan + també feu una de les coses següents:  +

      +
        +
      • + a) L'acompanyeu amb el codi font complet corresponent, + capaç de ser llegit per un ordinador i en un mitjà + utilitzat habitualment per a l'intercanvi de programari; o +
      • -
      • -c) L'acompanyeu amb la informació que hagueu rebut de l'oferiment -de distribuir el codi font corresponent (Aquesta alternativa només -és permesa per a la distribució no comercial i només -si heu rebut el programa en forma executable o de codi objecte amb aquest -oferiment, d'acord amb la subsecció b anterior).
      • -
      -El codi font per a una obra vol dir la forma preferida de l'obra per tal -de fer-hi modificacions. Per una obra executable, el codi font complet -vol dir tot el codi font per tots els mòduls que conté, més -tots els fitxers de definició d'interfícies associats si -s'escau, més els scripts que es facin servir per controlar -la compilació i la instal·lació de l'executable si -s'escau. Tanmateix, fent una excepció especial, el codi font que -es distribueixi no cal que inclogui res del que normalment es distribueixi -(sia en forma binària o de codi font) amb els components principals -(compilador, nucli o similars) del sistema operatiu en què s'executa -el programa, tret que el component en qüestió acompanyi l'executable. -

      Si la distribució de l'executable consisteix en donar accés -per copiar-lo d'un lloc determinat, aleshores serveix com a distribució -del codi font el fet de donar un accés equivalent per copiar el -codi font, encara que les terceres parts no estiguin obligades a copiar -el codi font en copiar el codi objecte.

      -

      4. No podeu copiar, modificar, reemetre llicències, o -distribuir el programa si no és de la forma expressa que atorga -aquesta Llicència. Qualsevol altre intent de copiar, modificar, -reemetre llicències, o distribuir el programa és il·lícit -i finalitzarà automàticament els drets que hagueu obtingut -d'aquesta llicència. Tanmateix, les parts que hagin rebut de vós -còpies o drets d'acord amb aquesta llicència no veuran les -seves llicències finalitzades mentre segueixin observant-les estrictament.

      -

      5. No esteu obligat a acceptar aquesta llicència, donat -que no l'heu signada. Tanmateix, no hi ha cap altra opció que us -doni permís per modificar o distribuir el programa o les seves obres -derivades. Aquestes accions queden prohibides per la llei si no accepteu -aquesta llicència. Així doncs, en modificar o distribuir -el programa o les seves obres derivades, esteu indicant que accepteu aquesta -llicència per fer-ho, i tots els seus termes i condicions per copiar, -distribuir o modificar el programa o obres basades en ell.

      -

      6. Cada cop que distribuïu el programa (o qualsevol obra -basada en el programa), el destinatari rep automàticament, de qui -va emetre la llicència originàriament, una llicència -per copiar, distribuir o modificar el programa sotmesa a aquests termes -i condicions. No podeu imposar cap més restricció a l'exercici -dels drets que aquí es confereixen. No sou responsable de fer complir -aquesta llicència a terceres parts.

      -

      7. Si, a conseqüència d'una decisió judicial, -una demanda per infracció d'una patent o per qualsevol altra raó -(no exclusivament relacionada amb patents), se us imposen condicions (tant -si és per ordre judicial, acord, o el que sigui) que contradiuen -les condicions d'aquesta llicència, no quedeu excusat de les condicions -d'aquesta llicència. Si no us és possible distribuir de manera -que satisfeu alhora les obligacions que us imposa aquesta llicència -i qualsevol altra obligació pertinent, aleshores resulta que no -podeu distribuir el programa en absolut. Per exemple, si una llicència -de patent no permetés redistribuir gratuïtament el programa -a aquells que hagin rebut còpies de vós directament o indirecta, -aleshores la única manera en què podríeu satisfer -tant això com aquesta llicència seria abstenir-vos completament -de distribuir el programa.

      -

      Si qualsevol fragment d'aquesta secció quedés invalidat -o no es pogués fer complir en qualsevol circumstància particular, -la intenció és que s'apliqui el balanç de la secció, -i que s'apliqui la secció en la seva totalitat en altres circumstàncies.

      -

      El propòsit d'aquesta secció no és induir-vos a -infringir cap patent ni cap altre requeriment del dret a la propietat, -o a discutir-ne la validesa; l'únic propòsit d'aquesta secció -és protegir la integritat del sistema de distribució de programari -lliure, que s'implementa amb pràctiques de llicència pública. -Molta gent ha fet generoses contribucions a l'ampli ventall de programari -distribuït per aquest sistema refiant-se de l'aplicació consistent -del sistema; li pertoca a l'autor, autora o donant decidir si vol distribuir -programari per algun altre sistema, i un beneficiari de la llicència -no pot imposar aquesta opció.

      -

      Aquesta secció pretén deixar del tot clar el que es considera -una conseqüència de la resta de la llicència.

      -

      8. Si hi ha països que restringeixen la distribució -o l'ús del programari, ja sigui per patents o per interfícies -sota copyright, el posseïdor del copyright original que posi el programa -sota aquesta llicència pot afegir limitacions geogràfiques -explícites que excloguin aquests països, de manera que la distribució -només quedi permesa dintre dels països no exclosos, o entre -ells. En tal cas, aquesta llicència incorpora la limitació -com si estigués escrita en el text de la llicència.

      -

      9. La Free Software Foundation (Fundació per al programari -lliure) pot publicar versions revisades o noves de la llicència -pública general de tant en tant. Aquestes versions noves seran semblants -en esperit a la versió present, però poden diferir en detalls -per tractar nous neguits o problemes.

      -

      Cada versió rep un número de versió distintiu. -Si el programa especifica un número de versió d'aquesta llicència -que li és aplicable i "qualsevol versió posterior", teniu -l'opció de seguir els termes i condicions de la versió especificada -o de qualsevol versió publicada posteriorment per la Free Software -Foundation. Si el programa no especifica un número de versió -d'aquesta llicència, podeu triar qualsevol versió que hagi -publicat la Free Software Foundation en qualsevol data.

      -

      10. Si voleu incorporar parts del programa en altres programes -lliures les condicions de distribució dels quals són diferents, -escriviu a l'autor per demanar-li permís. Per al programari que -està sota copyright de la Free Software Foundation, escriviu a la -Free Software Foundation; de vegades fem excepcions per permetre-ho. Prendrem -la nostra decisió guiats pels dos objectius de mantenir la condició -de lliure de tots els derivats del nostre programari lliure i de promoure -la compartició i la reutilització del programari en general.

      -

      ABSÈNCIA DE GARANTIES

      -

      11. COM QUE LA LLICÈNCIA DEL PROGRAMA ÉS GRATUÏTA, -NO HI HA GARANTIA PER AL PROGRAMA, EN LA MESURA QUE HO PERMETI LA LLEI -APLICABLE. EXCEPTE EL QUE ALTRAMENT ES DIGUI PER ESCRIT, ELS POSSEÏDORS -DEL COPYRIGHT I/O ALTRES PARTS SUBMINISTREN EL PROGRAMA "TAL QUAL" SENSE -CAP MENA DE GARANTIA, NI EXPLÍCITA NI IMPLÍCITA, INCLOSES, -ENTRE ALTRES, LES GARANTIES IMPLÍCITES DE COMERCIALITZABILITAT I -APTITUD PER A PROPÒSITS DETERMINATS. TOT EL RISC PEL QUE FA A LA -QUALITAT I RENDIMENT DEL PROGRAMA ÉS VOSTRE. EN CAS QUE EL PROGRAMA -RESULTÉS DEFECTUÓS, VÓS ASSUMIU TOT EL COST D'ASSISTÈNCIA, -REPARACIÓ O CORRECCIÓ.

      -

      12. EL POSSEÏDOR DEL COPYRIGHT, O QUALSEVOL ALTRA PART QUE -PUGUI MODIFICAR O REDISTRIBUIR EL PROGRAMA TAL I COM ES PERMET MÉS -AMUNT NO US HAURÀ DE RESPONDRE EN CAP CAS, TRET DEL QUE REQUEREIXI -LA LLEI APLICABLE O ELS ACORDS PER ESCRIT, PER PERJUDICIS, INCLOSOS ELS -INCIDENTALS, DERIVATS, ESPECIALS O GENERALS QUE ES DERIVIN DE L'ÚS -O DE LA IMPOSSIBILITAT D'ÚS DEL PROGRAMA (INCLOSES ENTRE D'ALTRES -LES PÈRDUES DE DADES, LES DADES QUE EL PROGRAMA HAGI MALMÈS, -LES PÈRDUES QUE US HAGI PROVOCAT A VÓS O A TERCERS O LA IMPOSSIBILITAT -DE QUE EL PROGRAMA FUNCIONI AMB QUALSEVOL ALTRE PROGRAMA), FINS I TOT SI -AQUEST POSSEÏDOR O ALTRA PART HA ESTAT ADVERTIDA DE LA POSSIBILITAT -D'AQUESTS PERJUDICIS.

      -

      FINAL DELS TERMES I CONDICIONS

      +
    • + b) L'acompanyeu amb un oferiment per escrit, amb validesa com a + mínim fins al cap de tres anys, de subministrar a tota tercera + part, i per un preu no superior al que us costi físicament + realitzar la distribució, el codi font complet corresponent, que + es distribuirà d'acord amb els termes de les seccions 1 i 2 + anteriors en un mitjà utilitzat habitualment per a l'intercanvi + de programari; o, +
    • -

      -Com -podeu aplicar aquests termes als vostres programes nous

      -Si desenvolupeu un programa nou, i voleu que tingui l'ús més -gran possible per part del públic, la millor manera d'aconseguir-ho -és fer-lo programari lliure que tothom podrà redistribuir -i modificar d'acord amb aquests termes. -

      Per fer-ho, afegiu els avisos següents al programa. El més -segur és posar-los al començament de cada fitxer font per -transmetre de la manera més efectiva l'exclusió de garanties; -i cada fitxer hauria de portar com a mínim la línia de "copyright" -i un apuntador que indiqui on es pot trobar la nota sencera.

      -
      Una línia amb el nom del programa i una idea de què fa.
      +      
    • + c) L'acompanyeu amb la informació que hagueu rebut de + l'oferiment de distribuir el codi font corresponent (Aquesta alternativa + només és permesa per a la distribució no comercial + i només si heu rebut el programa en forma executable o de codi + objecte amb aquest oferiment, d'acord amb la subsecció b + anterior). +
    • +
    + El codi font per a una obra vol dir la forma preferida de l'obra per tal de + fer-hi modificacions. Per una obra executable, el codi font complet vol dir + tot el codi font per tots els mòduls que conté, més + tots els fitxers de definició d'interfícies associats si + s'escau, més els scripts que es facin servir per controlar la + compilació i la instal·lació de l'executable si + s'escau. Tanmateix, fent una excepció especial, el codi font que es + distribueixi no cal que inclogui res del que normalment es distribueixi (sia + en forma binària o de codi font) amb els components principals + (compilador, nucli o similars) del sistema operatiu en què s'executa + el programa, tret que el component en qüestió acompanyi + l'executable. +

    + Si la distribució de l'executable consisteix en donar accés + per copiar-lo d'un lloc determinat, aleshores serveix com a + distribució del codi font el fet de donar un accés + equivalent per copiar el codi font, encara que les terceres parts no + estiguin obligades a copiar el codi font en copiar el codi objecte. +

    +

    + 4. No podeu copiar, modificar, reemetre llicències, o + distribuir el programa si no és de la forma expressa que atorga + aquesta Llicència. Qualsevol altre intent de copiar, modificar, + reemetre llicències, o distribuir el programa és + il·lícit i finalitzarà automàticament els + drets que hagueu obtingut d'aquesta llicència. Tanmateix, les parts + que hagin rebut de vós còpies o drets d'acord amb aquesta + llicència no veuran les seves llicències finalitzades mentre + segueixin observant-les estrictament. +

    +

    + 5. No esteu obligat a acceptar aquesta llicència, donat que + no l'heu signada. Tanmateix, no hi ha cap altra opció que us doni + permís per modificar o distribuir el programa o les seves obres + derivades. Aquestes accions queden prohibides per la llei si no accepteu + aquesta llicència. Així doncs, en modificar o distribuir el + programa o les seves obres derivades, esteu indicant que accepteu aquesta + llicència per fer-ho, i tots els seus termes i condicions per + copiar, distribuir o modificar el programa o obres basades en ell. +

    +

    + 6. Cada cop que distribuïu el programa (o qualsevol obra + basada en el programa), el destinatari rep automàticament, de qui + va emetre la llicència originàriament, una llicència + per copiar, distribuir o modificar el programa sotmesa a aquests termes i + condicions. No podeu imposar cap més restricció a l'exercici + dels drets que aquí es confereixen. No sou responsable de fer + complir aquesta llicència a terceres parts. +

    +

    + 7. Si, a conseqüència d'una decisió judicial, + una demanda per infracció d'una patent o per qualsevol altra + raó (no exclusivament relacionada amb patents), se us imposen + condicions (tant si és per ordre judicial, acord, o el que sigui) + que contradiuen les condicions d'aquesta llicència, no quedeu + excusat de les condicions d'aquesta llicència. Si no us és + possible distribuir de manera que satisfeu alhora les obligacions que us + imposa aquesta llicència i qualsevol altra obligació + pertinent, aleshores resulta que no podeu distribuir el programa en + absolut. Per exemple, si una llicència de patent no permetés + redistribuir gratuïtament el programa a aquells que hagin rebut + còpies de vós directament o indirecta, aleshores la + única manera en què podríeu satisfer tant això + com aquesta llicència seria abstenir-vos completament de distribuir + el programa. +

    +

    + Si qualsevol fragment d'aquesta secció quedés invalidat o no + es pogués fer complir en qualsevol circumstància particular, + la intenció és que s'apliqui el balanç de la + secció, i que s'apliqui la secció en la seva totalitat en + altres circumstàncies. +

    +

    + El propòsit d'aquesta secció no és induir-vos a + infringir cap patent ni cap altre requeriment del dret a la propietat, o a + discutir-ne la validesa; l'únic propòsit d'aquesta + secció és protegir la integritat del sistema de + distribució de programari lliure, que s'implementa amb + pràctiques de llicència pública. Molta gent ha fet + generoses contribucions a l'ampli ventall de programari distribuït + per aquest sistema refiant-se de l'aplicació consistent del + sistema; li pertoca a l'autor, autora o donant decidir si vol distribuir + programari per algun altre sistema, i un beneficiari de la + llicència no pot imposar aquesta opció. +

    +

    + Aquesta secció pretén deixar del tot clar el que es + considera una conseqüència de la resta de la llicència. +

    +

    + 8. Si hi ha països que restringeixen la distribució o + l'ús del programari, ja sigui per patents o per interfícies + sota copyright, el posseïdor del copyright original que posi el + programa sota aquesta llicència pot afegir limitacions + geogràfiques explícites que excloguin aquests països, + de manera que la distribució només quedi permesa dintre dels + països no exclosos, o entre ells. En tal cas, aquesta + llicència incorpora la limitació com si estigués + escrita en el text de la llicència. +

    +

    + 9. La Free Software Foundation (Fundació per al programari + lliure) pot publicar versions revisades o noves de la llicència + pública general de tant en tant. Aquestes versions noves seran + semblants en esperit a la versió present, però poden diferir + en detalls per tractar nous neguits o problemes. +

    +

    + Cada versió rep un número de versió distintiu. Si el + programa especifica un número de versió d'aquesta + llicència que li és aplicable i "qualsevol versió + posterior", teniu l'opció de seguir els termes i condicions de la + versió especificada o de qualsevol versió publicada + posteriorment per la Free Software Foundation. Si el programa no + especifica un número de versió d'aquesta llicència, + podeu triar qualsevol versió que hagi publicat la Free Software + Foundation en qualsevol data. +

    +

    + 10. Si voleu incorporar parts del programa en altres programes + lliures les condicions de distribució dels quals són + diferents, escriviu a l'autor per demanar-li permís. Per al + programari que està sota copyright de la Free Software Foundation, + escriviu a la Free Software Foundation; de vegades fem excepcions per + permetre-ho. Prendrem la nostra decisió guiats pels dos objectius + de mantenir la condició de lliure de tots els derivats del nostre + programari lliure i de promoure la compartició i la + reutilització del programari en general. +

    +

    ABSÈNCIA DE GARANTIES

    +

    + 11. COM QUE LA LLICÈNCIA DEL PROGRAMA ÉS + GRATUÏTA, NO HI HA GARANTIA PER AL PROGRAMA, EN LA MESURA QUE HO + PERMETI LA LLEI APLICABLE. EXCEPTE EL QUE ALTRAMENT ES DIGUI PER ESCRIT, + ELS POSSEÏDORS DEL COPYRIGHT I/O ALTRES PARTS SUBMINISTREN EL + PROGRAMA "TAL QUAL" SENSE CAP MENA DE GARANTIA, NI EXPLÍCITA NI + IMPLÍCITA, INCLOSES, ENTRE ALTRES, LES GARANTIES IMPLÍCITES + DE COMERCIALITZABILITAT I APTITUD PER A PROPÒSITS DETERMINATS. TOT + EL RISC PEL QUE FA A LA QUALITAT I RENDIMENT DEL PROGRAMA ÉS + VOSTRE. EN CAS QUE EL PROGRAMA RESULTÉS DEFECTUÓS, + VÓS ASSUMIU TOT EL COST D'ASSISTÈNCIA, REPARACIÓ O + CORRECCIÓ. +

    +

    + 12. EL POSSEÏDOR DEL COPYRIGHT, O QUALSEVOL ALTRA PART QUE + PUGUI MODIFICAR O REDISTRIBUIR EL PROGRAMA TAL I COM ES PERMET MÉS + AMUNT NO US HAURÀ DE RESPONDRE EN CAP CAS, TRET DEL QUE REQUEREIXI + LA LLEI APLICABLE O ELS ACORDS PER ESCRIT, PER PERJUDICIS, INCLOSOS ELS + INCIDENTALS, DERIVATS, ESPECIALS O GENERALS QUE ES DERIVIN DE L'ÚS + O DE LA IMPOSSIBILITAT D'ÚS DEL PROGRAMA (INCLOSES ENTRE D'ALTRES + LES PÈRDUES DE DADES, LES DADES QUE EL PROGRAMA HAGI MALMÈS, + LES PÈRDUES QUE US HAGI PROVOCAT A VÓS O A TERCERS O LA + IMPOSSIBILITAT DE QUE EL PROGRAMA FUNCIONI AMB QUALSEVOL ALTRE PROGRAMA), + FINS I TOT SI AQUEST POSSEÏDOR O ALTRA PART HA ESTAT ADVERTIDA DE LA + POSSIBILITAT D'AQUESTS PERJUDICIS. +

    +

    FINAL DELS TERMES I CONDICIONS

    + +

    + Com podeu aplicar aquests termes als vostres programes nous +

    + Si desenvolupeu un programa nou, i voleu que tingui l'ús més + gran possible per part del públic, la millor manera d'aconseguir-ho + és fer-lo programari lliure que tothom podrà redistribuir i + modificar d'acord amb aquests termes. +

    + Per fer-ho, afegiu els avisos següents al programa. El més + segur és posar-los al començament de cada fitxer font per + transmetre de la manera més efectiva l'exclusió de + garanties; i cada fitxer hauria de portar com a mínim la + línia de "copyright" i un apuntador que indiqui on es pot trobar la + nota sencera. +

    +
    Una línia amb el nom del programa i una idea de què fa.
     Copyright (C) any  nom de l'autor o autora
     
     Aquest programa és lliure; el podeu redistribuir i/o modificar
    @@ -360,51 +472,67 @@ la Llicència general pública de GNU per a més detalls. 
     Hauríeu d'haver rebut una còpia de la llicència pública general 
     de GNU amb aquest programa; si no, escriviu a la Free Software 
     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    -Poseu-hi la informació que calgui per contactar amb vós per -correu electrònic i de paper. -

    Si el programa és interactiu, feu-lo treure una breu nota com -aquesta quan arrenca en mode interactiu:

    -
    Gnomovisió versió 69, Copyright (C) any nom de l'autor o autora
    +    Poseu-hi la informació que calgui per contactar amb vós per
    +    correu electrònic i de paper.
    +    

    + Si el programa és interactiu, feu-lo treure una breu nota com + aquesta quan arrenca en mode interactiu: +

    +
    Gnomovisió versió 69, Copyright (C) any nom de l'autor o autora
     El Gnomovisió va SENSE CAP MENA DE GARANTIA; premeu 'mostra g' per saber-ne 
     els detalls.  Això és programari lliure, i se us convida a redistribuir-lo
     d'acord amb certes condicions; piqueu 'mostra c' per saber-ne els detalls.
    -

    Les instruccions hipotètiques 'mostra g' i 'mostra -c' haurien de mostrar les parts escaients de la llicència pública -general. Naturalment, les instruccions poden tenir altres noms que no siguin -'mostra -g' i -'mostra c'; fins i tot podrien ser pics amb el ratolí -o opcions de menú, o el que li vagi bé al vostre programa. -

    També hauríeu d'aconseguir que l'empresari per qui treballeu -(si treballeu de programador) o la vostra escola, si és el cas, -signin una "renúncia de copyright" pel programa, si s'escau. Aquí -teniu un exemple, canvieu-hi els noms:

    -
    Ioiodina, S.A. , per la present renuncia a tot interès 
    +    

    + Les instruccions hipotètiques 'mostra g' i + 'mostra c' haurien de mostrar les parts escaients de la + llicència pública general. Naturalment, les instruccions poden + tenir altres noms que no siguin 'mostra g' i 'mostra c'; + fins i tot podrien ser pics amb el ratolí o opcions de menú, o + el que li vagi bé al vostre programa. +

    + També hauríeu d'aconseguir que l'empresari per qui treballeu + (si treballeu de programador) o la vostra escola, si és el cas, + signin una "renúncia de copyright" pel programa, si s'escau. + Aquí teniu un exemple, canvieu-hi els noms: +

    +
    Ioiodina, S.A. , per la present renuncia a tot interès 
     en el copyright del programa `Gnomovisió' (que fa l'aleta 
     als compiladors) escrit   pel Jordi Pica Codi
     
     signat per Mag Nat, 28 de desembre de 1989
     Mag Nat, Vici-President
    -Aquesta Llicència pública general no us permet incorporar -el vostre programa en programes de propietat. Si el vostre programa és -una biblioteca de subrutines, potser trobeu més útil permetre -enllaçar (link) aplicacions de propietat amb la biblioteca. Si és -això el que voleu, feu servir la Llicència pública -general per a biblioteques de GNU per comptes d'aquesta llicència -[NdeT: la FSF ara li diu llicència pública menys general -per comptes de llicència pública general per a biblioteques].  -
    Torna a la pàgina principal -de GNU. -

    Per preguntes i aclariments de GNU i la FSF escriviu a: gnu@gnu.org. -Altres maneres de contactar -amb -la FSF:

    -

    Envieu comentaris sobre aquestes planes de web a webmasters@www.gnu.org, -Envieu altres preguntes a gnu@gnu.org.

    -

    La nota de Copyright és més amunt.

    -
    Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, -MA 02111, USA -

    Actualitzat:3 Jan 2000 rms

    -
    - - \ No newline at end of file + Aquesta Llicència pública general no us permet incorporar el + vostre programa en programes de propietat. Si el vostre programa és + una biblioteca de subrutines, potser trobeu més útil permetre + enllaçar (link) aplicacions de propietat amb la biblioteca. Si + és això el que voleu, feu servir la Llicència + pública general per a biblioteques de GNU per comptes d'aquesta + llicència [NdeT: la FSF ara li diu llicència pública + menys general per comptes de llicència pública general per a + biblioteques].  +
    + Torna a + la pàgina principal de GNU. +

    + Per preguntes i aclariments de GNU i la FSF escriviu a: + gnu@gnu.org. Altres + maneres de contactar amb la FSF: +

    +

    + Envieu comentaris sobre aquestes planes de web a + webmasters@www.gnu.org, Envieu altres preguntes a + gnu@gnu.org. +

    +

    La nota de Copyright és més amunt.

    +
    Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, + MA 02111, USA +

    Actualitzat:3 Jan 2000 rms

    +
    + + diff --git a/pandora_console/general/license/pandora_info_en.html b/pandora_console/general/license/pandora_info_en.html index 8abb8c934c..d92b2df1b4 100644 --- a/pandora_console/general/license/pandora_info_en.html +++ b/pandora_console/general/license/pandora_info_en.html @@ -1,364 +1,353 @@ - - - GNU General Public License - - -

    GNU General Public License

    -

    Table of Contents

    - -
    -

    -

    GNU GENERAL PUBLIC LICENSE

    -

    Version 2, June 1991

    -
    Copyright (C) 1989, 1991 Free Software Foundation, Inc. 
    +
    +  
    +    GNU General Public License
    +  
    +  
    +    

    GNU General Public License

    +

    Table of Contents

    + + +
    +

    +

    GNU GENERAL PUBLIC LICENSE

    +

    Version 2, June 1991

    +
    +Copyright (C) 1989, 1991 Free Software Foundation, Inc. 
     59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
     
     Everyone is permitted to copy and distribute verbatim copies
    -of this license document, but changing it is not allowed.
    +of this license document, but changing it is not allowed.
    -

    Preamble

    +

    Preamble

    -

    -The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. -

    -

    -When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. -

    -

    -To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. -

    -

    -For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. -

    -

    -We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. -

    -

    -Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. -

    -

    -Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. -

    -

    -The precise terms and conditions for copying, distribution and -modification follow. -

    +

    + The licenses for most software are designed to take away your freedom to + share and change it. By contrast, the GNU General Public License is + intended to guarantee your freedom to share and change free software--to + make sure the software is free for all its users. This General Public + License applies to most of the Free Software Foundation's software and to + any other program whose authors commit to using it. (Some other Free + Software Foundation software is covered by the GNU Library General Public + License instead.) You can apply it to your programs, too. +

    +

    + When we speak of free software, we are referring to freedom, not price. + Our General Public Licenses are designed to make sure that you have the + freedom to distribute copies of free software (and charge for this service + if you wish), that you receive source code or can get it if you want it, + that you can change the software or use pieces of it in new free programs; + and that you know you can do these things. +

    +

    + To protect your rights, we need to make restrictions that forbid anyone to + deny you these rights or to ask you to surrender the rights. These + restrictions translate to certain responsibilities for you if you + distribute copies of the software, or if you modify it. +

    +

    + For example, if you distribute copies of such a program, whether gratis or + for a fee, you must give the recipients all the rights that you have. You + must make sure that they, too, receive or can get the source code. And you + must show them these terms so they know their rights. +

    +

    + We protect your rights with two steps: (1) copyright the software, and (2) + offer you this license which gives you legal permission to copy, + distribute and/or modify the software. +

    +

    + Also, for each author's protection and ours, we want to make certain that + everyone understands that there is no warranty for this free software. If + the software is modified by someone else and passed on, we want its + recipients to know that what they have is not the original, so that any + problems introduced by others will not reflect on the original authors' + reputations. +

    +

    + Finally, any free program is threatened constantly by software patents. We + wish to avoid the danger that redistributors of a free program will + individually obtain patent licenses, in effect making the program + proprietary. To prevent this, we have made it clear that any patent must + be licensed for everyone's free use or not licensed at all. +

    +

    + The precise terms and conditions for copying, distribution and + modification follow. +

    -

    TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

    +

    + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +

    -

    -0. -This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". -

    -

    -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. -

    -

    -1. -You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. -

    -

    -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. -

    -

    -2. - You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: -

    -

    +

    + 0. This License applies to any program or other work + which contains a notice placed by the copyright holder saying it may be + distributed under the terms of this General Public License. The "Program", + below, refers to any such program or work, and a "work based on the + Program" means either the Program or any derivative work under copyright + law: that is to say, a work containing the Program or a portion of it, + either verbatim or with modifications and/or translated into another + language. (Hereinafter, translation is included without limitation in the + term "modification".) Each licensee is addressed as "you". +

    +

    + Activities other than copying, distribution and modification are not + covered by this License; they are outside its scope. The act of running + the Program is not restricted, and the output from the Program is covered + only if its contents constitute a work based on the Program (independent + of having been made by running the Program). Whether that is true depends + on what the Program does. +

    +

    + 1. You may copy and distribute verbatim copies of the + Program's source code as you receive it, in any medium, provided that you + conspicuously and appropriately publish on each copy an appropriate + copyright notice and disclaimer of warranty; keep intact all the notices + that refer to this License and to the absence of any warranty; and give + any other recipients of the Program a copy of this License along with the + Program. +

    +

    + You may charge a fee for the physical act of transferring a copy, and you + may at your option offer warranty protection in exchange for a fee. +

    +

    + 2. You may modify your copy or copies of the Program or + any portion of it, thus forming a work based on the Program, and copy and + distribute such modifications or work under the terms of Section 1 above, + provided that you also meet all of these conditions: +

    +

    -
    -
    -a) - You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. -
    -
    -
    -
    -b) - You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. -
    -
    -
    -
    -c) - If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) -
    -
    -

    -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. -

    -

    -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. -

    -

    In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. -

    -

    3. - You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: -

    -
    -
    -a) - Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, -
    -
    -b) - Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, -
    -
    -
    -
    -c) - Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) -
    -
    -

    -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. -

    -

    -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. -

    -

    -4. -You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. -

    -

    -5. -You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. -

    -

    -6. -Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. -

    -

    -7. -If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. -

    -

    -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. -

    -

    -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. -

    -

    -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. -

    -

    -8. - If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. -

    -

    -9. - The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. -

    -

    -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. -

    -

    -10. -If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. -

    -

    -NO WARRANTY -

    -

    -11. -BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. -

    -

    -12. - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. -

    -

    -

    END OF TERMS AND CONDITIONS

    - \ No newline at end of file +
    +
    + a) You must cause the modified files to carry prominent + notices stating that you changed the files and the date of any change. +
    +
    +
    +
    + b) You must cause any work that you distribute or + publish, that in whole or in part contains or is derived from the + Program or any part thereof, to be licensed as a whole at no charge to + all third parties under the terms of this License. +
    +
    +
    +
    + c) If the modified program normally reads commands + interactively when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a notice that + there is no warranty (or else, saying that you provide a warranty) and + that users may redistribute the program under these conditions, and + telling the user how to view a copy of this License. (Exception: if the + Program itself is interactive but does not normally print such an + announcement, your work based on the Program is not required to print an + announcement.) +
    +
    +

    + These requirements apply to the modified work as a whole. If identifiable + sections of that work are not derived from the Program, and can be + reasonably considered independent and separate works in themselves, then + this License, and its terms, do not apply to those sections when you + distribute them as separate works. But when you distribute the same + sections as part of a whole which is a work based on the Program, the + distribution of the whole must be on the terms of this License, whose + permissions for other licensees extend to the entire whole, and thus to + each and every part regardless of who wrote it. +

    +

    + Thus, it is not the intent of this section to claim rights or contest your + rights to work written entirely by you; rather, the intent is to exercise + the right to control the distribution of derivative or collective works + based on the Program. +

    +

    + In addition, mere aggregation of another work not based on the Program + with the Program (or with a work based on the Program) on a volume of a + storage or distribution medium does not bring the other work under the + scope of this License. +

    +

    + 3. You may copy and distribute the Program (or a work + based on it, under Section 2) in object code or executable form under the + terms of Sections 1 and 2 above provided that you also do one of the + following: +

    +
    +
    + a) Accompany it with the complete corresponding + machine-readable source code, which must be distributed under the terms + of Sections 1 and 2 above on a medium customarily used for software + interchange; or, +
    +
    + b) Accompany it with a written offer, valid for at + least three years, to give any third party, for a charge no more than + your cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, +
    +
    +
    +
    + c) Accompany it with the information you received as to + the offer to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you received the + program in object code or executable form with such an offer, in accord + with Subsection b above.) +
    +
    +

    + The source code for a work means the preferred form of the work for making + modifications to it. For an executable work, complete source code means + all the source code for all modules it contains, plus any associated + interface definition files, plus the scripts used to control compilation + and installation of the executable. However, as a special exception, the + source code distributed need not include anything that is normally + distributed (in either source or binary form) with the major components + (compiler, kernel, and so on) of the operating system on which the + executable runs, unless that component itself accompanies the executable. +

    +

    + If distribution of executable or object code is made by offering access to + copy from a designated place, then offering equivalent access to copy the + source code from the same place counts as distribution of the source code, + even though third parties are not compelled to copy the source along with + the object code. +

    +

    + 4. You may not copy, modify, sublicense, or distribute + the Program except as expressly provided under this License. Any attempt + otherwise to copy, modify, sublicense or distribute the Program is void, + and will automatically terminate your rights under this License. However, + parties who have received copies, or rights, from you under this License + will not have their licenses terminated so long as such parties remain in + full compliance. +

    +

    + 5. You are not required to accept this License, since you + have not signed it. However, nothing else grants you permission to modify + or distribute the Program or its derivative works. These actions are + prohibited by law if you do not accept this License. Therefore, by + modifying or distributing the Program (or any work based on the Program), + you indicate your acceptance of this License to do so, and all its terms + and conditions for copying, distributing or modifying the Program or works + based on it. +

    +

    + 6. Each time you redistribute the Program (or any work + based on the Program), the recipient automatically receives a license from + the original licensor to copy, distribute or modify the Program subject to + these terms and conditions. You may not impose any further restrictions on + the recipients' exercise of the rights granted herein. You are not + responsible for enforcing compliance by third parties to this License. +

    +

    + 7. If, as a consequence of a court judgment or allegation + of patent infringement or for any other reason (not limited to patent + issues), conditions are imposed on you (whether by court order, agreement + or otherwise) that contradict the conditions of this License, they do not + excuse you from the conditions of this License. If you cannot distribute + so as to satisfy simultaneously your obligations under this License and + any other pertinent obligations, then as a consequence you may not + distribute the Program at all. For example, if a patent license would not + permit royalty-free redistribution of the Program by all those who receive + copies directly or indirectly through you, then the only way you could + satisfy both it and this License would be to refrain entirely from + distribution of the Program. +

    +

    + If any portion of this section is held invalid or unenforceable under any + particular circumstance, the balance of the section is intended to apply + and the section as a whole is intended to apply in other circumstances. +

    +

    + It is not the purpose of this section to induce you to infringe any + patents or other property right claims or to contest validity of any such + claims; this section has the sole purpose of protecting the integrity of + the free software distribution system, which is implemented by public + license practices. Many people have made generous contributions to the + wide range of software distributed through that system in reliance on + consistent application of that system; it is up to the author/donor to + decide if he or she is willing to distribute software through any other + system and a licensee cannot impose that choice. +

    +

    + This section is intended to make thoroughly clear what is believed to be a + consequence of the rest of this License. +

    +

    + 8. If the distribution and/or use of the Program is + restricted in certain countries either by patents or by copyrighted + interfaces, the original copyright holder who places the Program under + this License may add an explicit geographical distribution limitation + excluding those countries, so that distribution is permitted only in or + among countries not thus excluded. In such case, this License incorporates + the limitation as if written in the body of this License. +

    +

    + 9. The Free Software Foundation may publish revised + and/or new versions of the General Public License from time to time. Such + new versions will be similar in spirit to the present version, but may + differ in detail to address new problems or concerns. +

    +

    + Each version is given a distinguishing version number. If the Program + specifies a version number of this License which applies to it and "any + later version", you have the option of following the terms and conditions + either of that version or of any later version published by the Free + Software Foundation. If the Program does not specify a version number of + this License, you may choose any version ever published by the Free + Software Foundation. +

    +

    + 10. If you wish to incorporate parts of the Program into + other free programs whose distribution conditions are different, write to + the author to ask for permission. For software which is copyrighted by the + Free Software Foundation, write to the Free Software Foundation; we + sometimes make exceptions for this. Our decision will be guided by the two + goals of preserving the free status of all derivatives of our free + software and of promoting the sharing and reuse of software generally. +

    +

    NO WARRANTY

    +

    + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE + IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. + EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER + PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER + EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE + ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. + SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY + SERVICING, REPAIR OR CORRECTION. +

    +

    + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR + AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY + MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO + YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR + CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE + PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED + INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE + PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER + PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +

    +

    +

    END OF TERMS AND CONDITIONS

    + + diff --git a/pandora_console/general/license/pandora_info_es.html b/pandora_console/general/license/pandora_info_es.html index aa20e3bc57..39f337a006 100644 --- a/pandora_console/general/license/pandora_info_es.html +++ b/pandora_console/general/license/pandora_info_es.html @@ -1,391 +1,542 @@ - - -Licencia Pública GNU - - + + + Licencia Pública GNU + + +

    Licencia Pública GNU

    +

    Contenido

    -

    Licencia Pública GNU

    -

    Contenido

    + +
    +

    Licencia Pública GNU

    +

    + Esta es la conocida GNU Public License (GPL), versión 2 (de junio + de 1.991), que cubre la mayor parte del software de la Free Software + Foundation, y muchos más programas. +

    - -
    -

    Licencia Pública GNU

    -

    -Esta es la conocida GNU Public License (GPL), versión 2 (de junio -de 1.991), que cubre la mayor parte del software de la Free Software Foundation, -y muchos más programas.

    +

    Los autores de esta traducción son:

    + -

    Los autores de esta traducción son: -

    +
    +
    + NOTA IMPORTANTE: +

    + Esta es una traducción no oficial al español de la GNU + General Public License. No ha sido publicada por la Free Software + Foundation, y no establece legalmente las condiciones de + distribución para el software que usa la GNU GPL. Estas + condiciones se establecen solamente por el texto original, en + inglés, de la GNU GPL. Sin embargo, esperamos que esta + traducción ayude a los hispanohablantes a entender mejor la GNU + GPL. +

    +

    IMPORTANT NOTICE:

    +

    + This is an unofficial translation of the GNU General Public License into + Spanish. It was not published by the Free Software Foundation, and does + not legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, + we hope that this translation will help Spanish speakers understand the + GNU GPL better. +

    +

    +
    +
    -
    -
    -NOTA IMPORTANTE: -

    -Esta es una traducción no oficial al español de la GNU General Public -License. No ha sido publicada por la Free Software Foundation, y no -establece legalmente las condiciones de distribución para el software -que usa la GNU GPL. Estas condiciones se establecen solamente por -el texto original, en inglés, de la GNU GPL. Sin embargo, esperamos -que esta traducción ayude a los hispanohablantes a entender mejor la -GNU GPL. -

    +

    Copyright (C) 1989, 1991 Free Software Foundation, Inc.

    +

    675 Mass Ave, Cambridge, MA 02139, EEUU

    +

    + Se permite la copia y distribución de copias literales de este + documento, pero no se permite su modificación. +

    -IMPORTANT NOTICE: -

    -This is an unofficial translation of the GNU General Public License -into Spanish. It was not published by the Free Software -Foundation, and does not legally state the distribution terms for -software that uses the GNU GPL--only the original English text of -the GNU GPL does that. However, we hope that this translation will -help Spanish speakers understand the GNU GPL better. -

    -


    -
    +

    Preámbulo

    +

    + Las licencias que cubren la mayor parte del software están + diseñadas para quitarle a usted la libertad de compartirlo y + modificarlo. Por el contrario, la Licencia Pública General de GNU + pretende garantizarle la libertad de compartir y modificar software libre, + para asegurar que el software es libre para todos sus usuarios. Esta + Licencia Pública General se aplica a la mayor parte del software + del la Free Software Foundation y a cualquier otro programa si sus autores + se comprometen a utilizarla. (Existe otro software de la Free Software + Foundation que está cubierto por la Licencia Pública General + de GNU para Bibliotecas). Si quiere, también puede aplicarla a sus + propios programas. +

    +

    + Cuando hablamos de software libre, estamos refiriéndonos a + libertad, no a precio. Nuestras Licencias Públicas Generales + están diseñadas para asegurarnos de que tenga la libertad de + distribuir copias de software libre (y cobrar por ese servicio si quiere), + de que reciba el código fuente o que pueda conseguirlo si lo + quiere, de que pueda modificar el software o usar fragmentos de él + en nuevos programas libres, y de que sepa que puede hacer todas estas + cosas. +

    +

    + Para proteger sus derechos necesitamos algunas restricciones que prohiban + a cualquiera negarle a usted estos derechos o pedirle que renuncie a + ellos. Estas restricciones se traducen en ciertas obligaciones que le + afectan si distribuye copias del software, o si lo modifica. +

    +

    + Por ejemplo, si distribuye copias de uno de estos programas, sea + gratuitamente, o a cambio de una contraprestación, debe dar a los + receptores todos los derechos que tiene. Debe asegurarse de que ellos + también reciben, o pueden conseguir, el código fuente. Y + debe mostrarles estas condiciones de forma que conozcan sus derechos. +

    +

    Protegemos sus derechos con la combinación de dos medidas:

    +
      +
    1. Ponemos el software bajo copyright y
    2. +
    3. + le ofrecemos esta licencia, que le da permiso legal para copiar, + distribuir y/o modificar el software. +
    4. +
    +

    + También, para la protección de cada autor y la nuestra + propia, queremos asegurarnos de que todo el mundo comprende que no se + proporciona ninguna garantía para este software libre. Si el + software se modifica por cualquiera y éste a su vez lo distribuye, + queremos que sus receptores sepan que lo que tienen no es el original, de + forma que cualquier problema introducido por otros no afecte a la + reputación de los autores originales. +

    +

    + Por último, cualquier programa libre está constantemente + amenazado por patentes sobre el software. Queremos evitar el peligro de + que los redistribuidores de un programa libre obtengan patentes por su + cuenta, convirtiendo de facto el programa en propietario. Para evitar + esto, hemos dejado claro que cualquier patente debe ser pedida para el uso + libre de cualquiera, o no ser pedida. +

    +

    + Los términos exactos y las condiciones para la copia, + distribución y modificación se exponen a + continuación. +

    -

    Copyright (C) 1989, 1991 Free Software Foundation, Inc. -

    675 Mass Ave, Cambridge, MA 02139, EEUU -

    Se permite la copia y distribución de copias literales de este -documento, pero no se permite su modificación. -

    +

    + Términos y condiciones para la copia, distribución y + modificación +

    +
      +
    1. + Esta Licencia se aplica a cualquier programa u otro tipo de trabajo que + contenga una nota colocada por el tenedor del copyright diciendo que + puede ser distribuido bajo los términos de esta Licencia + Pública General. En adelante, �Programa� se referirá a + cualquier programa o trabajo que cumpla esa condición y �trabajo + basado en el Programa� se referirá bien al Programa o a cualquier + trabajo derivado de él según la ley de copyright. Esto es, + un trabajo que contenga el programa o una proción de él, + bien en forma literal o con modificaciones y/o traducido en otro + lenguaje. Por lo tanto, la traducción está incluida sin + limitaciones en el término �modificación�. Cada + concesionario (licenciatario) será denominado �usted�. +

      + Cualquier otra actividad que no sea la copia, distribución o + modificación no está cubierta por esta Licencia, + está fuera de su ámbito. El acto de ejecutar el Programa + no está restringido, y los resultados del Programa están + cubiertos únicamente si sus contenidos constituyen un trabajo + basado en el Programa, independientemente de haberlo producido + mediante la ejecución del programa. El que esto se cumpla, + depende de lo que haga el programa. +

      +
    2. +
    3. + Usted puede copiar y distribuir copias literales del código + fuente del Programa, según lo has recibido, en cualquier medio, + supuesto que de forma adecuada y bien visible publique en cada copia un + anuncio de copyright adecuado y un repudio de garantía, mantenga + intactos todos los anuncios que se refieran a esta Licencia y a la + ausencia de garantía, y proporcione a cualquier otro receptor del + programa una copia de esta Licencia junto con el Programa. +

      + Puede cobrar un precio por el acto físico de transferir una + copia, y puede, según su libre albedrío, ofrecer + garantía a cambio de unos honorarios. +

      +
    4. +
    5. + Puede modificar su copia o copias del Programa o de cualquier + porción de él, formando de esta manera un trabajo basado + en el Programa, y copiar y distribuir esa modificación o trabajo + bajo los términos del apartado 1, antedicho, supuesto que + además cumpla las siguientes condiciones: +
        +
      1. + Debe hacer que los ficheros modificados lleven anuncios prominentes + indicando que los ha cambiado y la fecha de cualquier cambio. +
      2. +
      3. + Debe hacer que cualquier trabajo que distribuya o publique y que en + todo o en parte contenga o sea derivado del Programa o de cualquier + parte de él sea licenciada como un todo, sin carga alguna, a + todas las terceras partes y bajo los términos de esta + Licencia. +
      4. +
      5. + Si el programa modificado lee normalmente órdenes + interactivamente cuando es ejecutado, debe hacer que, cuando + comience su ejecución para ese uso interactivo de la forma + más habitual, muestre o escriba un mensaje que incluya un + anuncio de copyright y un anuncio de que no se ofrece ninguna + garantía (o por el contrario que sí se ofrece + garantía) y que los usuarios pueden redistribuir el programa + bajo estas condiciones, e indicando al usuario cómo ver una + copia de esta licencia. (Excepción: si el propio programa es + interactivo pero normalmente no muestra ese anuncio, no se requiere + que su trabajo basado en el Programa muestre ningún anuncio). +
      6. +
      + Estos requisitos se aplican al trabajo modificado como un todo. Si + partes identificables de ese trabajo no son derivadas del Programa, y + pueden, razonablemente, ser consideradas trabajos independientes y + separados por ellos mismos, entonces esta Licencia y sus términos + no se aplican a esas partes cuando sean distribuidas como trabajos + separados. Pero cuando distribuya esas mismas secciones como partes de + un todo que es un trabajo basado en el Programa, la distribución + del todo debe ser según los términos de esta licencia, + cuyos permisos para otros licenciatarios se extienden al todo completo, + y por lo tanto a todas y cada una de sus partes, con independencia de + quién la escribió. +

      + Por lo tanto, no es la intención de este apartado reclamar + derechos o desafiar sus derechos sobre trabajos escritos totalmente + por usted mismo. El intento es ejercer el derecho a controlar la + distribución de trabajos derivados o colectivos basados en el + Programa. +

      +

      + Además, el simple hecho de reunir un trabajo no basado en el + Programa con el Programa (o con un trabajo basado en el Programa) en + un volumen de almacenamiento o en un medio de distribución no + hace que dicho trabajo entre dentro del ámbito cubierto por + esta Licencia. +

      +
    6. +
    7. + Puede copiar y distribuir el Programa (o un trabajo basado en él, + según se especifica en el apartado 2, como código objeto o + en formato ejecutable según los términos de los apartados + 1 y 2, supuesto que además cumpla una de las siguientes + condiciones: +
        +
      1. + Acompañarlo con el código fuente completo + correspondiente, en formato electrónico, que debe ser + distribuido según se especifica en los apartados 1 y 2 de + esta Licencia en un medio habitualmente utilizado para el + intercambio de programas, o +
      2. +
      3. + Acompañarlo con una oferta por escrito, válida durante + al menos tres años, de proporcionar a cualquier tercera parte + una copia completa en formato electrónico del código + fuente correspondiente, a un coste no mayor que el de realizar + físicamente la distribución del fuente, que + será distribuido bajo las condiciones descritas en los + apartados 1 y 2 anteriores, en un medio habitualmente utilizado para + el intercambio de programas, o +
      4. +
      5. + Acompañarlo con la información que recibiste + ofreciendo distribuir el código fuente correspondiente. (Esta + opción se permite sólo para distribución no + comercial y sólo si usted recibió el programa como + código objeto o en formato ejecutable con tal oferta, de + acuerdo con el apartado b anterior). +
      6. +
      + Por código fuente de un trabajo se entiende la forma preferida + del trabajo cuando se le hacen modificaciones. Para un trabajo + ejecutable, se entiende por código fuente completo todo el + código fuente para todos los módulos que contiene, + más cualquier fichero asociado de definición de + interfaces, más los guiones utilizados para controlar la + compilación e instalación del ejecutable. Como + excepción especial el código fuente distribuido no + necesita incluir nada que sea distribuido normalmente (bien como fuente, + bien en forma binaria) con los componentes principales (compilador, + kernel y similares) del sistema operativo en el cual funciona el + ejecutable, a no ser que el propio componente acompañe al + ejecutable. +

      + Si la distribución del ejecutable o del código objeto se + hace mediante la oferta acceso para copiarlo de un cierto lugar, + entonces se considera la oferta de acceso para copiar el código + fuente del mismo lugar como distribución del código + fuente, incluso aunque terceras partes no estén forzadas a + copiar el fuente junto con el código objeto. +

      +
    8. +
    9. + No puede copiar, modificar, sublicenciar o distribuir el Programa + excepto como prevé expresamente esta Licencia. Cualquier intento + de copiar, modificar sublicenciar o distribuir el Programa de otra forma + es inválida, y hará que cesen automáticamente los + derechos que te proporciona esta Licencia. En cualquier caso, las partes + que hayan recibido copias o derechos de usted bajo esta Licencia no + cesarán en sus derechos mientras esas partes continúen + cumpliéndola. +
    10. +
    11. + No está obligado a aceptar esta licencia, ya que no la ha + firmado. Sin embargo, no hay hada más que le proporcione permiso + para modificar o distribuir el Programa o sus trabajos derivados. Estas + acciones están prohibidas por la ley si no acepta esta Licencia. + Por lo tanto, si modifica o distribuye el Programa (o cualquier trabajo + basado en el Programa), está indicando que acepta esta Licencia + para poder hacerlo, y todos sus términos y condiciones para + copiar, distribuir o modificar el Programa o trabajos basados en + él. +
    12. +
    13. + Cada vez que redistribuya el Programa (o cualquier trabajo basado en el + Programa), el receptor recibe automáticamente una licencia del + licenciatario original para copiar, distribuir o modificar el Programa, + de forma sujeta a estos términos y condiciones. No puede imponer + al receptor ninguna restricción más sobre el ejercicio de + los derechos aquí garantizados. No es usted responsable de hacer + cumplir esta licencia por terceras partes. +
    14. +
    15. + Si como consecuencia de una resolución judicial o de una + alegación de infracción de patente o por cualquier otra + razón (no limitada a asuntos relacionados con patentes) se le + imponen condiciones (ya sea por mandato judicial, por acuerdo o por + cualquier otra causa) que contradigan las condiciones de esta Licencia, + ello no le exime de cumplir las condiciones de esta Licencia. Si no + puede realizar distribuciones de forma que se satisfagan + simultáneamente sus obligaciones bajo esta licencia y cualquier + otra obligación pertinente entonces, como consecuencia, no puede + distribuir el Programa de ninguna forma. Por ejemplo, si una patente no + permite la redistribución libre de derechos de autor del Programa + por parte de todos aquellos que reciban copias directa o indirectamente + a través de usted, entonces la única forma en que + podría satisfacer tanto esa condición como esta Licencia + sería evitar completamente la distribución del Programa. +

      + Si cualquier porción de este apartado se considera + inválida o imposible de cumplir bajo cualquier circunstancia + particular ha de cumplirse el resto y la sección por entero ha + de cumplirse en cualquier otra circunstancia. +

      +

      + No es el propósito de este apartado inducirle a infringir + ninguna reivindicación de patente ni de ningún otro + derecho de propiedad o impugnar la validez de ninguna de dichas + reivindicaciones. Este apartado tiene el único propósito + de proteger la integridad del sistema de distribución de + software libre, que se realiza mediante prácticas de licencia + pública. Mucha gente ha hecho contribuciones generosas a la + gran variedad de software distribuido mediante ese sistema con la + confianza de que el sistema se aplicará consistentemente. + Será el autor/donante quien decida si quiere distribuir + software mediante cualquier otro sistema y una licencia no puede + imponer esa elección. +

      +

      + Este apartado pretende dejar completamente claro lo que se cree que es + una consecuencia del resto de esta Licencia. +

      +
    16. +
    17. + Si la distribución y/o uso de el Programa está restringida + en ciertos países, bien por patentes o por interfaces bajo + copyright, el tenedor del copyright que coloca este Programa bajo esta + Licencia puede añadir una limitación explícita de + distribución geográfica excluyendo esos países, de + forma que la distribución se permita sólo en o entre los + países no excluidos de esta manera. En ese caso, esta Licencia + incorporará la limitación como si estuviese escrita en el + cuerpo de esta Licencia. +
    18. +
    19. + La Free Software Foundation puede publicar versiones revisadas y/o + nuevas de la Licencia Pública General de tiempo en tiempo. Dichas + nuevas versiones serán similares en espíritu a la presente + versión, pero pueden ser diferentes en detalles para considerar + nuevos problemas o situaciones. +

      + Cada versión recibe un número de versión que la + distingue de otras. Si el Programa especifica un número de + versión de esta Licencia que se refiere a ella y a �cualquier + versión posterior�, tienes la opción de seguir los + términos y condiciones, bien de esa versión, bien de + cualquier versión posterior publicada por la Free Software + Foundation. Si el Programa no especifica un número de + versión de esta Licencia, puedes escoger cualquier + versión publicada por la Free Software Foundation. +

      +
    20. +
    21. + Si quiere incorporar partes del Programa en otros programas libres cuyas + condiciones de distribución son diferentes, escribe al autor para + pedirle permiso. Si el software tiene copyright de la Free Software + Foundation, escribe a la Free Software Foundation: algunas veces hacemos + excepciones en estos casos. Nuestra decisión estará guiada + por el doble objetivo de de preservar la libertad de todos los derivados + de nuestro software libre y promover el que se comparta y reutilice el + software en general. +
    22. +
    -

    Preámbulo

    -

    -Las licencias que cubren la mayor parte del software están diseñadas -para quitarle a usted la libertad de compartirlo y modificarlo. Por el -contrario, la Licencia Pública General de GNU pretende garantizarle -la libertad de compartir y modificar software libre, para asegurar que -el software es libre para todos sus usuarios. Esta Licencia Pública -General se aplica a la mayor parte del software del la Free Software Foundation -y a cualquier otro programa si sus autores se comprometen a utilizarla. -(Existe otro software de la Free Software Foundation que está cubierto -por la Licencia Pública General de GNU para Bibliotecas). Si quiere, -también puede aplicarla a sus propios programas.

    -

    Cuando hablamos de software libre, estamos refiriéndonos a libertad, -no a precio. Nuestras Licencias Públicas Generales están -diseñadas para asegurarnos de que tenga la libertad de distribuir -copias de software libre (y cobrar por ese servicio si quiere), de que -reciba el código fuente o que pueda conseguirlo si lo quiere, de -que pueda modificar el software o usar fragmentos de él en nuevos -programas libres, y de que sepa que puede hacer todas estas cosas. -

    Para proteger sus derechos necesitamos algunas restricciones que prohiban -a cualquiera negarle a usted estos derechos o pedirle que renuncie a ellos. -Estas restricciones se traducen en ciertas obligaciones que le afectan -si distribuye copias del software, o si lo modifica. -

    Por ejemplo, si distribuye copias de uno de estos programas, sea gratuitamente, -o a cambio de una contraprestación, debe dar a los receptores todos -los derechos que tiene. Debe asegurarse de que ellos también reciben, -o pueden conseguir, el código fuente. Y debe mostrarles estas condiciones -de forma que conozcan sus derechos. -

    Protegemos sus derechos con la combinación de dos medidas: -

      -
    1. Ponemos el software bajo copyright y -
    2. le ofrecemos esta licencia, que le da permiso legal para copiar, distribuir -y/o modificar el software.
    -

    -También, para la protección de cada autor y la nuestra propia, -queremos asegurarnos de que todo el mundo comprende que no se proporciona -ninguna garantía para este software libre. Si el software se modifica -por cualquiera y éste a su vez lo distribuye, queremos que sus receptores -sepan que lo que tienen no es el original, de forma que cualquier problema -introducido por otros no afecte a la reputación de los autores originales.

    -

    Por último, cualquier programa libre está constantemente -amenazado por patentes sobre el software. Queremos evitar el peligro de -que los redistribuidores de un programa libre obtengan patentes por su -cuenta, convirtiendo de facto el programa en propietario. Para evitar esto, -hemos dejado claro que cualquier patente debe ser pedida para el uso libre -de cualquiera, o no ser pedida. -

    Los términos exactos y las condiciones para la copia, distribución -y modificación se exponen a continuación.

    +

    AUSENCIA DE GARANTÍA

    -

    Términos y condiciones para la copia, -distribución y modificación

    +
      +
    1. + Como el programa se licencia libre de cargas, no se ofrece ninguna + garantía sobre el programa, en todas la extensión + permitida por la legislación aplicable. Excepto cuando se indique + de otra forma por escrito, los tenedores del copyright y/u otras partes + proporcionan el programa �tal cual�, sin garantía de ninguna + clase, bien expresa o implícita, con inclusión, pero sin + limitación a las garantías mercantiles implícitas o + a la conveniencia para un propósito particular. Cualquier riesgo + referente a la calidad y prestaciones del programa es asumido por usted. + Si se probase que el Programa es defectuoso, asume el coste de cualquier + servicio, reparación o corrección. +
    2. +
    3. + En ningún caso, salvo que lo requiera la legislación + aplicable o haya sido acordado por escrito, ningún tenedor del + copyright ni ninguna otra parte que modifique y/o redistribuya el + Programa según se permite en esta Licencia será + responsable ante usted por daños, incluyendo cualquier + daño general, especial, incidental o resultante producido por el + uso o la imposibilidad de uso del Programa (con inclusión, pero + sin limitación a la pérdida de datos o a la + generación incorrecta de datos o a pérdidas sufridas por + usted o por terceras partes o a un fallo del Programa al funcionar en + combinación con cualquier otro programa), incluso si dicho + tenedor u otra parte ha sido advertido de la posibilidad de dichos + daños. +
    4. +
    -
      -
    1. Esta Licencia se aplica a cualquier programa u otro tipo -de trabajo que contenga una nota colocada por el tenedor del copyright -diciendo que puede ser distribuido bajo los términos de esta Licencia -Pública General. En adelante, �Programa� se referirá -a cualquier programa o trabajo que cumpla esa condición y �trabajo -basado en el Programa� se referirá bien al Programa o a cualquier -trabajo derivado de él según la ley de copyright. Esto es, -un trabajo que contenga el programa o una proción de él, -bien en forma literal o con modificaciones y/o traducido en otro lenguaje. -Por lo tanto, la traducción está incluida sin limitaciones -en el término �modificación�. Cada concesionario -(licenciatario) será denominado �usted�. -

      Cualquier otra actividad que no sea la copia, distribución o -modificación no está cubierta por esta Licencia, está -fuera de su ámbito. El acto de ejecutar el Programa no está -restringido, y los resultados del Programa están cubiertos únicamente -si sus contenidos constituyen un trabajo basado en el Programa, independientemente -de haberlo producido mediante la ejecución del programa. El que -esto se cumpla, depende de lo que haga el programa. -

    2. Usted puede copiar y distribuir copias literales del código fuente -del Programa, según lo has recibido, en cualquier medio, supuesto -que de forma adecuada y bien visible publique en cada copia un anuncio -de copyright adecuado y un repudio de garantía, mantenga intactos -todos los anuncios que se refieran a esta Licencia y a la ausencia de garantía, -y proporcione a cualquier otro receptor del programa una copia de esta -Licencia junto con el Programa. -

      Puede cobrar un precio por el acto físico de transferir una copia, -y puede, según su libre albedrío, ofrecer garantía -a cambio de unos honorarios. -

    3. Puede modificar su copia o copias del Programa o de cualquier porción -de él, formando de esta manera un trabajo basado en el Programa, -y copiar y distribuir esa modificación o trabajo bajo los términos -del apartado 1, antedicho, supuesto que además cumpla las siguientes -condiciones: -
      1. Debe hacer que los ficheros modificados lleven anuncios -prominentes indicando que los ha cambiado y la fecha de cualquier cambio. -
      2. Debe hacer que cualquier trabajo que distribuya o publique y que en -todo o en parte contenga o sea derivado del Programa o de cualquier parte -de él sea licenciada como un todo, sin carga alguna, a todas las -terceras partes y bajo los términos de esta Licencia. -
      3. Si el programa modificado lee normalmente órdenes interactivamente -cuando es ejecutado, debe hacer que, cuando comience su ejecución -para ese uso interactivo de la forma más habitual, muestre o escriba -un mensaje que incluya un anuncio de copyright y un anuncio de que no se -ofrece ninguna garantía (o por el contrario que sí se ofrece -garantía) y que los usuarios pueden redistribuir el programa bajo -estas condiciones, e indicando al usuario cómo ver una copia de -esta licencia. (Excepción: si el propio programa es interactivo -pero normalmente no muestra ese anuncio, no se requiere que su trabajo -basado en el Programa muestre ningún anuncio).
      -Estos requisitos se aplican al trabajo modificado como un todo. Si partes -identificables de ese trabajo no son derivadas del Programa, y pueden, -razonablemente, ser consideradas trabajos independientes y separados por -ellos mismos, entonces esta Licencia y sus términos no se aplican -a esas partes cuando sean distribuidas como trabajos separados. Pero cuando -distribuya esas mismas secciones como partes de un todo que es un trabajo -basado en el Programa, la distribución del todo debe ser según -los términos de esta licencia, cuyos permisos para otros licenciatarios -se extienden al todo completo, y por lo tanto a todas y cada una de sus -partes, con independencia de quién la escribió. -

      Por lo tanto, no es la intención de este apartado reclamar derechos -o desafiar sus derechos sobre trabajos escritos totalmente por usted mismo. -El intento es ejercer el derecho a controlar la distribución de -trabajos derivados o colectivos basados en el Programa. -

      Además, el simple hecho de reunir un trabajo no basado en el -Programa con el Programa (o con un trabajo basado en el Programa) en un -volumen de almacenamiento o en un medio de distribución no hace -que dicho trabajo entre dentro del ámbito cubierto por esta Licencia. -

    4. Puede copiar y distribuir el Programa (o un trabajo basado en él, -según se especifica en el apartado 2, como código objeto -o en formato ejecutable según los términos de los apartados -1 y 2, supuesto que además cumpla una de las siguientes condiciones: -
      1. Acompañarlo con el código fuente completo -correspondiente, en formato electrónico, que debe ser distribuido -según se especifica en los apartados 1 y 2 de esta Licencia en un -medio habitualmente utilizado para el intercambio de programas, o -
      2. Acompañarlo con una oferta por escrito, válida durante -al menos tres años, de proporcionar a cualquier tercera parte una -copia completa en formato electrónico del código fuente correspondiente, -a un coste no mayor que el de realizar físicamente la distribución -del fuente, que será distribuido bajo las condiciones descritas -en los apartados 1 y 2 anteriores, en un medio habitualmente utilizado -para el intercambio de programas, o -
      3. Acompañarlo con la información que recibiste ofreciendo -distribuir el código fuente correspondiente. (Esta opción -se permite sólo para distribución no comercial y sólo -si usted recibió el programa como código objeto o en formato -ejecutable con tal oferta, de acuerdo con el apartado b anterior).
      -Por código fuente de un trabajo se entiende la forma preferida del -trabajo cuando se le hacen modificaciones. Para un trabajo ejecutable, -se entiende por código fuente completo todo el código fuente -para todos los módulos que contiene, más cualquier fichero -asociado de definición de interfaces, más los guiones utilizados -para controlar la compilación e instalación del ejecutable. -Como excepción especial el código fuente distribuido no necesita -incluir nada que sea distribuido normalmente (bien como fuente, bien en -forma binaria) con los componentes principales (compilador, kernel y similares) -del sistema operativo en el cual funciona el ejecutable, a no ser que el -propio componente acompañe al ejecutable. -

      Si la distribución del ejecutable o del código objeto -se hace mediante la oferta acceso para copiarlo de un cierto lugar, entonces -se considera la oferta de acceso para copiar el código fuente del -mismo lugar como distribución del código fuente, incluso -aunque terceras partes no estén forzadas a copiar el fuente junto -con el código objeto. -

    5. No puede copiar, modificar, sublicenciar o distribuir el Programa excepto -como prevé expresamente esta Licencia. Cualquier intento de copiar, -modificar sublicenciar o distribuir el Programa de otra forma es inválida, -y hará que cesen automáticamente los derechos que te proporciona -esta Licencia. En cualquier caso, las partes que hayan recibido copias -o derechos de usted bajo esta Licencia no cesarán en sus derechos -mientras esas partes continúen cumpliéndola. -
    6. No está obligado a aceptar esta licencia, ya que no la ha firmado. -Sin embargo, no hay hada más que le proporcione permiso para modificar -o distribuir el Programa o sus trabajos derivados. Estas acciones están -prohibidas por la ley si no acepta esta Licencia. Por lo tanto, si modifica -o distribuye el Programa (o cualquier trabajo basado en el Programa), está -indicando que acepta esta Licencia para poder hacerlo, y todos sus términos -y condiciones para copiar, distribuir o modificar el Programa o trabajos -basados en él. -
    7. Cada vez que redistribuya el Programa (o cualquier trabajo basado en -el Programa), el receptor recibe automáticamente una licencia del -licenciatario original para copiar, distribuir o modificar el Programa, -de forma sujeta a estos términos y condiciones. No puede imponer -al receptor ninguna restricción más sobre el ejercicio de -los derechos aquí garantizados. No es usted responsable de hacer -cumplir esta licencia por terceras partes. -
    8. Si como consecuencia de una resolución judicial o de una alegación -de infracción de patente o por cualquier otra razón (no limitada -a asuntos relacionados con patentes) se le imponen condiciones (ya sea -por mandato judicial, por acuerdo o por cualquier otra causa) que contradigan -las condiciones de esta Licencia, ello no le exime de cumplir las condiciones -de esta Licencia. Si no puede realizar distribuciones de forma que se satisfagan -simultáneamente sus obligaciones bajo esta licencia y cualquier -otra obligación pertinente entonces, como consecuencia, no puede -distribuir el Programa de ninguna forma. Por ejemplo, si una patente no -permite la redistribución libre de derechos de autor del Programa -por parte de todos aquellos que reciban copias directa o indirectamente -a través de usted, entonces la única forma en que podría -satisfacer tanto esa condición como esta Licencia sería evitar -completamente la distribución del Programa. -

      Si cualquier porción de este apartado se considera inválida -o imposible de cumplir bajo cualquier circunstancia particular ha de cumplirse -el resto y la sección por entero ha de cumplirse en cualquier otra -circunstancia. -

      No es el propósito de este apartado inducirle a infringir ninguna -reivindicación de patente ni de ningún otro derecho de propiedad -o impugnar la validez de ninguna de dichas reivindicaciones. Este apartado -tiene el único propósito de proteger la integridad del sistema -de distribución de software libre, que se realiza mediante prácticas -de licencia pública. Mucha gente ha hecho contribuciones generosas -a la gran variedad de software distribuido mediante ese sistema con la -confianza de que el sistema se aplicará consistentemente. Será -el autor/donante quien decida si quiere distribuir software mediante cualquier -otro sistema y una licencia no puede imponer esa elección. -

      Este apartado pretende dejar completamente claro lo que se cree que -es una consecuencia del resto de esta Licencia. -

    9. Si la distribución y/o uso de el Programa está restringida -en ciertos países, bien por patentes o por interfaces bajo copyright, -el tenedor del copyright que coloca este Programa bajo esta Licencia puede -añadir una limitación explícita de distribución -geográfica excluyendo esos países, de forma que la distribución -se permita sólo en o entre los países no excluidos de esta -manera. En ese caso, esta Licencia incorporará la limitación -como si estuviese escrita en el cuerpo de esta Licencia. -
    10. La Free Software Foundation puede publicar versiones revisadas y/o nuevas -de la Licencia Pública General de tiempo en tiempo. Dichas nuevas -versiones serán similares en espíritu a la presente versión, -pero pueden ser diferentes en detalles para considerar nuevos problemas -o situaciones. -

      Cada versión recibe un número de versión que la -distingue de otras. Si el Programa especifica un número de versión -de esta Licencia que se refiere a ella y a �cualquier versión -posterior�, tienes la opción de seguir los términos -y condiciones, bien de esa versión, bien de cualquier versión -posterior publicada por la Free Software Foundation. Si el Programa no -especifica un número de versión de esta Licencia, puedes -escoger cualquier versión publicada por la Free Software Foundation. -

    11. Si quiere incorporar partes del Programa en otros programas libres cuyas -condiciones de distribución son diferentes, escribe al autor para -pedirle permiso. Si el software tiene copyright de la Free Software Foundation, -escribe a la Free Software Foundation: algunas veces hacemos excepciones -en estos casos. Nuestra decisión estará guiada por el doble -objetivo de de preservar la libertad de todos los derivados de nuestro -software libre y promover el que se comparta y reutilice el software en -general.
    +

    FIN DE TÉRMINOS Y CONDICIONES

    -

    AUSENCIA DE GARANTÍA

    - -
      -
    1. Como el programa se licencia libre de cargas, -no se ofrece ninguna garantía sobre el programa, en todas la extensión -permitida por la legislación aplicable. Excepto cuando se indique -de otra forma por escrito, los tenedores del copyright y/u otras partes -proporcionan el programa �tal cual�, sin garantía de -ninguna clase, bien expresa o implícita, con inclusión, pero -sin limitación a las garantías mercantiles implícitas -o a la conveniencia para un propósito particular. Cualquier riesgo -referente a la calidad y prestaciones del programa es asumido por usted. -Si se probase que el Programa es defectuoso, asume el coste de cualquier -servicio, reparación o corrección. -
    2. En ningún caso, salvo que lo requiera la legislación aplicable -o haya sido acordado por escrito, ningún tenedor del copyright ni -ninguna otra parte que modifique y/o redistribuya el Programa según -se permite en esta Licencia será responsable ante usted por daños, -incluyendo cualquier daño general, especial, incidental o resultante -producido por el uso o la imposibilidad de uso del Programa (con inclusión, -pero sin limitación a la pérdida de datos o a la generación -incorrecta de datos o a pérdidas sufridas por usted o por terceras -partes o a un fallo del Programa al funcionar en combinación con -cualquier otro programa), incluso si dicho tenedor u otra parte ha sido -advertido de la posibilidad de dichos daños.
    - -

    FIN DE TÉRMINOS Y CONDICIONES

    - -

    Apéndice: Cómo aplicar estos -términos a sus nuevos programas.

    -

    -Si usted desarrolla un nuevo Programa, y quiere que sea del mayor uso posible -para el público en general, la mejor forma de conseguirlo es convirtiéndolo -en software libre que cualquiera pueda redistribuir y cambiar bajo estos -términos.

    -

    Para hacerlo, añada los siguientes anuncios al programa. Lo más -seguro es añadirlos al principio de cada fichero fuente para transmitir -lo más efectivamente posible la ausencia de garantía. Además -cada fichero debería tener al menos la línea de �copyright� -y un indicador a dónde puede encontrarse el anuncio completo. -

    <una línea para indicar el nombre -del programa y una rápida idea de qué hace.> -

    Copyright (C) 19aa <nombre del autor> -

    Este programa es software libre. Puede redistribuirlo y/o modificarlo -bajo los términos de la Licencia Pública General de GNU según -es publicada por la Free Software Foundation, bien de la versión -2 de dicha Licencia o bien (según su elección) de cualquier -versión posterior. -

    Este programa se distribuye con la esperanza de que sea útil, -pero SIN NINGUNA GARANT�A, incluso sin la garantía MERCANTIL -implícita o sin garantizar la CONVENIENCIA PARA UN PROP�SITO -PARTICULAR. Véase la Licencia Pública General de GNU para -más detalles. -

    Debería haber recibido una copia de la Licencia Pública -General junto con este programa. Si no ha sido así, escriba a la -Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, EEUU.

    -

    -Añada también información sobre cómo contactar -con usted mediante correo electrónico y postal.

    -

    Si el programa es interactivo, haga que muestre un pequeño anuncio -como el siguiente, cuando comienza a funcionar en modo interactivo: -

    Gnomovision versión 69, Copyright -(C) 19aa nombre del autor -

    Gnomovision no ofrece ABSOLUTAMENTE NINGUNA GARANTÍA. Para más -detalles escriba �show w�.

    -

    -Los comandos hipotéticos �show w� y �show c� -deberían mostrar las partes adecuadas de la Licencia Pública -General. Por supuesto, los comandos que use pueden llamarse de cualquier -otra manera. Podrían incluso ser pulsaciones del ratón o -elementos de un menú (lo que sea apropiado para su programa).

    -

    También deberías conseguir que su empleador (si trabaja -como programador) o tu Universidad (si es el caso) firme un �renuncia -de copyright� para el programa, si es necesario. A continuación -se ofrece un ejemplo, altere los nombres según sea conveniente: -

      -
    1. -Yoyodyne, Inc. mediante este documento renuncia -a cualquier interés de derechos de copyright con respecto al programa -Gnomovision (que hace pasadas a compiladores) escrito por Pepe Programador. -

      <firma de Pepito Grillo>, 20 de diciembre de 1996 -

      Pepito Grillo, Presidente de Asuntillos Varios.

    -

    -Esta Licencia Pública General no permite que incluya sus programas -en programas propietarios. Si su programa es una biblioteca de subrutinas, -puede considerar más útil el permitir el enlazado de aplicaciones -propietarias con la biblioteca. Si este es el caso, use la Licencia Pública -General de GNU para Bibliotecas en lugar de esta Licencia.

    - - \ No newline at end of file +

    + Apéndice: Cómo aplicar estos + términos a sus nuevos programas. +

    +

    + Si usted desarrolla un nuevo Programa, y quiere que sea del mayor uso + posible para el público en general, la mejor forma de conseguirlo + es convirtiéndolo en software libre que cualquiera pueda + redistribuir y cambiar bajo estos términos. +

    +

    + Para hacerlo, añada los siguientes anuncios al programa. Lo + más seguro es añadirlos al principio de cada fichero fuente + para transmitir lo más efectivamente posible la ausencia de + garantía. Además cada fichero debería tener al menos + la línea de �copyright� y un indicador a dónde puede + encontrarse el anuncio completo. +

    +
    + <una línea para indicar el nombre del programa y una + rápida idea de qué hace.> +

    Copyright (C) 19aa <nombre del autor>

    +

    + Este programa es software libre. Puede redistribuirlo y/o modificarlo + bajo los términos de la Licencia Pública General de GNU + según es publicada por la Free Software Foundation, bien de la + versión 2 de dicha Licencia o bien (según su + elección) de cualquier versión posterior. +

    +

    + Este programa se distribuye con la esperanza de que sea útil, + pero SIN NINGUNA GARANT�A, incluso sin la garantía MERCANTIL + implícita o sin garantizar la CONVENIENCIA PARA UN PROP�SITO + PARTICULAR. Véase la Licencia Pública General de GNU para + más detalles. +

    +

    + Debería haber recibido una copia de la Licencia Pública + General junto con este programa. Si no ha sido así, escriba a la + Free Software Foundation, Inc., en 675 Mass Ave, Cambridge, MA 02139, + EEUU. +

    +
    +

    + Añada también información sobre cómo contactar + con usted mediante correo electrónico y postal. +

    +

    + Si el programa es interactivo, haga que muestre un pequeño anuncio + como el siguiente, cuando comienza a funcionar en modo interactivo: +

    +
    + Gnomovision versión 69, Copyright (C) 19aa nombre del autor +

    + Gnomovision no ofrece ABSOLUTAMENTE NINGUNA GARANTÍA. Para + más detalles escriba �show w�. +

    +
    +

    + Los comandos hipotéticos �show w� y �show c� deberían + mostrar las partes adecuadas de la Licencia Pública General. Por + supuesto, los comandos que use pueden llamarse de cualquier otra manera. + Podrían incluso ser pulsaciones del ratón o elementos de un + menú (lo que sea apropiado para su programa). +

    +

    + También deberías conseguir que su empleador (si trabaja como + programador) o tu Universidad (si es el caso) firme un �renuncia de + copyright� para el programa, si es necesario. A continuación se + ofrece un ejemplo, altere los nombres según sea conveniente: +

    +
      +
    1. + Yoyodyne, Inc. mediante este documento renuncia a cualquier + interés de derechos de copyright con respecto al programa + Gnomovision (que hace pasadas a compiladores) escrito por Pepe + Programador. +

      <firma de Pepito Grillo>, 20 de diciembre de 1996

      +

      Pepito Grillo, Presidente de Asuntillos Varios.

      +
    2. +
    +

    + Esta Licencia Pública General no permite que incluya sus programas + en programas propietarios. Si su programa es una biblioteca de subrutinas, + puede considerar más útil el permitir el enlazado de + aplicaciones propietarias con la biblioteca. Si este es el caso, use la + Licencia Pública General de GNU para Bibliotecas en lugar de esta + Licencia. +

    + + diff --git a/pandora_console/general/license/pandora_info_fr.html b/pandora_console/general/license/pandora_info_fr.html index c0e83632b5..28ab89e3b2 100644 --- a/pandora_console/general/license/pandora_info_fr.html +++ b/pandora_console/general/license/pandora_info_fr.html @@ -1,437 +1,553 @@ - - Licence Publique Générale GNU - - -

    Licence Publique Générale GNU

    + + Licence Publique Générale GNU + + +

    Licence Publique Générale GNU

    -

    Benjamin Drieu, APRIL (bdrieu@april.org), Mélanie -Clément-Fontaine (melanie@amberlab.net), -Arnaud Fontaine (arnaud@crao.net), Lo�c Dachary -(loic@gnu.org), Frédéric Couchet (fcouchet@fsffrance.org). -

    -

    Advertiment

    -

    -This is an unofficial translation of the GNU General Public -License into French. It was not published by the Free Software -Foundation, and does not legally state the distribution terms -for software that uses the GNU GPL--only the original English -text of the GNU GPL does that. However, we hope that this -translation will help French speakers understand the GNU GPL -better. -

    +

    + Benjamin Drieu, APRIL (bdrieu@april.org), Mélanie Clément-Fontaine (melanie@amberlab.net), Arnaud Fontaine (arnaud@crao.net), Lo�c Dachary (loic@gnu.org), + Frédéric Couchet (fcouchet@fsffrance.org). + +

    +

    Advertiment

    +

    + This is an unofficial translation of the GNU General Public License into + French. It was not published by the Free Software Foundation, and does not + legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, we + hope that this translation will help French speakers understand the GNU + GPL better. +

    -

    -Ceci est une traduction non officielle de la GNU General Public -License en fran�ais. Elle n'a pas été publiée par la Free -Software Foundation, et ne détermine pas les termes de -distribution pour les logiciels qui utilisent la GNU GPL, seul -le texte anglais original de la GNU GPL déterminent ces -termes. Cependant, nous espérons que cette traduction aidera les -francophones à mieux comprendre la GNU GPL. -

    +

    + Ceci est une traduction non officielle de la GNU General Public License en + fran�ais. Elle n'a pas été publiée par la Free + Software Foundation, et ne détermine pas les termes de distribution + pour les logiciels qui utilisent la GNU GPL, seul le texte anglais + original de la GNU GPL déterminent ces termes. Cependant, nous + espérons que cette traduction aidera les francophones à + mieux comprendre la GNU GPL. +

    -

    Licence Publique Générale GNU

    -

    Les licences de la plupart des logiciels sont -con�ues pour vous enlever toute liberté de les partager et de les -modifier.

    -

    A contrario, la Licence Publique Générale est destinée à garantir -votre liberté de partager et de modifier les logiciels libres, -et à assurer que ces logiciels soient libres pour tous leurs -utilisateurs.

    -

    La présente Licence Publique Générale s'applique à la -plupart des logiciels de la Free Software Foundation, ainsi -qu'à tout autre programme pour lequel ses auteurs s'engagent à -l'utiliser.

    -

    (Certains autres logiciels de la Free Software Foundation -sont couverts par la GNU Lesser General Public License à la place.)

    -

    Vous pouvez aussi l'appliquer aux programmes qui sont les v�tres.

    -

    Quand nous parlons de logiciels libres, nous parlons de -liberté, non de prix.

    -

    Nos licences publiques générales sont con�ues pour vous donner -l'assurance d'�tre libres de distribuer des copies des -logiciels libres (et de facturer ce service, si vous le -souhaitez), de recevoir le code source ou de pouvoir -l'obtenir si vous le souhaitez, de pouvoir modifier les -logiciels ou en utiliser des éléments dans de nouveaux -programmes libres et de savoir que vous pouvez le -faire.

    -

    Pour protéger vos droits, il nous est nécessaire d'imposer -des limitations qui interdisent à quiconque de vous refuser -ces droits ou de vous demander d'y renoncer.

    -

    Certaines responsabilités vous incombent en raison de ces -limitations si vous distribuez des copies de ces logiciels, ou -si vous les modifiez.

    -

    Par exemple, si vous distribuez des copies d'un tel -programme, à titre gratuit ou contre une rémunération, vous devez -accorder aux destinataires tous les droits dont vous disposez. -

    -

    Vous devez vous assurer qu'eux aussi re�oivent ou puissent -disposer du code source.

    -

    Et vous devez leur montrer les présentes conditions afin -qu'ils aient connaissance de leurs droits.

    -

    Nous protégeons vos droits en deux étapes : (1) nous sommes -titulaires des droits d'auteur du logiciel, et -(2) nous vous delivrons cette licence, qui vous donne -l'autorisation légale de copier, distribuer et/ou modifier -le logiciel.

    -

    En outre, pour la protection de chaque auteur ainsi que la n�tre, -nous voulons nous assurer que chacun comprenne que ce logiciel libre ne fait l'objet -d'aucune garantie.

    -

    Si le logiciel est modifié par quelqu'un d'autre puis -transmis à des tiers, nous voulons que les destinataires -soient mis au courant que ce qu'ils ont re�u n'est pas le logiciel d'origine, de sorte -que tout problème introduit par d'autres ne puisse entacher -la réputation de -l'auteur originel.

    -

    En définitive, un programme libre restera à la merci des -brevets de logiciels.

    -

    Nous souhaitons éviter le risque que les redistributeurs -d'un programme libre fassent des demandes individuelles de -licence de brevet, ceci ayant pour effet de rendre le programme -propriétaire. -

    -

    Pour éviter cela, nous établissons clairement que toute licence de brevet -doit �tre concédée de fa�on a ce que l'usage en soit libre pour tous -ou bien qu'aucune licence ne soit concédée.

    -

    Les termes exacts et les conditions de copie, distribution et -modification sont les suivants:

    -

    Conditions de copie, distribution -et modification de la Licence Publique Générale GNU.

    -

    0. La présente Licence s'applique à tout programme -ou tout autre ouvrage contenant un avis, apposé par le titulaire des -droits d'auteur, stipulant qu'il peut �tre distribué au titre -des conditions de la présente Licence Publique -Générale.

    -

    Ci-après, le "Programme" désigne l'un quelconque de ces -programmes ou ouvrages, et un "ouvrage fondé sur le Programme" -désigne soit le Programme, soit un ouvrage qui en dérive au -titre des lois sur le droit d'auteur: en d'autres termes, -un ouvrage contenant le Programme ou une partie de -ce dernier, soit à l'identique, soit avec des modifications et/ou -traduit dans un autre langage.

    -

    (Ci-après, le terme "modification" implique, sans s'y réduire, le terme traduction)

    -

    Chaque concessionaire sera désigné par "vous".

    -

    Les activités autres que la copie, la distribution et -la modification ne sont pas couvertes par la présente Licence -; elles sont hors de son champ d'application.

    -

    L'opération consistant à exécuter le Programme n'est soumise à aucune limitation -et les sorties du programme ne sont couvertes que si leur -contenu constitue un ouvrage fondé sur le Programme -(indépendamment du fait qu'il ait été réalisé par l'exécution -du Programme).

    -

    La validité de ce qui précède dépend de ce que fait le -Programme.

    -

    1. Vous pouvez copier et distribuer des copies à -l'identique du code source du Programme tel que vous l'avez -re�u, sur n'importe quel support, du moment que vous apposiez -sur chaque copie, de manière ad hoc et parfaitement -visible, l'avis de droit d'auteur adéquat et -une exonération de garantie ; que vous gardiez intacts tous les -avis faisant référence à la présente Licence et à l'absence de -toute garantie ; et que vous fournissiez à tout destinataire du -Programme autre que vous m�me un exemplaire de la présente -Licence en m�me temps que le Programme.

    -

    Vous pouvez faire payer l'acte physique de -transmission d'une copie, et vous pouvez, à votre discrétion, -proposer une garantie contre rémunération.

    -

    2. Vous pouvez modifier votre copie ou des copies du Programme -ou n'importe quelle partie de celui-ci, créant ainsi un ouvrage -fondé sur le Programme, et copier et distribuer de telles modifications ou ouvrage selon les -termes de l'Article 1 ci-dessus, à condition de vous conformer également -à chacune des obligations suivantes:

    -

    a) Vous devez munir les fichiers modifiés d'avis bien visibles -stipulants que vous avez modifié ces -fichiers, ainsi que la date de chaque modification;

    -

    b) Vous devez prendre les dispositions nécessaires pour que -tout ouvrage -que vous distribuez ou publiez, et qui, en totalité ou en partie, -contient ou est fondé sur le Programme - ou une partie -quelconque de ce dernier - soit concédé comme un tout, -à titre gratuit, à n'importe quel tiers, au titre des conditions -de la présente Licence.

    -

    c) Si le programme modifié lit habituellement des instructions -de fa�on interactive lorsqu'on l'exécute, vous devez, -quand il commence son exécution pour ladite -utilisation interactive de la manière la plus usuelle, faire -en sorte qu'il imprime ou affiche une annonce -comprenant un avis de droit d'auteur ad hoc, et un avis -stipulant qu'il n'y a pas de garantie (ou bien indiquant que -c'est vous qui fournissez la garantie), et que -les utilisateurs peuvent redistribuer le programme en respectant -les présentes obligations, et expliquant à l'utilisateur comment -voir une copie de la présente Licence.

    -

    (Exception : si le Programme est lui-m�me interactif -mais n'imprime pas habituellement une telle annonce, votre -ouvrage fondé sur le Programme n'est pas obligé -d'imprimer une annonce).

    -

    Ces obligations s'appliquent à l'ouvrage modifié -pris comme un tout. -

    -

    Si des éléments identifiables -de cet ouvrage ne sont pas fondées sur le Programme et peuvent -raisonnablement �tre considérées comme des ouvrages indépendants -distincts en eux m�mes, alors la présente Licence et -ses conditions ne -s'appliquent pas à ces éléments lorsque vous les distribuez -en tant qu'ouvrages distincts.

    -

    -Mais lorsque vous distribuez ces m�mes éléments comme partie -d'un tout, lequel constitue un ouvrage fondé sur le Programme, -la distribution de ce tout doit �tre soumise aux conditions de -la présente Licence, et les autorisations qu'elle octroie aux -autres concessionaires s'étendent à l'ensemble de l'ouvrage et -par conséquent à chaque et toute partie indifférement de qui -l'a écrite. -

    -

    Par conséquent, l'objet du présent article n'est pas de revendiquer des droits -ou de contester vos droits sur un ouvrage entièrement écrit par -vous; son objet est plut�t d'exercer le droit de contr�ler -la distribution d'ouvrages dérivés ou d'ouvrages collectifs fondés -sur le Programme. -

    -

    -De plus, la simple proximité du Programme avec un autre -ouvrage qui n'est pas fondé sur le Programme (ou un ouvrage -fondé sur le Programme) sur une partition d'un espace de -stockage ou un support de distribution ne place pas cet autre -ouvrage dans le champ d'application de la présente Licence. -

    -

    3. Vous pouvez copier et distribuer le Programme (ou un -ouvrage fondé sur lui, selon l'Article 2) sous forme de code -objet ou d'exécutable, selon les termes des Articles 1 et 2 -ci-dessus, à condition que vous accomplissiez l'un des points -suivants :

    -

    a) L'accompagner de l'intégralité du code source correspondant, -sous une forme lisible par un ordinateur, lequel doit �tre distribué -au titre -des termes des Articles 1 et 2 ci-dessus, sur un support -habituellement utilisé pour l'échange de logiciels; ou,

    -

    b) L'accompagner d'une proposition écrite, valable pendant -au moins trois ans, de fournir à tout tiers, à un tarif qui -ne soit pas supérieur à ce que vous co�te l'acte physique de -réaliser une distribution source, une copie intégrale du code -source correspondant sous une forme lisible par un -ordinateur, qui sera distribuée au titre des termes des -Articles 1 et 2 ci-dessus, sur un support habituellement -utilisé pour l'échange de logiciels; ou, -

    -

    c) L'accompagner des informations re�ues par vous concernant la proposition de distribution du code source correspondant. (Cette -solution n'est autorisée que dans le cas d'une distribution non-commerciale -et seulement si vous avez re�u le programme sous forme de code objet ou -d'éxécutable accompagné d'une telle proposition - en conformité avec le -sous-Article b ci-dessus.) -

    -

    Le code source d'un ouvrage désigne la forme favorite pour -travailler à des modifications de cet ouvrage. Pour un -ouvrage exécutable, le code source intégral désigne la -totalité du code source de la totalité des modules qu'il -contient, ainsi que les éventuels fichiers de définition des -interfaces qui y sont associés, ainsi que les scripts utilisés -pour contr�ler la compilation et l'installation de -l'exécutable. Cependant, par exception spéciale, le code -source distribué n'est pas censé inclure quoi que ce soit de -normalement distribué (que ce soit sous forme source ou -binaire) avec les composants principaux (compilateur, noyau, -et autre) du système d'exploitation sur lequel l'exécutable -tourne, à moins que ce composant lui-m�me n'accompagne -l'exécutable. -

    -

    -Si distribuer un exécutable ou un code objet consiste à -offrir un accès permettant leur copie depuis un -endroit particulier, alors l'offre d'un accès équivalent pour -copier le code source depuis le m�me endroit compte comme une -distribution du code source - m�me si les tiers ne sont pas -contraints de copier le source en m�me temps que le code -objet. -

    -

    4. Vous ne pouvez copier, modifier, concéder en sous-licence, ou distribuer -le Programme, sauf tel qu'expressément prévu par la présente Licence. -Toute tentative de copier, modifier, concéder en sous-licence, ou -distribuer le Programme d'une autre manière est réputée non valable, et met -immédiatement fin à vos droits au titre de la présente Licence. -Toutefois, les tiers ayant re�u de vous des copies, ou des droits, -au titre de la présente Licence ne verront pas leurs autorisations résiliées -aussi longtemps que ledits tiers se conforment pleinement à elle. -

    -

    5. Vous n'�tes pas obligé d'accepter la présente Licence étant donné que vous ne -l'avez pas signée. Cependant, rien d'autre -ne vous accorde l'autorisation de modifier ou -distribuer le Programme ou les ouvrages fondés sur lui. Ces actions sont -interdites par la loi si vous n'acceptez pas la présente Licence. -En conséquence, en modifiant ou -distribuant le Programme (ou un ouvrage quelconque fondé sur -le Programme), vous signifiez votre acceptation de la présente Licence en le faisant, -et de toutes ses conditions concernant la copie, la -distribution ou la modification du Programme ou d'ouvrages fondés -sur lui.

    -

    -6. Chaque fois que vous redistribuez le Programme (ou n'importe quel -ouvrage fondé sur le Programme), une licence est automatiquement -concédée au destinataire par le concédant originel de la licence, -l'autorisant à -copier, distribuer ou modifier le Programme, sous réserve -des présentes conditions. Vous ne pouvez imposer -une quelconque limitation supplémentaire à l'exercice des -droits octroyés au titre des présentes par le destinataire. Vous -n'avez pas la responsabilité d'imposer le respect de -la présente Licence à des tiers.

    -

    -7. Si, conséquement à une décision de justice ou l'allégation -d'une transgression de brevet ou pour toute autre raison (non limitée à un -probleme de brevet), des obligations vous sont imposées (que ce soit par jugement, -conciliation ou autre) qui contredisent les conditions de la présente Licence, elles -ne vous excusent pas des conditions de la présente Licence. Si vous ne pouvez -distribuer de manière à satisfaire simultanément vos obligations au titre -de la présente Licence et toute autre obligation pertinente, alors il en découle que vous ne pouvez pas du tout distribuer le Programme. Par exemple, -si une licence de brevet ne permettait pas une redistribution sans redevance du -Programme par tous ceux qui re�oivent une copie directement ou indirectement -par votre intermédiaire, alors la seule fa�on pour vous de satisfaire à la -fois à la licence du brevet et à la présente Licence serait de vous abstenir -totalement de toute distribution du Programme. -

    -

    Si une partie quelconque de cet article est tenue pour -nulle ou inopposable dans une circonstance particulière -quelconque, l'intention est que le reste de l'article -s'applique. La totalité de la section s'appliquera dans toutes les -autres circonstances.

    -

    Cet article n'a pas pour but de vous induire à transgresser un -quelconque brevet ou d'autres revendications à un droit de propriété ou -à contester la validité de la moindre de ces revendications ; cet article a pour -seul objectif de protéger l'intégrité du système de distribution -du logiciel libre, qui est mis en oeuvre par la pratique des licenses -publiques. De nombreuses personnes ont fait de généreuses contributions -au large spectre de logiciels distribués par ce système en se fiant à -l'application cohérente de ce système ; il appartient à chaque auteur/donateur -de décider si il ou elle veut distribuer du logiciel par l'intermédiaire -d'un quelconque autre système et un concessionaire ne peut imposer ce -choix. -

    -

    Cet article a pour but de rendre totalement limpide ce que l'on pense -�tre une conséquence du reste de la présente Licence.

    -

    8. Si la distribution et/ou l'utilisation du Programme est limitée -dans certains pays que ce soit par des brevets ou par des interfaces soumises -au droit d'auteur, le titulaire originel des droits d'auteur -qui décide de couvrir le Programme par la présente Licence peut ajouter -une limitation géographique de distribution explicite qui exclue ces pays afin -que la distribution soit permise seulement dans ou entre les pays qui ne sont -pas ainsi exclus. Dans ce cas, la présente Licence incorpore la limitation -comme si elle était écrite dans le corps de la présente Licence. -

    -

    9. La Free Software Foundation peut, de temps à autre, publier des -versions révisées et/ou nouvelles de la Licence Publique Générale. De telles -nouvelles versions seront similaires à la présente version dans l'esprit -mais pourront différer dans le détail pour prendre en compte -de nouvelles problématiques ou inquiétudes. -

    -

    Chaque version possède un numéro de version la distinguant. Si le Programme -précise le numéro de version de la présente Licence qui s'y applique -et "une version ultérieure quelconque", vous avez le choix -de suivre les -conditions de -la présente version ou de toute autre version ultérieure publiée par la -Free Software Foundation. Si le Programme ne spécifie aucun numéro de -version de la présente Licence, vous pouvez choisir une version quelconque -publiée par la Free Software Foundation à quelque moment que ce soit.

    -

    10. Si vous souhaitez incorporer des parties du Programme -dans d'autres programmes libres dont les conditions de -distribution sont différentes, écrivez à l'auteur pour lui en demander -l'autorisation. Pour les logiciels dont la Free Software Foundation est -titulaire des droits d'auteur, écrivez à la Free Software Foundation ; -nous faisons parfois des exceptions dans ce sens. Notre décision sera guidée -par le double objectif de préserver le statut libre de tous les dérivés de nos -logiciels libres et de promouvoir le partage et la réutilisation des logiciels -en général. -

    -

    ABSENCE DE GARANTIE

    -

    11. COMME LA LICENCE DU PROGRAMME EST CONCEDEE A TITRE GRATUIT, -AUCUNE GARANTIE NE S'APPLIQUE AU PROGRAMME, DANS LES LIMITES -AUTORISEES PAR LA LOI APPLICABLE. SAUF MENTION CONTRAIRE ECRITE, -LES TITULAIRES DU DROIT D'AUTEUR ET/OU LES AUTRES PARTIES FOURNISSENT -LE PROGRAMME "EN L'ETAT", SANS AUCUNE GARANTIE DE -QUELQUE NATURE QUE CE SOIT, EXPRESSE OU IMPLICITE, Y COMPRIS, MAIS -SANS Y ETRE LIMITE, LES GARANTIES IMPLICITES DE COMMERCIABILITE ET -DE LA CONFORMITE A UNE UTILISATION PARTICULIERE. VOUS -ASSUMEZ LA TOTALITE DES RISQUES LIES A LA QUALITE ET AUX PERFORMANCES DU PROGRAMME. -SI LE PROGRAMME SE REVELAIT DEFECTUEUX, LE COUT DE L'ENTRETIEN, -DES REPARATIONS OU DES CORRECTIONS NECESSAIRES -VOUS INCOMBENT INTEGRALEMENT.

    -

    12. EN AUCUN CAS, SAUF LORSQUE LA LOI APPLICABLE OU UNE CONVENTION ECRITE L'EXIGE, UN TITULAIRE DE DROIT D'AUTEUR QUEL QU'IL SOIT, OU TOUTE PARTIE QUI POURRAIT MODIFIER ET/OU REDISTRIBUER LE PROGRAMME COMME PERMIS CI-DESSUS, NE POURRAIT ETRE TENU POUR RESPONSABLE A VOTRE EGARD DES DOMMAGES, INCLUANT LES DOMMAGES GENERIQUES, SPECIFIQUES, SECONDAIRES OU CONSECUTIFS, RESULTANT DE L'UTILISATION OU DE L'INCAPACITE D'UTILISER LE PROGRAMME (Y COMPRIS, MAIS SANS Y ETRE LIMITE, LA PERTE DE DONNEES, OU LE FAIT QUE DES DONNEES SOIENT RENDUES IMPRECISES, OU LES PERTES EPROUVEES PAR VOUS OU PAR DES TIERS, OU LE FAIT QUE LE PROGRAMME ECHOUE A INTEROPERER AVEC UN AUTRE PROGRAMME QUEL QU'IL SOIT) MEME SI LE DIT TITULAIRE DU DROIT D'AUTEUR OU LE PARTIE CONCERNEE A ETE AVERTI DE L'EVENTUALITE DE TELS DOMMAGES. -

    -

    FIN DES CONDITIONS

    -

    Comment appliquer ces conditions à vos nouveaux programmes

    -

    Si vous développez un nouveau programme, et si vous voulez qu'il soit de la plus grande utilité possible pour le public, le meilleur moyen d'y parvenir est d'en faire un logiciel libre que chacun peut redistribuer et modifier au titre des présentes conditions.

    -

    Pour ce faire, munissez le programme des avis qui suivent. -Le plus s�r est de les ajouter au début de chaque fichier source -pour véhiculer le plus efficacement possible l'absence -de toute garantie; chaque fichier devrait aussi contenir au moins -la ligne "copyright" et une indication de l'endroit où se trouve l'avis -compl�t. -

    -

    [Une ligne donnant le nom du programme et une courte idée de ce qu'il fait.] -

    -

    -Copyright (C) [année] [nom de l'auteur] -

    -

    -Ce programme est un logiciel libre ; vous pouvez le -redistribuer et/ou le modifier au titre des clauses de la -Licence Publique Générale GNU, telle que publiée par la Free -Software Foundation ; soit la version 2 de la Licence, ou (à -votre discrétion) une version ultérieure quelconque. -

    -

    -Ce programme est distribué dans l'espoir qu'il sera utile, -mais SANS AUCUNE GARANTIE ; sans m�me une garantie implicite de -COMMERCIABILITE ou DE CONFORMITE A UNE UTILISATION -PARTICULIERE. Voir la Licence Publique -Générale GNU pour plus de détails. -

    -

    -Vous devriez avoir re�u un exemplaire de la Licence Publique -Générale GNU avec ce programme ; si ce n'est pas le cas, -écrivez à la Free Software Foundation Inc., 51 Franklin -Street, Fifth Floor, Boston, MA 02110-1301, USA.

    -

    Ajoutez aussi des informations sur la manière de vous contacter -par courrier électronique et courrier postal.

    -

    Si le programme est interactif, faites en sorte qu'il -affiche un court avis tel que celui-ci lorsqu'il démarre en -mode interactif : -

    -

    Gnomovision version 69, Copyright (C) année nom de l'auteur -Gnomovision n'est accompagné d'ABSOLUMENT AUCUNE GARANTIE ; pour plus de -détails tapez "show w". Ceci est un logiciel libre et vous �tes -invité à le redistribuer en respectant certaines obligations ; pour plus -de détails tapez "show c".

    -

    Les instructions hypothétiques "show w" et "show c" sont supposées montrer -les parties ad hoc de la Licence Publique Générale. Bien -entendu, les instructions que vous utilisez peuvent porter d'autres -noms que "show w" et "show c" ; elles peuvent m�me �tre des -clics de souris ou des éléments d'un menu ou tout ce qui convient à -votre programme.

    -

    Vous devriez aussi obtenir de votre employeur (si vous -travaillez en tant que développeur) ou de votre école, si c'est -le cas, qu'il (ou elle) signe une "renonciation aux droits -d'auteur" concernant le programme, si nécessaire. Voici un -exemple (changez les noms) : -

    -

    Yoyodyne, Inc., déclare par la présente renoncer à toute prétention -sur les droits d'auteur du programme "Gnomovision" (qui fait des -avances aux compilateurs) écrit par James Hacker. -

    -

    -[signature de Ty Coon], 1er avril 1989 -

    -

    -Ty Coon, President du Vice

    -

    La présente Licence Publique Générale n'autorise pas l'incorporation de votre -programme dans des programmes -propriétaires. Si votre programme est une bibliothèque de -sous-programmes, vous pouvez considérer plus utile -d'autoriser l'édition de liens d'applications propriétaires avec -la bibliothèque. Si c'est ce que vous voulez faire, utilisez la -GNU Lesser General Public License au lieu de la présente Licence. -

    - - \ No newline at end of file +

    Licence Publique Générale GNU

    +

    + Les licences de la plupart des logiciels sont con�ues pour vous enlever + toute liberté de les partager et de les modifier. +

    +

    + A contrario, la Licence Publique Générale est + destinée à garantir votre liberté de partager et de + modifier les logiciels libres, et à assurer que ces logiciels + soient libres pour tous leurs utilisateurs. +

    +

    + La présente Licence Publique Générale s'applique + à la plupart des logiciels de la Free Software Foundation, ainsi + qu'à tout autre programme pour lequel ses auteurs s'engagent + à l'utiliser. +

    +

    + (Certains autres logiciels de la Free Software Foundation sont couverts + par la GNU Lesser General Public License à la place.) +

    +

    Vous pouvez aussi l'appliquer aux programmes qui sont les v�tres.

    +

    + Quand nous parlons de logiciels libres, nous parlons de liberté, + non de prix. +

    +

    + Nos licences publiques générales sont con�ues pour vous + donner l'assurance d'�tre libres de distribuer des copies des logiciels + libres (et de facturer ce service, si vous le souhaitez), de recevoir le + code source ou de pouvoir l'obtenir si vous le souhaitez, de pouvoir + modifier les logiciels ou en utiliser des éléments dans de + nouveaux programmes libres et de savoir que vous pouvez le faire. +

    +

    + Pour protéger vos droits, il nous est nécessaire d'imposer + des limitations qui interdisent à quiconque de vous refuser ces + droits ou de vous demander d'y renoncer. +

    +

    + Certaines responsabilités vous incombent en raison de ces + limitations si vous distribuez des copies de ces logiciels, ou si vous les + modifiez. +

    +

    + Par exemple, si vous distribuez des copies d'un tel programme, à + titre gratuit ou contre une rémunération, vous devez + accorder aux destinataires tous les droits dont vous disposez. +

    +

    + Vous devez vous assurer qu'eux aussi re�oivent ou puissent disposer du + code source. +

    +

    + Et vous devez leur montrer les présentes conditions afin qu'ils + aient connaissance de leurs droits. +

    +

    + Nous protégeons vos droits en deux étapes : (1) nous sommes + titulaires des droits d'auteur du logiciel, et (2) nous vous delivrons + cette licence, qui vous donne l'autorisation légale de copier, + distribuer et/ou modifier le logiciel. +

    +

    + En outre, pour la protection de chaque auteur ainsi que la n�tre, nous + voulons nous assurer que chacun comprenne que ce logiciel libre ne fait + l'objet d'aucune garantie. +

    +

    + Si le logiciel est modifié par quelqu'un d'autre puis transmis + à des tiers, nous voulons que les destinataires soient mis au + courant que ce qu'ils ont re�u n'est pas le logiciel d'origine, de sorte + que tout problème introduit par d'autres ne puisse entacher la + réputation de l'auteur originel. +

    +

    + En définitive, un programme libre restera à la merci des + brevets de logiciels. +

    +

    + Nous souhaitons éviter le risque que les redistributeurs d'un + programme libre fassent des demandes individuelles de licence de brevet, + ceci ayant pour effet de rendre le programme propriétaire. +

    +

    + Pour éviter cela, nous établissons clairement que toute + licence de brevet doit �tre concédée de fa�on a ce que + l'usage en soit libre pour tous ou bien qu'aucune licence ne soit + concédée. +

    +

    + Les termes exacts et les conditions de copie, distribution et modification + sont les suivants: +

    +

    + Conditions de copie, distribution et modification de la Licence Publique + Générale GNU. +

    +

    + 0. La présente Licence s'applique à tout programme ou tout + autre ouvrage contenant un avis, apposé par le titulaire des droits + d'auteur, stipulant qu'il peut �tre distribué au titre des + conditions de la présente Licence Publique Générale. +

    +

    + Ci-après, le "Programme" désigne l'un quelconque de ces + programmes ou ouvrages, et un "ouvrage fondé sur le Programme" + désigne soit le Programme, soit un ouvrage qui en dérive au + titre des lois sur le droit d'auteur: en d'autres termes, un ouvrage + contenant le Programme ou une partie de ce dernier, soit à + l'identique, soit avec des modifications et/ou traduit dans un autre + langage. +

    +

    + (Ci-après, le terme "modification" implique, sans s'y + réduire, le terme traduction) +

    +

    Chaque concessionaire sera désigné par "vous".

    +

    + Les activités autres que la copie, la distribution et la + modification ne sont pas couvertes par la présente Licence ; elles + sont hors de son champ d'application. +

    +

    + L'opération consistant à exécuter le Programme n'est + soumise à aucune limitation et les sorties du programme ne sont + couvertes que si leur contenu constitue un ouvrage fondé sur le + Programme (indépendamment du fait qu'il ait été + réalisé par l'exécution du Programme). +

    +

    + La validité de ce qui précède dépend de ce que + fait le Programme. +

    +

    + 1. Vous pouvez copier et distribuer des copies à l'identique du + code source du Programme tel que vous l'avez re�u, sur n'importe quel + support, du moment que vous apposiez sur chaque copie, de manière + ad hoc et parfaitement visible, l'avis de droit d'auteur adéquat et + une exonération de garantie ; que vous gardiez intacts tous les + avis faisant référence à la présente Licence + et à l'absence de toute garantie ; et que vous fournissiez à + tout destinataire du Programme autre que vous m�me un exemplaire de la + présente Licence en m�me temps que le Programme. +

    +

    + Vous pouvez faire payer l'acte physique de transmission d'une copie, et + vous pouvez, à votre discrétion, proposer une garantie + contre rémunération. +

    +

    + 2. Vous pouvez modifier votre copie ou des copies du Programme ou + n'importe quelle partie de celui-ci, créant ainsi un ouvrage + fondé sur le Programme, et copier et distribuer de telles + modifications ou ouvrage selon les termes de l'Article 1 ci-dessus, + à condition de vous conformer également à chacune des + obligations suivantes: +

    +

    + a) Vous devez munir les fichiers modifiés d'avis bien visibles + stipulants que vous avez modifié ces fichiers, ainsi que la date de + chaque modification; +

    +

    + b) Vous devez prendre les dispositions nécessaires pour que tout + ouvrage que vous distribuez ou publiez, et qui, en totalité ou en + partie, contient ou est fondé sur le Programme - ou une partie + quelconque de ce dernier - soit concédé comme un tout, + à titre gratuit, à n'importe quel tiers, au titre des + conditions de la présente Licence. +

    +

    + c) Si le programme modifié lit habituellement des instructions de + fa�on interactive lorsqu'on l'exécute, vous devez, quand il + commence son exécution pour ladite utilisation interactive de la + manière la plus usuelle, faire en sorte qu'il imprime ou affiche + une annonce comprenant un avis de droit d'auteur ad hoc, et un avis + stipulant qu'il n'y a pas de garantie (ou bien indiquant que c'est vous + qui fournissez la garantie), et que les utilisateurs peuvent redistribuer + le programme en respectant les présentes obligations, et expliquant + à l'utilisateur comment voir une copie de la présente + Licence. +

    +

    + (Exception : si le Programme est lui-m�me interactif mais n'imprime pas + habituellement une telle annonce, votre ouvrage fondé sur le + Programme n'est pas obligé d'imprimer une annonce). +

    +

    + Ces obligations s'appliquent à l'ouvrage modifié pris comme + un tout. +

    +

    + Si des éléments identifiables de cet ouvrage ne sont pas + fondées sur le Programme et peuvent raisonnablement �tre + considérées comme des ouvrages indépendants distincts + en eux m�mes, alors la présente Licence et ses conditions ne + s'appliquent pas à ces éléments lorsque vous les + distribuez en tant qu'ouvrages distincts. +

    +

    + Mais lorsque vous distribuez ces m�mes éléments comme partie + d'un tout, lequel constitue un ouvrage fondé sur le Programme, la + distribution de ce tout doit �tre soumise aux conditions de la + présente Licence, et les autorisations qu'elle octroie aux autres + concessionaires s'étendent à l'ensemble de l'ouvrage et par + conséquent à chaque et toute partie indifférement de + qui l'a écrite. +

    +

    + Par conséquent, l'objet du présent article n'est pas de + revendiquer des droits ou de contester vos droits sur un ouvrage + entièrement écrit par vous; son objet est plut�t d'exercer + le droit de contr�ler la distribution d'ouvrages dérivés ou + d'ouvrages collectifs fondés sur le Programme. +

    +

    + De plus, la simple proximité du Programme avec un autre ouvrage qui + n'est pas fondé sur le Programme (ou un ouvrage fondé sur le + Programme) sur une partition d'un espace de stockage ou un support de + distribution ne place pas cet autre ouvrage dans le champ d'application de + la présente Licence. +

    +

    + 3. Vous pouvez copier et distribuer le Programme (ou un ouvrage + fondé sur lui, selon l'Article 2) sous forme de code objet ou + d'exécutable, selon les termes des Articles 1 et 2 ci-dessus, + à condition que vous accomplissiez l'un des points suivants : +

    +

    + a) L'accompagner de l'intégralité du code source + correspondant, sous une forme lisible par un ordinateur, lequel doit �tre + distribué au titre des termes des Articles 1 et 2 ci-dessus, sur un + support habituellement utilisé pour l'échange de logiciels; + ou, +

    +

    + b) L'accompagner d'une proposition écrite, valable pendant au moins + trois ans, de fournir à tout tiers, à un tarif qui ne soit + pas supérieur à ce que vous co�te l'acte physique de + réaliser une distribution source, une copie intégrale du + code source correspondant sous une forme lisible par un ordinateur, qui + sera distribuée au titre des termes des Articles 1 et 2 ci-dessus, + sur un support habituellement utilisé pour l'échange de + logiciels; ou, +

    +

    + c) L'accompagner des informations re�ues par vous concernant la + proposition de distribution du code source correspondant. (Cette solution + n'est autorisée que dans le cas d'une distribution non-commerciale + et seulement si vous avez re�u le programme sous forme de code objet ou + d'éxécutable accompagné d'une telle proposition - en + conformité avec le sous-Article b ci-dessus.) +

    +

    + Le code source d'un ouvrage désigne la forme favorite pour + travailler à des modifications de cet ouvrage. Pour un ouvrage + exécutable, le code source intégral désigne la + totalité du code source de la totalité des modules qu'il + contient, ainsi que les éventuels fichiers de définition des + interfaces qui y sont associés, ainsi que les scripts + utilisés pour contr�ler la compilation et l'installation de + l'exécutable. Cependant, par exception spéciale, le code + source distribué n'est pas censé inclure quoi que ce soit de + normalement distribué (que ce soit sous forme source ou binaire) + avec les composants principaux (compilateur, noyau, et autre) du + système d'exploitation sur lequel l'exécutable tourne, + à moins que ce composant lui-m�me n'accompagne l'exécutable. +

    +

    + Si distribuer un exécutable ou un code objet consiste à + offrir un accès permettant leur copie depuis un endroit + particulier, alors l'offre d'un accès équivalent pour copier + le code source depuis le m�me endroit compte comme une distribution du + code source - m�me si les tiers ne sont pas contraints de copier le source + en m�me temps que le code objet. +

    +

    + 4. Vous ne pouvez copier, modifier, concéder en sous-licence, ou + distribuer le Programme, sauf tel qu'expressément prévu par + la présente Licence. Toute tentative de copier, modifier, + concéder en sous-licence, ou distribuer le Programme d'une autre + manière est réputée non valable, et met + immédiatement fin à vos droits au titre de la + présente Licence. Toutefois, les tiers ayant re�u de vous des + copies, ou des droits, au titre de la présente Licence ne verront + pas leurs autorisations résiliées aussi longtemps que ledits + tiers se conforment pleinement à elle. +

    +

    + 5. Vous n'�tes pas obligé d'accepter la présente Licence + étant donné que vous ne l'avez pas signée. Cependant, + rien d'autre ne vous accorde l'autorisation de modifier ou distribuer le + Programme ou les ouvrages fondés sur lui. Ces actions sont + interdites par la loi si vous n'acceptez pas la présente Licence. + En conséquence, en modifiant ou distribuant le Programme (ou un + ouvrage quelconque fondé sur le Programme), vous signifiez votre + acceptation de la présente Licence en le faisant, et de toutes ses + conditions concernant la copie, la distribution ou la modification du + Programme ou d'ouvrages fondés sur lui. +

    +

    + 6. Chaque fois que vous redistribuez le Programme (ou n'importe quel + ouvrage fondé sur le Programme), une licence est automatiquement + concédée au destinataire par le concédant originel de + la licence, l'autorisant à copier, distribuer ou modifier le + Programme, sous réserve des présentes conditions. Vous ne + pouvez imposer une quelconque limitation supplémentaire à + l'exercice des droits octroyés au titre des présentes par le + destinataire. Vous n'avez pas la responsabilité d'imposer le + respect de la présente Licence à des tiers. +

    +

    + 7. Si, conséquement à une décision de justice ou + l'allégation d'une transgression de brevet ou pour toute autre + raison (non limitée à un probleme de brevet), des + obligations vous sont imposées (que ce soit par jugement, + conciliation ou autre) qui contredisent les conditions de la + présente Licence, elles ne vous excusent pas des conditions de la + présente Licence. Si vous ne pouvez distribuer de manière + à satisfaire simultanément vos obligations au titre de la + présente Licence et toute autre obligation pertinente, alors il en + découle que vous ne pouvez pas du tout distribuer le Programme. Par + exemple, si une licence de brevet ne permettait pas une redistribution + sans redevance du Programme par tous ceux qui re�oivent une copie + directement ou indirectement par votre intermédiaire, alors la + seule fa�on pour vous de satisfaire à la fois à la licence + du brevet et à la présente Licence serait de vous abstenir + totalement de toute distribution du Programme. +

    +

    + Si une partie quelconque de cet article est tenue pour nulle ou + inopposable dans une circonstance particulière quelconque, + l'intention est que le reste de l'article s'applique. La totalité + de la section s'appliquera dans toutes les autres circonstances. +

    +

    + Cet article n'a pas pour but de vous induire à transgresser un + quelconque brevet ou d'autres revendications à un droit de + propriété ou à contester la validité de la + moindre de ces revendications ; cet article a pour seul objectif de + protéger l'intégrité du système de + distribution du logiciel libre, qui est mis en oeuvre par la pratique des + licenses publiques. De nombreuses personnes ont fait de + généreuses contributions au large spectre de logiciels + distribués par ce système en se fiant à l'application + cohérente de ce système ; il appartient à chaque + auteur/donateur de décider si il ou elle veut distribuer du + logiciel par l'intermédiaire d'un quelconque autre système + et un concessionaire ne peut imposer ce choix. +

    +

    + Cet article a pour but de rendre totalement limpide ce que l'on pense �tre + une conséquence du reste de la présente Licence. +

    +

    + 8. Si la distribution et/ou l'utilisation du Programme est limitée + dans certains pays que ce soit par des brevets ou par des interfaces + soumises au droit d'auteur, le titulaire originel des droits d'auteur qui + décide de couvrir le Programme par la présente Licence peut + ajouter une limitation géographique de distribution explicite qui + exclue ces pays afin que la distribution soit permise seulement dans ou + entre les pays qui ne sont pas ainsi exclus. Dans ce cas, la + présente Licence incorpore la limitation comme si elle était + écrite dans le corps de la présente Licence. +

    +

    + 9. La Free Software Foundation peut, de temps à autre, publier des + versions révisées et/ou nouvelles de la Licence Publique + Générale. De telles nouvelles versions seront similaires + à la présente version dans l'esprit mais pourront + différer dans le détail pour prendre en compte de nouvelles + problématiques ou inquiétudes. +

    +

    + Chaque version possède un numéro de version la distinguant. + Si le Programme précise le numéro de version de la + présente Licence qui s'y applique et "une version ultérieure + quelconque", vous avez le choix de suivre les conditions de la + présente version ou de toute autre version ultérieure + publiée par la Free Software Foundation. Si le Programme ne + spécifie aucun numéro de version de la présente + Licence, vous pouvez choisir une version quelconque publiée par la + Free Software Foundation à quelque moment que ce soit. +

    +

    + 10. Si vous souhaitez incorporer des parties du Programme dans d'autres + programmes libres dont les conditions de distribution sont + différentes, écrivez à l'auteur pour lui en demander + l'autorisation. Pour les logiciels dont la Free Software Foundation est + titulaire des droits d'auteur, écrivez à la Free Software + Foundation ; nous faisons parfois des exceptions dans ce sens. Notre + décision sera guidée par le double objectif de + préserver le statut libre de tous les dérivés de nos + logiciels libres et de promouvoir le partage et la réutilisation + des logiciels en général. +

    +

    ABSENCE DE GARANTIE

    +

    + 11. COMME LA LICENCE DU PROGRAMME EST CONCEDEE A TITRE GRATUIT, AUCUNE + GARANTIE NE S'APPLIQUE AU PROGRAMME, DANS LES LIMITES AUTORISEES PAR LA + LOI APPLICABLE. SAUF MENTION CONTRAIRE ECRITE, LES TITULAIRES DU DROIT + D'AUTEUR ET/OU LES AUTRES PARTIES FOURNISSENT LE PROGRAMME "EN L'ETAT", + SANS AUCUNE GARANTIE DE QUELQUE NATURE QUE CE SOIT, EXPRESSE OU IMPLICITE, + Y COMPRIS, MAIS SANS Y ETRE LIMITE, LES GARANTIES IMPLICITES DE + COMMERCIABILITE ET DE LA CONFORMITE A UNE UTILISATION PARTICULIERE. VOUS + ASSUMEZ LA TOTALITE DES RISQUES LIES A LA QUALITE ET AUX PERFORMANCES DU + PROGRAMME. SI LE PROGRAMME SE REVELAIT DEFECTUEUX, LE COUT DE L'ENTRETIEN, + DES REPARATIONS OU DES CORRECTIONS NECESSAIRES VOUS INCOMBENT + INTEGRALEMENT. +

    +

    + 12. EN AUCUN CAS, SAUF LORSQUE LA LOI APPLICABLE OU UNE CONVENTION ECRITE + L'EXIGE, UN TITULAIRE DE DROIT D'AUTEUR QUEL QU'IL SOIT, OU TOUTE PARTIE + QUI POURRAIT MODIFIER ET/OU REDISTRIBUER LE PROGRAMME COMME PERMIS + CI-DESSUS, NE POURRAIT ETRE TENU POUR RESPONSABLE A VOTRE EGARD DES + DOMMAGES, INCLUANT LES DOMMAGES GENERIQUES, SPECIFIQUES, SECONDAIRES OU + CONSECUTIFS, RESULTANT DE L'UTILISATION OU DE L'INCAPACITE D'UTILISER LE + PROGRAMME (Y COMPRIS, MAIS SANS Y ETRE LIMITE, LA PERTE DE DONNEES, OU LE + FAIT QUE DES DONNEES SOIENT RENDUES IMPRECISES, OU LES PERTES EPROUVEES + PAR VOUS OU PAR DES TIERS, OU LE FAIT QUE LE PROGRAMME ECHOUE A + INTEROPERER AVEC UN AUTRE PROGRAMME QUEL QU'IL SOIT) MEME SI LE DIT + TITULAIRE DU DROIT D'AUTEUR OU LE PARTIE CONCERNEE A ETE AVERTI DE + L'EVENTUALITE DE TELS DOMMAGES. +

    +

    FIN DES CONDITIONS

    +

    Comment appliquer ces conditions à vos nouveaux programmes

    +

    + Si vous développez un nouveau programme, et si vous voulez qu'il + soit de la plus grande utilité possible pour le public, le meilleur + moyen d'y parvenir est d'en faire un logiciel libre que chacun peut + redistribuer et modifier au titre des présentes conditions. +

    +

    + Pour ce faire, munissez le programme des avis qui suivent. Le plus s�r est + de les ajouter au début de chaque fichier source pour + véhiculer le plus efficacement possible l'absence de toute + garantie; chaque fichier devrait aussi contenir au moins la ligne + "copyright" et une indication de l'endroit où se trouve l'avis + compl�t. +

    +

    + [Une ligne donnant le nom du programme et une courte idée de ce + qu'il fait.] +

    +

    Copyright (C) [année] [nom de l'auteur]

    +

    + Ce programme est un logiciel libre ; vous pouvez le redistribuer et/ou le + modifier au titre des clauses de la Licence Publique + Générale GNU, telle que publiée par la Free Software + Foundation ; soit la version 2 de la Licence, ou (à votre + discrétion) une version ultérieure quelconque. +

    +

    + Ce programme est distribué dans l'espoir qu'il sera utile, mais + SANS AUCUNE GARANTIE ; sans m�me une garantie implicite de COMMERCIABILITE + ou DE CONFORMITE A UNE UTILISATION PARTICULIERE. Voir la Licence Publique + Générale GNU pour plus de détails. +

    +

    + Vous devriez avoir re�u un exemplaire de la Licence Publique + Générale GNU avec ce programme ; si ce n'est pas le cas, + écrivez à la Free Software Foundation Inc., 51 Franklin + Street, Fifth Floor, Boston, MA 02110-1301, USA. +

    +

    + Ajoutez aussi des informations sur la manière de vous contacter par + courrier électronique et courrier postal. +

    +

    + Si le programme est interactif, faites en sorte qu'il affiche un court + avis tel que celui-ci lorsqu'il démarre en mode interactif : +

    +

    + Gnomovision version 69, Copyright (C) année nom de l'auteur + Gnomovision n'est accompagné d'ABSOLUMENT AUCUNE GARANTIE ; pour + plus de détails tapez "show w". Ceci est un logiciel libre et vous + �tes invité à le redistribuer en respectant certaines + obligations ; pour plus de détails tapez "show c". +

    +

    + Les instructions hypothétiques "show w" et "show c" sont + supposées montrer les parties ad hoc de la Licence Publique + Générale. Bien entendu, les instructions que vous utilisez + peuvent porter d'autres noms que "show w" et "show c" ; elles peuvent m�me + �tre des clics de souris ou des éléments d'un menu ou tout + ce qui convient à votre programme. +

    +

    + Vous devriez aussi obtenir de votre employeur (si vous travaillez en tant + que développeur) ou de votre école, si c'est le cas, qu'il + (ou elle) signe une "renonciation aux droits d'auteur" concernant le + programme, si nécessaire. Voici un exemple (changez les noms) : +

    +

    + Yoyodyne, Inc., déclare par la présente renoncer à + toute prétention sur les droits d'auteur du programme "Gnomovision" + (qui fait des avances aux compilateurs) écrit par James Hacker. +

    +

    [signature de Ty Coon], 1er avril 1989

    +

    Ty Coon, President du Vice

    +

    + La présente Licence Publique Générale n'autorise pas + l'incorporation de votre programme dans des programmes + propriétaires. Si votre programme est une bibliothèque de + sous-programmes, vous pouvez considérer plus utile d'autoriser + l'édition de liens d'applications propriétaires avec la + bibliothèque. Si c'est ce que vous voulez faire, utilisez la GNU + Lesser General Public License au lieu de la présente Licence. +

    + + diff --git a/pandora_console/general/license/pandora_info_it.html b/pandora_console/general/license/pandora_info_it.html index a28c18e0ee..f96cf46faa 100644 --- a/pandora_console/general/license/pandora_info_it.html +++ b/pandora_console/general/license/pandora_info_it.html @@ -1,279 +1,304 @@ - -Licenze GNU - - + + Licenze GNU + + +

    Licenze GNU

    -

    Licenze GNU

    +

    Sommario

    + -

    Sommario

    +
    - +

    Introduzione

    -
    +

    + Tutto il software pubblicato dovrebbe essere software libero. + Perché sia libero, bisogna pubblicarlo con una licenza per il + software libero. Normalmente utilizziamo la + Licenza Pubblica Generica GNU (GNU GPL), ma talvolta + utilizziamo anche + altre licenze per software libero. Per il + software GNU utilizziamo solo licenze compatibili con la GNU GPL. +

    -

    Introduzione

    +

    + La documentazione per il software libero dovrebbe essere documentazione + libera, in modo che si possa distribuire e migliorare assieme al software + che essa descrive. Per rendere libera la documentazione occorre + rilasciarla con una licenza di documentazione libera. Normalmente + utilizziamo la + Licenza per Documentazione Libera GNU (GNU FDL), ma + talvolta utilizziamo anche + altre licenze per la documentazione libera. +

    -

    -Tutto il software pubblicato dovrebbe essere software libero. Perché sia -libero, bisogna pubblicarlo con una licenza per il software libero. -Normalmente utilizziamo la Licenza -Pubblica Generica GNU (GNU GPL), ma talvolta utilizziamo anche altre licenze per software -libero. Per il software GNU utilizziamo solo licenze compatibili -con la GNU GPL. -

    +

    La Licenza Pubblica Generica GNU

    -

    -La documentazione per il software libero dovrebbe -essere documentazione -libera, in modo che si possa distribuire e migliorare assieme al -software che essa descrive. Per rendere libera la documentazione -occorre rilasciarla con una licenza di documentazione -libera. Normalmente utilizziamo -la Licenza per Documentazione Libera -GNU (GNU FDL), ma talvolta utilizziamo -anche altre licenze per la -documentazione libera. -

    +

    + La Licenza Pubblica Generica GNU è spesso indicata brevemente come + GNU GPL; è usata dalla maggioranza dei programmi GNU, e da + più della metà di tutti i pacchetti di software libero. +

    -

    La Licenza Pubblica Generica GNU

    +

    + Licenza Pubblica Generica Attenuata GNU +

    -

    -La Licenza Pubblica Generica GNU è spesso indicata brevemente come GNU -GPL; è usata dalla maggioranza dei programmi GNU, e da più della metà di -tutti i pacchetti di software libero. -

    +

    + La Licenza Pubblica Generica Attenuata GNU è utilizzata da alcune + (non tutte) delle librerie GNU. Questa licenza era originariamente + chiamata la GPL per Librerie, ma in seguito le cambiammo nome + perché il vecchio nome ne incoraggiava un uso più frequente + del dovuto. +

    -

    Licenza Pubblica Generica Attenuata GNU

    +

    + La Licenza per Documentazione Libera GNU +

    -

    -La Licenza Pubblica Generica Attenuata GNU è utilizzata da alcune (non -tutte) delle librerie GNU. Questa licenza era originariamente chiamata -la GPL per Librerie, ma in seguito le cambiammo nome perché il vecchio -nome ne incoraggiava un uso più frequente del dovuto. -

    +

    + La licenza di Documentazione Libera è una forma di permesso + d'autore (copyleft) pensata per un manuale, libro di testo o altro + documento, in modo da garantire a chiunque l'effettiva libertà di + usarlo e distribuirlo, con o senza modifiche, commercialmente o meno. +

    +

    + Copie letterali e distribuzione +

    +

    + La nota standard di copyright per le pagine web GNU recita: + La copia letterale e la distribuzione di questo articolo nella sua + integrità sono permesse con qualsiasi mezzo, a condizione che + questa nota sia riprodotta. Si tenga presente questo commento di Eben Moglen: +

    -

    La Licenza per Documentazione Libera GNU

    +

    + «Con la frase "copia letterale con qualsiasi mezzo" non intendiamo + richiedere il mantenimento di intestazioni, piè di pagina o altre + caratteristiche di formattazione. Si richiede tuttavia di mantenere link + web sia per i media ipertestuali sia per quelli non ipertestuali (in forma + di note o URL riportate letteralmente su media non HTML).» +

    -

    -La licenza di Documentazione Libera è una forma di permesso d'autore -(copyleft) pensata per un manuale, libro di testo o altro documento, in -modo da garantire a chiunque l'effettiva libertà di usarlo e -distribuirlo, con o senza modifiche, commercialmente o meno. -

    +

    + Elenco di licenze per il software libero +

    -

    Copie letterali e distribuzione

    -

    -La nota standard di copyright per le pagine web GNU recita: La copia -letterale e la distribuzione di questo articolo nella sua integrità sono -permesse con qualsiasi mezzo, a condizione che questa nota sia -riprodotta. Si tenga presente questo commento di Eben Moglen: -

    +
      +
    • + Elenco di licenze per il software libero -

      -«Con la frase "copia letterale con qualsiasi mezzo" non intendiamo -richiedere il mantenimento di intestazioni, piè di pagina o altre -caratteristiche di formattazione. Si richiede tuttavia di mantenere link -web sia per i media ipertestuali sia per quelli non ipertestuali (in -forma di note o URL riportate letteralmente su media non HTML).» -

      +

      + Se state pensando di scrivere una nuova licenza, vi preghiamo di + contattare la FSF scrivendo a + <licensing@fsf.org>. Il + proliferare di diverse licenze di software libero significa un aumento + di lavoro per gli utenti per la loro comprensione. Potremmo essere in + grado di aiutarvi a trovare una licenza esistente per software libero + che soddisfi le vostre esigenze. +

      -

      Elenco di licenze per il software libero

      +

      + Nel caso ciò non sia possibile, se effettivamente avete bisogno + di una nuova licenza con il nostro aiuto potete assicuravi che la + vostra licenza sia effettivamente una licenza per software libero, ed + evitare vari problemi pratici. +

      +
    • +
    -
      -
    • - Elenco di licenze per il software libero +

      + Cos'è il permesso d'autore (copyleft)? +

      -

      Se state pensando di scrivere una nuova licenza, vi preghiamo di -contattare la FSF scrivendo a <licensing@fsf.org>. Il -proliferare di diverse licenze di software libero significa un aumento -di lavoro per gli utenti per la loro comprensione. Potremmo essere in -grado di aiutarvi a trovare una licenza esistente per software libero -che soddisfi le vostre esigenze. -

      +

      + Il permesso d'autore (copyleft) è un metodo + generico per rendere un programma libero ed imporre che tutte le modifiche + e versioni estese del programma siano anch'esse software libero. +

      -

      -Nel caso ciò non sia possibile, se effettivamente avete bisogno di una -nuova licenza con il nostro aiuto potete assicuravi che la vostra -licenza sia effettivamente una licenza per software libero, ed evitare -vari problemi pratici. -

      +

      + [NdT: si tratta di un gioco di parole, che qui viene reso con "permesso di + autore": copyright (diritto di autore) è formato dalle parola + "copy" (copia) e "right" (diritto, ma anche destra), opposto di "left" + (sinistra, ma anche lasciato).] +

      -
    • -
    +

    + Il modo più semplice per rendere un programma libero è + dichiararlo di dominio pubblico, privo di copyright. [NdT: in Italia + questo concetto a rigore non esiste, perché l'autore non può + rinunciare alla paternità dell'opera; effetti simili si possono + ottenere con l'uso di una licenza permissiva, come la licenza di X del + MIT]. Ciò permette a chiunque di condividere il programma e i suoi + miglioramenti. Tuttavia permette anche a chi non vuol cooperare di + convertire il programma in software proprietario. Costoro possono infatti + apportare modifiche, che siano significative o meno, e distribuire il + risultato come prodotto proprietario. Chi riceve il programma nella forma + modificata non ha la libertà data dall'autore originario; + l'intermediario l'avrà rimossa. +

    -

    Cos'è il permesso d'autore (copyleft)?

    +

    + Nel Progetto GNU, la nostra intenzione è dare a tutti gli + utenti la libertà di ridistribuire e modificare software GNU. Se + l'intermediario potesse rimuoverne la libertà, potremmo avere molti + utenti, ma costoro non avrebbero libertà. Così, invece di + rilasciare il software GNU come dominio pubblico, utilizziamo il permesso + d'autore. Il permesso d'autore (copyleft) significa che chiunque + distribuisca il software, con o senza modifiche, deve accompagnarlo con la + libertà di ulteriori copie o modifiche. Il permesso d'autore + garantisce che ogni utente sia libero. +

    -

    -Il permesso d'autore (copyleft) è un metodo generico -per rendere un programma libero ed imporre che tutte le modifiche e -versioni estese del programma siano anch'esse software libero. -

    +

    + Il permesso d'autore costituisce anche un incentivo per altri + programmatori ad incrementare il software libero. Alcuni programmi liberi + importanti, come il compilatore GNU C++, esistono solo grazie a questo. +

    -

    -[NdT: si tratta di un gioco di parole, che qui viene reso con "permesso -di autore": copyright (diritto di autore) è formato dalle parola "copy" -(copia) e "right" (diritto, ma anche destra), opposto di "left" -(sinistra, ma anche lasciato).] -

    +

    + Il permesso d'autore aiuta anche i programmatori che desiderano + contribuire con miglioramenti al software libero ad ottenerne il permesso. + Questi programmatori spesso lavorano per aziende o università che + farebbero quasi qualunque cosa per avere più denaro. Un + programmatore potrebbe voler cedere le sue modifiche alla comunità, + ma il suo superiore potrebbe volerne fare un prodotto software + proprietario. +

    -

    -Il modo più semplice per rendere un programma libero è dichiararlo di dominio -pubblico, privo di copyright. [NdT: in Italia questo concetto a -rigore non esiste, perché l'autore non può rinunciare alla paternità -dell'opera; effetti simili si possono ottenere con l'uso di una licenza -permissiva, come la licenza di X del MIT]. Ciò permette a chiunque di -condividere il programma e i suoi miglioramenti. Tuttavia permette anche -a chi non vuol cooperare di convertire il programma in software -proprietario. Costoro possono infatti apportare modifiche, che -siano significative o meno, e distribuire il risultato come prodotto -proprietario. Chi riceve il programma nella forma modificata non ha la -libertà data dall'autore originario; l'intermediario l'avrà rimossa. -

    +

    + Quando spieghiamo ai datori di lavoro che è illegale distribuire la + versione migliorata se non come software libero, questi normalmente + decidono di rilasciarla come software libero piuttosto che buttarla via. +

    -

    -Nel Progetto GNU, la nostra -intenzione è dare a tutti gli utenti la libertà di -ridistribuire e modificare software GNU. Se l'intermediario potesse -rimuoverne la libertà, potremmo avere molti utenti, ma costoro non -avrebbero libertà. Così, invece di rilasciare il software GNU come -dominio pubblico, utilizziamo il permesso d'autore. Il permesso -d'autore (copyleft) significa che chiunque distribuisca il software, con -o senza modifiche, deve accompagnarlo con la libertà di ulteriori -copie o modifiche. Il permesso d'autore garantisce che ogni utente sia -libero. -

    +

    + Nel rendere un programma copyleft, per prima cosa mettiamo in chiaro che + è soggetto a diritto d'autore; poi aggiungiamo le condizioni di + distribuzione, che sono uno strumento legale per dare a chiunque i diritti + d'uso, di modifica e ridistribuzione del codice del programma + ed ogni programma da esso derivato, ma solo se si lasciano + invariati i termini di distribuzione. Così, il codice e le + libertà divengono legalmente inseparabili. +

    -

    -Il permesso d'autore costituisce anche un incentivo per altri -programmatori ad incrementare il software libero. Alcuni programmi -liberi importanti, come il compilatore GNU C++, esistono solo grazie a -questo. -

    +

    + Gli sviluppatori di software proprietario utilizzano il diritto d'autore + per togliere la libertà agli utenti. Noi lo utilizziamo per + garantire la loro libertà. Ecco perché invertiamo il + termine, trasformando "diritto d'autore" in "permesso d'autore" + ("copyright" in "copyleft"). +

    -

    -Il permesso d'autore aiuta anche i programmatori che desiderano -contribuire con miglioramenti al software libero ad ottenerne il -permesso. Questi programmatori spesso lavorano per aziende o università -che farebbero quasi qualunque cosa per avere più denaro. Un -programmatore potrebbe voler cedere le sue modifiche alla comunità, ma -il suo superiore potrebbe volerne fare un prodotto software -proprietario. -

    +

    + Il permesso d'autore è un concetto generale; ci sono molti modi di + completare i dettagli. Nel Progetto GNU, le specifiche condizioni di + distribuzione che utilizziamo sono contenute nella Licenza Pubblica + Generica GNU, la Licenza Pubblica Generica Attenuata GNU e la Licenza per + Documentazione Libera GNU. +

    -

    -Quando spieghiamo ai datori di lavoro che è illegale distribuire la -versione migliorata se non come software libero, questi normalmente -decidono di rilasciarla come software libero piuttosto che buttarla via. -

    +

    + La licenza appropriata è inclusa in molti manuali e in ogni + distribuzione di codice sorgente GNU. +

    -

    -Nel rendere un programma copyleft, per prima cosa mettiamo in chiaro che -è soggetto a diritto d'autore; poi aggiungiamo le condizioni di -distribuzione, che sono uno strumento legale per dare a chiunque i -diritti d'uso, di modifica e ridistribuzione del codice del programma -ed ogni programma da esso derivato, ma solo se si lasciano -invariati i termini di distribuzione. Così, il codice e le libertà -divengono legalmente inseparabili. -

    +

    + La GNU GPL è progettata perché possiate applicarla + facilmente ai vostri programmi se siete i titolari dei relativi diritti. + Per far questo non dovete modificare la GNU GPL ma solo aggiungere nel + programma una nota che vi faccia riferimento. Vi preghiamo di tener + presente che se usate la GNU GPL dovete usare il testo integrale della + licenza. E' un tutto unico, versioni parziali non sono consentite (lo + stesso vale per la LGPL e la FDL). +

    -

    -Gli sviluppatori di software proprietario utilizzano il diritto d'autore -per togliere la libertà agli utenti. Noi lo utilizziamo per garantire la -loro libertà. Ecco perché invertiamo il termine, trasformando "diritto -d'autore" in "permesso d'autore" ("copyright" in "copyleft"). -

    +

    + Usare gli stessi termini di distribuzione per molti programmi rende facile + copiare codice tra programmi diversi. Dato che tutti hanno gli stessi + termini di distribuzione, non c'è bisogno di preoccuparsi se i + termini siano compatibili. La GPL Attenuata include una clausola che + permette di trasformare i termini di distribuzione nella GPL ordinaria, in + modo che possiate copiare codice in un altro programma coperto dalla GPL. +

    -

    -Il permesso d'autore è un concetto generale; ci sono molti modi di -completare i dettagli. Nel Progetto GNU, le specifiche condizioni di -distribuzione che utilizziamo sono contenute nella Licenza Pubblica -Generica GNU, la Licenza Pubblica Generica Attenuata GNU e la Licenza -per Documentazione Libera GNU. -

    +

    + Licenze per altri tipi di opere +

    -

    -La licenza appropriata è inclusa in molti manuali e in ogni -distribuzione di codice sorgente GNU. -

    +

    + Noi crediamo che il software e la documentazione che si pubblicano debbano + essere software libero e documentazione libera. + Consigliamo di rendere ugualmente libera ogni genere di opera educativa e + di riferimento, utilizzando licenze di documentazione libera come la + Licenza per Documentazione Libera GNU (GNU FDL). +

    -

    -La GNU GPL è progettata perché possiate applicarla facilmente ai vostri -programmi se siete i titolari dei relativi diritti. Per far questo non -dovete modificare la GNU GPL ma solo aggiungere nel programma una nota -che vi faccia riferimento. Vi preghiamo di tener presente che se usate -la GNU GPL dovete usare il testo integrale della licenza. E' un tutto -unico, versioni parziali non sono consentite (lo stesso vale per la LGPL -e la FDL). -

    +

    + Per saggi o pubblicazioni scientifiche, consigliamo la semplice licenza di + "copia letterale" utilizzata ad esempio per questa pagina Web. +

    -

    -Usare gli stessi termini di distribuzione per molti programmi rende -facile copiare codice tra programmi diversi. Dato che tutti hanno gli -stessi termini di distribuzione, non c'è bisogno di preoccuparsi se i -termini siano compatibili. La GPL Attenuata include una clausola che -permette di trasformare i termini di distribuzione nella GPL ordinaria, -in modo che possiate copiare codice in un altro programma coperto dalla -GPL. -

    +

    + Non prendiamo posizione sull'idea che i lavori artistici o letterari + debbano essere liberi, ma se volete fare in modo che un vostro lavoro lo + sia vi consigliamo la + Free Art License (in + inglese). +

    -

    Licenze per altri tipi di opere

    - -

    -Noi crediamo che il software e la documentazione che si pubblicano -debbano essere software libero e -documentazione libera. Consigliamo di rendere ugualmente libera -ogni genere di opera educativa e di riferimento, utilizzando licenze di -documentazione libera come la Licenza per -Documentazione Libera GNU (GNU FDL). -

    - -

    -Per saggi o pubblicazioni scientifiche, consigliamo la semplice licenza -di "copia letterale" utilizzata ad esempio per questa pagina Web.

    - -

    -Non prendiamo posizione sull'idea che i lavori artistici o letterari -debbano essere liberi, ma se volete fare in modo che un vostro lavoro -lo sia vi consigliamo la Free -Art License (in inglese).

    - - -

    -Copyright (C) 1996, 1997, 1998, 1999, 2003, 2004, 2005 Free Software Foundation, Inc., -51 Franklin St, Fifth Floor, Boston, MA 02110, USA -
    -La copia letterale e la distribuzione di questo articolo nella sua -integrità sono permesse con qualsiasi mezzo gratuitamente a -condizione che questa nota sia riprodotta. -

    - - +

    + Copyright (C) 1996, 1997, 1998, 1999, 2003, 2004, 2005 Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA +
    + La copia letterale e la distribuzione di questo articolo nella sua + integrità sono permesse con qualsiasi mezzo gratuitamente a + condizione che questa nota sia riprodotta. +

    + diff --git a/pandora_console/general/license/pandora_info_ja.html b/pandora_console/general/license/pandora_info_ja.html index 3a6dcedffe..3db88f9eb5 100644 --- a/pandora_console/general/license/pandora_info_ja.html +++ b/pandora_console/general/license/pandora_info_ja.html @@ -1,436 +1,433 @@ - + - - -GNU 一般公衆利用許諾契約書 - GNU プロジェクト - フリーソフトウェア財団 (FSF) - - + + + + GNU 一般公衆利用許諾契約書 - GNU プロジェクト - フリーソフトウェア財団 + (FSF) + + + + 本訳は、http://www.opensource.jp/gpl/gpl.ja.html.euc-jpより転載している。 -本訳は、http://www.opensource.jp/gpl/gpl.ja.html.euc-jpより転載している。 +
    -
    +

    GNU 一般公衆利用許諾契約書

    -

    GNU 一般公衆利用許諾契約書

    +

    もくじ

    + -

    もくじ

    - -
    -

    -

    GNU 一般公衆利用許諾契約書

    -

    -バージョン 2、1991年6月
    -日本語訳、2002年8月28日 -

    - -
    +    
     Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
     59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
     
     この利用許諾契約書を、一字一句そのままに複製し頒布することは許可する。
     しかし変更は認めない。
    -
    +
    -
    -This is an unofficial translation of the GNU General Public License -into Japanese. It was not published by the Free Software Foundation, -and does not legally state the distribution terms for software that -uses the GNU GPL--only the original English text of the GNU GPL does -that. However, we hope that this translation will help Japanese -speakers understand the GNU GPL better. -
    +
    + This is an unofficial translation of the GNU General Public License into + Japanese. It was not published by the Free Software Foundation, and does + not legally state the distribution terms for software that uses the GNU + GPL--only the original English text of the GNU GPL does that. However, we + hope that this translation will help Japanese speakers understand the GNU + GPL better. +
    -
    -(訳: 以下はGNU General Public Licenseの非公式な日本語訳です。これはフ -リーソフトウェア財団(the Free Software Foundation)によって発表されたも -のではなく、GNU GPLを適用したソフトウェアの頒布条件を法的に有効な形で -述べたものではありません。頒布条件としてはGNU GPLの英語版テキストで指 -定されているもののみが有効です。しかしながら、私たちはこの翻訳が、日本 -語を使用する人々にとってGNU GPLをより良く理解する助けとなることを望ん -でいます。) -
    +
    + (訳: 以下はGNU General Public Licenseの非公式な日本語訳です。これはフ + リーソフトウェア財団(the Free Software Foundation)によって発表されたも + のではなく、GNU GPLを適用したソフトウェアの頒布条件を法的に有効な形で + 述べたものではありません。頒布条件としてはGNU GPLの英語版テキストで指 + 定されているもののみが有効です。しかしながら、私たちはこの翻訳が、日本 + 語を使用する人々にとってGNU GPLをより良く理解する助けとなることを望ん + でいます。) +
    -
    -翻訳は 八田真行<mhatta@gnu.org>が行った。原文はhttp://www.gnu.org/licenses/gpl.html -である。誤訳の指摘や改善案を歓迎する。 -
    +
    + 翻訳は 八田真行<mhatta@gnu.org>が行った。原文はhttp://www.gnu.org/licenses/gpl.html + である。誤訳の指摘や改善案を歓迎する。 +
    -

    はじめに

    +

    はじめに

    -

    -ソフトウェア向けライセンスの大半は、あなたがそのソフトウェアを共有した -り変更したりする自由を奪うように設計されています。対照的に、GNU 一般公 -衆利用許諾契約書は、あなたがフリーソフトウェアを共有したり変更したりす -る自由を保証する--すなわち、ソフトウェアがそのユーザすべてにとってフリー -であることを保証することを目的としています。この一般公衆利用許諾契約書 -はフリーソフトウェア財団のソフトウェアのほとんどに適用されており、また -GNU GPLを適用すると決めたフリーソフトウェア財団以外の作者によるプログ -ラムにも適用されています(いくつかのフリーソフトウェア財団のソフトウェ -アには、GNU GPLではなくGNU ライブラリ一般公衆利用許諾契約書が適用され -ています)。あなたもまた、ご自分のプログラムにGNU GPLを適用することが可 -能です。 +

    + ソフトウェア向けライセンスの大半は、あなたがそのソフトウェアを共有した + り変更したりする自由を奪うように設計されています。対照的に、GNU 一般公 + 衆利用許諾契約書は、あなたがフリーソフトウェアを共有したり変更したりす + る自由を保証する--すなわち、ソフトウェアがそのユーザすべてにとってフリー + であることを保証することを目的としています。この一般公衆利用許諾契約書 + はフリーソフトウェア財団のソフトウェアのほとんどに適用されており、また GNU + GPLを適用すると決めたフリーソフトウェア財団以外の作者によるプログ + ラムにも適用されています(いくつかのフリーソフトウェア財団のソフトウェ + アには、GNU GPLではなくGNU ライブラリ一般公衆利用許諾契約書が適用され + ています)。あなたもまた、ご自分のプログラムにGNU GPLを適用することが可 + 能です。 +

    +

    + 私たちがフリーソフトウェアと言うとき、それは利用の自由について言及して + いるのであって、価格は問題にしていません。私たちの一般公衆利用許諾契約 + 書は、あなたがフリーソフトウェアの複製物を頒布する自由を保証するよう設 + 計されています(希望に応じてその種のサービスに手数料を課す自由も保証さ + れます)。また、あなたがソースコードを受け取るか、あるいは望めばそれを + 入手することが可能であるということ、あなたがソフトウェアを変更し、その + 一部を新たなフリーのプログラムで利用できるということ、そして、以上で述 + べたようなことができるということがあなたに知らされるということも保証さ + れます。 +

    +

    + あなたの権利を守るため、私たちは誰かがあなたの有するこれらの権利を否定 + することや、これらの権利を放棄するよう要求することを禁止するという制限 + を加える必要があります。よって、あなたがソフトウェアの複製物を頒布した + りそれを変更したりする場合には、そういった制限のためにあなたにある種の + 責任が発生することになります。 +

    +

    + 例えば、あなたがフリーなプログラムの複製物を頒布する場合、有料か無料に + 関わらず、あなたは自分が有する権利を全て受領者に与えなければなりません。 + また、あなたは彼らもソースコードを受け取るか手に入れることができるよう + 保証しなければなりません。そして、あなたは彼らに対して以下で述べる条件 + を示し、彼らに自らの持つ権利について知らしめるようにしなければなりませ + ん。 +

    +

    + 私たちはあなたの権利を二段階の手順を踏んで保護します。(1) まずソフトウェ + アに対して著作権を主張し、そして (2) あなたに対して、ソフトウェアの複 + 製や頒布または改変についての法的な許可を与えるこの契約書を提示します。 +

    +

    + また、各作者や私たちを保護するため、私たちはこのフリーソフトウェアには + 何の保証も無いということを誰もが確実に理解するようにし、またソフトウェ + アが誰か他人によって改変され、それが次々と頒布されていったとしても、そ + の受領者は彼らが手に入れたソフトウェアがオリジナルのバージョンでは無い + こと、そして原作者の名声は他人によって持ち込まれた可能性のある問題によっ + て影響されることがないということを周知させたいと思います。 +

    +

    + 最後に、ソフトウェア特許がいかなるフリーのプログラムの存在にも不断の脅 + 威を投げかけていますが、私たちは、フリーなプログラムの再頒布者が個々に + 特許ライセンスを取得することによって、事実上プログラムを独占的にしてし + まうという危険を避けたいと思います。こういった事態を予防するため、私た + ちはいかなる特許も誰もが自由に利用できるようライセンスされるか、全くラ + イセンスされないかのどちらかでなければならないことを明確にしました。 +

    -

    -

    -私たちがフリーソフトウェアと言うとき、それは利用の自由について言及して -いるのであって、価格は問題にしていません。私たちの一般公衆利用許諾契約 -書は、あなたがフリーソフトウェアの複製物を頒布する自由を保証するよう設 -計されています(希望に応じてその種のサービスに手数料を課す自由も保証さ -れます)。また、あなたがソースコードを受け取るか、あるいは望めばそれを -入手することが可能であるということ、あなたがソフトウェアを変更し、その -一部を新たなフリーのプログラムで利用できるということ、そして、以上で述 -べたようなことができるということがあなたに知らされるということも保証さ -れます。 +

    + (訳注: 本契約書で「独占的(proprietary)」とは、ソフトウェアの利用や再頒 + 布、改変が禁止されているか、許可を得ることが必要とされているか、あるい + は厳しい制限が課せられていて自由にそうすることが事実上できなくなってい + る状態のことを指す。詳しくはhttp://www.gnu.org/philosophy/categories.ja.html#ProprietarySoftware + を参照せよ。) +
    -

    -

    -あなたの権利を守るため、私たちは誰かがあなたの有するこれらの権利を否定 -することや、これらの権利を放棄するよう要求することを禁止するという制限 -を加える必要があります。よって、あなたがソフトウェアの複製物を頒布した -りそれを変更したりする場合には、そういった制限のためにあなたにある種の -責任が発生することになります。 +

    複製や頒布、改変についての正確な条件と制約を以下で述べていきます。

    -

    -

    -例えば、あなたがフリーなプログラムの複製物を頒布する場合、有料か無料に -関わらず、あなたは自分が有する権利を全て受領者に与えなければなりません。 -また、あなたは彼らもソースコードを受け取るか手に入れることができるよう -保証しなければなりません。そして、あなたは彼らに対して以下で述べる条件 -を示し、彼らに自らの持つ権利について知らしめるようにしなければなりませ -ん。 +

    複製、頒布、改変に関する条件と制約

    -

    -

    -私たちはあなたの権利を二段階の手順を踏んで保護します。(1) まずソフトウェ -アに対して著作権を主張し、そして (2) あなたに対して、ソフトウェアの複 -製や頒布または改変についての法的な許可を与えるこの契約書を提示します。 +

    + 0. + この利用許諾契約書は、そのプログラム(またはその他の著作物)をこの一般公 + 衆利用許諾契約書の定める条件の下で頒布できる、という告知が著作権者によっ + て記載されたプログラムまたはその他の著作物全般に適用される。以下では、 + 「『プログラム』」とはそのようにしてこの契約書が適用されたプログラムや + 著作物全般を意味し、また「『プログラム』を基にした著作物」とは『プログ + ラム』やその他著作権法の下で派生物と見なされるもの全般を指す。すなわち、 + 『プログラム』かその一部を、全く同一のままか、改変を加えたか、あるいは + 他の言語に翻訳された形で含む著作物のことである(「改変」という語の本来 + の意味からはずれるが、以下では翻訳も改変の一種と見なす)。それぞれの契 + 約者は「あなた」と表現される。 +

    +

    + 複製や頒布、改変以外の活動はこの契約書ではカバーされない。それらはこの + 契約書の対象外である。『プログラム』を実行する行為自体に制限はない。ま + た、そのような『プログラム』の出力結果は、その内容が『プログラム』を基 + にした著作物を構成する場合のみこの契約書によって保護される(『プログラ + ム』を実行したことによって作成されたということとは無関係である)。この + ような線引きの妥当性は、『プログラム』が何をするのかに依存する。 +

    +

    + 1. + それぞれの複製物において適切な著作権表示と保証の否認声明(disclaimer of + warranty)を目立つよう適切に掲載し、またこの契約書および一切の保証の不 + 在に触れた告知すべてをそのまま残し、そしてこの契約書の複製物を『プログ + ラム』のいかなる受領者にも『プログラム』と共に頒布する限り、あなたは + 『プログラム』のソースコードの複製物を、あなたが受け取った通りの形で複 + 製または頒布することができる。媒体は問わない。 +

    +

    + あなたは、物理的に複製物を譲渡するという行為に関して手数料を課しても良 + いし、希望によっては手数料を取って交換における保護の保証を提供しても良 + い。 +

    +

    + 2. + あなたは自分の『プログラム』の複製物かその一部を改変して『プログラム』 + を基にした著作物を形成し、そのような改変点や著作物を上記第1節の定める + 条件の下で複製または頒布することができる。ただし、そのためには以下の条 + 件すべてを満たしていなければならない: +

    +

    +
      +
    • + a) + あなたがそれらのファイルを変更したということと変更した日時が良く + 分かるよう、改変されたファイルに告示しなければならない。 -

      -

      -また、各作者や私たちを保護するため、私たちはこのフリーソフトウェアには -何の保証も無いということを誰もが確実に理解するようにし、またソフトウェ -アが誰か他人によって改変され、それが次々と頒布されていったとしても、そ -の受領者は彼らが手に入れたソフトウェアがオリジナルのバージョンでは無い -こと、そして原作者の名声は他人によって持ち込まれた可能性のある問題によっ -て影響されることがないということを周知させたいと思います。 +

      +
    • +
    • + b) + 『プログラム』またはその一部を含む著作物、あるいは『プログラム』 + かその一部から派生した著作物を頒布あるいは発表する場合には、その + 全体をこの契約書の条件に従って第三者へ無償で利用許諾しなけれ + ばならない。 -

      -

      -最後に、ソフトウェア特許がいかなるフリーのプログラムの存在にも不断の脅 -威を投げかけていますが、私たちは、フリーなプログラムの再頒布者が個々に -特許ライセンスを取得することによって、事実上プログラムを独占的にしてし -まうという危険を避けたいと思います。こういった事態を予防するため、私た -ちはいかなる特許も誰もが自由に利用できるようライセンスされるか、全くラ -イセンスされないかのどちらかでなければならないことを明確にしました。 +

      +
    • +
    • + c) + 改変されたプログラムが、通常実行する際に対話的にコマンドを読むよ + うになっているならば、そのプログラムを最も一般的な方法で対話的に + 実行する際、適切な著作権表示、無保証であること(あるいはあなたが保 + 証を提供するということ)、ユーザがプログラムをこの契約書で述べた条 + 件の下で頒布することができるということ、そしてこの契約書の複製物 + を閲覧するにはどうしたらよいかというユーザへの説明を含む告知が印 + 刷されるか、あるいは画面に表示されるようにしなければならない(例外 + として、『プログラム』そのものは対話的であっても通常そのような告 + 知を印刷しない場合には、『プログラム』を基にしたあなたの著作物に + そのような告知を印刷させる必要はない)。 +
    • +
    -

    + 以上の必要条件は全体としての改変された著作物に適用される。著作物の一部 + が『プログラム』から派生したものではないと確認でき、それら自身別の独立 + した著作物であると合理的に考えられるならば、あなたがそれらを別の著作物 + として分けて頒布する場合、そういった部分にはこの契約書とその条件は適用 + されない。しかし、あなたが同じ部分を『プログラム』を基にした著作物全体 + の一部として頒布するならば、全体としての頒布物は、この契約書が課す条件 + に従わなければならない。というのは、この契約書が他の契約者に与える許可 + は『プログラム』丸ごと全体に及び、誰が書いたかは関係なく各部分のすべて + を保護するからである。 +

    + よって、すべてあなたによって書かれた著作物に対し、権利を主張したりあな + たの権利に異議を申し立てることはこの節の意図するところではない。むしろ、 + その趣旨は『プログラム』を基にした派生物ないし集合著作物の頒布を管理す + る権利を行使するということにある。 +

    +

    + また、『プログラム』を基にしていないその他の著作物を『プログラム』(あ + るいは『プログラム』を基にした著作物)と一緒に集めただけのものを一巻の + 保管装置ないし頒布媒体に収めても、その他の著作物までこの契約書が保護す + る対象になるということにはならない。 +

    +

    + 3. + あなたは上記第1節および2節の条件に従い、『プログラム』(あるいは第2節に + おける派生物)をオブジェクトコードないし実行形式で複製または頒布するこ + とができる。ただし、その場合あなたは以下のうちどれか一つを実施しなけれ + ばならない: -

    -(訳注: 本契約書で「独占的(proprietary)」とは、ソフトウェアの利用や再頒 -布、改変が禁止されているか、許可を得ることが必要とされているか、あるい -は厳しい制限が課せられていて自由にそうすることが事実上できなくなってい -る状態のことを指す。詳しくはhttp://www.gnu.org/philosophy/categories.ja.html#ProprietarySoftware -を参照せよ。) -
    + + +

    +
      +
    • + a) + 著作物に、『プログラム』に対応した完全かつ機械で読み取り可能なソー + スコードを添付する。ただし、ソースコードは上記第1節および2節の条 + 件に従いソフトウェアの交換で習慣的に使われる媒体で頒布しなければ + ならない。あるいは、 +

      +
    • +
    • + b) + 著作物に、いかなる第三者に対しても、『プログラム』に対応した完全 + かつ機械で読み取り可能なソースコードを、頒布に要する物理的コスト + を上回らない程度の手数料と引き換えに提供する旨述べた少なくとも3年 + 間は有効な書面になった申し出を添える。ただし、ソースコードは上記 + 第1節および2節の条件に従いソフトウェアの交換で習慣的に使われる媒 + 体で頒布しなければならない。あるいは、 +

      +
    • +
    • + c) + 対応するソースコード頒布の申し出に際して、あなたが得た情報を一緒 + に引き渡す(この選択肢は、営利を目的としない頒布であって、かつあな + たが上記小節bで指定されているような申し出と共にオブジェクトコード + あるいは実行形式のプログラムしか入手していない場合に限り許可され る)。 +
    • +
    -

    -複製や頒布、改変についての正確な条件と制約を以下で述べていきます。 + 著作物のソースコードとは、それに対して改変を加える上で好ましいとされる + 著作物の形式を意味する。ある実行形式の著作物にとって完全なソースコード + とは、それが含むモジュールすべてのソースコード全部に加え、関連するイン + ターフェース定義ファイルのすべてとライブラリのコンパイルやインストール + を制御するために使われるスクリプトをも加えたものを意味する。しかし特別 + な例外として、そのコンポーネント自体が実行形式に付随するのでは無い限り、 + 頒布されるものの中に、実行形式が実行されるオペレーティングシステムの主 + 要なコンポーネント(コンパイラやカーネル等)と通常一緒に(ソースかバイナ + リ形式のどちらかで)頒布されるものを含んでいる必要はないとする。 +

    + 実行形式またはオブジェクトコードの頒布が、指定された場所からコピーする + ためのアクセス手段を提供することで為されるとして、その上でソースコード + も同等のアクセス手段によって同じ場所からコピーできるようになっているな + らば、第三者がオブジェクトコードと一緒にソースも強制的にコピーさせられ + るようになっていなくてもソースコード頒布の条件を満たしているものとする。 +

    +

    + 4. + あなたは『プログラム』を、この契約書において明確に提示された行為を除き + 複製や改変、サブライセンス、あるいは頒布してはならない。他に『プログラ + ム』を複製や改変、サブライセンス、あるいは頒布する企てはすべて無効であ + り、この契約書の下でのあなたの権利を自動的に終結させることになろう。し + かし、複製物や権利をこの契約書に従ってあなたから得た人々に関しては、そ + のような人々がこの契約書に完全に従っている限り彼らのライセンスまで終結 + することはない。 +

    +

    + 5. + あなたはこの契約書を受諾する必要は無い。というのは、あなたはこれに署名 + していないからである。しかし、この契約書以外にあなたに対して『プログラ + ム』やその派生物を改変または頒布する許可を与えるものは存在しない。これ + らの行為は、あなたがこの契約書を受け入れない限り法によって禁じられてい + る。そこで、『プログラム』(あるいは『プログラム』を基にした著作物全般) + を改変ないし頒布することにより、あなたは自分がそのような行為を行うため + にこの契約書を受諾したということ、そして『プログラム』とそれに基づく著 + 作物の複製や頒布、改変についてこの契約書が課す制約と条件をすべて受け入 + れたということを示したものと見なす。 +

    +

    + 6. + あなたが『プログラム』(または『プログラム』を基にした著作物全般)を再頒 + 布するたびに、その受領者は元々のライセンス許可者から、この契約書で指定 + された条件と制約の下で『プログラム』を複製や頒布、あるいは改変する許可 + を自動的に得るものとする。あなたは、受領者がここで認められた権利を行使 + することに関してこれ以上他のいかなる制限も課してはならない。あなたには、 + 第三者がこの契約書に従うことを強制する責任はない。 +

    +

    + 7. + 特許侵害あるいはその他の理由(特許関係に限らない)から、裁判所の判決ある + いは申し立ての結果としてあなたに(裁判所命令や契約などにより)このライセ + ンスの条件と矛盾する制約が課された場合でも、あなたがこの契約書の条 + 件を免除されるわけではない。もしこの契約書の下であなたに課せられた + 責任と他の関連する責任を同時に満たすような形で頒布できないならば、結果 + としてあなたは『プログラム』を頒布することが全くできないということであ + る。例えば特許ライセンスが、あなたから直接間接を問わずコピーを受け取っ + た人が誰でも『プログラム』を使用料無料で再頒布することを認めていない場 + 合、あなたがその制約とこの契約書を両方とも満たすには『プログラム』 + の頒布を完全に中止するしかないだろう。 +

    +

    + この節の一部分が特定の状況の下で無効ないし実施不可能な場合でも、節の残 + りの部分は適用されるよう意図されている。その他の状況では節が全体として + 適用されるよう意図されている。 +

    +

    + 特許やその他の財産権を侵害したり、そのような権利の主張の効力に異議を唱 + えたりするようあなたを誘惑することがこの節の目的ではない。この節には、 + 人々によってライセンス慣行として実現されてきた、フリーソフトウェア頒布 + のシステムの完全性を護るという目的しかない。多くの人々が、フリーソフト + ウェアの頒布システムが首尾一貫して適用されているという信頼に基づき、こ + のシステムを通じて頒布される多様なソフトウェアに寛大な貢献をしてきたの + は事実であるが、人がどのようなシステムを通じてソフトウェアを頒布したい + と思うかはあくまでも作者/寄与者次第であり、あなたが選択を押しつけるこ + とはできない。 +

    +

    + この節は、この契約書のこの節以外の部分の一帰結になると考えられるケー + スを徹底的に明らかにすることを目的としている。 +

    +

    + 8. + 『プログラム』の頒布や利用が、ある国においては特許または著作権が主張さ + れたインターフェースのいずれかによって制限されている場合、『プログラム』 + にこの契約書を適用した元の著作権者は、そういった国々を排除した明確 + な地理的頒布制限を加え、そこで排除されていない国の中やそれらの国々の間 + でのみ頒布が許可されるようにしても構わない。その場合、そのような制限は + この契約書本文で書かれているのと同様に見なされる。 +

    +

    + 9. + フリーソフトウェア財団は、時によって改訂または新版の一般公衆利用許諾書 + を発表することができる。そのような新版は現在のバージョンとその精神にお + いては似たものになるだろうが、新たな問題や懸念を解決するため細部では異 + なる可能性がある。 +

    +

    + それぞれのバージョンには、見分けが付くようにバージョン番号が振られてい + る。『プログラム』においてそれに適用されるこの契約書のバージョン番号が + 指定されていて、更に「それ以降のいかなるバージョン(any later version)」 + も適用して良いとなっていた場合、あなたは従う条件と制約として、指定のバー + ジョンか、フリーソフトウェア財団によって発行された指定のバージョン以降 + の版のどれか一つのどちらかを選ぶことが出来る。『プログラム』でライセン + スのバージョン番号が指定されていないならば、あなたは今までにフリーソフ + トウェア財団から発行されたバージョンの中から好きに選んで構わない。 +

    +

    + 10. + もしあなたが『プログラム』の一部を、その頒布条件がこの契約書と異なる他 + のフリーなプログラムと統合したいならば、作者に連絡して許可を求めよ。フ + リーソフトウェア財団が著作権を保有するソフトウェアについては、フリーソ + フトウェア財団に連絡せよ。私たちは、このような場合のために特別な例外を + 設けることもある。私たちが決定を下すにあたっては、私たちのフリーソフト + ウェアの派生物すべてがフリーな状態に保たれるということと、一般的にソフ + トウェアの共有と再利用を促進するという二つの目標を規準に検討されるであ + ろう。 +

    +

    無保証について

    -

    +

    + 11. + + 『プログラム』は代価無しに利用が許可されるので、適切な法が認める限りに + おいて、『プログラム』に関するいかなる保証も存在しない。書面で別に述べ + る場合を除いて、著作権者、またはその他の団体は、『プログラム』を、表明 + されたか言外にかは問わず、商業的適性を保証するほのめかしやある特定の目 + 的への適合性(に限られない)を含む一切の保証無しに「あるがまま」で提供す + る。『プログラム』の質と性能に関するリスクのすべてはあなたに帰属する。 + 『プログラム』に欠陥があると判明した場合、あなたは必要な保守点検や補修、 + 修正に要するコストのすべてを引き受けることになる。 + +

    +

    + 12. + + 適切な法か書面での同意によって命ぜられない限り、著作権者、または上記で + 許可されている通りに『プログラム』を改変または再頒布したその他の団体は、 + あなたに対して『プログラム』の利用ないし利用不能で生じた通常損害や特別 + 損害、偶発損害、間接損害(データの消失や不正確な処理、あなたか第三者が + 被った損失、あるいは『プログラム』が他のソフトウェアと一緒に動作しない + という不具合などを含むがそれらに限らない)に一切の責任を負わない。その + ような損害が生ずる可能性について彼らが忠告されていたとしても同様である。 + +

    - -

    複製、頒布、改変に関する条件と制約

    - - -

    - -0. -この利用許諾契約書は、そのプログラム(またはその他の著作物)をこの一般公 -衆利用許諾契約書の定める条件の下で頒布できる、という告知が著作権者によっ -て記載されたプログラムまたはその他の著作物全般に適用される。以下では、 -「『プログラム』」とはそのようにしてこの契約書が適用されたプログラムや -著作物全般を意味し、また「『プログラム』を基にした著作物」とは『プログ -ラム』やその他著作権法の下で派生物と見なされるもの全般を指す。すなわち、 -『プログラム』かその一部を、全く同一のままか、改変を加えたか、あるいは -他の言語に翻訳された形で含む著作物のことである(「改変」という語の本来 -の意味からはずれるが、以下では翻訳も改変の一種と見なす)。それぞれの契 -約者は「あなた」と表現される。 -

    - -複製や頒布、改変以外の活動はこの契約書ではカバーされない。それらはこの -契約書の対象外である。『プログラム』を実行する行為自体に制限はない。ま -た、そのような『プログラム』の出力結果は、その内容が『プログラム』を基 -にした著作物を構成する場合のみこの契約書によって保護される(『プログラ -ム』を実行したことによって作成されたということとは無関係である)。この -ような線引きの妥当性は、『プログラム』が何をするのかに依存する。 -

    - -1. -それぞれの複製物において適切な著作権表示と保証の否認声明(disclaimer of -warranty)を目立つよう適切に掲載し、またこの契約書および一切の保証の不 -在に触れた告知すべてをそのまま残し、そしてこの契約書の複製物を『プログ -ラム』のいかなる受領者にも『プログラム』と共に頒布する限り、あなたは -『プログラム』のソースコードの複製物を、あなたが受け取った通りの形で複 -製または頒布することができる。媒体は問わない。 -

    - -あなたは、物理的に複製物を譲渡するという行為に関して手数料を課しても良 -いし、希望によっては手数料を取って交換における保護の保証を提供しても良 -い。 -

    - -2. -あなたは自分の『プログラム』の複製物かその一部を改変して『プログラム』 -を基にした著作物を形成し、そのような改変点や著作物を上記第1節の定める -条件の下で複製または頒布することができる。ただし、そのためには以下の条 -件すべてを満たしていなければならない: -

    - -

      - -
    • a) - あなたがそれらのファイルを変更したということと変更した日時が良く - 分かるよう、改変されたファイルに告示しなければならない。 - -

      -

    • b) - 『プログラム』またはその一部を含む著作物、あるいは『プログラム』 - かその一部から派生した著作物を頒布あるいは発表する場合には、その - 全体をこの契約書の条件に従って第三者へ無償で利用許諾しなけれ - ばならない。 - -

      -

    • c) - 改変されたプログラムが、通常実行する際に対話的にコマンドを読むよ - うになっているならば、そのプログラムを最も一般的な方法で対話的に - 実行する際、適切な著作権表示、無保証であること(あるいはあなたが保 - 証を提供するということ)、ユーザがプログラムをこの契約書で述べた条 - 件の下で頒布することができるということ、そしてこの契約書の複製物 - を閲覧するにはどうしたらよいかというユーザへの説明を含む告知が印 - 刷されるか、あるいは画面に表示されるようにしなければならない(例外 - として、『プログラム』そのものは対話的であっても通常そのような告 - 知を印刷しない場合には、『プログラム』を基にしたあなたの著作物に - そのような告知を印刷させる必要はない)。 -
    - -以上の必要条件は全体としての改変された著作物に適用される。著作物の一部 -が『プログラム』から派生したものではないと確認でき、それら自身別の独立 -した著作物であると合理的に考えられるならば、あなたがそれらを別の著作物 -として分けて頒布する場合、そういった部分にはこの契約書とその条件は適用 -されない。しかし、あなたが同じ部分を『プログラム』を基にした著作物全体 -の一部として頒布するならば、全体としての頒布物は、この契約書が課す条件 -に従わなければならない。というのは、この契約書が他の契約者に与える許可 -は『プログラム』丸ごと全体に及び、誰が書いたかは関係なく各部分のすべて -を保護するからである。 -

    - -よって、すべてあなたによって書かれた著作物に対し、権利を主張したりあな -たの権利に異議を申し立てることはこの節の意図するところではない。むしろ、 -その趣旨は『プログラム』を基にした派生物ないし集合著作物の頒布を管理す -る権利を行使するということにある。 -

    - -また、『プログラム』を基にしていないその他の著作物を『プログラム』(あ -るいは『プログラム』を基にした著作物)と一緒に集めただけのものを一巻の -保管装置ないし頒布媒体に収めても、その他の著作物までこの契約書が保護す -る対象になるということにはならない。 -

    - -3. -あなたは上記第1節および2節の条件に従い、『プログラム』(あるいは第2節に -おける派生物)をオブジェクトコードないし実行形式で複製または頒布するこ -とができる。ただし、その場合あなたは以下のうちどれか一つを実施しなけれ -ばならない: - - - -

      - -
    • a) - 著作物に、『プログラム』に対応した完全かつ機械で読み取り可能なソー - スコードを添付する。ただし、ソースコードは上記第1節および2節の条 - 件に従いソフトウェアの交換で習慣的に使われる媒体で頒布しなければ - ならない。あるいは、 -

      -

    • b) - 著作物に、いかなる第三者に対しても、『プログラム』に対応した完全 - かつ機械で読み取り可能なソースコードを、頒布に要する物理的コスト - を上回らない程度の手数料と引き換えに提供する旨述べた少なくとも3年 - 間は有効な書面になった申し出を添える。ただし、ソースコードは上記 - 第1節および2節の条件に従いソフトウェアの交換で習慣的に使われる媒 - 体で頒布しなければならない。あるいは、 -

      -

    • c) - 対応するソースコード頒布の申し出に際して、あなたが得た情報を一緒 - に引き渡す(この選択肢は、営利を目的としない頒布であって、かつあな - たが上記小節bで指定されているような申し出と共にオブジェクトコード - あるいは実行形式のプログラムしか入手していない場合に限り許可され - る)。 -
    - -著作物のソースコードとは、それに対して改変を加える上で好ましいとされる -著作物の形式を意味する。ある実行形式の著作物にとって完全なソースコード -とは、それが含むモジュールすべてのソースコード全部に加え、関連するイン -ターフェース定義ファイルのすべてとライブラリのコンパイルやインストール -を制御するために使われるスクリプトをも加えたものを意味する。しかし特別 -な例外として、そのコンポーネント自体が実行形式に付随するのでは無い限り、 -頒布されるものの中に、実行形式が実行されるオペレーティングシステムの主 -要なコンポーネント(コンパイラやカーネル等)と通常一緒に(ソースかバイナ -リ形式のどちらかで)頒布されるものを含んでいる必要はないとする。 -

    - -実行形式またはオブジェクトコードの頒布が、指定された場所からコピーする -ためのアクセス手段を提供することで為されるとして、その上でソースコード -も同等のアクセス手段によって同じ場所からコピーできるようになっているな -らば、第三者がオブジェクトコードと一緒にソースも強制的にコピーさせられ -るようになっていなくてもソースコード頒布の条件を満たしているものとする。 -

    - -4. -あなたは『プログラム』を、この契約書において明確に提示された行為を除き -複製や改変、サブライセンス、あるいは頒布してはならない。他に『プログラ -ム』を複製や改変、サブライセンス、あるいは頒布する企てはすべて無効であ -り、この契約書の下でのあなたの権利を自動的に終結させることになろう。し -かし、複製物や権利をこの契約書に従ってあなたから得た人々に関しては、そ -のような人々がこの契約書に完全に従っている限り彼らのライセンスまで終結 -することはない。 -

    - -5. -あなたはこの契約書を受諾する必要は無い。というのは、あなたはこれに署名 -していないからである。しかし、この契約書以外にあなたに対して『プログラ -ム』やその派生物を改変または頒布する許可を与えるものは存在しない。これ -らの行為は、あなたがこの契約書を受け入れない限り法によって禁じられてい -る。そこで、『プログラム』(あるいは『プログラム』を基にした著作物全般) -を改変ないし頒布することにより、あなたは自分がそのような行為を行うため -にこの契約書を受諾したということ、そして『プログラム』とそれに基づく著 -作物の複製や頒布、改変についてこの契約書が課す制約と条件をすべて受け入 -れたということを示したものと見なす。 -

    - -6. -あなたが『プログラム』(または『プログラム』を基にした著作物全般)を再頒 -布するたびに、その受領者は元々のライセンス許可者から、この契約書で指定 -された条件と制約の下で『プログラム』を複製や頒布、あるいは改変する許可 -を自動的に得るものとする。あなたは、受領者がここで認められた権利を行使 -することに関してこれ以上他のいかなる制限も課してはならない。あなたには、 -第三者がこの契約書に従うことを強制する責任はない。 - -

    - -7. -特許侵害あるいはその他の理由(特許関係に限らない)から、裁判所の判決ある -いは申し立ての結果としてあなたに(裁判所命令や契約などにより)このライセ -ンスの条件と矛盾する制約が課された場合でも、あなたがこの契約書の条 -件を免除されるわけではない。もしこの契約書の下であなたに課せられた -責任と他の関連する責任を同時に満たすような形で頒布できないならば、結果 -としてあなたは『プログラム』を頒布することが全くできないということであ -る。例えば特許ライセンスが、あなたから直接間接を問わずコピーを受け取っ -た人が誰でも『プログラム』を使用料無料で再頒布することを認めていない場 -合、あなたがその制約とこの契約書を両方とも満たすには『プログラム』 -の頒布を完全に中止するしかないだろう。 - -

    - -この節の一部分が特定の状況の下で無効ないし実施不可能な場合でも、節の残 -りの部分は適用されるよう意図されている。その他の状況では節が全体として -適用されるよう意図されている。 - -

    - -特許やその他の財産権を侵害したり、そのような権利の主張の効力に異議を唱 -えたりするようあなたを誘惑することがこの節の目的ではない。この節には、 -人々によってライセンス慣行として実現されてきた、フリーソフトウェア頒布 -のシステムの完全性を護るという目的しかない。多くの人々が、フリーソフト -ウェアの頒布システムが首尾一貫して適用されているという信頼に基づき、こ -のシステムを通じて頒布される多様なソフトウェアに寛大な貢献をしてきたの -は事実であるが、人がどのようなシステムを通じてソフトウェアを頒布したい -と思うかはあくまでも作者/寄与者次第であり、あなたが選択を押しつけるこ -とはできない。 - -

    - -この節は、この契約書のこの節以外の部分の一帰結になると考えられるケー -スを徹底的に明らかにすることを目的としている。 - -

    - -8. -『プログラム』の頒布や利用が、ある国においては特許または著作権が主張さ -れたインターフェースのいずれかによって制限されている場合、『プログラム』 -にこの契約書を適用した元の著作権者は、そういった国々を排除した明確 -な地理的頒布制限を加え、そこで排除されていない国の中やそれらの国々の間 -でのみ頒布が許可されるようにしても構わない。その場合、そのような制限は -この契約書本文で書かれているのと同様に見なされる。 - -

    - -9. -フリーソフトウェア財団は、時によって改訂または新版の一般公衆利用許諾書 -を発表することができる。そのような新版は現在のバージョンとその精神にお -いては似たものになるだろうが、新たな問題や懸念を解決するため細部では異 -なる可能性がある。 - -

    -それぞれのバージョンには、見分けが付くようにバージョン番号が振られてい -る。『プログラム』においてそれに適用されるこの契約書のバージョン番号が -指定されていて、更に「それ以降のいかなるバージョン(any later version)」 -も適用して良いとなっていた場合、あなたは従う条件と制約として、指定のバー -ジョンか、フリーソフトウェア財団によって発行された指定のバージョン以降 -の版のどれか一つのどちらかを選ぶことが出来る。『プログラム』でライセン -スのバージョン番号が指定されていないならば、あなたは今までにフリーソフ -トウェア財団から発行されたバージョンの中から好きに選んで構わない。 - -

    - - -10. -もしあなたが『プログラム』の一部を、その頒布条件がこの契約書と異なる他 -のフリーなプログラムと統合したいならば、作者に連絡して許可を求めよ。フ -リーソフトウェア財団が著作権を保有するソフトウェアについては、フリーソ -フトウェア財団に連絡せよ。私たちは、このような場合のために特別な例外を -設けることもある。私たちが決定を下すにあたっては、私たちのフリーソフト -ウェアの派生物すべてがフリーな状態に保たれるということと、一般的にソフ -トウェアの共有と再利用を促進するという二つの目標を規準に検討されるであ -ろう。 - -

    無保証について

    - -

    - -11. - -『プログラム』は代価無しに利用が許可されるので、適切な法が認める限りに -おいて、『プログラム』に関するいかなる保証も存在しない。書面で別に述べ -る場合を除いて、著作権者、またはその他の団体は、『プログラム』を、表明 -されたか言外にかは問わず、商業的適性を保証するほのめかしやある特定の目 -的への適合性(に限られない)を含む一切の保証無しに「あるがまま」で提供す -る。『プログラム』の質と性能に関するリスクのすべてはあなたに帰属する。 -『プログラム』に欠陥があると判明した場合、あなたは必要な保守点検や補修、 -修正に要するコストのすべてを引き受けることになる。 - - -

    - -12. - -適切な法か書面での同意によって命ぜられない限り、著作権者、または上記で -許可されている通りに『プログラム』を改変または再頒布したその他の団体は、 -あなたに対して『プログラム』の利用ないし利用不能で生じた通常損害や特別 -損害、偶発損害、間接損害(データの消失や不正確な処理、あなたか第三者が -被った損失、あるいは『プログラム』が他のソフトウェアと一緒に動作しない -という不具合などを含むがそれらに限らない)に一切の責任を負わない。その -ような損害が生ずる可能性について彼らが忠告されていたとしても同様である。 - -

    - -

    条件と制約終わり

    - +

    条件と制約終わり

    + + diff --git a/pandora_console/general/license/pandora_info_pt_BR.html b/pandora_console/general/license/pandora_info_pt_BR.html index b4eb7552e4..246330f30e 100644 --- a/pandora_console/general/license/pandora_info_pt_BR.html +++ b/pandora_console/general/license/pandora_info_pt_BR.html @@ -1,424 +1,457 @@ - - -Licen�a Pública Geral GNU - - - -

    LICEN�A P�BLICA GERAL GNU

    -

    Vers�o 2, junho de 1991

    -

    -This is an unofficial translation of the GNU General Public License -into Brazilian Portuguese. It was not published by the Free Software -Foundation, and does not legally state the distribution terms for -software that uses the GNU GPL -- only the original English text of -the GNU GPL does that. However, we hope that this translation will -help Brazilian Portuguese speakers understand the GNU GPL better. -

    -

    -Esta � uma tradu��o n�o-oficial da Licen�a P�blica Geral GNU ("GPL -GNU") para o portugu�s do Brasil. Ela n�o foi publicada pela Free -Software Foundation, e legalmente n�o afirma os termos de distribui��o -de software que utiliza a GPL GNU -- apenas o texto original da GPL -GNU, em ingl�s, faz isso. Contudo, esperamos que esta tradu��o ajude -aos que utilizam o portugu�s do Brasil a entender melhor a GPL GNU. -

    -

    Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA

    -

    -A qualquer pessoa � permitido copiar e distribuir c�pias desse -documento de licen�a, desde que sem qualquer altera��o. -

    - -

    Introdu��o

    - -

    As licen�as de muitos software s�o desenvolvidas para restringir sua -liberdade de compartilh�-lo e mud�-lo. Contr�ria a isso, a Licen�a -P�blica Geral GNU pretende garantir sua liberdade de compartilhar e -alterar software livres -- garantindo que o software ser� livre e -gratuito para os seus usu�rios. Esta Licen�a P�blica Geral aplica-se � -maioria dos software da Free Software Foundation e a qualquer outro -programa cujo autor decida aplic�-la. (Alguns outros software da FSF -s�o cobertos pela Licen�a P�blica Geral de Bibliotecas, no entanto.) -Voc� pode aplic�-la tamb�m aos seus programas.

    - -

    Quando nos referimos a software livre, estamos nos referindo a -liberdade e n�o a pre�o. Nossa Licen�a P�blica Geral foi desenvolvida -para garantir que voc� tenha a liberdade de distribuir c�pias de -software livre (e cobrar por isso, se quiser); que voc� receba o -c�digo-fonte ou tenha acesso a ele, se quiser; que voc� possa mudar o -software ou utilizar partes dele em novos programas livres e -gratuitos; e que voc� saiba que pode fazer tudo isso.

    - -

    Para proteger seus direitos, precisamos fazer restri��es que impe�am -a qualquer um negar estes direitos ou solicitar que voc� deles -abdique. Estas restri��es traduzem-se em certas responsabilidades para -voc�, se voc� for distribuir c�pias do software ou modific�-lo.

    - -

    Por exemplo, se voc� distribuir c�pias de um programa, gratuitamente -ou por alguma quantia, voc� tem que fornecer aos recebedores todos os -direitos que voc� possui. Voc� tem que garantir que eles tamb�m -recebam ou possam obter o c�digo-fonte. E voc� tem que mostrar-lhes -estes termos para que eles possam conhecer seus direitos.

    - -

    N�s protegemos seus direitos em dois passos: (1) com copyright do -software e (2) com a oferta desta licen�a, que lhe d� permiss�o legal -para copiar, distribuir e/ou modificar o software.

    - -

    Al�m disso, tanto para a prote��o do autor quanto a nossa, -gostar�amos de certificar-nos que todos entendam que n�o h� qualquer -garantia nestes software livres. Se o software � modificado por algu�m -mais e passado adiante, queremos que seus recebedores saibam que o que -eles obtiveram n�o � original, de forma que qualquer problema -introduzido por terceiros n�o interfira na reputa��o do autor -original.

    - -

    Finalmente, qualquer programa � amea�ado constantemente por patentes -de software. Queremos evitar o perigo de que distribuidores de -software livre obtenham patentes individuais, o que tem o efeito de -tornar o programa propriet�rio. Para prevenir isso, deixamos claro que -qualquer patente tem que ser licenciada para uso livre e gratuito por -qualquer pessoa, ou ent�o que nem necessite ser licenciada. -

    - -

    Os termos e condi��es precisas para c�pia, distribui��o e -modifica��o se encontram abaixo:

    - -

    LICEN�A P�BLICA GERAL GNU TERMOS E CONDI��ES PARA C�PIA, DISTRIBUI��O E MODIFICA��O

    - -

    -0.Esta licen�a se aplica a qualquer programa ou outro trabalho que -contenha um aviso colocado pelo detentor dos direitos autorais -informando que aquele pode ser distribu�do sob as condi��es desta -Licen�a P�blica Geral. O "Programa" abaixo refere-se a qualquer -programa ou trabalho, e "trabalho baseado no Programa" significa tanto -o Programa em si como quaisquer trabalhos derivados, de acordo com a -lei de direitos autorais: isto quer dizer um trabalho que contenha o -Programa ou parte dele, tanto originalmente ou com modifica��es, e/ou -tradu��o para outros idiomas. (Doravante o processo de tradu��o est� -inclu�do sem limites no termo "modifica��o".) Cada licenciado � -mencionado como "voc�".

    -

    -Atividades outras que a c�pia, a distribui��o e modifica��o n�o est�o -cobertas por esta Licen�a; elas est�o fora de seu escopo. O ato de -executar o Programa n�o � restringido e o resultado do Programa � -coberto apenas se seu conte�do contenha trabalhos baseados no Programa -(independentemente de terem sido gerados pela execu��o do -Programa). Se isso � verdadeiro depende do que o programa faz.

    - -

    -1.Voc� pode copiar e distribuir c�pias fi�is do c�digo-fonte do -Programa da mesma forma que voc� o recebeu, usando qualquer meio, -deste que voc� consp�cua e apropriadamente publique em cada c�pia um -aviso de direitos autorais e uma declara��o de inexist�ncia de -garantias; mantenha intactas todos os avisos que se referem a esta -Licen�a e � aus�ncia total de garantias; e forne�a a outros -recebedores do Programa uma c�pia desta Licen�a, junto com o Programa. -

    -

    -Voc� pode cobrar pelo ato f�sico de transferir uma c�pia e pode, -opcionalmente, oferecer garantia em troca de pagamento. -

    -

    -2. Voc� pode modificar sua c�pia ou c�pias do Programa, ou qualquer -parte dele, assim gerando um trabalho baseado no Programa, e copiar e -distribuir essas modifica��es ou trabalhos sob os temos da se��o 1 -acima, desde que voc� tamb�m se enquadre em todas estas condi��es:

    -
    -a) Voc� tem que fazer com que os arquivos modificados levem avisos - proeminentes afirmando que voc� alterou os arquivos, incluindo a - data de qualquer altera��o. -
    - -
    -b) Voc� tem que fazer com que quaisquer trabalhos que voc� - distribua ou publique, e que integralmente ou em partes contenham - ou sejam derivados do Programa ou de suas partes, sejam - licenciados, integralmente e sem custo algum para quaisquer - terceiros, sob os termos desta Licen�a. -
    - -
    -c) Se qualquer programa modificado normalmente l� comandos - interativamente quando executados, voc� tem que fazer com que, - quando iniciado tal uso interativo da forma mais simples, seja - impresso ou mostrado um an�ncio de que n�o h� qualquer garantia - (ou ent�o que voc� fornece a garantia) e que os usu�rios podem - redistribuir o programa sob estas condi��es, ainda informando os - usu�rios como consultar uma c�pia desta Licen�a. (Exce��o: se o - Programa em si � interativo mas normalmente n�o imprime estes - tipos de an�ncios, seu trabalho baseado no Programa n�o precisa - imprimir um an�ncio.) -
    -

    -Estas exig�ncias aplicam-se ao trabalho modificado como um todo. Se -se��es identific�veis de tal trabalho n�o s�o derivadas do Programa, e -podem ser razoavelmente consideradas trabalhos independentes e -separados por si s�, ent�o esta Licen�a, e seus termos, n�o se aplicam -a estas se��es quando voc� distribui-las como trabalhos em -separado. Mas quando voc� distribuir as mesmas se��es como parte de um -todo que � trabalho baseado no Programa, a distribui��o como um todo -tem que se enquadrar nos termos desta Licen�a, cujas permiss�es para -outros licenciados se estendem ao todo, portanto tamb�m para cada e -toda parte independente de quem a escreveu. -

    -

    -Desta forma, esta se��o n�o tem a inten��o de reclamar direitos os -contestar seus direitos sobre o trabalho escrito completamente por -voc�; ao inv�s disso, a inten��o � a de exercitar o direito de -controlar a distribui��o de trabalhos, derivados ou coletivos, -baseados no Programa. -

    -

    -Adicionalmente, a mera adi��o ao Programa de outro trabalho n�o -baseado no Programa (ou de trabalho baseado no Programa) em um volume -de armazenamento ou meio de distribui��o n�o faz o outro trabalho -parte do escopo desta Licen�a. -

    -

    3. Voc� pode copiar e distribuir o Programa (ou trabalho baseado -nele, conforme descrito na Se��o 2) em c�digo-objeto ou em forma -execut�vel sob os termos das Se��es 1 e 2 acima, desde que voc� -fa�a um dos seguintes: -

    -
    -a)O acompanhe com o c�digo-fonte completo e em forma acess�vel - por m�quinas, que tem que ser distribu�do sob os termos das Se��es - 1 e 2 acima e em meio normalmente utilizado para o interc�mbio de - software; ou, -
    - -
    -b) O acompanhe com uma oferta escrita, v�lida por pelo menos tr�s - anos, de fornecer a qualquer um, com um custo n�o superior ao - custo de distribui��o f�sica do material, uma c�pia do - c�digo-fonte completo e em forma acess�vel por m�quinas, que tem - que ser distribu�do sob os termos das Se��es 1 e 2 acima e em meio - normalmente utilizado para o interc�mbio de software; ou, -
    - -
    -

    -c) O acompanhe com a informa��o que voc� recebeu em rela��o � - oferta de distribui��o do c�digo-fonte correspondente. (Esta - alternativa � permitida somente em distribui��o n�o comerciais, e - apenas se voc� recebeu o programa em forma de c�digo-objeto ou - execut�vel, com oferta de acordo com a Subse��o b acima.) -

    -
    -

    -O c�digo-fonte de um trabalho corresponde � forma de trabalho -preferida para se fazer modifica��es. Para um trabalho em forma -execut�vel, o c�digo-fonte completo significa todo o c�digo-fonte de -todos os m�dulos que ele cont�m, mais quaisquer arquivos de defini��o -de "interface", mais os "scripts" utilizados para se controlar a -compila��o e a instala��o do execut�vel. Contudo, como exce��o -especial, o c�digo-fonte distribu�do n�o precisa incluir qualquer -componente normalmente distribu�do (tanto em forma original quanto -bin�ria) com os maiores componentes (o compilador, o "kernel" etc.) do -sistema operacional sob o qual o execut�vel funciona, a menos que o -componente em si acompanhe o execut�vel. -

    -

    -Se a distribui��o do execut�vel ou c�digo-objeto � feita atrav�s da -oferta de acesso a c�pias de algum lugar, ent�o ofertar o acesso -equivalente a c�pia, do mesmo lugar, do c�digo-fonte equivale � -distribui��o do c�digo-fonte, mesmo que terceiros n�o sejam compelidos -a copiar o c�digo-fonte com o c�digo-objeto. -

    -

    -4. Voc� n�o pode copiar, modificar, sub-licenciar ou distribuir o -Programa, exceto de acordo com as condi��es expressas nesta -Licen�a. Qualquer outra tentativa de c�pia, modifica��o, -sub-licenciamento ou distribui��o do Programa n�o � valida, e -cancelar� automaticamente os direitos que lhe foram fornecidos por -esta Licen�a. No entanto, terceiros que de voc� receberam c�pias ou -direitos, fornecidos sob os termos desta Licen�a, n�o ter�o suas -licen�as terminadas, desde que permane�am em total concord�ncia com -ela. -

    -

    -5. Voc� n�o � obrigado a aceitar esta Licen�a j� que n�o a -assinou. No entanto, nada mais o dar� permiss�o para modificar ou -distribuir o Programa ou trabalhos derivados deste. Estas a��es s�o -proibidas por lei, caso voc� n�o aceite esta Licen�a. Desta forma, ao -modificar ou distribuir o Programa (ou qualquer trabalho derivado do -Programa), voc� estar� indicando sua total aceita��o desta Licen�a -para faz�-los, e todos os seus termos e condi��es para copiar, -distribuir ou modificar o Programa, ou trabalhos baseados nele. -

    -

    -6. Cada vez que voc� redistribuir o Programa (ou qualquer trabalho -baseado nele), os recebedores adquirir�o automaticamente do -licenciador original uma licen�a para copiar, distribuir ou modificar -o Programa, sujeitos a estes termos e condi��es. Voc� n�o poder� impor -aos recebedores qualquer outra restri��o ao exerc�cio dos direitos -ent�o adquiridos. Voc� n�o � respons�vel em garantir a concord�ncia de -terceiros a esta Licen�a. -

    -

    -7. Se, em conseq��ncia de decis�es judiciais ou alega��es de -infringimento de patentes ou quaisquer outras raz�es (n�o limitadas a -assuntos relacionados a patentes), condi��es forem impostas a voc� -(por ordem judicial, acordos ou outras formas) e que contradigam as -condi��es desta Licen�a, elas n�o o livram das condi��es desta -Licen�a. Se voc� n�o puder distribuir de forma a satisfazer -simultaneamente suas obriga��es para com esta Licen�a e para com as -outras obriga��es pertinentes, ent�o como conseq��ncia voc� n�o poder� -distribuir o Programa. Por exemplo, se uma licen�a de patente n�o -permitir� a redistribui��o, livre de "royalties", do Programa, por -todos aqueles que receberem c�pias direta ou indiretamente de voc�, -ent�o a �nica forma de voc� satisfazer a ela e a esta Licen�a seria a -de desistir completamente de distribuir o Programa. -

    -

    -Se qualquer parte desta se��o for considerada inv�lida ou n�o -aplic�vel em qualquer circunst�ncia particular, o restante da se��o se -aplica, e a se��o como um todo se aplica em outras circunst�ncias. -

    -

    -O prop�sito desta se��o n�o � o de induzi-lo a infringir quaisquer -patentes ou reivindica��o de direitos de propriedade outros, ou a -contestar a validade de quaisquer dessas reivindica��es; esta se��o -tem como �nico prop�sito proteger a integridade dos sistemas de -distribui��o de software livres, o que � implementado pela pr�tica de -licen�as p�blicas. V�rias pessoas t�m contribu�do generosamente e em -grande escala para os software distribu�dos usando este sistema, na -certeza de que sua aplica��o � feita de forma consistente; fica a -crit�rio do autor/doador decidir se ele ou ela est� disposto a -distribuir software utilizando outro sistema, e um licenciado n�o pode -impor qualquer escolha. -

    -

    -Esta se��o destina-se a tornar bastante claro o que se acredita ser -conseq��ncia do restante desta Licen�a. -

    -

    -8. Se a distribui��o e/ou uso do Programa s�o restringidos em certos -pa�ses por patentes ou direitos autorais, o detentor dos direitos -autorais original, e que colocou o Programa sob esta Licen�a, pode -incluir uma limita��o geogr�fica de distribui��o, excluindo aqueles -pa�ses de forma a tornar a distribui��o permitida apenas naqueles ou -entre aqueles pa�ses ent�o n�o exclu�dos. Nestes casos, esta Licen�a -incorpora a limita��o como se a mesma constasse escrita nesta Licen�a. -

    -

    -9. A Free Software Foundation pode publicar vers�es revisadas e/ou -novas da Licen�a P�blica Geral de tempos em tempos. Estas novas -vers�es ser�o similares em esp�rito � vers�o atual, mas podem diferir -em detalhes que resolvem novos problemas ou situa��es. -

    -

    -A cada vers�o � dada um n�mero distinto. Se o Programa especifica um -n�mero de vers�o espec�fico desta Licen�a que se aplica a ele e a -"qualquer nova vers�o", voc� tem a op��o de aceitar os termos e -condi��es daquela vers�o ou de qualquer outra vers�o publicada pela -Free Software Foundation. Se o programa n�o especifica um n�mero de -vers�o desta Licen�a, voc� pode escolher qualquer vers�o j� publicada -pela Free Software Foundation. -

    -

    -10. Se voc� pretende incorporar partes do Programa em outros -programas livres cujas condi��es de distribui��o s�o diferentes, -escreva ao autor e solicite permiss�o. Para o software que a Free -Software Foundation det�m direitos autorais, escreva � Free Software -Foundation; �s vezes n�s permitimos exce��es a este caso. Nossa -decis�o ser� guiada pelos dois objetivos de preservar a condi��o de -liberdade de todas as deriva��es do nosso software livre, e de -promover o compartilhamento e reutiliza��o de software em aspectos -gerais. -

    -

    -AUS�NCIA DE GARANTIAS -

    -

    -11. UMA VEZ QUE O PROGRAMA � LICENCIADO SEM �NUS, N�O H� QUALQUER -GARANTIA PARA O PROGRAMA, NA EXTENS�O PERMITIDA PELAS LEIS -APLIC�VEIS. EXCETO QUANDO EXPRESSADO DE FORMA ESCRITA, OS DETENTORES -DOS DIREITOS AUTORAIS E/OU TERCEIROS DISPONIBILIZAM O PROGRAMA "NO -ESTADO", SEM QUALQUER TIPO DE GARANTIAS, EXPRESSAS OU IMPL�CITAS, -INCLUINDO, MAS N�O LIMITADO A, AS GARANTIAS IMPL�CITAS DE -COMERCIALIZA��O E AS DE ADEQUA��O A QUALQUER PROP�SITO. O RISCO TOTAL -COM A QUALIDADE E DESEMPENHO DO PROGRAMA � SEU. SE O PROGRAMA SE -MOSTRAR DEFEITUOSO, VOC� ASSUME OS CUSTOS DE TODAS AS MANUTEN��ES, -REPAROS E CORRE��ES. -

    -

    -12. EM NENHUMA OCASI�O, A MENOS QUE EXIGIDO PELAS LEIS APLIC�VEIS OU -ACORDO ESCRITO, OS DETENTORES DOS DIREITOS AUTORAIS, OU QUALQUER OUTRA -PARTE QUE POSSA MODIFICAR E/OU REDISTRIBUIR O PROGRAMA CONFORME -PERMITIDO ACIMA, SER�O RESPONSABILIZADOS POR VOC� POR DANOS, INCLUINDO -QUALQUER DANO EM GERAL, ESPECIAL, ACIDENTAL OU CONSEQ�ENTE, -RESULTANTES DO USO OU INCAPACIDADE DE USO DO PROGRAMA (INCLUINDO, MAS -N�O LIMITADO A, A PERDA DE DADOS OU DADOS TORNADOS INCORRETOS, OU -PERDAS SOFRIDAS POR VOC� OU POR OUTRAS PARTES, OU FALHAS DO PROGRAMA -AO OPERAR COM QUALQUER OUTRO PROGRAMA), MESMO QUE TAL DETENTOR OU -PARTE TENHAM SIDO AVISADOS DA POSSIBILIDADE DE TAIS DANOS. -

    -

    FIM DOS TERMOS E CONDI��ES

    + + + Licen�a Pública Geral GNU + + +

    LICEN�A P�BLICA GERAL GNU

    +

    Vers�o 2, junho de 1991

    +

    + This is an unofficial translation of the GNU General Public License into + Brazilian Portuguese. It was not published by the Free Software + Foundation, and does not legally state the distribution terms for software + that uses the GNU GPL -- only the original English text of the GNU GPL + does that. However, we hope that this translation will help Brazilian + Portuguese speakers understand the GNU GPL better. +

    +

    + Esta � uma tradu��o n�o-oficial da Licen�a P�blica Geral GNU ("GPL GNU") + para o portugu�s do Brasil. Ela n�o foi publicada pela Free Software + Foundation, e legalmente n�o afirma os termos de distribui��o de software + que utiliza a GPL GNU -- apenas o texto original da GPL GNU, em ingl�s, + faz isso. Contudo, esperamos que esta tradu��o ajude aos que utilizam o + portugu�s do Brasil a entender melhor a GPL GNU. +

    +

    + Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, + Cambridge, MA 02139, USA +

    +

    + A qualquer pessoa � permitido copiar e distribuir c�pias desse documento + de licen�a, desde que sem qualquer altera��o. +

    -

    Como Aplicar Estes Termos aos Seus Novos Programas

    - -

    Se voc� desenvolver um novo programa, e quer que ele seja utilizado -amplamente pelo p�blico, a melhor forma de alcan�ar este objetivo � -torn�-lo software livre que qualquer um pode redistribuir e alterar, -sob estes termos. -

    -

    Para isso, anexe os seguintes avisos ao programa. � mais seguro -anex�-los logo no in�cio de cada arquivo-fonte para refor�arem mais -efetivamente a inexist�ncia de garantias; e cada arquivo deve possuir -pelo menos a linha de "copyright" e uma indica��o de onde o texto -completo se encontra. -

    -

    <uma linha que forne�a o nome do programa e uma id�ia do que ele faz.> - Copyright (C) <ano> <nome do autor> -

    -

    Este programa � software livre; voc� pode redistribu�-lo e/ou - modific�-lo sob os termos da Licen�a P�blica Geral GNU, conforme - publicada pela Free Software Foundation; tanto a vers�o 2 da - Licen�a como (a seu crit�rio) qualquer vers�o mais nova. -

    -

    Este programa � distribu�do na expectativa de ser �til, mas SEM - QUALQUER GARANTIA; sem mesmo a garantia impl�cita de - COMERCIALIZA��O ou de ADEQUA��O A QUALQUER PROP�SITO EM - PARTICULAR. Consulte a Licen�a P�blica Geral GNU para obter mais - detalhes. -

    -

    Voc� deve ter recebido uma c�pia da Licen�a P�blica Geral GNU - junto com este programa; se n�o, escreva para a Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - 02111-1307, USA. -

    -

    Inclua tamb�m informa��es sobre como contact�-lo eletronicamente e por carta.

    -

    Se o programa � interativo, fa�a-o mostrar um aviso breve como este, ao iniciar um modo interativo: -

    -

    Gnomovision vers�o 69, Copyright (C) ano nome do autor - O Gnomovision n�o possui QUALQUER GARANTIA; para obter mais - detalhes digite `show w'. Ele � software livre e voc� est� - convidado a redistribui-lo sob certas condi��es; digite `show c' - para obter detalhes. -

    -

    Os comandos hipot�ticos `show w' e `show c' devem mostrar as partes -apropriadas da Licen�a P�blica Geral. Claro, os comandos que voc� usar -podem ser ativados de outra forma que `show w' e `show c'; eles podem -at� ser cliques do mouse ou itens de um menu -- o que melhor se -adequar ao programa. -

    -

    Voc� tamb�m deve obter do seu empregador (se voc� trabalha como -programador) ou escola, se houver, uma "declara��o de aus�ncia de -direitos autorais" sobre o programa, se necess�rio. Aqui est� um -exemplo; altere os nomes: -

    -

    Yoyodyne, Inc., aqui declara a aus�ncia de quaisquer direitos - autorais sobre o programa `Gnomovision' (que executa interpreta��es - em compiladores) escrito por James Hacker. -

    -

    <assinatura de Ty Coon>, 1o. de abril de 1989 -

    -

    Ty Con, Vice-presidente - -

    -

    Esta Licen�a P�blica Geral n�o permite incorporar seu programa em -programas propriet�rios. Se seu programa � uma biblioteca de -sub-rotinas, voc� deve considerar mais �til permitir ligar aplica��es -propriet�rias com a biblioteca. Se isto � o que voc� deseja, use a -Licen�a P�blica Geral de Bibliotecas GNU, ao inv�s desta Licen�a. -

    - \ No newline at end of file +

    Introdu��o

    + +

    + As licen�as de muitos software s�o desenvolvidas para restringir sua + liberdade de compartilh�-lo e mud�-lo. Contr�ria a isso, a Licen�a P�blica + Geral GNU pretende garantir sua liberdade de compartilhar e alterar + software livres -- garantindo que o software ser� livre e gratuito para os + seus usu�rios. Esta Licen�a P�blica Geral aplica-se � maioria dos software + da Free Software Foundation e a qualquer outro programa cujo autor decida + aplic�-la. (Alguns outros software da FSF s�o cobertos pela Licen�a + P�blica Geral de Bibliotecas, no entanto.) Voc� pode aplic�-la tamb�m aos + seus programas. +

    + +

    + Quando nos referimos a software livre, estamos nos referindo a liberdade e + n�o a pre�o. Nossa Licen�a P�blica Geral foi desenvolvida para garantir + que voc� tenha a liberdade de distribuir c�pias de software livre (e + cobrar por isso, se quiser); que voc� receba o c�digo-fonte ou tenha + acesso a ele, se quiser; que voc� possa mudar o software ou utilizar + partes dele em novos programas livres e gratuitos; e que voc� saiba que + pode fazer tudo isso. +

    + +

    + Para proteger seus direitos, precisamos fazer restri��es que impe�am a + qualquer um negar estes direitos ou solicitar que voc� deles abdique. + Estas restri��es traduzem-se em certas responsabilidades para voc�, se + voc� for distribuir c�pias do software ou modific�-lo. +

    + +

    + Por exemplo, se voc� distribuir c�pias de um programa, gratuitamente ou + por alguma quantia, voc� tem que fornecer aos recebedores todos os + direitos que voc� possui. Voc� tem que garantir que eles tamb�m recebam ou + possam obter o c�digo-fonte. E voc� tem que mostrar-lhes estes termos para + que eles possam conhecer seus direitos. +

    + +

    + N�s protegemos seus direitos em dois passos: (1) com copyright do software + e (2) com a oferta desta licen�a, que lhe d� permiss�o legal para copiar, + distribuir e/ou modificar o software. +

    + +

    + Al�m disso, tanto para a prote��o do autor quanto a nossa, gostar�amos de + certificar-nos que todos entendam que n�o h� qualquer garantia nestes + software livres. Se o software � modificado por algu�m mais e passado + adiante, queremos que seus recebedores saibam que o que eles obtiveram n�o + � original, de forma que qualquer problema introduzido por terceiros n�o + interfira na reputa��o do autor original. +

    + +

    + Finalmente, qualquer programa � amea�ado constantemente por patentes de + software. Queremos evitar o perigo de que distribuidores de software livre + obtenham patentes individuais, o que tem o efeito de tornar o programa + propriet�rio. Para prevenir isso, deixamos claro que qualquer patente tem + que ser licenciada para uso livre e gratuito por qualquer pessoa, ou ent�o + que nem necessite ser licenciada. +

    + +

    + Os termos e condi��es precisas para c�pia, distribui��o e modifica��o se + encontram abaixo: +

    + +

    + LICEN�A P�BLICA GERAL GNU TERMOS E CONDI��ES PARA C�PIA, DISTRIBUI��O E + MODIFICA��O +

    + +

    + 0.Esta licen�a se aplica a qualquer programa ou outro + trabalho que contenha um aviso colocado pelo detentor dos direitos + autorais informando que aquele pode ser distribu�do sob as condi��es desta + Licen�a P�blica Geral. O "Programa" abaixo refere-se a qualquer programa + ou trabalho, e "trabalho baseado no Programa" significa tanto o Programa + em si como quaisquer trabalhos derivados, de acordo com a lei de direitos + autorais: isto quer dizer um trabalho que contenha o Programa ou parte + dele, tanto originalmente ou com modifica��es, e/ou tradu��o para outros + idiomas. (Doravante o processo de tradu��o est� inclu�do sem limites no + termo "modifica��o".) Cada licenciado � mencionado como "voc�". +

    +

    + Atividades outras que a c�pia, a distribui��o e modifica��o n�o est�o + cobertas por esta Licen�a; elas est�o fora de seu escopo. O ato de + executar o Programa n�o � restringido e o resultado do Programa � coberto + apenas se seu conte�do contenha trabalhos baseados no Programa + (independentemente de terem sido gerados pela execu��o do Programa). Se + isso � verdadeiro depende do que o programa faz. +

    + +

    + 1.Voc� pode copiar e distribuir c�pias fi�is do + c�digo-fonte do Programa da mesma forma que voc� o recebeu, usando + qualquer meio, deste que voc� consp�cua e apropriadamente publique em cada + c�pia um aviso de direitos autorais e uma declara��o de inexist�ncia de + garantias; mantenha intactas todos os avisos que se referem a esta Licen�a + e � aus�ncia total de garantias; e forne�a a outros recebedores do + Programa uma c�pia desta Licen�a, junto com o Programa. +

    +

    + Voc� pode cobrar pelo ato f�sico de transferir uma c�pia e pode, + opcionalmente, oferecer garantia em troca de pagamento. +

    +

    + 2. Voc� pode modificar sua c�pia ou c�pias do Programa, + ou qualquer parte dele, assim gerando um trabalho baseado no Programa, e + copiar e distribuir essas modifica��es ou trabalhos sob os temos da se��o + 1 acima, desde que voc� tamb�m se enquadre em todas estas condi��es: +

    +
    +
    + a) Voc� tem que fazer com que os arquivos modificados + levem avisos proeminentes afirmando que voc� alterou os arquivos, + incluindo a data de qualquer altera��o. +
    +
    + +
    +
    + b) Voc� tem que fazer com que quaisquer trabalhos que + voc� distribua ou publique, e que integralmente ou em partes contenham + ou sejam derivados do Programa ou de suas partes, sejam licenciados, + integralmente e sem custo algum para quaisquer terceiros, sob os termos + desta Licen�a. +
    +
    + +
    +
    + c) Se qualquer programa modificado normalmente l� + comandos interativamente quando executados, voc� tem que fazer com que, + quando iniciado tal uso interativo da forma mais simples, seja impresso + ou mostrado um an�ncio de que n�o h� qualquer garantia (ou ent�o que + voc� fornece a garantia) e que os usu�rios podem redistribuir o programa + sob estas condi��es, ainda informando os usu�rios como consultar uma + c�pia desta Licen�a. (Exce��o: se o Programa em si � interativo mas + normalmente n�o imprime estes tipos de an�ncios, seu trabalho baseado no + Programa n�o precisa imprimir um an�ncio.) +
    +
    +

    + Estas exig�ncias aplicam-se ao trabalho modificado como um todo. Se se��es + identific�veis de tal trabalho n�o s�o derivadas do Programa, e podem ser + razoavelmente consideradas trabalhos independentes e separados por si s�, + ent�o esta Licen�a, e seus termos, n�o se aplicam a estas se��es quando + voc� distribui-las como trabalhos em separado. Mas quando voc� distribuir + as mesmas se��es como parte de um todo que � trabalho baseado no Programa, + a distribui��o como um todo tem que se enquadrar nos termos desta Licen�a, + cujas permiss�es para outros licenciados se estendem ao todo, portanto + tamb�m para cada e toda parte independente de quem a escreveu. +

    +

    + Desta forma, esta se��o n�o tem a inten��o de reclamar direitos os + contestar seus direitos sobre o trabalho escrito completamente por voc�; + ao inv�s disso, a inten��o � a de exercitar o direito de controlar a + distribui��o de trabalhos, derivados ou coletivos, baseados no Programa. +

    +

    + Adicionalmente, a mera adi��o ao Programa de outro trabalho n�o baseado no + Programa (ou de trabalho baseado no Programa) em um volume de + armazenamento ou meio de distribui��o n�o faz o outro trabalho parte do + escopo desta Licen�a. +

    +

    + 3. Voc� pode copiar e distribuir o Programa (ou trabalho + baseado nele, conforme descrito na Se��o 2) em c�digo-objeto ou em forma + execut�vel sob os termos das Se��es 1 e 2 acima, desde que voc� fa�a um + dos seguintes: +

    +
    +
    + a)O acompanhe com o c�digo-fonte completo e em forma + acess�vel por m�quinas, que tem que ser distribu�do sob os termos das + Se��es 1 e 2 acima e em meio normalmente utilizado para o interc�mbio de + software; ou, +
    +
    + +
    +
    + b) O acompanhe com uma oferta escrita, v�lida por pelo + menos tr�s anos, de fornecer a qualquer um, com um custo n�o superior ao + custo de distribui��o f�sica do material, uma c�pia do c�digo-fonte + completo e em forma acess�vel por m�quinas, que tem que ser distribu�do + sob os termos das Se��es 1 e 2 acima e em meio normalmente utilizado + para o interc�mbio de software; ou, +
    +
    + +
    +
    +

    + c) O acompanhe com a informa��o que voc� recebeu em + rela��o � oferta de distribui��o do c�digo-fonte correspondente. (Esta + alternativa � permitida somente em distribui��o n�o comerciais, e + apenas se voc� recebeu o programa em forma de c�digo-objeto ou + execut�vel, com oferta de acordo com a Subse��o b acima.) +

    +
    +
    +

    + O c�digo-fonte de um trabalho corresponde � forma de trabalho preferida + para se fazer modifica��es. Para um trabalho em forma execut�vel, o + c�digo-fonte completo significa todo o c�digo-fonte de todos os m�dulos + que ele cont�m, mais quaisquer arquivos de defini��o de "interface", mais + os "scripts" utilizados para se controlar a compila��o e a instala��o do + execut�vel. Contudo, como exce��o especial, o c�digo-fonte distribu�do n�o + precisa incluir qualquer componente normalmente distribu�do (tanto em + forma original quanto bin�ria) com os maiores componentes (o compilador, o + "kernel" etc.) do sistema operacional sob o qual o execut�vel funciona, a + menos que o componente em si acompanhe o execut�vel. +

    +

    + Se a distribui��o do execut�vel ou c�digo-objeto � feita atrav�s da oferta + de acesso a c�pias de algum lugar, ent�o ofertar o acesso equivalente a + c�pia, do mesmo lugar, do c�digo-fonte equivale � distribui��o do + c�digo-fonte, mesmo que terceiros n�o sejam compelidos a copiar o + c�digo-fonte com o c�digo-objeto. +

    +

    + 4. Voc� n�o pode copiar, modificar, sub-licenciar ou + distribuir o Programa, exceto de acordo com as condi��es expressas nesta + Licen�a. Qualquer outra tentativa de c�pia, modifica��o, sub-licenciamento + ou distribui��o do Programa n�o � valida, e cancelar� automaticamente os + direitos que lhe foram fornecidos por esta Licen�a. No entanto, terceiros + que de voc� receberam c�pias ou direitos, fornecidos sob os termos desta + Licen�a, n�o ter�o suas licen�as terminadas, desde que permane�am em total + concord�ncia com ela. +

    +

    + 5. Voc� n�o � obrigado a aceitar esta Licen�a j� que n�o + a assinou. No entanto, nada mais o dar� permiss�o para modificar ou + distribuir o Programa ou trabalhos derivados deste. Estas a��es s�o + proibidas por lei, caso voc� n�o aceite esta Licen�a. Desta forma, ao + modificar ou distribuir o Programa (ou qualquer trabalho derivado do + Programa), voc� estar� indicando sua total aceita��o desta Licen�a para + faz�-los, e todos os seus termos e condi��es para copiar, distribuir ou + modificar o Programa, ou trabalhos baseados nele. +

    +

    + 6. Cada vez que voc� redistribuir o Programa (ou qualquer + trabalho baseado nele), os recebedores adquirir�o automaticamente do + licenciador original uma licen�a para copiar, distribuir ou modificar o + Programa, sujeitos a estes termos e condi��es. Voc� n�o poder� impor aos + recebedores qualquer outra restri��o ao exerc�cio dos direitos ent�o + adquiridos. Voc� n�o � respons�vel em garantir a concord�ncia de terceiros + a esta Licen�a. +

    +

    + 7. Se, em conseq��ncia de decis�es judiciais ou alega��es + de infringimento de patentes ou quaisquer outras raz�es (n�o limitadas a + assuntos relacionados a patentes), condi��es forem impostas a voc� (por + ordem judicial, acordos ou outras formas) e que contradigam as condi��es + desta Licen�a, elas n�o o livram das condi��es desta Licen�a. Se voc� n�o + puder distribuir de forma a satisfazer simultaneamente suas obriga��es + para com esta Licen�a e para com as outras obriga��es pertinentes, ent�o + como conseq��ncia voc� n�o poder� distribuir o Programa. Por exemplo, se + uma licen�a de patente n�o permitir� a redistribui��o, livre de + "royalties", do Programa, por todos aqueles que receberem c�pias direta ou + indiretamente de voc�, ent�o a �nica forma de voc� satisfazer a ela e a + esta Licen�a seria a de desistir completamente de distribuir o Programa. +

    +

    + Se qualquer parte desta se��o for considerada inv�lida ou n�o aplic�vel em + qualquer circunst�ncia particular, o restante da se��o se aplica, e a + se��o como um todo se aplica em outras circunst�ncias. +

    +

    + O prop�sito desta se��o n�o � o de induzi-lo a infringir quaisquer + patentes ou reivindica��o de direitos de propriedade outros, ou a + contestar a validade de quaisquer dessas reivindica��es; esta se��o tem + como �nico prop�sito proteger a integridade dos sistemas de distribui��o + de software livres, o que � implementado pela pr�tica de licen�as + p�blicas. V�rias pessoas t�m contribu�do generosamente e em grande escala + para os software distribu�dos usando este sistema, na certeza de que sua + aplica��o � feita de forma consistente; fica a crit�rio do autor/doador + decidir se ele ou ela est� disposto a distribuir software utilizando outro + sistema, e um licenciado n�o pode impor qualquer escolha. +

    +

    + Esta se��o destina-se a tornar bastante claro o que se acredita ser + conseq��ncia do restante desta Licen�a. +

    +

    + 8. Se a distribui��o e/ou uso do Programa s�o + restringidos em certos pa�ses por patentes ou direitos autorais, o + detentor dos direitos autorais original, e que colocou o Programa sob esta + Licen�a, pode incluir uma limita��o geogr�fica de distribui��o, excluindo + aqueles pa�ses de forma a tornar a distribui��o permitida apenas naqueles + ou entre aqueles pa�ses ent�o n�o exclu�dos. Nestes casos, esta Licen�a + incorpora a limita��o como se a mesma constasse escrita nesta Licen�a. +

    +

    + 9. A Free Software Foundation pode publicar vers�es + revisadas e/ou novas da Licen�a P�blica Geral de tempos em tempos. Estas + novas vers�es ser�o similares em esp�rito � vers�o atual, mas podem + diferir em detalhes que resolvem novos problemas ou situa��es. +

    +

    + A cada vers�o � dada um n�mero distinto. Se o Programa especifica um + n�mero de vers�o espec�fico desta Licen�a que se aplica a ele e a + "qualquer nova vers�o", voc� tem a op��o de aceitar os termos e condi��es + daquela vers�o ou de qualquer outra vers�o publicada pela Free Software + Foundation. Se o programa n�o especifica um n�mero de vers�o desta + Licen�a, voc� pode escolher qualquer vers�o j� publicada pela Free + Software Foundation. +

    +

    + 10. Se voc� pretende incorporar partes do Programa em + outros programas livres cujas condi��es de distribui��o s�o diferentes, + escreva ao autor e solicite permiss�o. Para o software que a Free Software + Foundation det�m direitos autorais, escreva � Free Software Foundation; �s + vezes n�s permitimos exce��es a este caso. Nossa decis�o ser� guiada pelos + dois objetivos de preservar a condi��o de liberdade de todas as deriva��es + do nosso software livre, e de promover o compartilhamento e reutiliza��o + de software em aspectos gerais. +

    +

    AUS�NCIA DE GARANTIAS

    +

    + 11. UMA VEZ QUE O PROGRAMA � LICENCIADO SEM �NUS, N�O H� + QUALQUER GARANTIA PARA O PROGRAMA, NA EXTENS�O PERMITIDA PELAS LEIS + APLIC�VEIS. EXCETO QUANDO EXPRESSADO DE FORMA ESCRITA, OS DETENTORES DOS + DIREITOS AUTORAIS E/OU TERCEIROS DISPONIBILIZAM O PROGRAMA "NO ESTADO", + SEM QUALQUER TIPO DE GARANTIAS, EXPRESSAS OU IMPL�CITAS, INCLUINDO, MAS + N�O LIMITADO A, AS GARANTIAS IMPL�CITAS DE COMERCIALIZA��O E AS DE + ADEQUA��O A QUALQUER PROP�SITO. O RISCO TOTAL COM A QUALIDADE E DESEMPENHO + DO PROGRAMA � SEU. SE O PROGRAMA SE MOSTRAR DEFEITUOSO, VOC� ASSUME OS + CUSTOS DE TODAS AS MANUTEN��ES, REPAROS E CORRE��ES. +

    +

    + 12. EM NENHUMA OCASI�O, A MENOS QUE EXIGIDO PELAS LEIS + APLIC�VEIS OU ACORDO ESCRITO, OS DETENTORES DOS DIREITOS AUTORAIS, OU + QUALQUER OUTRA PARTE QUE POSSA MODIFICAR E/OU REDISTRIBUIR O PROGRAMA + CONFORME PERMITIDO ACIMA, SER�O RESPONSABILIZADOS POR VOC� POR DANOS, + INCLUINDO QUALQUER DANO EM GERAL, ESPECIAL, ACIDENTAL OU CONSEQ�ENTE, + RESULTANTES DO USO OU INCAPACIDADE DE USO DO PROGRAMA (INCLUINDO, MAS N�O + LIMITADO A, A PERDA DE DADOS OU DADOS TORNADOS INCORRETOS, OU PERDAS + SOFRIDAS POR VOC� OU POR OUTRAS PARTES, OU FALHAS DO PROGRAMA AO OPERAR + COM QUALQUER OUTRO PROGRAMA), MESMO QUE TAL DETENTOR OU PARTE TENHAM SIDO + AVISADOS DA POSSIBILIDADE DE TAIS DANOS. +

    +

    FIM DOS TERMOS E CONDI��ES

    + +

    Como Aplicar Estes Termos aos Seus Novos Programas

    + +

    + Se voc� desenvolver um novo programa, e quer que ele seja utilizado + amplamente pelo p�blico, a melhor forma de alcan�ar este objetivo � + torn�-lo software livre que qualquer um pode redistribuir e alterar, sob + estes termos. +

    +

    + Para isso, anexe os seguintes avisos ao programa. � mais seguro anex�-los + logo no in�cio de cada arquivo-fonte para refor�arem mais efetivamente a + inexist�ncia de garantias; e cada arquivo deve possuir pelo menos a linha + de "copyright" e uma indica��o de onde o texto completo se encontra. +

    +

    + <uma linha que forne�a o nome do programa e uma id�ia do que ele + faz.> Copyright (C) <ano> <nome do autor> +

    +

    + Este programa � software livre; voc� pode redistribu�-lo e/ou modific�-lo + sob os termos da Licen�a P�blica Geral GNU, conforme publicada pela Free + Software Foundation; tanto a vers�o 2 da Licen�a como (a seu crit�rio) + qualquer vers�o mais nova. +

    +

    + Este programa � distribu�do na expectativa de ser �til, mas SEM QUALQUER + GARANTIA; sem mesmo a garantia impl�cita de COMERCIALIZA��O ou de + ADEQUA��O A QUALQUER PROP�SITO EM PARTICULAR. Consulte a Licen�a P�blica + Geral GNU para obter mais detalhes. +

    +

    + Voc� deve ter recebido uma c�pia da Licen�a P�blica Geral GNU junto com + este programa; se n�o, escreva para a Free Software Foundation, Inc., 59 + Temple Place, Suite 330, Boston, MA 02111-1307, USA. +

    +

    + Inclua tamb�m informa��es sobre como contact�-lo eletronicamente e por + carta. +

    +

    + Se o programa � interativo, fa�a-o mostrar um aviso breve como este, ao + iniciar um modo interativo: +

    +

    + Gnomovision vers�o 69, Copyright (C) ano nome do autor O Gnomovision n�o + possui QUALQUER GARANTIA; para obter mais detalhes digite `show w'. Ele � + software livre e voc� est� convidado a redistribui-lo sob certas + condi��es; digite `show c' para obter detalhes. +

    +

    + Os comandos hipot�ticos `show w' e `show c' devem mostrar as partes + apropriadas da Licen�a P�blica Geral. Claro, os comandos que voc� usar + podem ser ativados de outra forma que `show w' e `show c'; eles podem at� + ser cliques do mouse ou itens de um menu -- o que melhor se adequar ao + programa. +

    +

    + Voc� tamb�m deve obter do seu empregador (se voc� trabalha como + programador) ou escola, se houver, uma "declara��o de aus�ncia de direitos + autorais" sobre o programa, se necess�rio. Aqui est� um exemplo; altere os + nomes: +

    +

    + Yoyodyne, Inc., aqui declara a aus�ncia de quaisquer direitos autorais + sobre o programa `Gnomovision' (que executa interpreta��es em + compiladores) escrito por James Hacker. +

    +

    <assinatura de Ty Coon>, 1o. de abril de 1989

    +

    Ty Con, Vice-presidente

    +

    + Esta Licen�a P�blica Geral n�o permite incorporar seu programa em + programas propriet�rios. Se seu programa � uma biblioteca de sub-rotinas, + voc� deve considerar mais �til permitir ligar aplica��es propriet�rias com + a biblioteca. Se isto � o que voc� deseja, use a Licen�a P�blica Geral de + Bibliotecas GNU, ao inv�s desta Licen�a. +

    + + diff --git a/pandora_console/general/links_menu.php b/pandora_console/general/links_menu.php index e85a29a380..89ea87f6e1 100644 --- a/pandora_console/general/links_menu.php +++ b/pandora_console/general/links_menu.php @@ -4,24 +4,21 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - $sql = 'SELECT link, name FROM tlink ORDER BY name'; -$result = db_get_all_rows_sql ($sql); +$result = db_get_all_rows_sql($sql); if ($result !== false) { - echo '
    :: '.__('Links').' ::
    '; - echo ''; + echo '
    :: '.__('Links').' ::
    '; + echo ''; } -?> diff --git a/pandora_console/general/login_help_dialog.php b/pandora_console/general/login_help_dialog.php index 6e38d4ece0..323b465d5a 100644 --- a/pandora_console/general/login_help_dialog.php +++ b/pandora_console/general/login_help_dialog.php @@ -4,11 +4,9 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the @@ -21,113 +19,136 @@ global $config; if (is_ajax()) { - $skip_login_help = get_parameter('skip_login_help', 0); - - // Updates config['skip_login_help_dialog'] in order to don't show login help message - if ($skip_login_help) { - if (isset ($config['skip_login_help_dialog'])) - $result_config = db_process_sql_update('tconfig', array("value" => 1), array("token" => "skip_login_help_dialog")); - else - $result_config = db_process_sql_insert ('tconfig', array ("value" => 1, "token" => "skip_login_help_dialog")); - } - - return; + $skip_login_help = get_parameter('skip_login_help', 0); + + // Updates config['skip_login_help_dialog'] in order to don't show login help message + if ($skip_login_help) { + if (isset($config['skip_login_help_dialog'])) { + $result_config = db_process_sql_update('tconfig', ['value' => 1], ['token' => 'skip_login_help_dialog']); + } else { + $result_config = db_process_sql_insert('tconfig', ['value' => 1, 'token' => 'skip_login_help_dialog']); + } + } + + return; } // Prints help dialog information -echo '
    '; - - echo '
    '; - echo __("If this is your first time using %s, we suggest a few links that'll help you learn more about the software. Monitoring can be overwhelming, but take your time to learn how to harness the power of %s!", - get_product_name(), get_product_name()); - echo '
    '; - - echo '
    '; - echo ''; - echo ''; - echo ''; - - echo ''; - - echo ''; - - echo ''; - echo ''; - echo '
    '; - echo '' . - html_print_image('images/online_help.png', true, - array("alt" => __('Online help'), "border" => 0)) . ''; - echo '
    '; - echo '' . __('Online help') . ''; - echo '
    '; - echo '' . - html_print_image('images/enterprise_version.png', true, - array("alt" => __('Enterprise version'), "border" => 0)) . ''; - echo '
    '; - echo '' . __('Enterprise version') . ''; - echo '
    '; - echo '' . - html_print_image('images/support.png', true, - array("alt" => __('Support'), "border" => 0)) . ''; - echo '
    '; - echo '' . __('Support') . ' / ' . __('Forums') . ''; - echo '
    '; - echo '' . - html_print_image('images/documentation.png', true, - array("alt" => __('Documentation'), "border" => 0)) . ''; - echo '
    '; - echo '' . __('Documentation') . ''; - echo '
    '; - echo '
    '; - - echo '
    '; - echo '
    '; - html_print_checkbox('skip_login_help', 1, false, false, false, 'cursor: \'pointer\''); - echo ' ' .__("Click here to don't show again this message") . ''; - echo '
    '; - echo '
    '; - html_print_submit_button("Ok", 'hide-login-help', false, 'class="ui-button-dialog ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok" style="width:100px;"'); - echo '
    '; - echo '
    '; - -echo '
    '; -?> +echo '
    '; + + echo '
    '; + echo __( + "If this is your first time using %s, we suggest a few links that'll help you learn more about the software. Monitoring can be overwhelming, but take your time to learn how to harness the power of %s!", + get_product_name(), + get_product_name() + ); + echo '
    '; + + echo '
    '; + echo ''; + echo ''; + echo ''; + + echo ''; + + echo ''; + + echo ''; + echo ''; + echo '
    '; + echo ''.html_print_image( + 'images/online_help.png', + true, + [ + 'alt' => __('Online help'), + 'border' => 0, + ] + ).''; + echo '
    '; + echo ''.__('Online help').''; + echo '
    '; + echo ''.html_print_image( + 'images/enterprise_version.png', + true, + [ + 'alt' => __('Enterprise version'), + 'border' => 0, + ] + ).''; + echo '
    '; + echo ''.__('Enterprise version').''; + echo '
    '; + echo ''.html_print_image( + 'images/support.png', + true, + [ + 'alt' => __('Support'), + 'border' => 0, + ] + ).''; + echo '
    '; + echo ''.__('Support').' / '.__('Forums').''; + echo '
    '; + echo ''.html_print_image( + 'images/documentation.png', + true, + [ + 'alt' => __('Documentation'), + 'border' => 0, + ] + ).''; + echo '
    '; + echo ''.__('Documentation').''; + echo '
    '; + echo '
    '; + + echo '
    '; + echo '
    '; + html_print_checkbox('skip_login_help', 1, false, false, false, 'cursor: \'pointer\''); + echo ' '.__("Click here to don't show again this message").''; + echo '
    '; + echo '
    '; + html_print_submit_button('Ok', 'hide-login-help', false, 'class="ui-button-dialog ui-widget ui-state-default ui-corner-all ui-button-text-only sub ok" style="width:100px;"'); + echo '
    '; + echo '
    '; + + echo '
    '; + ?> diff --git a/pandora_console/general/login_required.php b/pandora_console/general/login_required.php index 1522ac8008..726d6ab5d1 100644 --- a/pandora_console/general/login_required.php +++ b/pandora_console/general/login_required.php @@ -4,11 +4,9 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the @@ -21,119 +19,154 @@ global $config; if (is_ajax()) { - - $save_identification = get_parameter ('save_required_wizard', 0); - $change_language = get_parameter ('change_language', 0); - $cancel_wizard = get_parameter ('cancel_wizard', 0); - - // Updates the values get on the identification wizard - if ($save_identification) { - $email = get_parameter ('email', false); - $timezone = get_parameter ('timezone', false); - $language = get_parameter ('language', false); - - if ($email !== false) config_update_value ('language', $language); - if ($timezone !== false) config_update_value ('timezone', $timezone); - if ($email !== false) db_process_sql_update ('tusuario', - array ('email' => $email), array('id_user' => $config['id_user'])); - - // Update the alert action Mail to XXX/Administrator if it is set to default - $mail_check = 'yourmail@domain.es'; - $mail_alert = alerts_get_alert_action_field1(1); - if ($mail_check === $mail_alert && $email !== false) { - alerts_update_alert_action (1, array('field1' => $email, - 'field1_recovery' => $email)); - } - - config_update_value ('initial_wizard', 1); - } - - //Change the language if is change in checkbox - if ($change_language !== 0) { - config_update_value ('language', $change_language); - } - - if ($cancel_wizard !== 0) { - config_update_value ('initial_wizard', 1); - } - - return; + $save_identification = get_parameter('save_required_wizard', 0); + $change_language = get_parameter('change_language', 0); + $cancel_wizard = get_parameter('cancel_wizard', 0); + + // Updates the values get on the identification wizard + if ($save_identification) { + $email = get_parameter('email', false); + $timezone = get_parameter('timezone', false); + $language = get_parameter('language', false); + + if ($email !== false) { + config_update_value('language', $language); + } + + if ($timezone !== false) { + config_update_value('timezone', $timezone); + } + + if ($email !== false) { + db_process_sql_update( + 'tusuario', + ['email' => $email], + ['id_user' => $config['id_user']] + ); + } + + // Update the alert action Mail to XXX/Administrator if it is set to default + $mail_check = 'yourmail@domain.es'; + $mail_alert = alerts_get_alert_action_field1(1); + if ($mail_check === $mail_alert && $email !== false) { + alerts_update_alert_action( + 1, + [ + 'field1' => $email, + 'field1_recovery' => $email, + ] + ); + } + + config_update_value('initial_wizard', 1); + } + + // Change the language if is change in checkbox + if ($change_language !== 0) { + config_update_value('language', $change_language); + } + + if ($cancel_wizard !== 0) { + config_update_value('initial_wizard', 1); + } + + return; } -$email = db_get_value ('email', 'tusuario', 'id_user', $config['id_user']); -//Avoid to show default email -if ($email == 'admin@example.com') $email = ''; +$email = db_get_value('email', 'tusuario', 'id_user', $config['id_user']); +// Avoid to show default email +if ($email == 'admin@example.com') { + $email = ''; +} // Prints first step pandora registration -echo ''; + + ?> diff --git a/pandora_console/general/news_dialog.php b/pandora_console/general/news_dialog.php index a451a75467..37ca016edf 100644 --- a/pandora_console/general/news_dialog.php +++ b/pandora_console/general/news_dialog.php @@ -4,11 +4,9 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the @@ -20,87 +18,87 @@ global $config; -$options = array(); +$options = []; $options['id_user'] = $config['id_user']; $options['modal'] = true; $news = get_news($options); // Clean subject entities -foreach($news as $k => $v) { - $news[$k]['text'] = io_safe_output($v['text']); - $news[$k]['subject'] = io_safe_output($v['subject']); +foreach ($news as $k => $v) { + $news[$k]['text'] = io_safe_output($v['text']); + $news[$k]['subject'] = io_safe_output($v['subject']); } if (!empty($news)) { - $options = array(); - $options['id'] = 'news_json'; - $options['hidden'] = 1; - $options['content'] = base64_encode(json_encode($news)); - html_print_div($options); + $options = []; + $options['id'] = 'news_json'; + $options['hidden'] = 1; + $options['content'] = base64_encode(json_encode($news)); + html_print_div($options); } // Prints news dialog template echo ''; -ui_require_javascript_file ('encode_decode_base64'); +ui_require_javascript_file('encode_decode_base64'); ?> "; -} +} if ($agentData === false) { - ui_print_info_message ( array ( 'no_close' => true, 'message' => - __("There is no GIS data for this agent, so it's positioned in default position of map.") ) ); + ui_print_info_message( + [ + 'no_close' => true, + 'message' => __("There is no GIS data for this agent, so it's positioned in default position of map."), + ] + ); } -ui_print_warning_message (array ( 'no_close' => true, 'message' => - __("When you change the Agent position, the agent automatically activates the 'Ignore new GIS data' option") ) ); + +ui_print_warning_message( + [ + 'no_close' => true, + 'message' => __("When you change the Agent position, the agent automatically activates the 'Ignore new GIS data' option"), + ] +); $table->width = '100%'; $table->class = 'databox filters'; -$table->data = array(); +$table->data = []; $table->cellpadding = 0; $table->cellspacing = 0; -$table->head[0] =__('Agent position'); +$table->head[0] = __('Agent position'); $table->head_colspan[0] = 4; -$table->headstyle[0] = "text-align:center"; +$table->headstyle[0] = 'text-align:center'; $table->style[0] = 'font-weight: bold; '; $table->style[2] = 'font-weight: bold; '; $table->data[1][0] = __('Latitude: '); -$table->data[1][1] = html_print_input_text_extended ('latitude', $agentData['stored_latitude'], 'text-latitude', '', 20, 20, false, '', - array('onchange' => "setIgnoreGISDataEnabled()", 'onkeyup' => "setIgnoreGISDataEnabled()"), true); +$table->data[1][1] = html_print_input_text_extended( + 'latitude', + $agentData['stored_latitude'], + 'text-latitude', + '', + 20, + 20, + false, + '', + [ + 'onchange' => 'setIgnoreGISDataEnabled()', + 'onkeyup' => 'setIgnoreGISDataEnabled()', + ], + true +); $table->data[1][2] = __('Longitude: '); -$table->data[1][3] = html_print_input_text_extended ('longitude', $agentData['stored_longitude'], 'text-longitude', '', 20, 20, false, '', - array('onchange' => "setIgnoreGISDataEnabled()", 'onkeyup' => "setIgnoreGISDataEnabled()"), true); +$table->data[1][3] = html_print_input_text_extended( + 'longitude', + $agentData['stored_longitude'], + 'text-longitude', + '', + 20, + 20, + false, + '', + [ + 'onchange' => 'setIgnoreGISDataEnabled()', + 'onkeyup' => 'setIgnoreGISDataEnabled()', + ], + true +); $table->data[2][0] = __('Altitude: '); -$table->data[2][1] = html_print_input_text_extended ('altitude', $agentData['stored_altitude'], 'text-altitude', '', 10, 10, false, '', - array('onchange' => "setIgnoreGISDataEnabled()", 'onkeyup' => "setIgnoreGISDataEnabled()"), true); +$table->data[2][1] = html_print_input_text_extended( + 'altitude', + $agentData['stored_altitude'], + 'text-altitude', + '', + 10, + 10, + false, + '', + [ + 'onchange' => 'setIgnoreGISDataEnabled()', + 'onkeyup' => 'setIgnoreGISDataEnabled()', + ], + true +); $table->data[2][2] = __('Ignore new GIS data:'); -$table->data[2][3] = __('Yes').' '.html_print_radio_button_extended ("update_gis_data", 0, '', $updateGisData, false, '', 'style="margin-right: 40px;"', true); -$table->data[2][3] .= __('No').' '.html_print_radio_button_extended ("update_gis_data", 1, '', $updateGisData, false, '', 'style="margin-right: 40px;"', true); +$table->data[2][3] = __('Yes').' '.html_print_radio_button_extended('update_gis_data', 0, '', $updateGisData, false, '', 'style="margin-right: 40px;"', true); +$table->data[2][3] .= __('No').' '.html_print_radio_button_extended('update_gis_data', 1, '', $updateGisData, false, '', 'style="margin-right: 40px;"', true); $url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=gis&id_agente='.$id_agente; -echo "
    "; +echo ""; html_print_input_hidden('update_gis', 1); html_print_table($table); -echo '
    '; -html_print_submit_button (__('Update'), '', false, 'class="sub upd"'); +echo '
    '; +html_print_submit_button(__('Update'), '', false, 'class="sub upd"'); echo '
    '; -echo ""; +echo ''; ?> diff --git a/pandora_console/godmode/agentes/agent_disk_conf_editor.php b/pandora_console/godmode/agentes/agent_disk_conf_editor.php index b4dd78253f..e1fa566f2d 100644 --- a/pandora_console/godmode/agentes/agent_disk_conf_editor.php +++ b/pandora_console/godmode/agentes/agent_disk_conf_editor.php @@ -1,10 +1,10 @@ "Pandora FMS Enterprise", - "message" => "

    This feature is not included on the Open Source version. Please visit our website to learn more about the advanced features of Pandora FMS Enterprise edition

    ", - "no_close" => 1); - - ui_print_info_message($message); +if (enterprise_include('godmode/agentes/agent_disk_conf_editor.php') === ENTERPRISE_NOT_HOOK) { + $message = [ + 'title' => 'Pandora FMS Enterprise', + 'message' => "

    This feature is not included on the Open Source version. Please visit our website to learn more about the advanced features of Pandora FMS Enterprise edition

    ", + 'no_close' => 1, + ]; + + ui_print_info_message($message); } -?> diff --git a/pandora_console/godmode/agentes/agent_incidents.php b/pandora_console/godmode/agentes/agent_incidents.php index e81d213dc0..e11e28481f 100644 --- a/pandora_console/godmode/agentes/agent_incidents.php +++ b/pandora_console/godmode/agentes/agent_incidents.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,75 +11,79 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -require_once ('include/functions_incidents.php'); +require_once 'include/functions_incidents.php'; -check_login (); +check_login(); $group = $id_grupo; -if (! check_acl ($config["id_user"], $group, "AW", $id_agente)) { - db_pandora_audit("ACL Violation", - "Trying to access agent manager"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], $group, 'AW', $id_agente)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access agent manager' + ); + include 'general/noaccess.php'; + return; } -$offset = (int) get_parameter("offset", 0); +$offset = (int) get_parameter('offset', 0); -//See if id_agente is set (either POST or GET, otherwise -1 -$id_agent = (int) get_parameter ("id_agente"); -$groups = users_get_groups ($config["id_user"], "IR"); -$filter = ' AND id_agent = ' . $id_agent; -$url = "index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=incident&id_agente=" . $id_agent; +// See if id_agente is set (either POST or GET, otherwise -1 +$id_agent = (int) get_parameter('id_agente'); +$groups = users_get_groups($config['id_user'], 'IR'); +$filter = ' AND id_agent = '.$id_agent; +$url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=incident&id_agente='.$id_agent; -//Select incidencts where the user has access to ($groups from -//get_user_groups), array_keys for the id, implode to pass to SQL -switch ($config["dbtype"]) { - case 'mysql': - $sql = "SELECT * FROM tincidencia WHERE - id_grupo IN (".implode (",",array_keys ($groups)).")".$filter." - ORDER BY actualizacion DESC LIMIT ".$offset.",".$config["block_size"]; - break; - case 'oracle': - $sql = "SELECT * FROM tincidencia WHERE - id_grupo IN (".implode (",",array_keys ($groups)).")".$filter." - AND rownum <= " . $offset.",".$config["block_size"] . " - ORDER BY actualizacion DESC"; - break; +// Select incidencts where the user has access to ($groups from +// get_user_groups), array_keys for the id, implode to pass to SQL +switch ($config['dbtype']) { + case 'mysql': + $sql = 'SELECT * FROM tincidencia WHERE + id_grupo IN ('.implode(',', array_keys($groups)).')'.$filter.' + ORDER BY actualizacion DESC LIMIT '.$offset.','.$config['block_size']; + break; + + case 'oracle': + $sql = 'SELECT * FROM tincidencia WHERE + id_grupo IN ('.implode(',', array_keys($groups)).')'.$filter.' + AND rownum <= '.$offset.','.$config['block_size'].' + ORDER BY actualizacion DESC'; + break; } -$result = db_get_all_rows_sql ($sql); -$count_sql = "SELECT count(*) FROM tincidencia WHERE - id_grupo IN (".implode (",",array_keys ($groups)).")".$filter." - ORDER BY actualizacion DESC"; +$result = db_get_all_rows_sql($sql); -$count = db_get_value_sql ($count_sql); +$count_sql = 'SELECT count(*) FROM tincidencia WHERE + id_grupo IN ('.implode(',', array_keys($groups)).')'.$filter.' + ORDER BY actualizacion DESC'; -if (empty ($result)) { - $result = array (); - $count = 0; - echo '
    '.__('No incidents associated to this agent').'

    '; - return; +$count = db_get_value_sql($count_sql); + +if (empty($result)) { + $result = []; + $count = 0; + echo '
    '.__('No incidents associated to this agent').'

    '; + return; } // Show pagination -ui_pagination ($count, $url, $offset, 0, false, 'offset'); //($count + $offset) it's real count of incidents because it's use LIMIT $offset in query. +ui_pagination($count, $url, $offset, 0, false, 'offset'); +// ($count + $offset) it's real count of incidents because it's use LIMIT $offset in query. echo '
    '; // Show headers -$table->width = "100%"; -$table->class = "databox"; +$table->width = '100%'; +$table->class = 'databox'; $table->cellpadding = 4; $table->cellspacing = 4; -$table->head = array (); -$table->data = array (); -$table->size = array (); -$table->align = array (); +$table->head = []; +$table->data = []; +$table->size = []; +$table->align = []; $table->head[0] = __('ID'); $table->head[1] = __('Status'); @@ -94,43 +97,46 @@ $table->head[7] = __('Owner'); $table->size[0] = 43; $table->size[7] = 50; -$table->align[1] = "center"; -$table->align[3] = "center"; -$table->align[4] = "center"; - +$table->align[1] = 'center'; +$table->align[3] = 'center'; +$table->align[4] = 'center'; + $rowPair = true; $iterator = 0; foreach ($result as $row) { - if ($rowPair) - $table->rowclass[$iterator] = 'rowPair'; - else - $table->rowclass[$iterator] = 'rowOdd'; - $rowPair = !$rowPair; - $iterator++; - - $data = array(); + if ($rowPair) { + $table->rowclass[$iterator] = 'rowPair'; + } else { + $table->rowclass[$iterator] = 'rowOdd'; + } - $data[0] = ''.$row["id_incidencia"].''; - $attach = incidents_get_attach ($row["id_incidencia"]); - - if (!empty ($attach)) - $data[0] .= '  '.html_print_image ("images/attachment.png", true, array ("style" => "align:middle;")); - - $data[1] = incidents_print_status_img ($row["estado"], true); - $data[2] = ''.substr(io_safe_output($row["titulo"]),0,45).''; - $data[3] = incidents_print_priority_img ($row["prioridad"], true); - $data[4] = ui_print_group_icon ($row["id_grupo"], true); - $data[5] = ui_print_timestamp ($row["actualizacion"], true); - $data[6] = $row["origen"]; - $data[7] = ui_print_username ($row["id_usuario"], true); + $rowPair = !$rowPair; + $iterator++; - array_push ($table->data, $data); + $data = []; + + $data[0] = ''.$row['id_incidencia'].''; + $attach = incidents_get_attach($row['id_incidencia']); + + if (!empty($attach)) { + $data[0] .= '  '.html_print_image('images/attachment.png', true, ['style' => 'align:middle;']); + } + + $data[1] = incidents_print_status_img($row['estado'], true); + $data[2] = ''.substr(io_safe_output($row['titulo']), 0, 45).''; + $data[3] = incidents_print_priority_img($row['prioridad'], true); + $data[4] = ui_print_group_icon($row['id_grupo'], true); + $data[5] = ui_print_timestamp($row['actualizacion'], true); + $data[6] = $row['origen']; + $data[7] = ui_print_username($row['id_usuario'], true); + + array_push($table->data, $data); } -html_print_table ($table); + +html_print_table($table); echo '
    '; -unset ($table); +unset($table); echo '

    '; echo '
     
    '; -?> diff --git a/pandora_console/godmode/agentes/agent_manager.php b/pandora_console/godmode/agentes/agent_manager.php index 4e6be0e725..004c947af4 100644 --- a/pandora_console/godmode/agentes/agent_manager.php +++ b/pandora_console/godmode/agentes/agent_manager.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,843 +11,1014 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars -enterprise_include ('godmode/agentes/agent_manager.php'); +enterprise_include('godmode/agentes/agent_manager.php'); -require_once ('include/functions_clippy.php'); -require_once ('include/functions_servers.php'); -require_once ('include/functions_gis.php'); -require_once($config['homedir'] . "/include/functions_agents.php"); -require_once ($config['homedir'] . '/include/functions_users.php'); +require_once 'include/functions_clippy.php'; +require_once 'include/functions_servers.php'; +require_once 'include/functions_gis.php'; +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_users.php'; -if (is_ajax ()) { - - global $config; - - $search_parents_2 = (bool) get_parameter ('search_parents_2'); - - if ($search_parents_2) { - require_once ('include/functions_agents.php'); - - $id_agent = (int) get_parameter ('id_agent'); - $string = (string) get_parameter ('q'); /* q is what autocomplete plugin gives */ - - $filter = array (); - - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $filter[] = '(nombre COLLATE utf8_general_ci LIKE "%' . $string . '%" OR direccion LIKE "%'.$string.'%" OR comentarios LIKE "%'.$string.'%" OR alias LIKE "%'.$string.'%")'; - break; - case "oracle": - $filter[] = '(upper(nombre) LIKE upper(\'%'.$string.'%\') OR upper(direccion) LIKE upper(\'%'.$string.'%\') OR upper(comentarios) LIKE upper(\'%'.$string.'%\') OR upper(alias) LIKE upper(\'%'.$string.'%\'))'; - break; - } - $filter[] = 'id_agente != ' . $id_agent; - - $agents = agents_get_agents ($filter, array ('id_agente', 'nombre', 'direccion')); - if ($agents === false) - $agents = array(); - - $data = array(); - foreach ($agents as $agent) { - $data[] = array('id' => $agent['id_agente'], - 'name' => io_safe_output($agent['nombre']), - 'ip' => io_safe_output($agent['direccion'])); - } - - echo io_json_mb_encode($data); - - return; - } - - $get_modules_json_for_multiple_snmp = (bool) get_parameter("get_modules_json_for_multiple_snmp", 0); - if ($get_modules_json_for_multiple_snmp) { - require_once ('include/graphs/functions_utils.php'); - - $idSNMP = get_parameter('id_snmp'); - - $id_snmp_serialize = get_parameter('id_snmp_serialize'); - $snmp = unserialize_in_temp($id_snmp_serialize, false); - - $oid_snmp = array(); - $out = false; - foreach ($idSNMP as $id) { - foreach ($snmp[$id] as $key => $value) { - - // Check if it has "ifXXXX" syntax and skip it - if (! preg_match ( "/if/", $key)) { - continue; - } - - $oid_snmp[$value['oid']] = $key; - } - - if ($out === false) { - $out = $oid_snmp; - } - else { - $out = array_intersect($out,$oid_snmp); - } - - $oid_snmp = array(); - } - - echo io_json_mb_encode($out); - } +if (is_ajax()) { + global $config; - // And and remove groups use the same function - $add_secondary_groups = get_parameter('add_secondary_groups'); - $remove_secondary_groups = get_parameter('remove_secondary_groups'); - if ($add_secondary_groups || $remove_secondary_groups) { - $id_agent = get_parameter('id_agent'); - $groups_to_add = get_parameter('groups'); - if (enterprise_installed()) { - if (empty($groups_to_add)) return 0; - enterprise_include('include/functions_agents.php'); - $ret = enterprise_hook( - 'agents_update_secondary_groups', - array( - $id_agent, - $add_secondary_groups ? $groups_to_add : array(), - $remove_secondary_groups ? $groups_to_add : array()) - ); - // Echo 0 in case of error. 0 Otherwise. - echo $ret ? 1 : 0; - } - } - return; + $search_parents_2 = (bool) get_parameter('search_parents_2'); + + if ($search_parents_2) { + include_once 'include/functions_agents.php'; + + $id_agent = (int) get_parameter('id_agent'); + $string = (string) get_parameter('q'); + // q is what autocomplete plugin gives + $filter = []; + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $filter[] = '(nombre COLLATE utf8_general_ci LIKE "%'.$string.'%" OR direccion LIKE "%'.$string.'%" OR comentarios LIKE "%'.$string.'%" OR alias LIKE "%'.$string.'%")'; + break; + + case 'oracle': + $filter[] = '(upper(nombre) LIKE upper(\'%'.$string.'%\') OR upper(direccion) LIKE upper(\'%'.$string.'%\') OR upper(comentarios) LIKE upper(\'%'.$string.'%\') OR upper(alias) LIKE upper(\'%'.$string.'%\'))'; + break; + } + + $filter[] = 'id_agente != '.$id_agent; + + $agents = agents_get_agents($filter, ['id_agente', 'nombre', 'direccion']); + if ($agents === false) { + $agents = []; + } + + $data = []; + foreach ($agents as $agent) { + $data[] = [ + 'id' => $agent['id_agente'], + 'name' => io_safe_output($agent['nombre']), + 'ip' => io_safe_output($agent['direccion']), + ]; + } + + echo io_json_mb_encode($data); + + return; + } + + $get_modules_json_for_multiple_snmp = (bool) get_parameter('get_modules_json_for_multiple_snmp', 0); + if ($get_modules_json_for_multiple_snmp) { + include_once 'include/graphs/functions_utils.php'; + + $idSNMP = get_parameter('id_snmp'); + + $id_snmp_serialize = get_parameter('id_snmp_serialize'); + $snmp = unserialize_in_temp($id_snmp_serialize, false); + + $oid_snmp = []; + $out = false; + foreach ($idSNMP as $id) { + foreach ($snmp[$id] as $key => $value) { + // Check if it has "ifXXXX" syntax and skip it + if (! preg_match('/if/', $key)) { + continue; + } + + $oid_snmp[$value['oid']] = $key; + } + + if ($out === false) { + $out = $oid_snmp; + } else { + $out = array_intersect($out, $oid_snmp); + } + + $oid_snmp = []; + } + + echo io_json_mb_encode($out); + } + + // And and remove groups use the same function + $add_secondary_groups = get_parameter('add_secondary_groups'); + $remove_secondary_groups = get_parameter('remove_secondary_groups'); + if ($add_secondary_groups || $remove_secondary_groups) { + $id_agent = get_parameter('id_agent'); + $groups_to_add = get_parameter('groups'); + if (enterprise_installed()) { + if (empty($groups_to_add)) { + return 0; + } + + enterprise_include('include/functions_agents.php'); + $ret = enterprise_hook( + 'agents_update_secondary_groups', + [ + $id_agent, + $add_secondary_groups ? $groups_to_add : [], + $remove_secondary_groups ? $groups_to_add : [], + ] + ); + // Echo 0 in case of error. 0 Otherwise. + echo $ret ? 1 : 0; + } + } + + return; } ui_require_javascript_file('openlayers.pandora'); -$new_agent = (bool) get_parameter ('new_agent'); +$new_agent = (bool) get_parameter('new_agent'); -if (! isset ($id_agente) && ! $new_agent) { - db_pandora_audit("ACL Violation", "Trying to access agent manager witout an agent"); - require ("general/noaccess.php"); - return; +if (! isset($id_agente) && ! $new_agent) { + db_pandora_audit('ACL Violation', 'Trying to access agent manager witout an agent'); + include 'general/noaccess.php'; + return; } if ($new_agent) { - if (! empty ($direccion_agente) && empty ($nombre_agente)) - $nombre_agente = $direccion_agente; - - $servers = servers_get_names(); - if (!empty($servers)) { - $array_keys_servers = array_keys($servers); - $server_name = reset($array_keys_servers); - } + if (! empty($direccion_agente) && empty($nombre_agente)) { + $nombre_agente = $direccion_agente; + } + + $servers = servers_get_names(); + if (!empty($servers)) { + $array_keys_servers = array_keys($servers); + $server_name = reset($array_keys_servers); + } } if (!$new_agent) { - // Agent remote configuration editor - enterprise_include_once('include/functions_config_agents.php'); - if (enterprise_installed()) { - $filename = config_agents_get_agent_config_filenames($id_agente); - } + // Agent remote configuration editor + enterprise_include_once('include/functions_config_agents.php'); + if (enterprise_installed()) { + $filename = config_agents_get_agent_config_filenames($id_agente); + } } -$disk_conf_delete = (bool) get_parameter ('disk_conf_delete'); +$disk_conf_delete = (bool) get_parameter('disk_conf_delete'); // Agent remote configuration DELETE if ($disk_conf_delete) { - //TODO: Get this working on computers where the Pandora server(s) are not on the webserver - //TODO: Get a remote_config editor working in the open version - @unlink ($filename['md5']); - @unlink ($filename['conf']); + // TODO: Get this working on computers where the Pandora server(s) are not on the webserver + // TODO: Get a remote_config editor working in the open version + @unlink($filename['md5']); + @unlink($filename['conf']); } echo '
    '; $table = new stdClass(); $table->width = '100%'; -$table->class = "databox filters"; +$table->class = 'databox filters'; -$table->head = array (); -$table->style = array (); +$table->head = []; +$table->style = []; $table->style[0] = 'font-weight: bold; width: 150px;'; -$table->data = array (); +$table->data = []; $table->align[2] = 'center'; -if(!$new_agent && $alias != ''){ - $table->data[0][0] = __('Agent name') . - ui_print_help_tip (__("The agent's name must be the same as the one defined at the console"), true); - $table->data[0][1] = html_print_input_text ('agente', $nombre_agente, '', 50, 100,true); +if (!$new_agent && $alias != '') { + $table->data[0][0] = __('Agent name').ui_print_help_tip(__("The agent's name must be the same as the one defined at the console"), true); + $table->data[0][1] = html_print_input_text('agente', $nombre_agente, '', 50, 100, true); - $table->data[0][2] = __('QR Code Agent view'); + $table->data[0][2] = __('QR Code Agent view'); - if ($id_agente) { - - $table->data[0][1] .= " " . __("ID") . "  $id_agente  "; - $table->data[0][1] .= '  '; - $table->data[0][1] .= html_print_image ("images/zoom.png", - true, array ("border" => 0, "title" => __('Agent detail'))); - $table->data[0][1] .= ''; - } + if ($id_agente) { + $table->data[0][1] .= ' '.__('ID')."  $id_agente  "; + $table->data[0][1] .= '  '; + $table->data[0][1] .= html_print_image( + 'images/zoom.png', + true, + [ + 'border' => 0, + 'title' => __('Agent detail'), + ] + ); + $table->data[0][1] .= ''; + } } // Remote configuration available if (!$new_agent) { - if (isset($filename)) { - if (file_exists ($filename['md5'])) { - $agent_name = agents_get_name($id_agente); - $agent_name = io_safe_output($agent_name); - $agent_md5 = md5 ($agent_name, false); - - $table->data[0][1] .= '  ' . - ''; - $table->data[0][1] .= html_print_image( - "images/application_edit.png", - true, - array("border" => 0, - "title" => __('This agent can be remotely configured'))); - $table->data[0][1] .= '' . - ui_print_help_tip ( - __('You can remotely edit this agent configuration'), true); - } - } + if (isset($filename)) { + if (file_exists($filename['md5'])) { + $agent_name = agents_get_name($id_agente); + $agent_name = io_safe_output($agent_name); + $agent_md5 = md5($agent_name, false); + + $table->data[0][1] .= '  '.''; + $table->data[0][1] .= html_print_image( + 'images/application_edit.png', + true, + [ + 'border' => 0, + 'title' => __('This agent can be remotely configured'), + ] + ); + $table->data[0][1] .= ''.ui_print_help_tip( + __('You can remotely edit this agent configuration'), + true + ); + } + } } // Delete link from here if (!$new_agent) { - $table->data[0][1] .= "  " . html_print_image('images/cross.png', true, array('title' => __("Delete agent"))) . ""; + $table->data[0][1] .= "  ".html_print_image('images/cross.png', true, ['title' => __('Delete agent')]).''; } + $table->data[1][0] = __('Alias'); -$table->data[1][1] = html_print_input_text ('alias', $alias, '', 50, 100, true); -if($new_agent){ - $table->data[1][1] .= html_print_checkbox ("alias_as_name", 1, $config['alias_as_name'], true).__('Use alias as name'); +$table->data[1][1] = html_print_input_text('alias', $alias, '', 50, 100, true); +if ($new_agent) { + $table->data[1][1] .= html_print_checkbox('alias_as_name', 1, $config['alias_as_name'], true).__('Use alias as name'); } $table->data[2][0] = __('IP Address'); -$table->data[2][1] = html_print_input_text ('direccion', $direccion_agente, '', 16, 100, true); +$table->data[2][1] = html_print_input_text('direccion', $direccion_agente, '', 16, 100, true); if ($id_agente) { - $table->data[2][1] .= '    '; + $table->data[2][1] .= '    '; - $ip_all = agents_get_addresses ($id_agente); + $ip_all = agents_get_addresses($id_agente); - $table->data[2][1] .= html_print_select ($ip_all, "address_list", $direccion_agente, '', '', 0, true); - $table->data[2][1] .= " ". html_print_checkbox ("delete_ip", 1, false, true).__('Delete selected'); + $table->data[2][1] .= html_print_select($ip_all, 'address_list', $direccion_agente, '', '', 0, true); + $table->data[2][1] .= ' '.html_print_checkbox('delete_ip', 1, false, true).__('Delete selected'); } ?> rowspan[2][2] = 3; - if ($id_agente) { - $table->data[2][2] = - ""; - } - else { - $table->data[2][2] = __("Only it is show when
    the agent is saved."); - } +if (!$new_agent) { + $table->rowspan[2][2] = 3; + if ($id_agente) { + $table->data[2][2] = ""; + } else { + $table->data[2][2] = __('Only it is show when
    the agent is saved.'); + } } -$groups = users_get_groups ($config["id_user"], "AR",false); +$groups = users_get_groups($config['id_user'], 'AR', false); -$modules = db_get_all_rows_sql("SELECT id_agente_modulo as id_module, nombre as name FROM tagente_modulo - WHERE id_agente = " . $id_parent); -$modules_values = array(); +$modules = db_get_all_rows_sql( + 'SELECT id_agente_modulo as id_module, nombre as name FROM tagente_modulo + WHERE id_agente = '.$id_parent +); +$modules_values = []; $modules_values[0] = __('Any'); -if(is_array($modules)){ - foreach ($modules as $m) { - $modules_values[$m['id_module']] = $m['name']; - } +if (is_array($modules)) { + foreach ($modules as $m) { + $modules_values[$m['id_module']] = $m['name']; + } } $table->data[4][0] = __('Primary group'); // Cannot change primary group if user have not permission for that group if (isset($groups[$grupo]) || $new_agent) { - $table->data[4][1] = html_print_select_groups(false, "AR", false, 'grupo', $grupo, '', '', 0, true); + $table->data[4][1] = html_print_select_groups(false, 'AR', false, 'grupo', $grupo, '', '', 0, true); } else { - $table->data[4][1] = groups_get_name($grupo); - $table->data[4][1] .= html_print_input_hidden('grupo', $grupo, true); + $table->data[4][1] = groups_get_name($grupo); + $table->data[4][1] .= html_print_input_hidden('grupo', $grupo, true); } + $table->data[4][1] .= ' '; -$table->data[4][1] .= ui_print_group_icon ($grupo, true); +$table->data[4][1] .= ui_print_group_icon($grupo, true); $table->data[4][1] .= ''; $table->data[5][0] = __('Interval'); -$table->data[5][1] = html_print_extended_select_for_time ('intervalo', $intervalo, '', '', '0', 10, true); +$table->data[5][1] = html_print_extended_select_for_time('intervalo', $intervalo, '', '', '0', 10, true); if ($intervalo < SECONDS_5MINUTES) { - $table->data[5][1] .= clippy_context_help("interval_agent_min"); + $table->data[5][1] .= clippy_context_help('interval_agent_min'); } + $table->data[6][0] = __('OS'); -$table->data[6][1] = html_print_select_from_sql ('SELECT id_os, name FROM tconfig_os', - 'id_os', $id_os, '', '', '0', true); +$table->data[6][1] = html_print_select_from_sql( + 'SELECT id_os, name FROM tconfig_os', + 'id_os', + $id_os, + '', + '', + '0', + true +); $table->data[6][1] .= ' '; -$table->data[6][1] .= ui_print_os_icon ($id_os, false, true); +$table->data[6][1] .= ui_print_os_icon($id_os, false, true); $table->data[6][1] .= ''; // Network server $servers = servers_get_names(); if (!array_key_exists($server_name, $servers)) { - $server_Name = 0; //Set the agent have not server. + $server_Name = 0; + // Set the agent have not server. } + $table->data[7][0] = __('Server'); if ($new_agent) { - //Set first server by default. - $servers_get_names = servers_get_names(); - $array_keys_servers_get_names = array_keys($servers_get_names); - $server_name = reset($array_keys_servers_get_names); + // Set first server by default. + $servers_get_names = servers_get_names(); + $array_keys_servers_get_names = array_keys($servers_get_names); + $server_name = reset($array_keys_servers_get_names); } -$table->data[7][1] = html_print_select (servers_get_names (), - 'server_name', $server_name, '', __('None'), 0, true). ' ' . ui_print_help_icon ('agent_server', true); + +$table->data[7][1] = html_print_select( + servers_get_names(), + 'server_name', + $server_name, + '', + __('None'), + 0, + true +).' '.ui_print_help_icon('agent_server', true); // Description $table->data[8][0] = __('Description'); -$table->data[8][1] = html_print_input_text ('comentarios', $comentarios, - '', 45, 200, true); +$table->data[8][1] = html_print_input_text( + 'comentarios', + $comentarios, + '', + 45, + 200, + true +); -html_print_table ($table); +html_print_table($table); unset($table); $table = new stdClass(); $table->width = '100%'; -$table->class = "databox filters"; +$table->class = 'databox filters'; -$table->head = array (); -$table->style = array (); +$table->head = []; +$table->style = []; $table->style[0] = 'font-weight: bold; '; $table->style[4] = 'font-weight: bold;'; -$table->data = array (); +$table->data = []; if (enterprise_installed()) { - $secondary_groups_selected = enterprise_hook('agents_get_secondary_groups', array($id_agente)); - $table->data['secondary_groups'][0] = __('Secondary groups') . - ui_print_help_icon("secondary_groups", true); - $table->data['secondary_groups'][1] = html_print_select_groups( - false, // Use the current user to select the groups - "AR", // ACL permission - false, // Not all group - 'secondary_groups', // HTML id - '', // No select any by default - '', // Javascript onChange code - '', // Do not user no selected value - 0, // Do not use no selected value - true, // Return HTML (not echo) - true, // Multiple selection - true, // Sorting by default - '', // CSS classnames (default) - false, // Not disabled (default) - false, // Inline styles (default) - false, // Option style select (default) - false, // Do not truncate the users tree (default) - 'id_grupo', // Key to get as value (default) - false, // Not strict user (default) - $secondary_groups_selected['plain'] // Do not show the primary group in this selection - ); + $secondary_groups_selected = enterprise_hook('agents_get_secondary_groups', [$id_agente]); + $table->data['secondary_groups'][0] = __('Secondary groups').ui_print_help_icon('secondary_groups', true); + $table->data['secondary_groups'][1] = html_print_select_groups( + false, + // Use the current user to select the groups + 'AR', + // ACL permission + false, + // Not all group + 'secondary_groups', + // HTML id + '', + // No select any by default + '', + // Javascript onChange code + '', + // Do not user no selected value + 0, + // Do not use no selected value + true, + // Return HTML (not echo) + true, + // Multiple selection + true, + // Sorting by default + '', + // CSS classnames (default) + false, + // Not disabled (default) + false, + // Inline styles (default) + false, + // Option style select (default) + false, + // Do not truncate the users tree (default) + 'id_grupo', + // Key to get as value (default) + false, + // Not strict user (default) + $secondary_groups_selected['plain'] + // Do not show the primary group in this selection + ); - $table->data['secondary_groups'][2] = - html_print_input_image ('add_secondary', 'images/darrowright.png', 1, '', true, array ( - 'title' => __('Add secondary groups'), - 'onclick' => "agent_manager_add_secondary_groups(event, " . $id_agente . ");" - )) . - '



    ' . - html_print_input_image ('remove_secondary', 'images/darrowleft.png', 1, '', true, array ( - 'title' => __('Remove secondary groups'), - 'onclick' => "agent_manager_remove_secondary_groups(event, " . $id_agente . ");" - )); + $table->data['secondary_groups'][2] = html_print_input_image( + 'add_secondary', + 'images/darrowright.png', + 1, + '', + true, + [ + 'title' => __('Add secondary groups'), + 'onclick' => 'agent_manager_add_secondary_groups(event, '.$id_agente.');', + ] + ).'



    '.html_print_input_image( + 'remove_secondary', + 'images/darrowleft.png', + 1, + '', + true, + [ + 'title' => __('Remove secondary groups'), + 'onclick' => 'agent_manager_remove_secondary_groups(event, '.$id_agente.');', + ] + ); - $table->data['secondary_groups'][3] = html_print_select ( - $secondary_groups_selected['for_select'], // Values - 'secondary_groups_selected', // HTML id - '', // Selected - '', // Javascript onChange code - '', // Nothing selected - 0, // Nothing selected - true, // Return HTML (not echo) - true // Multiple selection - ); + $table->data['secondary_groups'][3] = html_print_select( + $secondary_groups_selected['for_select'], + // Values + 'secondary_groups_selected', + // HTML id + '', + // Selected + '', + // Javascript onChange code + '', + // Nothing selected + 0, + // Nothing selected + true, + // Return HTML (not echo) + true + // Multiple selection + ); -//safe operation mode -if($id_agente){ - $sql_modules = db_get_all_rows_sql("SELECT id_agente_modulo as id_module, nombre as name FROM tagente_modulo - WHERE id_agente = " . $id_agente); - $safe_mode_modules = array(); - $safe_mode_modules[0] = __('Any'); - foreach ($sql_modules as $m) { - $safe_mode_modules[$m['id_module']] = $m['name']; - } + // safe operation mode + if ($id_agente) { + $sql_modules = db_get_all_rows_sql( + 'SELECT id_agente_modulo as id_module, nombre as name FROM tagente_modulo + WHERE id_agente = '.$id_agente + ); + $safe_mode_modules = []; + $safe_mode_modules[0] = __('Any'); + foreach ($sql_modules as $m) { + $safe_mode_modules[$m['id_module']] = $m['name']; + } - $table->data[2][0] = __('Safe operation mode') - . ui_print_help_tip(__('This mode allow %s to disable all modules - of this agent while the selected module is on CRITICAL status', get_product_name()), true); - $table->data[2][1] = html_print_checkbox('safe_mode', 1, $safe_mode, true); - $table->data[2][1] .= "  " . __('Module') . " " . html_print_select ($safe_mode_modules, "safe_mode_module", $safe_mode_module, "", "", 0, true); + $table->data[2][0] = __('Safe operation mode').ui_print_help_tip( + __( + 'This mode allow %s to disable all modules + of this agent while the selected module is on CRITICAL status', + get_product_name() + ), + true + ); + $table->data[2][1] = html_print_checkbox('safe_mode', 1, $safe_mode, true); + $table->data[2][1] .= '  '.__('Module').' '.html_print_select($safe_mode_modules, 'safe_mode_module', $safe_mode_module, '', '', 0, true); + } + + // Remote configuration + $table->data[5][0] = __('Remote configuration'); + + if (!$new_agent) { + $table->data[5][1] = ''.__('Not available').''; + if (isset($filename)) { + if (file_exists($filename['md5'])) { + $table->data[5][1] = date('F d Y H:i:s', fileatime($filename['md5'])); + // Delete remote configuration + $table->data[5][1] .= ''; + $table->data[5][1] .= html_print_image( + 'images/cross.png', + true, + [ + 'title' => __('Delete remote configuration file'), + 'style' => 'vertical-align: middle;', + ] + ).''; + $table->data[5][1] .= ''.ui_print_help_tip( + __('Delete this conf file implies that for restore you must reactive remote config in the local agent.'), + true + ); + } + } + } else { + $table->data[5][1] = ''.__('Not available').''; + } + + + + $cps_array[-1] = __('Disabled'); + if ($cps > 0) { + $cps_array[$cps] = __('Enabled'); + } else { + $cps_inc = 0; + if ($id_agente) { + $cps_inc = service_agents_cps($id_agente); + } + + $cps_array[$cps_inc] = __('Enabled'); + } + + $table->data[6][0] = __('Cascade protection services'); + $table->data[6][0] .= ui_print_help_tip(__('Disable the alerts and events of the elements that belong to this service'), true); + $table->data[6][1] = html_print_select($cps_array, 'cps', $cps, '', '', 0, true); } -// Remote configuration -$table->data[5][0] = __('Remote configuration'); - -if (!$new_agent) { - $table->data[5][1] = '' . __('Not available') . ''; - if (isset($filename)) { - if (file_exists ($filename['md5'])) { - $table->data[5][1] = date ("F d Y H:i:s", fileatime ($filename['md5'])); - // Delete remote configuration - $table->data[5][1] .= ''; - $table->data[5][1] .= html_print_image( - "images/cross.png", true, - array ('title' => __('Delete remote configuration file'), 'style' => 'vertical-align: middle;')).''; - $table->data[5][1] .= '' . - ui_print_help_tip( - __('Delete this conf file implies that for restore you must reactive remote config in the local agent.'), - true); - } - } -} -else - $table->data[5][1] = '' . __('Not available') . ''; - - - -$cps_array[-1] = __('Disabled'); -if($cps > 0){ - $cps_array[$cps] = __('Enabled'); -} -else{ - $cps_inc = 0; - if($id_agente){ - $cps_inc = service_agents_cps($id_agente); - } - $cps_array[$cps_inc] = __('Enabled'); -} - -$table->data[6][0] = __('Cascade protection services'); -$table->data[6][0] .= ui_print_help_tip(__('Disable the alerts and events of the elements that belong to this service'), true); -$table->data[6][1] = html_print_select($cps_array, 'cps', $cps, '', '', 0, true); - - -} // Custom ID $table->data[0][0] = __('Custom ID'); -$table->data[0][1] = html_print_input_text ('custom_id', $custom_id, '', 16, 255, true); +$table->data[0][1] = html_print_input_text('custom_id', $custom_id, '', 16, 255, true); $table->data[1][0] = __('Parent'); -$params = array(); +$params = []; $params['return'] = true; $params['show_helptip'] = true; $params['input_name'] = 'id_parent'; $params['print_hidden_input_idagent'] = true; $params['hidden_input_idagent_name'] = 'id_agent_parent'; $params['hidden_input_idagent_value'] = $id_parent; -$params['value'] = db_get_value ("alias","tagente","id_agente",$id_parent); +$params['value'] = db_get_value('alias', 'tagente', 'id_agente', $id_parent); $params['selectbox_id'] = 'cascade_protection_module'; $params['javascript_is_function_select'] = true; $params['cascade_protection'] = true; $table->data[1][1] = ui_print_agent_autocomplete_input($params); if (enterprise_installed()) { -$table->data[1][1] .= html_print_checkbox ("cascade_protection", 1, $cascade_protection, true).__('Cascade protection'). " " . ui_print_help_icon("cascade_protection", true); + $table->data[1][1] .= html_print_checkbox('cascade_protection', 1, $cascade_protection, true).__('Cascade protection').' '.ui_print_help_icon('cascade_protection', true); } -$table->data[1][1] .= "  " . __('Module') . " " . html_print_select ($modules_values, "cascade_protection_module", $cascade_protection_module, "", "", 0, true); + +$table->data[1][1] .= '  '.__('Module').' '.html_print_select($modules_values, 'cascade_protection_module', $cascade_protection_module, '', '', 0, true); // Learn mode / Normal mode -$table->data[3][0] = __('Module definition') . - ui_print_help_icon("module_definition", true); -$table->data[3][1] = __('Learning mode') . ' ' . - html_print_radio_button_extended ("modo", 1, '', $modo, false, 'show_modules_not_learning_mode_context_help();', - 'style="margin-right: 40px;"', true); -$table->data[3][1] .= __('Normal mode') . ' ' . - html_print_radio_button_extended ("modo", 0, '', $modo, false, 'show_modules_not_learning_mode_context_help();', - 'style="margin-right: 40px;"', true); -$table->data[3][1] .= __('Autodisable mode') . ' ' . - html_print_radio_button_extended ("modo", 2, '', $modo, false, 'show_modules_not_learning_mode_context_help();', - 'style="margin-right: 40px;"', true); +$table->data[3][0] = __('Module definition').ui_print_help_icon('module_definition', true); +$table->data[3][1] = __('Learning mode').' '.html_print_radio_button_extended( + 'modo', + 1, + '', + $modo, + false, + 'show_modules_not_learning_mode_context_help();', + 'style="margin-right: 40px;"', + true +); +$table->data[3][1] .= __('Normal mode').' '.html_print_radio_button_extended( + 'modo', + 0, + '', + $modo, + false, + 'show_modules_not_learning_mode_context_help();', + 'style="margin-right: 40px;"', + true +); +$table->data[3][1] .= __('Autodisable mode').' '.html_print_radio_button_extended( + 'modo', + 2, + '', + $modo, + false, + 'show_modules_not_learning_mode_context_help();', + 'style="margin-right: 40px;"', + true +); // Status (Disabled / Enabled) $table->data[4][0] = __('Status'); -$table->data[4][1] = __('Disabled') . ' ' . - ui_print_help_tip(__('If the remote configuration is enabled, it will also go into standby mode when disabling it.'), true) . ' ' . - html_print_radio_button_extended ("disabled", 1, '', $disabled, false, '', 'style="margin-right: 40px;"', true); -$table->data[4][1] .= __('Enabled') . ' ' . - html_print_radio_button_extended ("disabled", 0, '', $disabled, false, '', 'style="margin-right: 40px;"', true); - if (enterprise_installed()) { - $table->data[4][2] = __('Url address'); - $table->data[4][3] = html_print_input_text ('url_description', - $url_description, '', 45, 255, true); - }else{ - $table->data[5][0] = __('Url address'); - $table->data[5][1] = html_print_input_text ('url_description', - $url_description, '', 45, 255, true); - } +$table->data[4][1] = __('Disabled').' '.ui_print_help_tip(__('If the remote configuration is enabled, it will also go into standby mode when disabling it.'), true).' '.html_print_radio_button_extended('disabled', 1, '', $disabled, false, '', 'style="margin-right: 40px;"', true); +$table->data[4][1] .= __('Enabled').' '.html_print_radio_button_extended('disabled', 0, '', $disabled, false, '', 'style="margin-right: 40px;"', true); +if (enterprise_installed()) { + $table->data[4][2] = __('Url address').ui_print_help_tip(__('URL address must be complete, for example: https://pandorafms.com/'), true); + $table->data[4][3] = html_print_input_text( + 'url_description', + $url_description, + '', + 45, + 255, + true + ); +} else { + $table->data[5][0] = __('Url address'); + $table->data[5][1] = html_print_input_text( + 'url_description', + $url_description, + '', + 45, + 255, + true + ); +} + $table->data[5][2] = __('Quiet'); $table->data[5][3] .= ui_print_help_tip(__('The agent still runs but the alerts and events will be stop'), true); $table->data[5][3] = html_print_checkbox('quiet', 1, $quiet, true); $listIcons = gis_get_array_list_icons(); -$arraySelectIcon = array(); -foreach ($listIcons as $index => $value) - $arraySelectIcon[$index] = $index; +$arraySelectIcon = []; +foreach ($listIcons as $index => $value) { + $arraySelectIcon[$index] = $index; +} -$path = 'images/gis_map/icons/'; //TODO set better method the path -$table->data[0][2] = __('Agent icon') . ui_print_help_tip(__('Agent icon for GIS Maps.'), true); +$path = 'images/gis_map/icons/'; +// TODO set better method the path +$table->data[0][2] = __('Agent icon').ui_print_help_tip(__('Agent icon for GIS Maps.'), true); if ($icon_path == '') { - $display_icons = 'none'; - // Hack to show no icon. Use any given image to fix not found image errors - $path_without = "images/spinner.png"; - $path_default = "images/spinner.png"; - $path_ok = "images/spinner.png"; - $path_bad = "images/spinner.png"; - $path_warning = "images/spinner.png"; -} -else { - $display_icons = ''; - $path_without = $path . $icon_path . ".default.png"; - $path_default = $path . $icon_path . ".default.png"; - $path_ok = $path . $icon_path . ".ok.png"; - $path_bad = $path . $icon_path . ".bad.png"; - $path_warning = $path . $icon_path . ".warning.png"; + $display_icons = 'none'; + // Hack to show no icon. Use any given image to fix not found image errors + $path_without = 'images/spinner.png'; + $path_default = 'images/spinner.png'; + $path_ok = 'images/spinner.png'; + $path_bad = 'images/spinner.png'; + $path_warning = 'images/spinner.png'; +} else { + $display_icons = ''; + $path_without = $path.$icon_path.'.default.png'; + $path_default = $path.$icon_path.'.default.png'; + $path_ok = $path.$icon_path.'.ok.png'; + $path_bad = $path.$icon_path.'.bad.png'; + $path_warning = $path.$icon_path.'.warning.png'; } -$table->data[0][3] = html_print_select($arraySelectIcon, "icon_path", - $icon_path, "changeIcons();", __('None'), '', true) . - ' ' . html_print_image($path_ok, true, - array("id" => "icon_ok", "style" => "display:".$display_icons.";")) . - ' ' . html_print_image($path_bad, true, - array("id" => "icon_bad", "style" => "display:".$display_icons.";")) . - ' ' . html_print_image($path_warning, true, - array("id" => "icon_warning", "style" => "display:".$display_icons.";")); +$table->data[0][3] = html_print_select( + $arraySelectIcon, + 'icon_path', + $icon_path, + 'changeIcons();', + __('None'), + '', + true +).' '.html_print_image( + $path_ok, + true, + [ + 'id' => 'icon_ok', + 'style' => 'display:'.$display_icons.';', + ] +).' '.html_print_image( + $path_bad, + true, + [ + 'id' => 'icon_bad', + 'style' => 'display:'.$display_icons.';', + ] +).' '.html_print_image( + $path_warning, + true, + [ + 'id' => 'icon_warning', + 'style' => 'display:'.$display_icons.';', + ] +); if ($config['activate_gis']) { - $table->data[3][2] = __('Ignore new GIS data:'); - $table->data[3][3] = __('Yes') . ' ' . - html_print_radio_button_extended ("update_gis_data", 0, '', - $update_gis_data, false, '', 'style="margin-right: 40px;"', true); - $table->data[3][3] .= __('No') . ' ' . - html_print_radio_button_extended ("update_gis_data", 1, '', - $update_gis_data, false, '', 'style="margin-right: 40px;"', true); + $table->data[3][2] = __('Ignore new GIS data:'); + $table->data[3][3] = __('Yes').' '.html_print_radio_button_extended( + 'update_gis_data', + 0, + '', + $update_gis_data, + false, + '', + 'style="margin-right: 40px;"', + true + ); + $table->data[3][3] .= __('No').' '.html_print_radio_button_extended( + 'update_gis_data', + 1, + '', + $update_gis_data, + false, + '', + 'style="margin-right: 40px;"', + true + ); } -ui_toggle(html_print_table ($table, true), __('Advanced options')); +ui_toggle(html_print_table($table, true), __('Advanced options')); unset($table); $table = new stdClass(); $table->width = '100%'; -$table->class = "databox filters"; +$table->class = 'databox filters'; -$table->head = array (); -$table->style = array (); +$table->head = []; +$table->style = []; $table->style[0] = 'font-weight: bold; width: 100px;'; -$table->data = array (); +$table->data = []; $fields = db_get_all_fields_in_table('tagent_custom_fields'); -if ($fields === false) $fields = array(); +if ($fields === false) { + $fields = []; +} foreach ($fields as $field) { - - $data[0] = ''.$field['name'].''; - $data[0] .= ui_print_help_tip( - __('This field allows url insertion using the BBCode\'s url tag') - . '.
    ' - . __('The format is: [url=\'url to navigate\']\'text to show\'[/url]') - . '.

    ' - . __('e.g.: [url=google.com]Google web search[/url]') - , true); - - $custom_value = db_get_value_filter('description', - 'tagent_custom_data', - array('id_field' => $field['id_field'], 'id_agent' => $id_agente)); - - if ($custom_value === false) { - $custom_value = ''; - } - - if ($field['is_password_type']) { - $data[1] = html_print_input_text_extended ('customvalue_' . $field['id_field'], $custom_value, 'customvalue_' . $field['id_field'], '', - 30, 100, $view_mode, '', '', true, true); - } - else { - $data[1] = html_print_textarea ('customvalue_'.$field['id_field'], - 2, 65, $custom_value, 'style="min-height: 30px; width:96%;"', true); - } - - array_push ($table->data, $data); + $data[0] = ''.$field['name'].''; + $data[0] .= ui_print_help_tip( + __('This field allows url insertion using the BBCode\'s url tag').'.
    '.__('The format is: [url=\'url to navigate\']\'text to show\'[/url]').'.

    '.__('e.g.: [url=google.com]Google web search[/url]'), + true + ); + + $custom_value = db_get_value_filter( + 'description', + 'tagent_custom_data', + [ + 'id_field' => $field['id_field'], + 'id_agent' => $id_agente, + ] + ); + + if ($custom_value === false) { + $custom_value = ''; + } + + if ($field['is_password_type']) { + $data[1] = html_print_input_text_extended( + 'customvalue_'.$field['id_field'], + $custom_value, + 'customvalue_'.$field['id_field'], + '', + 30, + 100, + $view_mode, + '', + '', + true, + true + ); + } else { + $data[1] = html_print_textarea( + 'customvalue_'.$field['id_field'], + 2, + 65, + $custom_value, + 'style="min-height: 30px; width:96%;"', + true + ); + } + + array_push($table->data, $data); } if (!empty($fields)) { - ui_toggle(html_print_table ($table, true), __('Custom fields')); + ui_toggle(html_print_table($table, true), __('Custom fields')); } -echo '
    '; +echo '
    '; -//The context help about the learning mode +// The context help about the learning mode if ($modo == 0) { - echo ""; + echo ""; +} else { + echo "'; if ($id_agente) { - echo '
    '; - html_print_submit_button (__('Update'), 'updbutton', false, - 'class="sub upd"'); - html_print_input_hidden ('update_agent', 1); - html_print_input_hidden ('id_agente', $id_agente); -} -else { - html_print_submit_button (__('Create'), 'crtbutton', false, - 'class="sub wand"'); - html_print_input_hidden ('create_agent', 1); + echo '
    '; + html_print_submit_button( + __('Update'), + 'updbutton', + false, + 'class="sub upd"' + ); + html_print_input_hidden('update_agent', 1); + html_print_input_hidden('id_agente', $id_agente); +} else { + html_print_submit_button( + __('Create'), + 'crtbutton', + false, + 'class="sub wand"' + ); + html_print_input_hidden('create_agent', 1); } + echo '
    '; ui_require_jquery_file('pandora.controls'); ui_require_jquery_file('ajaxqueue'); ui_require_jquery_file('bgiframe'); - ?> diff --git a/pandora_console/godmode/agentes/agent_template.php b/pandora_console/godmode/agentes/agent_template.php index c5c3aca25d..64e78320f5 100644 --- a/pandora_console/godmode/agentes/agent_template.php +++ b/pandora_console/godmode/agentes/agent_template.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,254 +11,257 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; // Load global vars -if (!isset ($id_agente)) { - die ("Not Authorized"); +if (!isset($id_agente)) { + die('Not Authorized'); } -require_once($config['homedir'] . "/include/functions_modules.php"); +require_once $config['homedir'].'/include/functions_modules.php'; // ========================== // TEMPLATE ASSIGMENT LOGIC // ========================== -if (isset ($_POST["template_id"])) { - // Take agent data - $row = db_get_row ("tagente", "id_agente", $id_agente); - if ($row !== false) { - $intervalo = $row["intervalo"]; - $nombre_agente = $row["nombre"]; - $direccion_agente =$row["direccion"]; - $ultima_act = $row["ultimo_contacto"]; - $ultima_act_remota =$row["ultimo_contacto_remoto"]; - $comentarios = $row["comentarios"]; - $id_grupo = $row["id_grupo"]; - $id_os= $row["id_os"]; - $os_version = $row["os_version"]; - $agent_version = $row["agent_version"]; - $disabled= $row["disabled"]; - } - else { - return; - } - - $id_np = get_parameter_post ("template_id"); - $name_template = db_get_value ('name', 'tnetwork_profile', 'id_np', $id_np); - $npc = db_get_all_rows_field_filter ("tnetwork_profile_component", "id_np", $id_np); - if ($npc === false) { - $npc = array (); - } - - $success_count = $error_count = 0; - $modules_already_added = array(); - - foreach ($npc as $row) { - $nc = db_get_all_rows_field_filter ("tnetwork_component", "id_nc", $row["id_nc"]); +if (isset($_POST['template_id'])) { + // Take agent data + $row = db_get_row('tagente', 'id_agente', $id_agente); + if ($row !== false) { + $intervalo = $row['intervalo']; + $nombre_agente = $row['nombre']; + $direccion_agente = $row['direccion']; + $ultima_act = $row['ultimo_contacto']; + $ultima_act_remota = $row['ultimo_contacto_remoto']; + $comentarios = $row['comentarios']; + $id_grupo = $row['id_grupo']; + $id_os = $row['id_os']; + $os_version = $row['os_version']; + $agent_version = $row['agent_version']; + $disabled = $row['disabled']; + } else { + return; + } - if ($nc === false) { - $nc = array (); - } - foreach ($nc as $row2) { - // Insert each module from tnetwork_component into agent - $values = array( - 'id_agente' => $id_agente, - 'id_tipo_modulo' => $row2["type"], - 'descripcion' => __('Created by template ').$name_template. ' . '.$row2["description"], - 'max' => $row2["max"], - 'min' => $row2["min"], - 'module_interval' => $row2["module_interval"], - 'tcp_port' => $row2["tcp_port"], - 'tcp_send' => $row2["tcp_send"], - 'tcp_rcv' => $row2["tcp_rcv"], - 'snmp_community' => $row2["snmp_community"], - 'snmp_oid' => $row2["snmp_oid"], - 'ip_target' => $direccion_agente, - 'id_module_group' => $row2["id_module_group"], - 'id_modulo' => $row2["id_modulo"], - 'plugin_user' => $row2["plugin_user"], - 'plugin_pass' => $row2["plugin_pass"], - 'plugin_parameter' => $row2["plugin_parameter"], - 'unit' => $row2["unit"], - 'max_timeout' => $row2["max_timeout"], - 'max_retries' => $row2["max_retries"], - 'id_plugin' => $row2['id_plugin'], - 'post_process' => $row2['post_process'], - 'dynamic_interval' => $row2['dynamic_interval'], - 'dynamic_max' => $row2['dynamic_max'], - 'dynamic_min' => $row2['dynamic_min'], - 'dynamic_two_tailed' => $row2['dynamic_two_tailed'], - 'min_warning' => $row2['min_warning'], - 'max_warning' => $row2['max_warning'], - 'str_warning' => $row2['str_warning'], - 'min_critical' => $row2['min_critical'], - 'max_critical' => $row2['max_critical'], - 'str_critical' => $row2['str_critical'], - 'critical_inverse' => $row2['critical_inverse'], - 'warning_inverse' => $row2['warning_inverse'], - 'critical_instructions' => $row2['critical_instructions'], - 'warning_instructions' => $row2['warning_instructions'], - 'unknown_instructions' => $row2['unknown_instructions'], - 'id_category' => $row2['id_category'], - 'macros' => $row2['macros'], - 'each_ff' => $row2['each_ff'], - 'min_ff_event' => $row2['min_ff_event'], - 'min_ff_event_normal' => $row2['min_ff_event_normal'], - 'min_ff_event_warning' => $row2['min_ff_event_warning'], - 'min_ff_event_critical' => $row2['min_ff_event_critical'] - ); - - $name = $row2["name"]; - - // Put tags in array if the component has to add them later - if(!empty($row2["tags"])) { - $tags = explode(',', $row2["tags"]); - } - else { - $tags = array(); - } - - // Check if this module exists in the agent - $module_name_check = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('delete_pending' => 0, 'nombre' => $name, 'id_agente' => $id_agente)); - - if ($module_name_check !== false) { - $modules_already_added[] = $row2["name"]; - $error_count++; - } - else { - $id_agente_modulo = modules_create_agent_module($id_agente, $name, $values); - - if ($id_agente_modulo === false) { - $error_count++; - } - else { - if(!empty($tags)) { - // Creating tags - $tag_ids = array(); - foreach ($tags as $tag_name) { - $tag_id = tags_get_id($tag_name); - - //If tag exists in the system we store to create it - $tag_ids[] = $tag_id; - } - - tags_insert_module_tag ($id_agente_modulo, $tag_ids); - } - - $success_count++; - } - } - } - } - if ($error_count > 0) { - if (empty($modules_already_added)) - ui_print_error_message(__('Error adding modules') . sprintf(' (%s)', $error_count)); - else - ui_print_error_message(__('Error adding modules. The following errors already exists: ') . implode(', ', $modules_already_added)); - } - if ($success_count > 0) - ui_print_success_message(__('Modules successfully added')); + $id_np = get_parameter_post('template_id'); + $name_template = db_get_value('name', 'tnetwork_profile', 'id_np', $id_np); + $npc = db_get_all_rows_field_filter('tnetwork_profile_component', 'id_np', $id_np); + if ($npc === false) { + $npc = []; + } + + $success_count = $error_count = 0; + $modules_already_added = []; + + foreach ($npc as $row) { + $nc = db_get_all_rows_field_filter('tnetwork_component', 'id_nc', $row['id_nc']); + + if ($nc === false) { + $nc = []; + } + + foreach ($nc as $row2) { + // Insert each module from tnetwork_component into agent + $values = [ + 'id_agente' => $id_agente, + 'id_tipo_modulo' => $row2['type'], + 'descripcion' => __('Created by template ').$name_template.' . '.$row2['description'], + 'max' => $row2['max'], + 'min' => $row2['min'], + 'module_interval' => $row2['module_interval'], + 'tcp_port' => $row2['tcp_port'], + 'tcp_send' => $row2['tcp_send'], + 'tcp_rcv' => $row2['tcp_rcv'], + 'snmp_community' => $row2['snmp_community'], + 'snmp_oid' => $row2['snmp_oid'], + 'ip_target' => $direccion_agente, + 'id_module_group' => $row2['id_module_group'], + 'id_modulo' => $row2['id_modulo'], + 'plugin_user' => $row2['plugin_user'], + 'plugin_pass' => $row2['plugin_pass'], + 'plugin_parameter' => $row2['plugin_parameter'], + 'unit' => $row2['unit'], + 'max_timeout' => $row2['max_timeout'], + 'max_retries' => $row2['max_retries'], + 'id_plugin' => $row2['id_plugin'], + 'post_process' => $row2['post_process'], + 'dynamic_interval' => $row2['dynamic_interval'], + 'dynamic_max' => $row2['dynamic_max'], + 'dynamic_min' => $row2['dynamic_min'], + 'dynamic_two_tailed' => $row2['dynamic_two_tailed'], + 'min_warning' => $row2['min_warning'], + 'max_warning' => $row2['max_warning'], + 'str_warning' => $row2['str_warning'], + 'min_critical' => $row2['min_critical'], + 'max_critical' => $row2['max_critical'], + 'str_critical' => $row2['str_critical'], + 'critical_inverse' => $row2['critical_inverse'], + 'warning_inverse' => $row2['warning_inverse'], + 'critical_instructions' => $row2['critical_instructions'], + 'warning_instructions' => $row2['warning_instructions'], + 'unknown_instructions' => $row2['unknown_instructions'], + 'id_category' => $row2['id_category'], + 'macros' => $row2['macros'], + 'each_ff' => $row2['each_ff'], + 'min_ff_event' => $row2['min_ff_event'], + 'min_ff_event_normal' => $row2['min_ff_event_normal'], + 'min_ff_event_warning' => $row2['min_ff_event_warning'], + 'min_ff_event_critical' => $row2['min_ff_event_critical'], + ]; + + $name = $row2['name']; + + // Put tags in array if the component has to add them later + if (!empty($row2['tags'])) { + $tags = explode(',', $row2['tags']); + } else { + $tags = []; + } + + // Check if this module exists in the agent + $module_name_check = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['delete_pending' => 0, 'nombre' => $name, 'id_agente' => $id_agente]); + + if ($module_name_check !== false) { + $modules_already_added[] = $row2['name']; + $error_count++; + } else { + $id_agente_modulo = modules_create_agent_module($id_agente, $name, $values); + + if ($id_agente_modulo === false) { + $error_count++; + } else { + if (!empty($tags)) { + // Creating tags + $tag_ids = []; + foreach ($tags as $tag_name) { + $tag_id = tags_get_id($tag_name); + + // If tag exists in the system we store to create it + $tag_ids[] = $tag_id; + } + + tags_insert_module_tag($id_agente_modulo, $tag_ids); + } + + $success_count++; + } + } + } + } + + if ($error_count > 0) { + if (empty($modules_already_added)) { + ui_print_error_message(__('Error adding modules').sprintf(' (%s)', $error_count)); + } else { + ui_print_error_message(__('Error adding modules. The following errors already exists: ').implode(', ', $modules_already_added)); + } + } + + if ($success_count > 0) { + ui_print_success_message(__('Modules successfully added')); + } } // Main header - - // ========================== // TEMPLATE ASSIGMENT FORM // ========================== - echo '
    '; -$nps = db_get_all_fields_in_table ("tnetwork_profile", "name"); +$nps = db_get_all_fields_in_table('tnetwork_profile', 'name'); if ($nps === false) { - $nps = array (); + $nps = []; } -$select = array (); +$select = []; foreach ($nps as $row) { - $select[$row["id_np"]] = $row["name"]; + $select[$row['id_np']] = $row['name']; } echo ''; echo "'; echo ''; echo ''; -echo ""; -echo "
    "; -html_print_select ($select, "template_id", '', '', '', 0, false, false, true, '', false, 'max-width: 200px !important'); +html_print_select($select, 'template_id', '', '', '', 0, false, false, true, '', false, 'max-width: 200px !important'); echo ''; -html_print_submit_button (__('Assign'), 'crt', false, 'class="sub next" style="margin-top:0px;"'); +html_print_submit_button(__('Assign'), 'crt', false, 'class="sub next" style="margin-top:0px;"'); echo '
    "; +echo ''; +echo ''; echo ''; // ========================== // MODULE VISUALIZATION TABLE // ========================== -switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $sql = sprintf ("SELECT * +switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $sql = sprintf( + 'SELECT * FROM tagente_modulo WHERE id_agente = %d AND delete_pending = false - ORDER BY id_module_group, nombre", $id_agente); - break; - case "oracle": - $sql = sprintf ("SELECT * + ORDER BY id_module_group, nombre', + $id_agente + ); + break; + + case 'oracle': + $sql = sprintf( + 'SELECT * FROM tagente_modulo WHERE id_agente = %d AND (delete_pending <> 1 AND delete_pending IS NOT NULL) - ORDER BY id_module_group, dbms_lob.substr(nombre,4000,1)", $id_agente); - break; + ORDER BY id_module_group, dbms_lob.substr(nombre,4000,1)', + $id_agente + ); + break; } -$result = db_get_all_rows_sql ($sql); + +$result = db_get_all_rows_sql($sql); if ($result === false) { - $result = array (); + $result = []; } $table->width = '100%'; $table->cellpadding = 0; $table->cellspacing = 0; -$table->class = "databox data"; -$table->head = array (); -$table->data = array (); -$table->align = array (); +$table->class = 'databox data'; +$table->head = []; +$table->data = []; +$table->align = []; $table->head[0] = __('Module name'); $table->head[1] = __('Type'); $table->head[2] = __('Description'); $table->head[3] = __('Action'); -$table->align[1] = "left"; -$table->align[3] = "left"; -$table->size[0] = "30%"; -$table->size[1] = "5%"; -$table->size[3] = "8%"; +$table->align[1] = 'left'; +$table->align[3] = 'left'; +$table->size[0] = '30%'; +$table->size[1] = '5%'; +$table->size[3] = '8%'; foreach ($result as $row) { - $data = array (); - - $data[0] = '' . $row["nombre"]; - if ($row["id_tipo_modulo"] > 0) { - $data[1] = html_print_image("images/" . modules_show_icon_type ($row["id_tipo_modulo"]), true, array("border" => "0")); - } - else { - $data[1] = ''; - } - $data[2] = mb_substr ($row["descripcion"], 0, 60); - - $data[3] = '' . html_print_image("images/cross.png", true, array("border" => "0", "alt" => __('Delete'), "onclick" => "if (!confirm('".__('Are you sure?') . "')) return false;")) . '  '; - - $data[3] .= '  ' . html_print_image("images/config.png", true, array("border" => '0', "alt" => __('Update'))) . ''; - - array_push ($table->data, $data); + $data = []; + + $data[0] = ''.$row['nombre']; + if ($row['id_tipo_modulo'] > 0) { + $data[1] = html_print_image('images/'.modules_show_icon_type($row['id_tipo_modulo']), true, ['border' => '0']); + } else { + $data[1] = ''; + } + + $data[2] = mb_substr($row['descripcion'], 0, 60); + + $data[3] = ''.html_print_image('images/cross.png', true, ['border' => '0', 'alt' => __('Delete'), 'onclick' => "if (!confirm('".__('Are you sure?')."')) return false;"]).'  '; + + $data[3] .= '  '.html_print_image('images/config.png', true, ['border' => '0', 'alt' => __('Update')]).''; + + array_push($table->data, $data); } -if (!empty ($table->data)) { - html_print_table ($table); - unset ($table); +if (!empty($table->data)) { + html_print_table($table); + unset($table); +} else { + ui_print_empty_data(__('No modules')); } -else { - ui_print_empty_data ( __('No modules') ) ; -} -?> diff --git a/pandora_console/godmode/agentes/agent_wizard.php b/pandora_console/godmode/agentes/agent_wizard.php index 79cfdf44f5..949e1c3a94 100644 --- a/pandora_console/godmode/agentes/agent_wizard.php +++ b/pandora_console/godmode/agentes/agent_wizard.php @@ -4,47 +4,44 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); +check_login(); $wizard_section = get_parameter('wizard_section', 'snmp_interfaces_explorer'); $idAgent = (int) get_parameter('id_agente', 0); $ipAgent = db_get_value('direccion', 'tagente', 'id_agente', $idAgent); -switch($wizard_section) { - case 'snmp_interfaces_explorer': - $snmp_interfaces_explorer_style = 'font-weight: bold;'; - $wmi_explorer_style = ''; - break; - case 'wmi_explorer': - $snmp_interfaces_explorer_style = ''; - $wmi_explorer_style = 'font-weight: bold;'; - break; - case 'snmp_explorer': - $snmp_interfaces_explorer_style = ''; - $wmi_explorer_style = 'font-weight: bold;'; - break; +switch ($wizard_section) { + case 'snmp_interfaces_explorer': + $snmp_interfaces_explorer_style = 'font-weight: bold;'; + $wmi_explorer_style = ''; + break; + + case 'wmi_explorer': + $snmp_interfaces_explorer_style = ''; + $wmi_explorer_style = 'font-weight: bold;'; + break; + + case 'snmp_explorer': + $snmp_interfaces_explorer_style = ''; + $wmi_explorer_style = 'font-weight: bold;'; + break; } /* -echo "
    "; -echo "" . __('SNMP Interfaces explorer') . ""; -echo " | "; -echo "" . __('WMI explorer') . ""; -echo "
    "; + echo "
    "; + echo "" . __('SNMP Interfaces explorer') . ""; + echo " | "; + echo "" . __('WMI explorer') . ""; + echo "
    "; */ -require("agent_wizard." . $wizard_section . ".php"); - -?> +require 'agent_wizard.'.$wizard_section.'.php'; diff --git a/pandora_console/godmode/agentes/agent_wizard.snmp_explorer.php b/pandora_console/godmode/agentes/agent_wizard.snmp_explorer.php index ae35e31cb7..f424252e32 100644 --- a/pandora_console/godmode/agentes/agent_wizard.snmp_explorer.php +++ b/pandora_console/godmode/agentes/agent_wizard.snmp_explorer.php @@ -4,23 +4,20 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -include_once($config['homedir'] . "/include/functions_agents.php"); -require_once ('include/functions_modules.php'); -require_once ('include/functions_alerts.php'); -require_once ('include/functions_reporting.php'); -require_once ('include/graphs/functions_utils.php'); -require_once("include/functions_snmp.php"); +require_once $config['homedir'].'/include/functions_agents.php'; +require_once 'include/functions_modules.php'; +require_once 'include/functions_alerts.php'; +require_once 'include/functions_reporting.php'; +require_once 'include/graphs/functions_utils.php'; +require_once 'include/functions_snmp.php'; // Define a separator to implode/explode data $separator = '_.._'; @@ -28,11 +25,11 @@ $separator = '_.._'; $idAgent = (int) get_parameter('id_agente', 0); $ipAgent = db_get_value('direccion', 'tagente', 'id_agente', $idAgent); -check_login (); +check_login(); -$ip_target = (string) get_parameter ('ip_target', $ipAgent); -$use_agent = get_parameter ('use_agent'); -$snmp_community = (string) get_parameter ('snmp_community', 'public'); +$ip_target = (string) get_parameter('ip_target', $ipAgent); +$use_agent = get_parameter('use_agent'); +$snmp_community = (string) get_parameter('snmp_community', 'public'); $snmp_version = get_parameter('snmp_version', '1'); $server_to_exec = get_parameter('server_to_exec', 0); $snmp3_auth_user = io_safe_output(get_parameter('snmp3_auth_user')); @@ -41,660 +38,685 @@ $snmp3_auth_method = get_parameter('snmp3_auth_method'); $snmp3_auth_pass = io_safe_output(get_parameter('snmp3_auth_pass')); $snmp3_privacy_method = get_parameter('snmp3_privacy_method'); $snmp3_privacy_pass = io_safe_output(get_parameter('snmp3_privacy_pass')); -$tcp_port = (string) get_parameter ('tcp_port'); +$tcp_port = (string) get_parameter('tcp_port'); -//See if id_agente is set (either POST or GET, otherwise -1 +// See if id_agente is set (either POST or GET, otherwise -1 $id_agent = $idAgent; // Get passed variables -$snmpwalk = (int) get_parameter("snmpwalk", 0); -$create_modules = (int) get_parameter("create_modules", 0); +$snmpwalk = (int) get_parameter('snmpwalk', 0); +$create_modules = (int) get_parameter('create_modules', 0); // Get the plugin switch ($config['dbtype']) { - case 'mysql': - case 'postgresql': - $plugin = db_get_row_sql("SELECT id, macros FROM tplugin WHERE execute LIKE '%/snmp_remote.pl'"); - break; - case 'oracle': - $plugin = db_get_row_sql("SELECT id, TO_CHAR(macros) AS macros FROM tplugin WHERE execute LIKE '%/snmp_remote.pl'"); - break; + case 'mysql': + case 'postgresql': + $plugin = db_get_row_sql("SELECT id, macros FROM tplugin WHERE execute LIKE '%/snmp_remote.pl'"); + break; + + case 'oracle': + $plugin = db_get_row_sql("SELECT id, TO_CHAR(macros) AS macros FROM tplugin WHERE execute LIKE '%/snmp_remote.pl'"); + break; } if (empty($plugin)) { - ui_print_info_message(array('message' => __('The SNMP remote plugin doesnt seem to be installed') . '. ' . __('It is necessary to use some features') . '.

    ' . __('Please, install the SNMP remote plugin (The name of the plugin must be snmp_remote.pl)'), 'no_close' => true)); + ui_print_info_message(['message' => __('The SNMP remote plugin doesnt seem to be installed').'. '.__('It is necessary to use some features').'.

    '.__('Please, install the SNMP remote plugin (The name of the plugin must be snmp_remote.pl)'), 'no_close' => true]); } // Using plugin if (!empty($plugin)) { - $static_snmp_descriptions['avgCpuLoad'] = 'Average of CPUs Load (%)'; - $static_snmp_descriptions['memoryUse'] = 'Memory use (%)'; + $static_snmp_descriptions['avgCpuLoad'] = 'Average of CPUs Load (%)'; + $static_snmp_descriptions['memoryUse'] = 'Memory use (%)'; } $fail = false; -$devices = array(); -$processes = array(); -$disks = array(); -$temperatures = array(); +$devices = []; +$processes = []; +$disks = []; +$temperatures = []; $arrow = false; $snmp_translation_data = index_array(snmp_get_translation_wizard(), null, 'description'); -$other_snmp_data = array(); +$other_snmp_data = []; if ($snmpwalk) { - // OID Used is for DISKS - $snmpis = get_snmpwalk($ip_target, $snmp_version, $snmp_community, $snmp3_auth_user, - $snmp3_security_level, $snmp3_auth_method, $snmp3_auth_pass, - $snmp3_privacy_method, $snmp3_privacy_pass, 0, ".1.3.6.1.2.1.25.2.3.1.3", $tcp_port, - $server_to_exec); - - if (empty($snmpis)) { - $fail = true; - $snmpis = array(); - } - else { - // We get here only the interface part of the MIB, not full mib - foreach($snmpis as $key => $snmp) { - - $data = explode(': ',$snmp); - $keydata = explode('::',$key); - $keydata2 = explode('.',$keydata[1]); - - // Avoid results without index and results without name - if (!isset($keydata2[1]) || !isset($data[1])) { - continue; - } - - - if (array_key_exists(1,$data)) { - $disks[$data[1]] = $data[1]; - - } - else { - $disks[$data[0]] = $data[0]; - - } - } - - // OID Used is for PROCESSES - $snmpis = get_snmpwalk($ip_target, $snmp_version, $snmp_community, $snmp3_auth_user, - $snmp3_security_level, $snmp3_auth_method, $snmp3_auth_pass, - $snmp3_privacy_method, $snmp3_privacy_pass, 0, ".1.3.6.1.2.1.25.4.2.1.2", $tcp_port, - $server_to_exec); - - if ($snmpis === false) { - $snmpis = array(); - } - - - // We get here only the interface part of the MIB, not full mib - foreach($snmpis as $key => $snmp) { - - $data = explode(': ',$snmp); - $keydata = explode('::',$key); - $keydata2 = explode('.',$keydata[1]); - - // Avoid results without index and results without name - if (!isset($keydata2[1]) || !isset($data[1])) { - continue; - } - - if (array_key_exists(1,$data)) { - $process_name = str_replace ( "\"" , "" , $data[1]); - - } - else { - $process_name = str_replace ( "\"" , "" , $data[0]); - - } - - $processes[$process_name] = $process_name; - } - - // Keep only the first process found - $processes = array_unique($processes); - - - // OID Used is for SENSOR TEMPERATURES - $snmpis = get_snmpwalk($ip_target, $snmp_version, $snmp_community, $snmp3_auth_user, - $snmp3_security_level, $snmp3_auth_method, $snmp3_auth_pass, - $snmp3_privacy_method, $snmp3_privacy_pass, 0, ".1.3.6.1.4.1.2021.13.16.2.1", $tcp_port, - $server_to_exec); - - if ($snmpis === false) { - $snmpis = array(); - } - - - // We get here only the interface part of the MIB, not full mib - foreach($snmpis as $key => $snmp) { - - $data = explode(': ',$snmp); - $keydata = explode('::',$key); - $keydata2 = explode('.',$keydata[1]); - - // Avoid results without index and results without name - if (!isset($keydata2[1]) || !isset($data[1])) { - continue; - } - - - if ($keydata2[0] == 'lmTempSensorsDevice') { - if (array_key_exists(1,$data)) { - $temperatures[$keydata2[1]] = $data[1]; - - } - else { - $temperatures[$keydata2[1]] = $data[0]; - - } - } - } - - // Keep only the first sensor found - $temperatures = array_unique($temperatures); - - // OID Used is for DEVICES - $snmpis = get_snmpwalk($ip_target, $snmp_version, $snmp_community, $snmp3_auth_user, - $snmp3_security_level, $snmp3_auth_method, $snmp3_auth_pass, - $snmp3_privacy_method, $snmp3_privacy_pass, 0, ".1.3.6.1.4.1.2021.13.15.1.1", $tcp_port, - $server_to_exec); - - if ($snmpis === false) { - $snmpis = array(); - } - - - // We get here only the interface part of the MIB, not full mib - foreach($snmpis as $key => $snmp) { - - $data = explode(': ',$snmp); - $keydata = explode('::',$key); - $keydata2 = explode('.',$keydata[1]); - - // Avoid results without index and results without name - if (!isset($keydata2[1]) || !isset($data[1])) { - continue; - } - - - if ($keydata2[0] == 'diskIODevice') { - if (array_key_exists(1,$data)) { - $devices['diskIONRead' . $separator . $keydata2[1]] = $data[1] . ' - Bytes read'; - $devices['diskIONWritten' . $separator . $keydata2[1]] = $data[1] . ' - Bytes written'; - $devices['diskIONReads' . $separator . $keydata2[1]] = $data[1] . ' - Read accesses'; - $devices['diskIONWrites' . $separator . $keydata2[1]] = $data[1] . ' - Write accesses'; - } - else { - $devices['diskIONRead' . $separator . $keydata2[1]] = $data[0] . ' - Bytes read'; - $devices['diskIONWritten' . $separator . $keydata2[1]] = $data[0] . ' - Bytes written'; - $devices['diskIONReads' . $separator . $keydata2[1]] = $data[0] . ' - Read accesses'; - $devices['diskIONWrites' . $separator . $keydata2[1]] = $data[0] . ' - Write accesses'; - } - } - } - } - - // Other SNMP Data - $arrow = true; - - foreach ($snmp_translation_data as $oid => $temp) { - if ($snmp_version == 3) { - $result = false; //It is statics oids. - } - else { - $result = @snmpget($ip_target, $snmp_community, $oid); - } - - if ($result != false) { - $other_snmp_data[$oid] = $snmp_translation_data[$oid]; - } - } - if (empty($other_snmp_data)) { - $arrow = false; - $other_snmp_data[0] = __('Remote system doesnt support host SNMP information'); - } - + // OID Used is for DISKS + $snmpis = get_snmpwalk( + $ip_target, + $snmp_version, + $snmp_community, + $snmp3_auth_user, + $snmp3_security_level, + $snmp3_auth_method, + $snmp3_auth_pass, + $snmp3_privacy_method, + $snmp3_privacy_pass, + 0, + '.1.3.6.1.2.1.25.2.3.1.3', + $tcp_port, + $server_to_exec + ); + + if (empty($snmpis)) { + $fail = true; + $snmpis = []; + } else { + // We get here only the interface part of the MIB, not full mib + foreach ($snmpis as $key => $snmp) { + $data = explode(': ', $snmp); + $keydata = explode('::', $key); + $keydata2 = explode('.', $keydata[1]); + + // Avoid results without index and results without name + if (!isset($keydata2[1]) || !isset($data[1])) { + continue; + } + + + if (array_key_exists(1, $data)) { + $disks[$data[1]] = $data[1]; + } else { + $disks[$data[0]] = $data[0]; + } + } + + // OID Used is for PROCESSES + $snmpis = get_snmpwalk( + $ip_target, + $snmp_version, + $snmp_community, + $snmp3_auth_user, + $snmp3_security_level, + $snmp3_auth_method, + $snmp3_auth_pass, + $snmp3_privacy_method, + $snmp3_privacy_pass, + 0, + '.1.3.6.1.2.1.25.4.2.1.2', + $tcp_port, + $server_to_exec + ); + + if ($snmpis === false) { + $snmpis = []; + } + + + // We get here only the interface part of the MIB, not full mib + foreach ($snmpis as $key => $snmp) { + $data = explode(': ', $snmp); + $keydata = explode('::', $key); + $keydata2 = explode('.', $keydata[1]); + + // Avoid results without index and results without name + if (!isset($keydata2[1]) || !isset($data[1])) { + continue; + } + + if (array_key_exists(1, $data)) { + $process_name = str_replace('"', '', $data[1]); + } else { + $process_name = str_replace('"', '', $data[0]); + } + + $processes[$process_name] = $process_name; + } + + // Keep only the first process found + $processes = array_unique($processes); + + + // OID Used is for SENSOR TEMPERATURES + $snmpis = get_snmpwalk( + $ip_target, + $snmp_version, + $snmp_community, + $snmp3_auth_user, + $snmp3_security_level, + $snmp3_auth_method, + $snmp3_auth_pass, + $snmp3_privacy_method, + $snmp3_privacy_pass, + 0, + '.1.3.6.1.4.1.2021.13.16.2.1', + $tcp_port, + $server_to_exec + ); + + if ($snmpis === false) { + $snmpis = []; + } + + + // We get here only the interface part of the MIB, not full mib + foreach ($snmpis as $key => $snmp) { + $data = explode(': ', $snmp); + $keydata = explode('::', $key); + $keydata2 = explode('.', $keydata[1]); + + // Avoid results without index and results without name + if (!isset($keydata2[1]) || !isset($data[1])) { + continue; + } + + + if ($keydata2[0] == 'lmTempSensorsDevice') { + if (array_key_exists(1, $data)) { + $temperatures[$keydata2[1]] = $data[1]; + } else { + $temperatures[$keydata2[1]] = $data[0]; + } + } + } + + // Keep only the first sensor found + $temperatures = array_unique($temperatures); + + // OID Used is for DEVICES + $snmpis = get_snmpwalk( + $ip_target, + $snmp_version, + $snmp_community, + $snmp3_auth_user, + $snmp3_security_level, + $snmp3_auth_method, + $snmp3_auth_pass, + $snmp3_privacy_method, + $snmp3_privacy_pass, + 0, + '.1.3.6.1.4.1.2021.13.15.1.1', + $tcp_port, + $server_to_exec + ); + + if ($snmpis === false) { + $snmpis = []; + } + + + // We get here only the interface part of the MIB, not full mib + foreach ($snmpis as $key => $snmp) { + $data = explode(': ', $snmp); + $keydata = explode('::', $key); + $keydata2 = explode('.', $keydata[1]); + + // Avoid results without index and results without name + if (!isset($keydata2[1]) || !isset($data[1])) { + continue; + } + + + if ($keydata2[0] == 'diskIODevice') { + if (array_key_exists(1, $data)) { + $devices['diskIONRead'.$separator.$keydata2[1]] = $data[1].' - Bytes read'; + $devices['diskIONWritten'.$separator.$keydata2[1]] = $data[1].' - Bytes written'; + $devices['diskIONReads'.$separator.$keydata2[1]] = $data[1].' - Read accesses'; + $devices['diskIONWrites'.$separator.$keydata2[1]] = $data[1].' - Write accesses'; + } else { + $devices['diskIONRead'.$separator.$keydata2[1]] = $data[0].' - Bytes read'; + $devices['diskIONWritten'.$separator.$keydata2[1]] = $data[0].' - Bytes written'; + $devices['diskIONReads'.$separator.$keydata2[1]] = $data[0].' - Read accesses'; + $devices['diskIONWrites'.$separator.$keydata2[1]] = $data[0].' - Write accesses'; + } + } + } + } + + // Other SNMP Data + $arrow = true; + + foreach ($snmp_translation_data as $oid => $temp) { + if ($snmp_version == 3) { + $result = false; + // It is statics oids. + } else { + $result = @snmpget($ip_target, $snmp_community, $oid); + } + + if ($result != false) { + $other_snmp_data[$oid] = $snmp_translation_data[$oid]; + } + } + + if (empty($other_snmp_data)) { + $arrow = false; + $other_snmp_data[0] = __('Remote system doesnt support host SNMP information'); + } } if ($create_modules) { - $modules = io_safe_output(get_parameter("module", array())); - - $devices = array(); - $processes = array(); - $disks = array(); - $temperatures = array(); - $snmpdata = array(); - - foreach ($modules as $module) { - // Split module data to get type - $module_exploded = explode($separator, $module); - $type = $module_exploded[0]; - - // Delete type from module data - unset($module_exploded[0]); - - // Rebuild module data - $module = implode($separator, $module_exploded); - - switch($type) { - case 'device': - $devices[] = $module; - break; - case 'process': - $processes[] = $module; - break; - case 'disk': - $disks[] = $module; - break; - case 'temperature': - $temperatures[] = $module; - break; - case 'snmpdata': - $snmpdata[] = $module; - break; - } - } - - if (agents_get_name($id_agent) == false) { - ui_print_error_message (__('No agent selected or the agent does not exist')); - } - else { - - // Common values - $common_values = array(); - - if ($tcp_port != '') { - $common_values['tcp_port'] = $tcp_port; - } - $common_values['snmp_community'] = $snmp_community; - if($use_agent){ - $common_values['ip_target'] = 'auto'; - } - else{ - $common_values['ip_target'] = $ip_target; - } - - $common_values['tcp_send'] = $snmp_version; - - if ($snmp_version == '3') { - $common_values['plugin_user'] = $snmp3_auth_user; - $common_values['plugin_pass'] = $snmp3_auth_pass; - $common_values['plugin_parameter'] = $snmp3_auth_method; - $common_values['custom_string_1'] = $snmp3_privacy_method; - $common_values['custom_string_2'] = $snmp3_privacy_pass; - $common_values['custom_string_3'] = $snmp3_security_level; - } - - - // DEVICES - $devices_prefix_oids = array( - 'diskIONRead' => '.1.3.6.1.4.1.2021.13.15.1.1.3.', - 'diskIONWritten' => '.1.3.6.1.4.1.2021.13.15.1.1.4.', - 'diskIONReads' => '.1.3.6.1.4.1.2021.13.15.1.1.5.', - 'diskIONWrites' => '.1.3.6.1.4.1.2021.13.15.1.1.6.' - ); - - $devices_prefix_descriptions = array( - 'diskIONRead' => - __('The number of bytes read from this device since boot'), - 'diskIONWritten' => - __('The number of bytes written to this device since boot'), - 'diskIONReads' => - __('The number of read accesses from this device since boot'), - 'diskIONWrites' => - __('The number of write accesses from this device since boot') - ); - - $results = array(); - - foreach ($devices as $device) { - $module_values = $common_values; - - // Split module data to get type, name, etc - $device_exploded = explode($separator, $device); - $device_name = $device_exploded[0]; - - $name_exploded = explode('-', $device_name); - $name = ltrim(html_entity_decode($name_exploded[1])); - - $device_type = $device_exploded[1]; - - // Delete type from device id - unset($device_exploded[0]); - unset($device_exploded[1]); - - // Rebuild device_name - $device_id = implode($separator, $device_exploded); - - $module_values['descripcion'] = $devices_prefix_descriptions[$device_type]; - - if (($name == 'Bytes read') || ($name == 'Bytes written')) { - $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp_inc'); - } - else { - $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp'); - } - - $module_values['snmp_oid'] = $devices_prefix_oids[$device_type] . $device_id; - - $module_values['id_modulo'] = MODULE_SNMP; - - $result = modules_create_agent_module ($id_agent, io_safe_input($device_name), $module_values); - - $results[$result][] = $device_name; - } - - // TEMPERATURE SENSORS - $temperatures_prefix_oid = '.1.3.6.1.4.1.2021.13.16.2.1.3.'; - $temperatures_description = 'The temperature of this sensor in C'; - - foreach ($temperatures as $temperature) { - $module_values = $common_values; - - // Split module data to get type, name, etc - $temperature_exploded = explode($separator, $temperature); - $temperature_name = $temperature_exploded[0]; - - // Delete name from temperature sensor id - unset($temperature_exploded[0]); - - // Rebuild device_name - $temperature_id = implode($separator, $temperature_exploded); - - $module_values['descripcion'] = $temperatures_description; - - $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp'); - - $module_values['snmp_oid'] = $temperatures_prefix_oid . $temperature_id; - - $module_values['id_modulo'] = MODULE_SNMP; - - // Temperature are given in mC. Convert to Celsius - $module_values['post_process'] = 0.001; - - $module_values['unit'] = 'C'; - - $result = modules_create_agent_module ($id_agent, io_safe_input($temperature_name), $module_values); - - $results[$result][] = $temperature_name; - } - - // SNMP DATA (STATIC MODULES) - - foreach ($snmpdata as $snmpdata_oid) { - $module_values = $common_values; - $snmp_translation = snmp_get_translation($snmpdata_oid); - - $module_values['descripcion'] = - $snmp_translation['description']; - $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp'); - $module_values['post_process'] = $snmp_translation['post_process']; - - //Average use of CPUs is a plugin module - switch ($snmpdata_oid) { - case 'avgCpuLoad': - case 'memoryUse': - $module_values['id_modulo'] = MODULE_PLUGIN; - $module_values['id_plugin'] = $plugin['id']; - - // Avoid the return of a string containing the word 'null' if the macros column is not defined - $macros = array(); - if (isset($plugin['macros']) && !empty($plugin['macros'])) - $macros = json_decode($plugin['macros'], true); - - foreach ($macros as $k => $macro) { - switch($macro['macro']) { - case '_field1_': - // Field 1 is the IP Address - $macros[$k]['value'] = $module_values['ip_target']; - break; - case '_field2_': - // Field 2 is the community - $macros[$k]['value'] = $module_values['snmp_community']; - break; - case '_field3_': - // Field 3 is the plugin parameters - switch ($snmpdata_name) { - case 'avgCpuLoad': - $macros[$k]['value'] = '-m cpuload'; - break; - case 'memoryUse': - $macros[$k]['value'] = '-m memuse'; - break; - } - - if ($snmp_version == '3') { - $macros[$k]['value'] .= " -v3 "; - switch ($snmp3_security_level) { - case "authNoPriv": - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -A ' . $snmp3_auth_pass . - ' -l ' . $snmp3_security_level . - ' -a ' . $snmp3_auth_method; - break; - case "noAuthNoPriv": - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -l ' . $snmp3_security_level; - break; - default: - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -A ' . $snmp3_auth_pass . - ' -l ' . $snmp3_security_level . - ' -a ' . $snmp3_auth_method . - ' -x ' . $snmp3_privacy_method . - ' -X ' . $snmp3_privacy_pass; - break; - } - } - break; - } - } - - if (!empty($macros)) - $module_values['macros'] = io_json_mb_encode($macros); - - unset($module_values['snmp_community']); //snmp_community - unset($module_values['ip_target']); //ip_target - unset($module_values['tcp_send']); //snmp_version - break; - default: - $module_values['snmp_oid'] = $snmpdata_oid; - - $module_values['id_modulo'] = MODULE_SNMP; - break; - } - - $result = modules_create_agent_module( - $id_agent, io_safe_input($snmp_translation['description']), $module_values); - - $results[$result][] = $snmp_translation['description']; - } - - // PROCESSES - foreach ($processes as $process) { - $module_values = $common_values; - - $module_values['descripcion'] = sprintf(__('Check if the process %s is running or not'), $process); - $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp_proc'); - $module_values['id_modulo'] = MODULE_PLUGIN; - $module_values['id_plugin'] = $plugin['id']; - - // Avoid the return of a string containing the word 'null' if the macros column is not defined - $macros = array(); - if (isset($plugin['macros']) && !empty($plugin['macros'])) - $macros = json_decode($plugin['macros'], true); - - foreach ($macros as $k => $macro) { - switch($macro['macro']) { - case '_field1_': - // Field 1 is the IP Address - $macros[$k]['value'] = $module_values['ip_target']; - break; - case '_field2_': - // Field 2 is the community - $macros[$k]['value'] = $module_values['snmp_community']; - break; - case '_field3_': - // Field 3 is the plugin parameters - $macros[$k]['value'] = io_safe_input('-m process -p "' . $process . '"'); - - if ($snmp_version == '3') { - $macros[$k]['value'] .= " -v3 "; - switch ($snmp3_security_level) { - case "authNoPriv": - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -A ' . $snmp3_auth_pass . - ' -l ' . $snmp3_security_level . - ' -a ' . $snmp3_auth_method; - break; - case "noAuthNoPriv": - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -l ' . $snmp3_security_level; - break; - default: - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -A ' . $snmp3_auth_pass . - ' -l ' . $snmp3_security_level . - ' -a ' . $snmp3_auth_method . - ' -x ' . $snmp3_privacy_method . - ' -X ' . $snmp3_privacy_pass; - break; - } - } - break; - } - } - - if (!empty($macros)) - $module_values['macros'] = io_json_mb_encode($macros); - - unset($module_values['snmp_community']); //snmp_community - unset($module_values['ip_target']); //ip_target - unset($module_values['tcp_send']); //snmp_version - - $result = modules_create_agent_module ($id_agent, io_safe_input($process), $module_values); - - $results[$result][] = $process; - } - - - // DISKS USE - foreach ($disks as $disk) { - $module_values = $common_values; - - $module_values['descripcion'] = __('Disk use information'); - $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp'); - $module_values['id_modulo'] = MODULE_PLUGIN; - $module_values['id_plugin'] = $plugin['id']; - - // Avoid the return of a string containing the word 'null' if the macros column is not defined - $macros = array(); - if (isset($plugin['macros']) && !empty($plugin['macros'])) - $macros = json_decode($plugin['macros'], true); - - foreach ($macros as $k => $macro) { - switch($macro['macro']) { - case '_field1_': - // Field 1 is the IP Address - $macros[$k]['value'] = $module_values['ip_target']; - break; - case '_field2_': - // Field 2 is the community - $macros[$k]['value'] = $module_values['snmp_community']; - break; - case '_field3_': - // Field 3 is the plugin parameters - $macros[$k]['value'] = io_safe_input('-m diskuse -d "' . io_safe_output($disk) . '"'); - - if ($snmp_version == '3') { - $macros[$k]['value'] .= " -v3 "; - switch ($snmp3_security_level) { - case "authNoPriv": - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -A ' . $snmp3_auth_pass . - ' -l ' . $snmp3_security_level . - ' -a ' . $snmp3_auth_method; - break; - case "noAuthNoPriv": - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -l ' . $snmp3_security_level; - break; - default: - $macros[$k]['value'] .= - ' -u ' . $snmp3_auth_user . - ' -A ' . $snmp3_auth_pass . - ' -l ' . $snmp3_security_level . - ' -a ' . $snmp3_auth_method . - ' -x ' . $snmp3_privacy_method . - ' -X ' . $snmp3_privacy_pass; - break; - } - } - } - } - - if (!empty($macros)) - $module_values['macros'] = io_json_mb_encode($macros); - - unset($module_values['snmp_community']); //snmp_community - unset($module_values['ip_target']); //ip_target - unset($module_values['tcp_send']); //snmp_version - - $result = modules_create_agent_module($id_agent, - io_safe_input($disk), $module_values); - - $results[$result][] = $disk; - } - - $success_message = ''; - $error_message = ''; - - if (isset($results[NOERR])) { - if (count($results[NOERR]) > 0) { - $success_message .= sprintf(__('%s modules created succesfully'), count($results[NOERR])) . '
    '; - } - } - if (isset($results[ERR_GENERIC])) { - if (count($results[ERR_GENERIC]) > 0) { - $error_message .= sprintf(__('Error creating %s modules') . ':
      * ' . implode('
      * ', $results[ERR_GENERIC]), count($results[ERR_GENERIC])) . '
    '; - } - } - if (isset($results[ERR_DB])) { - if (count($results[ERR_DB]) > 0) { - $error_message .= sprintf(__('Error creating %s modules') . ':
      * ' . implode('
      * ', $results[ERR_DB]), count($results[ERR_DB])) . '
    '; - } - } - if (isset($results[ERR_EXIST])) { - if (count($results[ERR_EXIST]) > 0) { - $error_message .= sprintf(__('%s modules already exist') . ':
      * ' . implode('
      * ', $results[ERR_EXIST]), count($results[ERR_EXIST])) . '
    '; - } - } - - if (!empty($error_message)) { - ui_print_error_message($error_message); - } - else { - if (empty($success_message)) { - $success_message .= sprintf(__('Modules created succesfully')) . '
    '; - } - ui_print_success_message($success_message); - } - } + $modules = io_safe_output(get_parameter('module', [])); + + $devices = []; + $processes = []; + $disks = []; + $temperatures = []; + $snmpdata = []; + + foreach ($modules as $module) { + // Split module data to get type + $module_exploded = explode($separator, $module); + $type = $module_exploded[0]; + + // Delete type from module data + unset($module_exploded[0]); + + // Rebuild module data + $module = implode($separator, $module_exploded); + + switch ($type) { + case 'device': + $devices[] = $module; + break; + + case 'process': + $processes[] = $module; + break; + + case 'disk': + $disks[] = $module; + break; + + case 'temperature': + $temperatures[] = $module; + break; + + case 'snmpdata': + $snmpdata[] = $module; + break; + } + } + + if (agents_get_name($id_agent) == false) { + ui_print_error_message(__('No agent selected or the agent does not exist')); + } else { + // Common values + $common_values = []; + + if ($tcp_port != '') { + $common_values['tcp_port'] = $tcp_port; + } + + $common_values['snmp_community'] = $snmp_community; + if ($use_agent) { + $common_values['ip_target'] = 'auto'; + } else { + $common_values['ip_target'] = $ip_target; + } + + $common_values['tcp_send'] = $snmp_version; + + if ($snmp_version == '3') { + $common_values['plugin_user'] = $snmp3_auth_user; + $common_values['plugin_pass'] = $snmp3_auth_pass; + $common_values['plugin_parameter'] = $snmp3_auth_method; + $common_values['custom_string_1'] = $snmp3_privacy_method; + $common_values['custom_string_2'] = $snmp3_privacy_pass; + $common_values['custom_string_3'] = $snmp3_security_level; + } + + + // DEVICES + $devices_prefix_oids = [ + 'diskIONRead' => '.1.3.6.1.4.1.2021.13.15.1.1.3.', + 'diskIONWritten' => '.1.3.6.1.4.1.2021.13.15.1.1.4.', + 'diskIONReads' => '.1.3.6.1.4.1.2021.13.15.1.1.5.', + 'diskIONWrites' => '.1.3.6.1.4.1.2021.13.15.1.1.6.', + ]; + + $devices_prefix_descriptions = [ + 'diskIONRead' => __('The number of bytes read from this device since boot'), + 'diskIONWritten' => __('The number of bytes written to this device since boot'), + 'diskIONReads' => __('The number of read accesses from this device since boot'), + 'diskIONWrites' => __('The number of write accesses from this device since boot'), + ]; + + $results = []; + + foreach ($devices as $device) { + $module_values = $common_values; + + // Split module data to get type, name, etc + $device_exploded = explode($separator, $device); + $device_name = $device_exploded[0]; + + $name_exploded = explode('-', $device_name); + $name = ltrim(html_entity_decode($name_exploded[1])); + + $device_type = $device_exploded[1]; + + // Delete type from device id + unset($device_exploded[0]); + unset($device_exploded[1]); + + // Rebuild device_name + $device_id = implode($separator, $device_exploded); + + $module_values['descripcion'] = $devices_prefix_descriptions[$device_type]; + + if (($name == 'Bytes read') || ($name == 'Bytes written')) { + $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp_inc'); + } else { + $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp'); + } + + $module_values['snmp_oid'] = $devices_prefix_oids[$device_type].$device_id; + + $module_values['id_modulo'] = MODULE_SNMP; + + $result = modules_create_agent_module($id_agent, io_safe_input($device_name), $module_values); + + $results[$result][] = $device_name; + } + + // TEMPERATURE SENSORS + $temperatures_prefix_oid = '.1.3.6.1.4.1.2021.13.16.2.1.3.'; + $temperatures_description = 'The temperature of this sensor in C'; + + foreach ($temperatures as $temperature) { + $module_values = $common_values; + + // Split module data to get type, name, etc + $temperature_exploded = explode($separator, $temperature); + $temperature_name = $temperature_exploded[0]; + + // Delete name from temperature sensor id + unset($temperature_exploded[0]); + + // Rebuild device_name + $temperature_id = implode($separator, $temperature_exploded); + + $module_values['descripcion'] = $temperatures_description; + + $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp'); + + $module_values['snmp_oid'] = $temperatures_prefix_oid.$temperature_id; + + $module_values['id_modulo'] = MODULE_SNMP; + + // Temperature are given in mC. Convert to Celsius + $module_values['post_process'] = 0.001; + + $module_values['unit'] = 'C'; + + $result = modules_create_agent_module($id_agent, io_safe_input($temperature_name), $module_values); + + $results[$result][] = $temperature_name; + } + + // SNMP DATA (STATIC MODULES) + foreach ($snmpdata as $snmpdata_oid) { + $module_values = $common_values; + $snmp_translation = snmp_get_translation($snmpdata_oid); + + $module_values['descripcion'] = $snmp_translation['description']; + $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp'); + $module_values['post_process'] = $snmp_translation['post_process']; + + // Average use of CPUs is a plugin module + switch ($snmpdata_oid) { + case 'avgCpuLoad': + case 'memoryUse': + $module_values['id_modulo'] = MODULE_PLUGIN; + $module_values['id_plugin'] = $plugin['id']; + + // Avoid the return of a string containing the word 'null' if the macros column is not defined + $macros = []; + if (isset($plugin['macros']) && !empty($plugin['macros'])) { + $macros = json_decode($plugin['macros'], true); + } + + foreach ($macros as $k => $macro) { + switch ($macro['macro']) { + case '_field1_': + // Field 1 is the IP Address + $macros[$k]['value'] = $module_values['ip_target']; + break; + + case '_field2_': + // Field 2 is the community + $macros[$k]['value'] = $module_values['snmp_community']; + break; + + case '_field3_': + // Field 3 is the plugin parameters + switch ($snmpdata_name) { + case 'avgCpuLoad': + $macros[$k]['value'] = '-m cpuload'; + break; + + case 'memoryUse': + $macros[$k]['value'] = '-m memuse'; + break; + } + + if ($snmp_version == '3') { + $macros[$k]['value'] .= ' -v3 '; + switch ($snmp3_security_level) { + case 'authNoPriv': + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -A '.$snmp3_auth_pass.' -l '.$snmp3_security_level.' -a '.$snmp3_auth_method; + break; + + case 'noAuthNoPriv': + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -l '.$snmp3_security_level; + break; + + default: + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -A '.$snmp3_auth_pass.' -l '.$snmp3_security_level.' -a '.$snmp3_auth_method.' -x '.$snmp3_privacy_method.' -X '.$snmp3_privacy_pass; + break; + } + } + break; + } + } + + if (!empty($macros)) { + $module_values['macros'] = io_json_mb_encode($macros); + } + + unset($module_values['snmp_community']); + // snmp_community + unset($module_values['ip_target']); + // ip_target + unset($module_values['tcp_send']); + // snmp_version + break; + + default: + $module_values['snmp_oid'] = $snmpdata_oid; + + $module_values['id_modulo'] = MODULE_SNMP; + break; + } + + $result = modules_create_agent_module( + $id_agent, + io_safe_input($snmp_translation['description']), + $module_values + ); + + $results[$result][] = $snmp_translation['description']; + } + + // PROCESSES + foreach ($processes as $process) { + $module_values = $common_values; + + $module_values['descripcion'] = sprintf(__('Check if the process %s is running or not'), $process); + $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp_proc'); + $module_values['id_modulo'] = MODULE_PLUGIN; + $module_values['id_plugin'] = $plugin['id']; + + // Avoid the return of a string containing the word 'null' if the macros column is not defined + $macros = []; + if (isset($plugin['macros']) && !empty($plugin['macros'])) { + $macros = json_decode($plugin['macros'], true); + } + + foreach ($macros as $k => $macro) { + switch ($macro['macro']) { + case '_field1_': + // Field 1 is the IP Address + $macros[$k]['value'] = $module_values['ip_target']; + break; + + case '_field2_': + // Field 2 is the community + $macros[$k]['value'] = $module_values['snmp_community']; + break; + + case '_field3_': + // Field 3 is the plugin parameters + $macros[$k]['value'] = io_safe_input('-m process -p "'.$process.'"'); + + if ($snmp_version == '3') { + $macros[$k]['value'] .= ' -v3 '; + switch ($snmp3_security_level) { + case 'authNoPriv': + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -A '.$snmp3_auth_pass.' -l '.$snmp3_security_level.' -a '.$snmp3_auth_method; + break; + + case 'noAuthNoPriv': + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -l '.$snmp3_security_level; + break; + + default: + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -A '.$snmp3_auth_pass.' -l '.$snmp3_security_level.' -a '.$snmp3_auth_method.' -x '.$snmp3_privacy_method.' -X '.$snmp3_privacy_pass; + break; + } + } + break; + } + } + + if (!empty($macros)) { + $module_values['macros'] = io_json_mb_encode($macros); + } + + unset($module_values['snmp_community']); + // snmp_community + unset($module_values['ip_target']); + // ip_target + unset($module_values['tcp_send']); + // snmp_version + $result = modules_create_agent_module($id_agent, io_safe_input($process), $module_values); + + $results[$result][] = $process; + } + + + // DISKS USE + foreach ($disks as $disk) { + $module_values = $common_values; + + $module_values['descripcion'] = __('Disk use information'); + $module_values['id_tipo_modulo'] = modules_get_type_id('remote_snmp'); + $module_values['id_modulo'] = MODULE_PLUGIN; + $module_values['id_plugin'] = $plugin['id']; + + // Avoid the return of a string containing the word 'null' if the macros column is not defined + $macros = []; + if (isset($plugin['macros']) && !empty($plugin['macros'])) { + $macros = json_decode($plugin['macros'], true); + } + + foreach ($macros as $k => $macro) { + switch ($macro['macro']) { + case '_field1_': + // Field 1 is the IP Address + $macros[$k]['value'] = $module_values['ip_target']; + break; + + case '_field2_': + // Field 2 is the community + $macros[$k]['value'] = $module_values['snmp_community']; + break; + + case '_field3_': + // Field 3 is the plugin parameters + $macros[$k]['value'] = io_safe_input('-m diskuse -d "'.io_safe_output($disk).'"'); + + if ($snmp_version == '3') { + $macros[$k]['value'] .= ' -v3 '; + switch ($snmp3_security_level) { + case 'authNoPriv': + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -A '.$snmp3_auth_pass.' -l '.$snmp3_security_level.' -a '.$snmp3_auth_method; + break; + + case 'noAuthNoPriv': + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -l '.$snmp3_security_level; + break; + + default: + $macros[$k]['value'] .= ' -u '.$snmp3_auth_user.' -A '.$snmp3_auth_pass.' -l '.$snmp3_security_level.' -a '.$snmp3_auth_method.' -x '.$snmp3_privacy_method.' -X '.$snmp3_privacy_pass; + break; + } + } + } + } + + if (!empty($macros)) { + $module_values['macros'] = io_json_mb_encode($macros); + } + + unset($module_values['snmp_community']); + // snmp_community + unset($module_values['ip_target']); + // ip_target + unset($module_values['tcp_send']); + // snmp_version + $result = modules_create_agent_module( + $id_agent, + io_safe_input($disk), + $module_values + ); + + $results[$result][] = $disk; + } + + $success_message = ''; + $error_message = ''; + + if (isset($results[NOERR])) { + if (count($results[NOERR]) > 0) { + $success_message .= sprintf(__('%s modules created succesfully'), count($results[NOERR])).'
    '; + } + } + + if (isset($results[ERR_GENERIC])) { + if (count($results[ERR_GENERIC]) > 0) { + $error_message .= sprintf(__('Error creating %s modules').':
      * '.implode('
      * ', $results[ERR_GENERIC]), count($results[ERR_GENERIC])).'
    '; + } + } + + if (isset($results[ERR_DB])) { + if (count($results[ERR_DB]) > 0) { + $error_message .= sprintf(__('Error creating %s modules').':
      * '.implode('
      * ', $results[ERR_DB]), count($results[ERR_DB])).'
    '; + } + } + + if (isset($results[ERR_EXIST])) { + if (count($results[ERR_EXIST]) > 0) { + $error_message .= sprintf(__('%s modules already exist').':
      * '.implode('
      * ', $results[ERR_EXIST]), count($results[ERR_EXIST])).'
    '; + } + } + + if (!empty($error_message)) { + ui_print_error_message($error_message); + } else { + if (empty($success_message)) { + $success_message .= sprintf(__('Modules created succesfully')).'
    '; + } + + ui_print_success_message($success_message); + } + } } -echo ''; +echo ''; echo "
    "; $table->width = '100%'; @@ -702,47 +724,47 @@ $table->cellpadding = 0; $table->cellspacing = 0; $table->class = 'databox filters'; -$table->data[0][0] = '' . __('Target IP') . ''; -$table->data[0][1] = html_print_input_text ('ip_target', $ip_target, '', 15, 60, true); +$table->data[0][0] = ''.__('Target IP').''; +$table->data[0][1] = html_print_input_text('ip_target', $ip_target, '', 15, 60, true); -$table->data[0][2] = '' . __('Port') . ''; -$table->data[0][3] = html_print_input_text ('tcp_port', $tcp_port, '', 5, 20, true); +$table->data[0][2] = ''.__('Port').''; +$table->data[0][3] = html_print_input_text('tcp_port', $tcp_port, '', 5, 20, true); -$table->data[1][0] = '' . __('Use agent ip') . ''; -$table->data[1][1] = html_print_checkbox ('use_agent', 1, $use_agent, true); +$table->data[1][0] = ''.__('Use agent ip').''; +$table->data[1][1] = html_print_checkbox('use_agent', 1, $use_agent, true); -$servers_to_exec = array(); +$servers_to_exec = []; $servers_to_exec[0] = __('Local console'); if (enterprise_installed()) { - enterprise_include_once ('include/functions_satellite.php'); - - $rows = get_proxy_servers(true); - foreach ($rows as $row) { - if ($row['server_type'] != 13) { - $s_type = " (Standard)"; - } - else { - $s_type = " (Satellite)"; - } + enterprise_include_once('include/functions_satellite.php'); - $servers_to_exec[$row['id_server']] = $row['name'] . $s_type; - } + $rows = get_proxy_servers(true); + foreach ($rows as $row) { + if ($row['server_type'] != 13) { + $s_type = ' (Standard)'; + } else { + $s_type = ' (Satellite)'; + } + + $servers_to_exec[$row['id_server']] = $row['name'].$s_type; + } } -$table->data[1][2] = '' . __('Server to execute command') . ''; -$table->data[1][3] = html_print_select ($servers_to_exec, 'server_to_exec', $server_to_exec, '', '', '', true); + +$table->data[1][2] = ''.__('Server to execute command').''; +$table->data[1][3] = html_print_select($servers_to_exec, 'server_to_exec', $server_to_exec, '', '', '', true); $snmp_versions['1'] = 'v. 1'; $snmp_versions['2'] = 'v. 2'; $snmp_versions['2c'] = 'v. 2c'; $snmp_versions['3'] = 'v. 3'; -$table->data[2][0] = '' . __('SNMP community') . ''; -$table->data[2][1] = html_print_input_text ('snmp_community', $snmp_community, '', 15, 60, true); +$table->data[2][0] = ''.__('SNMP community').''; +$table->data[2][1] = html_print_input_text('snmp_community', $snmp_community, '', 15, 60, true); -$table->data[2][2] = '' . __('SNMP version') . ''; -$table->data[2][3] = html_print_select ($snmp_versions, 'snmp_version', $snmp_version, '', '', '', true, false, false, ''); +$table->data[2][2] = ''.__('SNMP version').''; +$table->data[2][3] = html_print_select($snmp_versions, 'snmp_version', $snmp_version, '', '', '', true, false, false, ''); -$table->data[2][3] .= ''; +$table->data[2][3] .= ''; html_print_input_hidden('snmpwalk', 1); @@ -750,166 +772,246 @@ html_print_table($table); unset($table); -//SNMP3 OPTIONS +// SNMP3 OPTIONS $table->width = '100%'; $table->data[2][1] = ''.__('Auth user').''; -$table->data[2][2] = html_print_input_text ('snmp3_auth_user', $snmp3_auth_user, '', 15, 60, true); +$table->data[2][2] = html_print_input_text('snmp3_auth_user', $snmp3_auth_user, '', 15, 60, true); $table->data[2][3] = ''.__('Auth password').''; -$table->data[2][4] = html_print_input_password ('snmp3_auth_pass', $snmp3_auth_pass, '', 15, 60, true); +$table->data[2][4] = html_print_input_password('snmp3_auth_pass', $snmp3_auth_pass, '', 15, 60, true); $table->data[2][4] .= html_print_input_hidden_extended('active_snmp_v3', 0, 'active_snmp_v3_awse', true); $table->data[5][0] = ''.__('Privacy method').''; -$table->data[5][1] = html_print_select(array('DES' => __('DES'), 'AES' => __('AES')), 'snmp3_privacy_method', $snmp3_privacy_method, '', '', '', true); +$table->data[5][1] = html_print_select(['DES' => __('DES'), 'AES' => __('AES')], 'snmp3_privacy_method', $snmp3_privacy_method, '', '', '', true); $table->data[5][2] = ''.__('privacy pass').''; -$table->data[5][3] = html_print_input_password ('snmp3_privacy_pass', $snmp3_privacy_pass, '', 15, 60, true); +$table->data[5][3] = html_print_input_password('snmp3_privacy_pass', $snmp3_privacy_pass, '', 15, 60, true); $table->data[6][0] = ''.__('Auth method').''; -$table->data[6][1] = html_print_select(array('MD5' => __('MD5'), 'SHA' => __('SHA')), 'snmp3_auth_method', $snmp3_auth_method, '', '', '', true); +$table->data[6][1] = html_print_select(['MD5' => __('MD5'), 'SHA' => __('SHA')], 'snmp3_auth_method', $snmp3_auth_method, '', '', '', true); $table->data[6][2] = ''.__('Security level').''; -$table->data[6][3] = html_print_select(array('noAuthNoPriv' => __('Not auth and not privacy method'), - 'authNoPriv' => __('Auth and not privacy method'), 'authPriv' => __('Auth and privacy method')), 'snmp3_security_level', $snmp3_security_level, '', '', '', true); +$table->data[6][3] = html_print_select( + [ + 'noAuthNoPriv' => __('Not auth and not privacy method'), + 'authNoPriv' => __('Auth and not privacy method'), + 'authPriv' => __('Auth and privacy method'), + ], + 'snmp3_security_level', + $snmp3_security_level, + '', + '', + '', + true +); if ($snmp_version == 3) { - echo '
    '; -} -else { - echo ''; + html_print_input_hidden('create_modules', 1); + html_print_input_hidden('ip_target', $ip_target); + html_print_input_hidden('use_agent', $use_agent); + html_print_input_hidden('tcp_port', $tcp_port); + html_print_input_hidden('snmp_community', $snmp_community); + html_print_input_hidden('snmp_version', $snmp_version); + html_print_input_hidden('snmp3_auth_user', $snmp3_auth_user); + html_print_input_hidden('snmp3_auth_pass', $snmp3_auth_pass); + html_print_input_hidden('snmp3_auth_method', $snmp3_auth_method); + html_print_input_hidden('snmp3_privacy_method', $snmp3_privacy_method); + html_print_input_hidden('snmp3_privacy_pass', $snmp3_privacy_pass); + html_print_input_hidden('snmp3_security_level', $snmp3_security_level); + + $table->width = '100%'; + + // Mode selector + $modes = []; + $modes['devices'] = __('Devices'); + $modes['processes'] = __('Processes'); + $modes['disks'] = __('Free space on disk'); + $modes['temperatures'] = __('Temperature sensors'); + $modes['snmpdata'] = __('Other SNMP data'); + + $table->data[1][0] = __('Wizard mode').': '; + $table->data[1][0] .= html_print_select( + $modes, + 'snmp_wizard_modes', + '', + '', + '', + '', + true, + false, + false + ); + $table->cellstyle[1][0] = 'vertical-align: middle;'; + + $table->colspan[1][0] = 2; + $table->data[1][2] = ''.__('Modules').''; + $table->cellstyle[1][2] = 'vertical-align: middle;'; + + // Devices list + $table->data[2][0] = '
    '; + $table->data[2][0] .= html_print_select( + $devices, + 'devices', + '', + '', + '', + '', + true, + true, + true, + '', + false, + 'width: 300px;' + ); + $table->data[2][0] .= '
    '; + + // If SNMP remote plugin is not installed, show an advice + if (empty($plugin)) { + // Processes list + $table->data[2][0] .= '
    '; + $table->data[2][0] .= ui_print_info_message(__('SNMP remote plugin is necessary for this feature'), '', true); + $table->data[2][0] .= '
    '; + + // Disks list + $table->data[2][0] .= '
    '; + $table->data[2][0] .= ui_print_info_message(__('SNMP remote plugin is necessary for this feature'), '', true); + $table->data[2][0] .= '
    '; + } else { + // Processes list + $table->data[2][0] .= '
    '; + $table->data[2][0] .= html_print_select( + $processes, + 'processes', + '', + '', + '', + '', + true, + true, + true, + '', + false, + 'width: 300px;' + ); + $table->data[2][0] .= '
    '; + + // Disks list + $table->data[2][0] .= '
    '; + $table->data[2][0] .= html_print_select( + $disks, + 'disks', + '', + '', + '', + '', + true, + true, + true, + '', + false, + 'width: 300px;' + ); + $table->data[2][0] .= '
    '; + } + + // Sensors temperatures list + $table->data[2][0] .= '
    '; + $table->data[2][0] .= html_print_select( + $temperatures, + 'temperatures', + '', + '', + '', + '', + true, + true, + true, + '', + false, + 'width: 300px;' + ); + $table->data[2][0] .= '
    '; + + // SNMP data list + $table->data[2][0] .= '
    '; + $table->data[2][0] .= html_print_select( + $other_snmp_data, + 'snmpdata', + '', + '', + '', + '', + true, + true, + true, + '', + false, + 'width: 300px;' + ); + $table->data[2][0] .= '
    '; + + $table->cellstyle[2][0] = 'vertical-align: top; text-align: center;'; + + // Devices arrow + $table->data[2][1] = '
    '.html_print_image('images/darrowright.png', true, ['title' => __('Add to modules list')]).'
    '; + // Processes arrow + $table->data[2][1] .= '
    '.html_print_image('images/darrowright.png', true, ['title' => __('Add to modules list')]).'
    '; + // Disks arrow + $table->data[2][1] .= '
    '.html_print_image('images/darrowright.png', true, ['title' => __('Add to modules list')]).'
    '; + // Temperatures arrow + $table->data[2][1] .= '
    '.html_print_image('images/darrowright.png', true, ['title' => __('Add to modules list')]).'
    '; + // SNMP data arrow + if ($arrow) { + $table->data[2][1] .= '
    '.html_print_image('images/darrowright.png', true, ['title' => __('Add to modules list')]).'
    '; + } + + $table->data[2][1] .= '

    '.html_print_image('images/cross.png', true, ['title' => __('Remove from modules list')]).'
    '; + $table->cellstyle[2][1] = 'vertical-align: middle; text-align: center;'; + + $table->data[2][2] = html_print_select([], 'module[]', 0, false, '', 0, true, true, true, '', false, 'width:300px; height: 100%;'); + $table->data[2][2] .= html_print_input_hidden('agent', $id_agent, true); + $table->cellstyle[2][2] = 'vertical-align: top; text-align: center;'; + + html_print_table($table); + + echo "
    "; + html_print_submit_button(__('Create modules'), 'create_modules_btn', false, ['class' => 'sub add']); + echo '
    '; + unset($table); + + echo ''; + echo ''; + echo '
    '; } -ui_require_jquery_file ('pandora.controls'); -ui_require_jquery_file ('ajaxqueue'); -ui_require_jquery_file ('bgiframe'); -ui_require_javascript_file ('pandora_modules'); +ui_require_jquery_file('pandora.controls'); +ui_require_jquery_file('ajaxqueue'); +ui_require_jquery_file('bgiframe'); +ui_require_javascript_file('pandora_modules'); ?> '; - - $agent = db_get_row ('tagente', 'id_agente', $id_agente); - db_pandora_audit("Agent management", - "Deleted module '".io_safe_output($module_data["nombre"])."' for agent ".io_safe_output($agent["alias"])); - } - + $agent = db_get_row('tagente', 'id_agente', $id_agente); + db_pandora_audit( + 'Agent management', + "Deleted module '".$module_data['nombre']."' for agent ".$agent['alias'] + ); + } } // MODULE DUPLICATION // ================== -if (!empty($duplicate_module)) { // DUPLICATE agent module ! - $id_duplicate_module = $duplicate_module; - - $original_name = modules_get_agentmodule_name($id_duplicate_module); - $copy_name = io_safe_input(sprintf(__('copy of %s'), io_safe_output($original_name))); - - $cont = 0; - $exists = true; - while($exists) { - $exists = (bool)db_get_value ('id_agente_modulo', 'tagente_modulo', - 'nombre', $copy_name); - if ($exists) { - $cont++; - $copy_name = io_safe_input( - sprintf(__('copy of %s (%d)'), io_safe_output($original_name), $cont)); - } - } - - $result = modules_copy_agent_module_to_agent ($id_duplicate_module, - modules_get_agentmodule_agent($id_duplicate_module), $copy_name); - - $agent = db_get_row ('tagente', 'id_agente', $id_agente); - - if ($result) { - db_pandora_audit("Agent management", - "Duplicate module '".$id_duplicate_module."' for agent " . io_safe_output($agent["alias"]) . " with the new id for clon " . $result); - } - else { - db_pandora_audit("Agent management", - "Fail to try duplicate module '".$id_duplicate_module."' for agent " . io_safe_output($agent["alias"])); - } +if (!empty($duplicate_module)) { + // DUPLICATE agent module ! + $id_duplicate_module = $duplicate_module; + + $original_name = modules_get_agentmodule_name($id_duplicate_module); + $copy_name = io_safe_input(sprintf(__('copy of %s'), io_safe_output($original_name))); + + $cont = 0; + $exists = true; + while ($exists) { + $exists = (bool) db_get_value( + 'id_agente_modulo', + 'tagente_modulo', + 'nombre', + $copy_name + ); + if ($exists) { + $cont++; + $copy_name = io_safe_input( + sprintf(__('copy of %s (%d)'), io_safe_output($original_name), $cont) + ); + } + } + + $result = modules_copy_agent_module_to_agent( + $id_duplicate_module, + modules_get_agentmodule_agent($id_duplicate_module), + $copy_name + ); + + $agent = db_get_row('tagente', 'id_agente', $id_agente); + + if ($result) { + db_pandora_audit( + 'Agent management', + "Duplicate module '".$id_duplicate_module."' for agent ".$agent['alias'].' with the new id for clon '.$result + ); + } else { + db_pandora_audit( + 'Agent management', + "Fail to try duplicate module '".$id_duplicate_module."' for agent ".$agent['alias'] + ); + } } // MODULE ENABLE/DISABLE // ===================== if ($enable_module) { - $result = modules_change_disabled($enable_module, 0); - $modulo_nombre = db_get_row_sql("SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = ".$enable_module.""); - $modulo_nombre = $modulo_nombre['nombre']; + $result = modules_change_disabled($enable_module, 0); + $modulo_nombre = db_get_row_sql('SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = '.$enable_module.''); + $modulo_nombre = $modulo_nombre['nombre']; - if ($result === NOERR) { - enterprise_hook('config_agents_enable_module_conf', array($id_agente, $enable_module)); - db_pandora_audit("Module management", 'Enable #' . $enable_module . ' | ' . $modulo_nombre . ' | ' . $agent["alias"]); - } - else { - db_pandora_audit("Module management", 'Fail to enable #' . $enable_module . ' | ' . $modulo_nombre . ' | ' . $agent["alias"]); - } - - ui_print_result_message ($result, - __('Successfully enabled'), __('Could not be enabled')); + if ($result === NOERR) { + enterprise_hook('config_agents_enable_module_conf', [$id_agente, $enable_module]); + db_pandora_audit('Module management', 'Enable #'.$enable_module.' | '.$modulo_nombre.' | '.$agent['alias']); + } else { + db_pandora_audit('Module management', 'Fail to enable #'.$enable_module.' | '.$modulo_nombre.' | '.$agent['alias']); + } + + ui_print_result_message( + $result, + __('Successfully enabled'), + __('Could not be enabled') + ); } if ($disable_module) { - $result = modules_change_disabled($disable_module, 1); - $modulo_nombre = db_get_row_sql("SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = ".$disable_module.""); - $modulo_nombre = $modulo_nombre['nombre']; + $result = modules_change_disabled($disable_module, 1); + $modulo_nombre = db_get_row_sql('SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = '.$disable_module.''); + $modulo_nombre = $modulo_nombre['nombre']; - if ($result === NOERR) { - enterprise_hook('config_agents_disable_module_conf', array($id_agente, $disable_module)); - db_pandora_audit("Module management", 'Disable #' . $disable_module . ' | ' . $modulo_nombre . ' | ' . $agent["alias"]); - } - else { - db_pandora_audit("Module management", 'Fail to disable #' . $disable_module . ' | ' . $modulo_nombre . ' | ' . $agent["alias"]); - } - - ui_print_result_message ($result, - __('Successfully disabled'), __('Could not be disabled')); + if ($result === NOERR) { + enterprise_hook('config_agents_disable_module_conf', [$id_agente, $disable_module]); + db_pandora_audit('Module management', 'Disable #'.$disable_module.' | '.$modulo_nombre.' | '.$agent['alias']); + } else { + db_pandora_audit('Module management', 'Fail to disable #'.$disable_module.' | '.$modulo_nombre.' | '.$agent['alias']); + } + + ui_print_result_message( + $result, + __('Successfully disabled'), + __('Could not be disabled') + ); } // UPDATE GIS // ========== $updateGIS = get_parameter('update_gis', 0); if ($updateGIS) { - $updateGisData = get_parameter("update_gis_data"); - $lastLatitude = get_parameter("latitude"); - $lastLongitude = get_parameter("longitude"); - $lastAltitude = get_parameter("altitude"); - $idAgente = get_parameter("id_agente"); - - $previusAgentGISData = db_get_row_sql(" + $updateGisData = get_parameter('update_gis_data'); + $lastLatitude = get_parameter('latitude'); + $lastLongitude = get_parameter('longitude'); + $lastAltitude = get_parameter('altitude'); + $idAgente = get_parameter('id_agente'); + + $previusAgentGISData = db_get_row_sql( + ' SELECT * FROM tgis_data_status - WHERE tagente_id_agente = " . $idAgente); - - db_process_sql_update('tagente', array('update_gis_data' => $updateGisData), - array('id_agente' => $idAgente)); - - if ($previusAgentGISData !== false) { - db_process_sql_insert('tgis_data_history', array( - "longitude" => $previusAgentGISData['stored_longitude'], - "latitude" => $previusAgentGISData['stored_latitude'], - "altitude" => $previusAgentGISData['stored_altitude'], - "start_timestamp" => $previusAgentGISData['start_timestamp'], - "end_timestamp" => date( 'Y-m-d H:i:s'), - "description" => __('Save by %s Console', get_product_name()), - "manual_placement" => $previusAgentGISData['manual_placement'], - "number_of_packages" => $previusAgentGISData['number_of_packages'], - "tagente_id_agente" => $previusAgentGISData['tagente_id_agente'] - )); - db_process_sql_update('tgis_data_status', array( - "tagente_id_agente" => $idAgente, - "current_longitude" => $lastLongitude, - "current_latitude" => $lastLatitude, - "current_altitude" => $lastAltitude, - "stored_longitude" => $lastLongitude, - "stored_latitude" => $lastLatitude, - "stored_altitude" => $lastAltitude, - "start_timestamp" => date( 'Y-m-d H:i:s'), - "manual_placement" => 1, - "description" => __('Update by %s Console', get_product_name())), - array("tagente_id_agente" => $idAgente)); - } - else { - db_process_sql_insert('tgis_data_status', array( - "tagente_id_agente" => $idAgente, - "current_longitude" => $lastLongitude, - "current_latitude" => $lastLatitude, - "current_altitude" => $lastAltitude, - "stored_longitude" => $lastLongitude, - "stored_latitude" => $lastLatitude, - "stored_altitude" => $lastAltitude, - "manual_placement" => 1, - "description" => __('Insert by %s Console', get_product_name()) - )); - } + WHERE tagente_id_agente = '.$idAgente + ); + + db_process_sql_update( + 'tagente', + ['update_gis_data' => $updateGisData], + ['id_agente' => $idAgente] + ); + + if ($previusAgentGISData !== false) { + db_process_sql_insert( + 'tgis_data_history', + [ + 'longitude' => $previusAgentGISData['stored_longitude'], + 'latitude' => $previusAgentGISData['stored_latitude'], + 'altitude' => $previusAgentGISData['stored_altitude'], + 'start_timestamp' => $previusAgentGISData['start_timestamp'], + 'end_timestamp' => date('Y-m-d H:i:s'), + 'description' => __('Save by %s Console', get_product_name()), + 'manual_placement' => $previusAgentGISData['manual_placement'], + 'number_of_packages' => $previusAgentGISData['number_of_packages'], + 'tagente_id_agente' => $previusAgentGISData['tagente_id_agente'], + ] + ); + db_process_sql_update( + 'tgis_data_status', + [ + 'tagente_id_agente' => $idAgente, + 'current_longitude' => $lastLongitude, + 'current_latitude' => $lastLatitude, + 'current_altitude' => $lastAltitude, + 'stored_longitude' => $lastLongitude, + 'stored_latitude' => $lastLatitude, + 'stored_altitude' => $lastAltitude, + 'start_timestamp' => date('Y-m-d H:i:s'), + 'manual_placement' => 1, + 'description' => __('Update by %s Console', get_product_name()), + ], + ['tagente_id_agente' => $idAgente] + ); + } else { + db_process_sql_insert( + 'tgis_data_status', + [ + 'tagente_id_agente' => $idAgente, + 'current_longitude' => $lastLongitude, + 'current_latitude' => $lastLatitude, + 'current_altitude' => $lastAltitude, + 'stored_longitude' => $lastLongitude, + 'stored_latitude' => $lastLatitude, + 'stored_altitude' => $lastAltitude, + 'manual_placement' => 1, + 'description' => __('Insert by %s Console', get_product_name()), + ] + ); + } } // ----------------------------------- // Load page depending on tab selected // ----------------------------------- switch ($tab) { - case "main": - require ("agent_manager.php"); - break; - case "module": - if ($id_agent_module || $edit_module) { - require ("module_manager_editor.php"); - } - else { - require ("module_manager.php"); - } - break; - case "alert": - /* Because $id_agente is set, it will show only agent alerts */ - /* This var is for not display create button on alert list */ - $dont_display_alert_create_bttn = true; - require ("godmode/alerts/alert_list.php"); - break; - case "template": - require ("agent_template.php"); - break; - case "gis": - require("agent_conf_gis.php"); - break; - case "incident": - require("agent_incidents.php"); - break; - case "remote_configuration": - enterprise_include("godmode/agentes/agent_disk_conf_editor.php"); - break; - case "extension": - $found = false; - foreach($config['extensions'] as $extension) { - if (isset($extension['extension_god_tab'])) { - $id = $extension['extension_god_tab']['id']; - $function = $extension['extension_god_tab']['function']; - - $id_extension = get_parameter('id_extension', ''); - - if ($id_extension == $id) { - call_user_func_array($function, array()); - $found = true; - } - } - } - if (!$found) { - ui_print_error_message (__('Invalid tab specified')); - } - break; - case "agent_wizard": - require("agent_wizard.php"); - break; - default: - if (enterprise_hook ('switch_agent_tab', array ($tab))) { - //This will make sure that blank pages will have at least some - //debug info in them - do not translate debug - ui_print_error_message (__('Invalid tab specified')); - } - break; + case 'main': + include 'agent_manager.php'; + break; + + case 'module': + if ($id_agent_module || $edit_module) { + include 'module_manager_editor.php'; + } else { + include 'module_manager.php'; + } + break; + + case 'alert': + /* + Because $id_agente is set, it will show only agent alerts */ + // This var is for not display create button on alert list + $dont_display_alert_create_bttn = true; + include 'godmode/alerts/alert_list.php'; + break; + + case 'template': + include 'agent_template.php'; + break; + + case 'gis': + include 'agent_conf_gis.php'; + break; + + case 'incident': + include 'agent_incidents.php'; + break; + + case 'remote_configuration': + enterprise_include('godmode/agentes/agent_disk_conf_editor.php'); + break; + + case 'extension': + $found = false; + foreach ($config['extensions'] as $extension) { + if (isset($extension['extension_god_tab'])) { + $id = $extension['extension_god_tab']['id']; + $function = $extension['extension_god_tab']['function']; + + $id_extension = get_parameter('id_extension', ''); + + if ($id_extension == $id) { + call_user_func_array($function, []); + $found = true; + } + } + } + + if (!$found) { + ui_print_error_message(__('Invalid tab specified')); + } + break; + + case 'agent_wizard': + include 'agent_wizard.php'; + break; + + default: + if (enterprise_hook('switch_agent_tab', [$tab])) { + // This will make sure that blank pages will have at least some + // debug info in them - do not translate debug + ui_print_error_message(__('Invalid tab specified')); + } + break; } ?> diff --git a/pandora_console/godmode/agentes/configure_field.php b/pandora_console/godmode/agentes/configure_field.php index d1d1044377..25afef0c21 100755 --- a/pandora_console/godmode/agentes/configure_field.php +++ b/pandora_console/godmode/agentes/configure_field.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,33 +11,30 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", "Trying to access Group Management2"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit('ACL Violation', 'Trying to access Group Management2'); + include 'general/noaccess.php'; + return; } -$id_field = (int) get_parameter ('id_field', 0); -$name = (string) get_parameter ('name', ''); -$display_on_front = (bool) get_parameter ('display_on_front', 0); -$is_password_type = (bool) get_parameter ('is_password_type', 0); +$id_field = (int) get_parameter('id_field', 0); +$name = (string) get_parameter('name', ''); +$display_on_front = (bool) get_parameter('display_on_front', 0); +$is_password_type = (bool) get_parameter('is_password_type', 0); // Header if ($id_field) { - $field = db_get_row_filter('tagent_custom_fields',array('id_field' => $id_field)); - $name = $field['name']; - $display_on_front = $field['display_on_front']; - $is_password_type = $field['is_password_type']; - ui_print_page_header (__("Update agent custom field"), "images/custom_field.png", false, "", true, ""); -} -else { - ui_print_page_header (__("Create agent custom field"), "images/custom_field.png", false, "", true, ""); + $field = db_get_row_filter('tagent_custom_fields', ['id_field' => $id_field]); + $name = $field['name']; + $display_on_front = $field['display_on_front']; + $is_password_type = $field['is_password_type']; + ui_print_page_header(__('Update agent custom field'), 'images/custom_field.png', false, '', true, ''); +} else { + ui_print_page_header(__('Create agent custom field'), 'images/custom_field.png', false, '', true, ''); } $table = new stdClass(); @@ -46,30 +42,28 @@ $table->width = '100%'; $table->class = 'databox filters'; $table->style[0] = 'font-weight: bold'; $table->style[2] = 'font-weight: bold'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Name'); -$table->data[0][1] = html_print_input_text ('name', $name, '', 35, 100, true); +$table->data[0][1] = html_print_input_text('name', $name, '', 35, 100, true); -$table->data[0][2] = __('Pass type').ui_print_help_tip (__('The fields with pass type enabled will be displayed like html input type pass in html'), true); -$table->data[0][3] = html_print_checkbox ('is_password_type', 1, $is_password_type, true); +$table->data[0][2] = __('Pass type').ui_print_help_tip(__('The fields with pass type enabled will be displayed like html input type pass in html'), true); +$table->data[0][3] = html_print_checkbox('is_password_type', 1, $is_password_type, true); -$table->data[0][4] = __('Display on front').ui_print_help_tip (__('The fields with display on front enabled will be displayed into the agent details'), true); -$table->data[0][5] = html_print_checkbox ('display_on_front', 1, $display_on_front, true); +$table->data[0][4] = __('Display on front').ui_print_help_tip(__('The fields with display on front enabled will be displayed into the agent details'), true); +$table->data[0][5] = html_print_checkbox('display_on_front', 1, $display_on_front, true); echo '
    '; -html_print_table ($table); +html_print_table($table); echo '
    '; if ($id_field) { - html_print_input_hidden ('update_field', 1); - html_print_input_hidden ('id_field', $id_field); - html_print_submit_button (__('Update'), 'updbutton', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create_field', 1); - html_print_submit_button (__('Create'), 'crtbutton', false, 'class="sub wand"'); + html_print_input_hidden('update_field', 1); + html_print_input_hidden('id_field', $id_field); + html_print_submit_button(__('Update'), 'updbutton', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create_field', 1); + html_print_submit_button(__('Create'), 'crtbutton', false, 'class="sub wand"'); } echo '
    '; echo '
    '; -?> diff --git a/pandora_console/godmode/agentes/fields_manager.php b/pandora_console/godmode/agentes/fields_manager.php index c90662246f..867942871d 100644 --- a/pandora_console/godmode/agentes/fields_manager.php +++ b/pandora_console/godmode/agentes/fields_manager.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,78 +11,86 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars global $config; check_login(); -if (!check_acl($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Group Management"); - require ("general/noaccess.php"); - - return; +if (!check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Group Management' + ); + include 'general/noaccess.php'; + + return; } // Header -ui_print_page_header (__("Agents custom fields manager"), "images/custom_field.png", false, "", true, ""); +ui_print_page_header(__('Agents custom fields manager'), 'images/custom_field.png', false, '', true, ''); -$create_field = (bool) get_parameter ('create_field'); -$update_field = (bool) get_parameter ('update_field'); -$delete_field = (bool) get_parameter ('delete_field'); -$id_field = (int) get_parameter ('id_field', 0); -$name = (string) get_parameter ('name', ''); -$display_on_front = (int) get_parameter ('display_on_front', 0); -$is_password_type = (int) get_parameter ('is_password_type', 0); +$create_field = (bool) get_parameter('create_field'); +$update_field = (bool) get_parameter('update_field'); +$delete_field = (bool) get_parameter('delete_field'); +$id_field = (int) get_parameter('id_field', 0); +$name = (string) get_parameter('name', ''); +$display_on_front = (int) get_parameter('display_on_front', 0); +$is_password_type = (int) get_parameter('is_password_type', 0); -/* Create field */ +// Create field if ($create_field) { - /*Check if name field is empty*/ - if ($name == "") { - ui_print_error_message(__('The name must not be empty')); - } - else if ($name == db_get_value ('name', 'tagent_custom_fields', 'name', $name)) { - ui_print_error_message(__('The name must be unique')); - } - else { - $result = db_process_sql_insert('tagent_custom_fields', - array('name' => $name, 'display_on_front' => $display_on_front, - 'is_password_type' => $is_password_type)); - ui_print_success_message(__('Field successfully created')); - } + // Check if name field is empty + if ($name == '') { + ui_print_error_message(__('The name must not be empty')); + } else if ($name == db_get_value('name', 'tagent_custom_fields', 'name', $name)) { + ui_print_error_message(__('The name must be unique')); + } else { + $result = db_process_sql_insert( + 'tagent_custom_fields', + [ + 'name' => $name, + 'display_on_front' => $display_on_front, + 'is_password_type' => $is_password_type, + ] + ); + ui_print_success_message(__('Field successfully created')); + } } -/* Update field */ +// Update field if ($update_field) { - /*Check if name field is empty*/ - if ( $name != "") { - $values = array('name' => $name, 'display_on_front' => $display_on_front, 'is_password_type' => $is_password_type); - - $result = db_process_sql_update('tagent_custom_fields', $values, array('id_field' => $id_field)); - } - else { - $result = false; - } - - if ($result !== false) { - ui_print_success_message(__('Field successfully updated')); - } - else { - ui_print_error_message(__('There was a problem modifying field')); - } + // Check if name field is empty + if ($name != '') { + $values = [ + 'name' => $name, + 'display_on_front' => $display_on_front, + 'is_password_type' => $is_password_type, + ]; + + $result = db_process_sql_update('tagent_custom_fields', $values, ['id_field' => $id_field]); + } else { + $result = false; + } + + if ($result !== false) { + ui_print_success_message(__('Field successfully updated')); + } else { + ui_print_error_message(__('There was a problem modifying field')); + } } -/* Delete field */ +// Delete field if ($delete_field) { - $result = db_process_sql_delete('tagent_custom_fields', - array('id_field' => $id_field)); - - if (!$result) - ui_print_error_message(__('There was a problem deleting field')); - else - ui_print_success_message(__('Field successfully deleted')); + $result = db_process_sql_delete( + 'tagent_custom_fields', + ['id_field' => $id_field] + ); + + if (!$result) { + ui_print_error_message(__('There was a problem deleting field')); + } else { + ui_print_success_message(__('Field successfully deleted')); + } } $fields = db_get_all_fields_in_table('tagent_custom_fields'); @@ -92,53 +99,50 @@ $table = new stdClass(); $table->width = '100%'; $table->class = 'databox data'; if ($fields) { - $table->head = array (); - $table->head[0] = __('ID'); - $table->head[1] = __('Field'); - $table->head[2] = __('Display on front').ui_print_help_tip (__('The fields with display on front enabled will be displayed into the agent details'), true); - $table->head[3] = __('Actions'); - $table->align = array (); - $table->align[0] = 'left'; - $table->align[2] = 'left'; - $table->align[3] = 'left'; - $table->size[3] = '8%'; - $table->data = array (); -} -else { - require_once ($config['homedir'] . "/general/firts_task/fields_manager.php"); - return; + $table->head = []; + $table->head[0] = __('ID'); + $table->head[1] = __('Field'); + $table->head[2] = __('Display on front').ui_print_help_tip(__('The fields with display on front enabled will be displayed into the agent details'), true); + $table->head[3] = __('Actions'); + $table->align = []; + $table->align[0] = 'left'; + $table->align[2] = 'left'; + $table->align[3] = 'left'; + $table->size[3] = '8%'; + $table->data = []; +} else { + include_once $config['homedir'].'/general/firts_task/fields_manager.php'; + return; } -if ($fields === false) $fields = array(); +if ($fields === false) { + $fields = []; +} foreach ($fields as $field) { - - $data[0] = $field['id_field']; - - $data[1] = ''.$field['name'].''; - - if ($field['display_on_front']) { - $data[2] = html_print_image('images/tick.png', true); - } - else { - $data[2] = html_print_image('images/icono_stop.png', true,array ('style' => 'width:21px;height:21px;')); - } - - $data[3] = '' . html_print_image("images/config.png", true, array("alt" => __('Edit'), "title" => __('Edit'), "border" => '0')) . ''; - $data[3] .= '  ' . html_print_image("images/cross.png", true, array("alt" => __('Delete'), "title" => __('Delete'), "border" => '0')) . ''; - - array_push ($table->data, $data); + $data[0] = $field['id_field']; + + $data[1] = ''.$field['name'].''; + + if ($field['display_on_front']) { + $data[2] = html_print_image('images/tick.png', true); + } else { + $data[2] = html_print_image('images/icono_stop.png', true, ['style' => 'width:21px;height:21px;']); + } + + $data[3] = ''.html_print_image('images/config.png', true, ['alt' => __('Edit'), 'title' => __('Edit'), 'border' => '0']).''; + $data[3] .= '  '.html_print_image('images/cross.png', true, ['alt' => __('Delete'), 'title' => __('Delete'), 'border' => '0']).''; + + array_push($table->data, $data); } if ($fields) { - html_print_table ($table); + html_print_table($table); } echo '
    '; echo '
    '; -html_print_submit_button (__('Create field'), 'crt', false, 'class="sub next"'); +html_print_submit_button(__('Create field'), 'crt', false, 'class="sub next"'); echo '
    '; echo '
    '; - -?> diff --git a/pandora_console/godmode/agentes/modificar_agente.php b/pandora_console/godmode/agentes/modificar_agente.php index 9ba82d9934..4673bf2f46 100644 --- a/pandora_console/godmode/agentes/modificar_agente.php +++ b/pandora_console/godmode/agentes/modificar_agente.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,140 +11,146 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars -check_login (); +check_login(); // Take some parameters (GET) -$offset = (int) get_parameter ("offset"); -$group_id = (int) get_parameter ("group_id"); -$ag_group = get_parameter ("ag_group_refresh", -1); +$offset = (int) get_parameter('offset'); +$group_id = (int) get_parameter('group_id'); +$ag_group = get_parameter('ag_group_refresh', -1); $sortField = get_parameter('sort_field'); $sort = get_parameter('sort', 'none'); -$recursion = (bool) get_parameter('recursion',false); +$recursion = (bool) get_parameter('recursion', false); $disabled = get_parameter('disabled', 0); $os = get_parameter('os', 0); -if ($ag_group == -1 ) - $ag_group = (int) get_parameter ("ag_group", -1); +if ($ag_group == -1) { + $ag_group = (int) get_parameter('ag_group', -1); +} -if (($ag_group == -1) && ($group_id != 0)) - $ag_group = $group_id; +if (($ag_group == -1) && ($group_id != 0)) { + $ag_group = $group_id; +} -if (! check_acl ($config["id_user"], 0, "AW") && ! check_acl ($config["id_user"], 0, "AD")) { - db_pandora_audit("ACL Violation", - "Trying to access agent manager"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'AW') && ! check_acl($config['id_user'], 0, 'AD')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access agent manager' + ); + include 'general/noaccess.php'; + exit; } enterprise_include_once('include/functions_policies.php'); -require_once ('include/functions_agents.php'); -require_once ('include/functions_users.php'); +require_once 'include/functions_agents.php'; +require_once 'include/functions_users.php'; -$search = get_parameter ("search", ""); +$search = get_parameter('search', ''); // Prepare the tab system to the future $tab = 'view'; -/* Setup tab */ -$viewtab['text'] = '' - . html_print_image ("images/operation.png", true, array ("title" =>__('View'))) - . ''; +// Setup tab +$viewtab['text'] = ''.html_print_image('images/operation.png', true, ['title' => __('View')]).''; $viewtab['operation'] = true; $viewtab['active'] = false; -$onheader = array('view' => $viewtab); +$onheader = ['view' => $viewtab]; // Header -ui_print_page_header (__('Agents defined in %s', get_product_name()), "images/agent_mc.png", false, "", true, $onheader); +ui_print_page_header(__('Agents defined in %s', get_product_name()), 'images/agent_mc.png', false, '', true, $onheader); // Perform actions -$agent_to_delete = (int)get_parameter('borrar_agente'); -$enable_agent = (int)get_parameter('enable_agent'); -$disable_agent = (int)get_parameter('disable_agent'); +$agent_to_delete = (int) get_parameter('borrar_agente'); +$enable_agent = (int) get_parameter('enable_agent'); +$disable_agent = (int) get_parameter('disable_agent'); -if($disable_agent != 0){ - $server_name = db_get_row_sql('select server_name from tagente where id_agente = '.$disable_agent); -} -elseif ($enable_agent != 0) { - $server_name = db_get_row_sql('select server_name from tagente where id_agente = '.$enable_agent); +if ($disable_agent != 0) { + $server_name = db_get_row_sql('select server_name from tagente where id_agente = '.$disable_agent); +} else if ($enable_agent != 0) { + $server_name = db_get_row_sql('select server_name from tagente where id_agente = '.$enable_agent); } $result = null; if ($agent_to_delete) { - $id_agente = $agent_to_delete; - if (check_acl_one_of_groups ( - $config["id_user"], - agents_get_all_groups_agent($id_agente), - "AW" - )) { - $id_agentes[0] = $id_agente; - $result = agents_delete_agent($id_agentes); - } - else { - // NO permissions. - db_pandora_audit("ACL Violation", - "Trying to delete agent \'" . agents_get_name ($id_agente). "\'"); - require ("general/noaccess.php"); - exit; - } - - ui_print_result_message($result, __('Success deleted agent.'), __('Could not be deleted.')); - - if (enterprise_installed()) { - // Check if the remote config file still exist - if (isset ($config["remote_config"])) { - enterprise_include_once('include/functions_config_agents.php'); - if (enterprise_hook('config_agents_has_remote_configuration', array($id_agente))) { - ui_print_error_message(__('Maybe the files conf or md5 could not be deleted')); - } - } - } + $id_agente = $agent_to_delete; + if (check_acl_one_of_groups( + $config['id_user'], + agents_get_all_groups_agent($id_agente), + 'AW' + ) + ) { + $id_agentes[0] = $id_agente; + $result = agents_delete_agent($id_agentes); + } else { + // NO permissions. + db_pandora_audit( + 'ACL Violation', + "Trying to delete agent \'".agents_get_name($id_agente)."\'" + ); + include 'general/noaccess.php'; + exit; + } + + ui_print_result_message($result, __('Success deleted agent.'), __('Could not be deleted.')); + + if (enterprise_installed()) { + // Check if the remote config file still exist + if (isset($config['remote_config'])) { + enterprise_include_once('include/functions_config_agents.php'); + if (enterprise_hook('config_agents_has_remote_configuration', [$id_agente])) { + ui_print_error_message(__('Maybe the files conf or md5 could not be deleted')); + } + } + } } if ($enable_agent) { - $result = db_process_sql_update('tagente', array('disabled' => 0), array('id_agente' => $enable_agent)); - $alias = agents_get_alias($enable_agent); - - if ($result) { - // Update the agent from the metaconsole cache - enterprise_include_once('include/functions_agents.php'); - $values = array('disabled' => 0); - enterprise_hook ('agent_update_from_cache', array($enable_agent, $values,$server_name)); - - db_pandora_audit("Agent management", 'Enable ' . $alias); - } - else { - db_pandora_audit("Agent management", 'Fail to enable ' . $alias); - } - - ui_print_result_message ($result, - __('Successfully enabled'), __('Could not be enabled')); + $result = db_process_sql_update('tagente', ['disabled' => 0], ['id_agente' => $enable_agent]); + $alias = agents_get_alias($enable_agent); + + if ($result) { + // Update the agent from the metaconsole cache + enterprise_include_once('include/functions_agents.php'); + $values = ['disabled' => 0]; + enterprise_hook('agent_update_from_cache', [$enable_agent, $values, $server_name]); + + db_pandora_audit('Agent management', 'Enable '.$alias); + } else { + db_pandora_audit('Agent management', 'Fail to enable '.$alias); + } + + ui_print_result_message( + $result, + __('Successfully enabled'), + __('Could not be enabled') + ); } if ($disable_agent) { - $result = db_process_sql_update('tagente', array('disabled' => 1), array('id_agente' => $disable_agent)); - $alias = agents_get_alias($disable_agent); - - if ($result) { - // Update the agent from the metaconsole cache - enterprise_include_once('include/functions_agents.php'); - $values = array('disabled' => 1); - enterprise_hook ('agent_update_from_cache', array($disable_agent, $values,$server_name)); - - db_pandora_audit("Agent management", 'Disable ' . $alias); - } - else { - db_pandora_audit("Agent management", 'Fail to disable ' . $alias); - } - - ui_print_result_message ($result, - __('Successfully disabled'), __('Could not be disabled')); + $result = db_process_sql_update('tagente', ['disabled' => 1], ['id_agente' => $disable_agent]); + $alias = agents_get_alias($disable_agent); + + if ($result) { + // Update the agent from the metaconsole cache + enterprise_include_once('include/functions_agents.php'); + $values = ['disabled' => 1]; + enterprise_hook('agent_update_from_cache', [$disable_agent, $values, $server_name]); + + db_pandora_audit('Agent management', 'Disable '.$alias); + } else { + db_pandora_audit('Agent management', 'Fail to disable '.$alias); + } + + ui_print_result_message( + $result, + __('Successfully disabled'), + __('Could not be disabled') + ); } echo " @@ -153,67 +158,70 @@ echo "
    "; -echo ""; - -echo ""; +echo ''; -echo "'; + +echo '
    "; +echo ''; -echo __('Group') . ' '; +echo __('Group').' '; $own_info = get_user_info($config['id_user']); -if (!$own_info['is_admin'] && !check_acl ($config['id_user'], 0, "AW")) - $return_all_group = false; -else - $return_all_group = true; -html_print_select_groups(false, "AR", $return_all_group, "ag_group", $ag_group, 'this.form.submit();', '', 0, false, false, true, '', false); - -echo ""; -echo __('Show Agents') . ' '; -$fields = array( - 2 => __('Everyone'), - 1 => __('Only disabled'), - 0 => __('Only enabled'), - ); -html_print_select($fields,"disabled",$disabled,'this.form.submit()'); - -echo ""; -echo __('Operative System') . ' '; - -$pre_fields = db_get_all_rows_sql('select distinct(tagente.id_os),tconfig_os.name from tagente,tconfig_os where tagente.id_os = tconfig_os.id_os'); -$fields = array(); - -foreach ($pre_fields as $key => $value) { - $fields[$value['id_os']] = $value['name']; +if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'AW')) { + $return_all_group = false; +} else { + $return_all_group = true; } -html_print_select($fields,"os",$os,'this.form.submit()','All',0); +html_print_select_groups(false, 'AR', $return_all_group, 'ag_group', $ag_group, 'this.form.submit();', '', 0, false, false, true, '', false); -echo "'; +echo __('Show Agents').' '; +$fields = [ + 2 => __('Everyone'), + 1 => __('Only disabled'), + 0 => __('Only enabled'), +]; +html_print_select($fields, 'disabled', $disabled, 'this.form.submit()'); -echo ""; -echo __('Recursion') . ' '; -html_print_checkbox ("recursion", 1, $recursion, false, false, 'this.form.submit()'); +echo '"; -echo __('Search') . ' '; -html_print_input_text ("search", $search, '', 12); +echo ''; +echo __('Operative System').' '; + +$pre_fields = db_get_all_rows_sql('select distinct(tagente.id_os),tconfig_os.name from tagente,tconfig_os where tagente.id_os = tconfig_os.id_os'); +$fields = []; + +foreach ($pre_fields as $key => $value) { + $fields[$value['id_os']] = $value['name']; +} + +html_print_select($fields, 'os', $os, 'this.form.submit()', 'All', 0); + +echo ''; +echo __('Recursion').' '; +html_print_checkbox('recursion', 1, $recursion, false, false, 'this.form.submit()'); + +echo ''; +echo __('Search').' '; +html_print_input_text('search', $search, '', 12); echo ui_print_help_tip(__('Search filter by alias, name, description, IP address or custom fields content'), true); -echo ""; +echo ''; echo ""; -echo ""; -echo ""; -echo "
    "; +echo ''; +echo ''; +echo ''; -$order_collation = ""; -switch ($config["dbtype"]) { - case "mysql": - $order_collation = ""; - $order_collation = "COLLATE utf8_general_ci"; - break; - case "postgresql": - case "oracle": - $order_collation = ""; - break; +$order_collation = ''; +switch ($config['dbtype']) { + case 'mysql': + $order_collation = ''; + $order_collation = 'COLLATE utf8_general_ci'; + break; + + case 'postgresql': + case 'oracle': + $order_collation = ''; + break; } $selected = 'border: 1px solid black;'; @@ -224,154 +232,184 @@ $selectOsDown = ''; $selectGroupUp = ''; $selectGroupDown = ''; switch ($sortField) { - case 'remote': - switch ($sort) { - case 'up': - $selectRemoteUp = $selected; - $order = array('field' => 'remote ', - 'field2' => 'nombre ' . $order_collation, - 'order' => 'ASC'); - break; - case 'down': - $selectRemoteDown = $selected; - $order = array('field' => 'remote ', - 'field2' => 'nombre ' . $order_collation, - 'order' => 'DESC'); - break; - } - break; - case 'name': - switch ($sort) { - case 'up': - $selectNameUp = $selected; - $order = array('field' => 'alias ' . $order_collation, - 'field2' => 'alias ' . $order_collation, - 'order' => 'ASC'); - break; - case 'down': - $selectNameDown = $selected; - $order = array('field' => 'alias ' . $order_collation, - 'field2' => 'alias ' . $order_collation, - 'order' => 'DESC'); - break; - } - break; - case 'os': - switch ($sort) { - case 'up': - $selectOsUp = $selected; - $order = array('field' => 'id_os', - 'field2' => 'alias ' . $order_collation, - 'order' => 'ASC'); - break; - case 'down': - $selectOsDown = $selected; - $order = array('field' => 'id_os', - 'field2' => 'alias ' . $order_collation, - 'order' => 'DESC'); - break; - } - break; - case 'group': - switch ($sort) { - case 'up': - $selectGroupUp = $selected; - $order = array('field' => 'id_grupo', - 'field2' => 'alias ' . $order_collation, - 'order' => 'ASC'); - break; - case 'down': - $selectGroupDown = $selected; - $order = array('field' => 'id_grupo', - 'field2' => 'alias ' . $order_collation, - 'order' => 'DESC'); - break; - } - break; - default: - $selectNameUp = $selected; - $selectNameDown = ''; - $selectOsUp = ''; - $selectOsDown = ''; - $selectGroupUp = ''; - $selectGroupDown = ''; - $order = array('field' => 'alias ' . $order_collation, - 'field2' => 'alias ' . $order_collation, - 'order' => 'ASC'); - break; + case 'remote': + switch ($sort) { + case 'up': + $selectRemoteUp = $selected; + $order = [ + 'field' => 'remote ', + 'field2' => 'nombre '.$order_collation, + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectRemoteDown = $selected; + $order = [ + 'field' => 'remote ', + 'field2' => 'nombre '.$order_collation, + 'order' => 'DESC', + ]; + break; + } + break; + + case 'name': + switch ($sort) { + case 'up': + $selectNameUp = $selected; + $order = [ + 'field' => 'alias '.$order_collation, + 'field2' => 'alias '.$order_collation, + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectNameDown = $selected; + $order = [ + 'field' => 'alias '.$order_collation, + 'field2' => 'alias '.$order_collation, + 'order' => 'DESC', + ]; + break; + } + break; + + case 'os': + switch ($sort) { + case 'up': + $selectOsUp = $selected; + $order = [ + 'field' => 'id_os', + 'field2' => 'alias '.$order_collation, + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectOsDown = $selected; + $order = [ + 'field' => 'id_os', + 'field2' => 'alias '.$order_collation, + 'order' => 'DESC', + ]; + break; + } + break; + + case 'group': + switch ($sort) { + case 'up': + $selectGroupUp = $selected; + $order = [ + 'field' => 'id_grupo', + 'field2' => 'alias '.$order_collation, + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectGroupDown = $selected; + $order = [ + 'field' => 'id_grupo', + 'field2' => 'alias '.$order_collation, + 'order' => 'DESC', + ]; + break; + } + break; + + default: + $selectNameUp = $selected; + $selectNameDown = ''; + $selectOsUp = ''; + $selectOsDown = ''; + $selectGroupUp = ''; + $selectGroupDown = ''; + $order = [ + 'field' => 'alias '.$order_collation, + 'field2' => 'alias '.$order_collation, + 'order' => 'ASC', + ]; + break; } $search_sql = ''; -if ($search != "") { - $sql = "SELECT DISTINCT taddress_agent.id_agent FROM taddress +if ($search != '') { + $sql = "SELECT DISTINCT taddress_agent.id_agent FROM taddress INNER JOIN taddress_agent ON taddress.id_a = taddress_agent.id_a WHERE taddress.ip LIKE '%$search%'"; - $id = db_get_all_rows_sql($sql); - if($id != ''){ - $aux = $id[0]['id_agent']; - $search_sql = " AND ( LOWER(nombre) " . $order_collation . " + $id = db_get_all_rows_sql($sql); + if ($id != '') { + $aux = $id[0]['id_agent']; + $search_sql = ' AND ( LOWER(nombre) '.$order_collation." LIKE LOWER('%$search%') OR tagente.id_agente = $aux"; - if(count($id)>=2){ - for ($i = 1; $i < count($id); $i++){ - $aux = $id[$i]['id_agent']; - $search_sql .= " OR tagente.id_agente = $aux"; - } - } - $search_sql .= ")"; - }else{ - $search_sql = " AND ( nombre " . $order_collation . " - LIKE LOWER('%$search%') OR alias " . $order_collation . " - LIKE LOWER('%$search%') OR comentarios " . $order_collation . " LIKE LOWER('%$search%') + if (count($id) >= 2) { + for ($i = 1; $i < count($id); $i++) { + $aux = $id[$i]['id_agent']; + $search_sql .= " OR tagente.id_agente = $aux"; + } + } + + $search_sql .= ')'; + } else { + $search_sql = ' AND ( nombre '.$order_collation." + LIKE LOWER('%$search%') OR alias ".$order_collation." + LIKE LOWER('%$search%') OR comentarios ".$order_collation." LIKE LOWER('%$search%') OR EXISTS (SELECT * FROM tagent_custom_data WHERE id_agent = id_agente AND description LIKE '%$search%'))"; - } + } } -if ($disabled == 1) -{ - $search_sql .= " AND disabled = ". $disabled . $search_sql; -} -else { - if ($disabled == 0) { - $search_sql .= " AND disabled = 0" . $search_sql; - } +if ($disabled == 1) { + $search_sql .= ' AND disabled = '.$disabled.$search_sql; +} else { + if ($disabled == 0) { + $search_sql .= ' AND disabled = 0'.$search_sql; + } } -if($os != 0){ - $search_sql .= " AND id_os = " . $os; +if ($os != 0) { + $search_sql .= ' AND id_os = '.$os; } -$user_groups_to_sql = ""; +$user_groups_to_sql = ''; // Show only selected groups if ($ag_group > 0) { - $ag_groups = array(); - $ag_groups = (array)$ag_group; - if ($recursion) { - $ag_groups = groups_get_id_recursive($ag_group, true); - } - $user_groups_to_sql = implode (",", $ag_groups); -} else { - // Concatenate AW and AD permisions to get all the possible groups where the user can manage - $user_groupsAW = users_get_groups ($config['id_user'], 'AW'); - $user_groupsAD = users_get_groups ($config['id_user'], 'AD'); + $ag_groups = []; + $ag_groups = (array) $ag_group; + if ($recursion) { + $ag_groups = groups_get_id_recursive($ag_group, true); + } - $user_groups = $user_groupsAW + $user_groupsAD; - $user_groups_to_sql = implode (',', array_keys ($user_groups)); + $user_groups_to_sql = implode(',', $ag_groups); +} else { + // Concatenate AW and AD permisions to get all the possible groups where the user can manage + $user_groupsAW = users_get_groups($config['id_user'], 'AW'); + $user_groupsAD = users_get_groups($config['id_user'], 'AD'); + + $user_groups = ($user_groupsAW + $user_groupsAD); + $user_groups_to_sql = implode(',', array_keys($user_groups)); } -$sql = sprintf ('SELECT COUNT(DISTINCT(tagente.id_agente)) +$sql = sprintf( + 'SELECT COUNT(DISTINCT(tagente.id_agente)) FROM tagente LEFT JOIN tagent_secondary_group tasg ON tagente.id_agente = tasg.id_agent WHERE (tagente.id_grupo IN (%s) OR tasg.id_group IN (%s)) %s', - $user_groups_to_sql, $user_groups_to_sql, - $search_sql); + $user_groups_to_sql, + $user_groups_to_sql, + $search_sql +); -$total_agents = db_get_sql ($sql); +$total_agents = db_get_sql($sql); -$sql = sprintf ('SELECT * +$sql = sprintf( + 'SELECT * FROM tagente LEFT JOIN tagent_secondary_group tasg ON tagente.id_agente = tasg.id_agent WHERE (tagente.id_grupo IN (%s) OR tasg.id_group IN (%s)) @@ -379,303 +417,301 @@ $sql = sprintf ('SELECT * GROUP BY tagente.id_agente ORDER BY %s %s, %s %s LIMIT %d, %d', - $user_groups_to_sql, $user_groups_to_sql, - $search_sql, - $order['field'], $order['order'], $order['field2'], $order['order'], - $offset, $config["block_size"]); + $user_groups_to_sql, + $user_groups_to_sql, + $search_sql, + $order['field'], + $order['order'], + $order['field2'], + $order['order'], + $offset, + $config['block_size'] +); -$agents = db_get_all_rows_sql ($sql); +$agents = db_get_all_rows_sql($sql); // Delete rnum row generated by oracle_recode_query() function if (($config['dbtype'] == 'oracle') && ($agents !== false)) { - for ($i=0; $i < count($agents); $i++) { - unset($agents[$i]['rnum']); - } + for ($i = 0; $i < count($agents); $i++) { + unset($agents[$i]['rnum']); + } } // Prepare pagination -ui_pagination ($total_agents, "index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id=$ag_group&recursion=$recursion&search=$search&sort_field=$sortField&sort=$sort&disabled=$disabled&os=$os", $offset); +ui_pagination($total_agents, "index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id=$ag_group&recursion=$recursion&search=$search&sort_field=$sortField&sort=$sort&disabled=$disabled&os=$os", $offset); if ($agents !== false) { - - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - $color=1; - - $rowPair = true; - $iterator = 0; - foreach ($agents as $agent) { - - /* Begin Update tagente.remote 0/1 with remote agent function return */ - - if(enterprise_hook('config_agents_has_remote_configuration',array($agent['id_agente']))){ - db_process_sql_update('tagente', array('remote' => 1),'id_agente = '.$agent['id_agente'].''); - } - else{ - db_process_sql_update('tagente', array('remote' => 0),'id_agente = '.$agent['id_agente'].''); - } - - /* End Update tagente.remote 0/1 with remote agent function return */ + echo "
    ".__('Agent name') . ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectNameUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectNameDown)) . ''; - echo "".__('R'). ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectRemoteUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectRemoteDown)) . ''; - echo "".__('OS'). ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectOsUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectOsDown)) . ''; - echo "".__('Type'). "".__('Group'). ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectGroupUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectGroupDown)) . ''; - echo "" . __('Description') . "" . __('Actions') . "
    "; + echo ''; + echo "'; + echo ''; + echo ''; + echo ''; + echo ''; + echo "'; + $color = 1; - $all_groups = agents_get_all_groups_agent($agent["id_agente"], $agent["id_grupo"]); - $check_aw = check_acl_one_of_groups ($config["id_user"], $all_groups, "AW"); - $check_ad = check_acl_one_of_groups ($config["id_user"], $all_groups, "AD"); + $rowPair = true; + $iterator = 0; + foreach ($agents as $agent) { + // Begin Update tagente.remote 0/1 with remote agent function return + if (enterprise_hook('config_agents_has_remote_configuration', [$agent['id_agente']])) { + db_process_sql_update('tagente', ['remote' => 1], 'id_agente = '.$agent['id_agente'].''); + } else { + db_process_sql_update('tagente', ['remote' => 0], 'id_agente = '.$agent['id_agente'].''); + } - $cluster = db_get_row_sql('select id from tcluster where id_agent = '.$agent['id_agente']); + // End Update tagente.remote 0/1 with remote agent function return + $all_groups = agents_get_all_groups_agent($agent['id_agente'], $agent['id_grupo']); + $check_aw = check_acl_one_of_groups($config['id_user'], $all_groups, 'AW'); + $check_ad = check_acl_one_of_groups($config['id_user'], $all_groups, 'AD'); - // Do not show the agent if there is not enough permissions - if (!$check_aw && !$check_ad) continue; - - if ($color == 1) { - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - - - if ($rowPair) - $rowclass = 'rowPair'; - else - $rowclass = 'rowOdd'; - $rowPair = !$rowPair; - $iterator++; - // Agent name - echo ""; - - echo ""; - - // Operating System icon - echo ""; - - // Type agent (Networt, Software or Satellite) - echo ""; + &id_agente='.$agent['id_agente'].'">'.__('View').''; + } + + echo ''; + echo ''; + + echo "'; + + // Operating System icon + echo "'; + + // Type agent (Networt, Software or Satellite) + echo "'; - // Group icon and name - echo ""; - // Description - echo ""; - // Action - //When there is only one element in page it's necesary go back page. - if ((count($agents) == 1) && ($offset >= $config["block_size"])) - $offsetArg = $offset - $config["block_size"]; - else - $offsetArg = $offset; - - echo ""; - } - echo "
    '.__('Agent name').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectNameUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectNameDown]).''; + echo '".__('R').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectRemoteUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectRemoteDown]).''; + echo ''.__('OS').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectOsUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectOsDown]).''; + echo ''.__('Type').''.__('Group').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectGroupUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectGroupDown]).''; + echo ''.__('Description').'".__('Actions').'
    "; - if ($agent["disabled"]) { - echo ""; - } - echo ''; - echo ""; - - if ($check_aw) { - $main_tab = 'main'; - } - else { - $main_tab = 'module'; - } + $cluster = db_get_row_sql('select id from tcluster where id_agent = '.$agent['id_agente']); - if($agent["alias"] == ''){ - $agent["alias"] = $agent["nombre"]; - } + // Do not show the agent if there is not enough permissions + if (!$check_aw && !$check_ad) { + continue; + } - if($agent["id_os"] == 100){ - $cluster = db_get_row_sql('select id from tcluster where id_agent = '.$agent['id_agente']); - echo ''.$agent['alias'].''; - }else{ - echo ""; + if ($agent['disabled']) { + echo ''; + } + + echo ''; + echo ''; + + if ($check_aw) { + $main_tab = 'main'; + } else { + $main_tab = 'module'; + } + + if ($agent['alias'] == '') { + $agent['alias'] = $agent['nombre']; + } + + if ($agent['id_os'] == 100) { + $cluster = db_get_row_sql('select id from tcluster where id_agent = '.$agent['id_agente']); + echo ''.$agent['alias'].''; + } else { + echo '" . - ''.$agent["alias"].'' . - ""; - } - echo ""; + id_agente=".$agent['id_agente']."'>".''.$agent['alias'].''.''; + } - $in_planned_downtime = db_get_sql('SELECT executed FROM tplanned_downtime + echo ''; + + $in_planned_downtime = db_get_sql( + 'SELECT executed FROM tplanned_downtime INNER JOIN tplanned_downtime_agents ON tplanned_downtime.id = tplanned_downtime_agents.id_downtime - WHERE tplanned_downtime_agents.id_agent = '. $agent["id_agente"] . ' AND tplanned_downtime.executed = 1'); - - if ($agent["disabled"]) { - ui_print_help_tip(__('Disabled')); + WHERE tplanned_downtime_agents.id_agent = '.$agent['id_agente'].' AND tplanned_downtime.executed = 1' + ); - if (!$in_planned_downtime) { - echo ""; - } - } - - if ($agent['quiet']) { - echo " "; - html_print_image("images/dot_blue.png", false, array("border" => '0', "title" => __('Quiet'), "alt" => "")); - } + if ($agent['disabled']) { + ui_print_help_tip(__('Disabled')); - if ($in_planned_downtime) { - ui_print_help_tip (__('Agent in planned downtime'), false, 'images/minireloj-16.png'); + if (!$in_planned_downtime) { + echo ''; + } + } - echo ""; - } + if ($agent['quiet']) { + echo ' '; + html_print_image('images/dot_blue.png', false, ['border' => '0', 'title' => __('Quiet'), 'alt' => '']); + } - echo ''; - echo ""; - // Has remote configuration ? - if (enterprise_installed()) { - enterprise_include_once('include/functions_config_agents.php'); - if (enterprise_hook('config_agents_has_remote_configuration',array($agent["id_agente"]))) { - echo ""; - echo html_print_image("images/application_edit.png", true, array("align" => 'middle', "title" => __('Edit remote config'))); - echo ""; - } - } - echo ""; - ui_print_os_icon ($agent["id_os"], false); - echo ""; - echo ui_print_type_agent_icon ($agent["id_os"], $agent['ultimo_contacto_remoto'], - $agent['ultimo_contacto'], $agent['remote'], $agent['agent_version']); - echo ""; + // Has remote configuration ? + if (enterprise_installed()) { + enterprise_include_once('include/functions_config_agents.php'); + if (enterprise_hook('config_agents_has_remote_configuration', [$agent['id_agente']])) { + echo ""; + echo html_print_image('images/application_edit.png', true, ['align' => 'middle', 'title' => __('Edit remote config')]); + echo ''; + } + } + + echo '"; + ui_print_os_icon($agent['id_os'], false); + echo '"; + echo ui_print_type_agent_icon( + $agent['id_os'], + $agent['ultimo_contacto_remoto'], + $agent['ultimo_contacto'], + $agent['remote'], + $agent['agent_version'] + ); + echo '" . ui_print_group_icon ($agent["id_grupo"], true)."" . - ui_print_truncate_text($agent["comentarios"], 'description', true, true, true, '[…]', 'font-size: 6.5pt;').""; - - if ($agent['disabled']) { - echo ""; - } - else{ - echo ' onClick="if (!confirm(\' '.__('You are going to enable a cluster agent. Are you sure?').'\')) return false;">'; - } - - echo html_print_image('images/lightbulb_off.png', true, array('alt' => __('Enable agent'), 'title' => __('Enable agent'))) .""; - } - else { - echo ""; - } - else{ - echo ' onClick="if (!confirm(\' '.__('You are going to disable a cluster agent. Are you sure?').'\')) return false;">'; - } - - echo html_print_image('images/lightbulb.png', true, array('alt' => __('Disable agent'), 'title' => __('Disable agent'))) .""; - } - - if ($check_aw) { - echo "  '; - } - else{ - echo ' onClick="if (!confirm(\' '.__('WARNING! - You are going to delete a cluster agent. Are you sure?').'\')) return false;">'; - } - - echo html_print_image('images/cross.png', true, array("border" => '0')) . ""; - } - - echo "
    "; - ui_pagination ($total_agents, "index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id=$ag_group&search=$search&sort_field=$sortField&sort=$sort&disabled=$disabled&os=$os", $offset); - echo "'; + // Description + echo "'; + // Action + // When there is only one element in page it's necesary go back page. + if ((count($agents) == 1) && ($offset >= $config['block_size'])) { + $offsetArg = ($offset - $config['block_size']); + } else { + $offsetArg = $offset; + } + + echo "'; + } + + echo '
    "; -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined agents') ) ); + // Group icon and name + echo "".ui_print_group_icon($agent['id_grupo'], true).'".ui_print_truncate_text($agent['comentarios'], 'description', true, true, true, '[…]', 'font-size: 6.5pt;').'"; + + if ($agent['disabled']) { + echo "'; + } else { + echo ' onClick="if (!confirm(\' '.__('You are going to enable a cluster agent. Are you sure?').'\')) return false;">'; + } + + echo html_print_image('images/lightbulb_off.png', true, ['alt' => __('Enable agent'), 'title' => __('Enable agent')]).''; + } else { + echo "'; + } else { + echo ' onClick="if (!confirm(\' '.__('You are going to disable a cluster agent. Are you sure?').'\')) return false;">'; + } + + echo html_print_image('images/lightbulb.png', true, ['alt' => __('Disable agent'), 'title' => __('Disable agent')]).''; + } + + if ($check_aw) { + echo "  '; + } else { + echo ' onClick="if (!confirm(\' '.__('WARNING! - You are going to delete a cluster agent. Are you sure?').'\')) return false;">'; + } + + echo html_print_image('images/cross.png', true, ['border' => '0']).''; + } + + echo '
    '; + ui_pagination($total_agents, "index.php?sec=gagente&sec2=godmode/agentes/modificar_agente&group_id=$ag_group&search=$search&sort_field=$sortField&sort=$sort&disabled=$disabled&os=$os", $offset); + echo "
    "; +} else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined agents') ]); } -if (check_acl ($config["id_user"], 0, "AW")) { - // Create agent button - echo '
    '; - echo '
    '; - html_print_input_hidden ('new_agent', 1); - html_print_submit_button (__('Create agent'), 'crt-2', false, - 'class="sub next"'); - echo "
    "; - echo '
    '; +if (check_acl($config['id_user'], 0, 'AW')) { + // Create agent button + echo '
    '; + echo '
    '; + html_print_input_hidden('new_agent', 1); + html_print_submit_button( + __('Create agent'), + 'crt-2', + false, + 'class="sub next"' + ); + echo '
    '; + echo '
    '; } -echo "
    "; +echo ''; ?> diff --git a/pandora_console/godmode/agentes/module_manager.php b/pandora_console/godmode/agentes/module_manager.php index 494b0798c4..9df6860591 100644 --- a/pandora_console/godmode/agentes/module_manager.php +++ b/pandora_console/godmode/agentes/module_manager.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,297 +11,353 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -/* You can redefine $url and unset $id_agente to reuse the form. Dirty (hope temporal) hack */ -if (isset ($id_agente)) { - $url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=module&id_agente='.$id_agente; -} -else { - $url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=module'; +// You can redefine $url and unset $id_agente to reuse the form. Dirty (hope temporal) hack +if (isset($id_agente)) { + $url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=module&id_agente='.$id_agente; +} else { + $url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=module'; } -enterprise_include ('godmode/agentes/module_manager.php'); -$isFunctionPolicies = enterprise_include_once ('include/functions_policies.php'); -require_once ($config['homedir'] . '/include/functions_modules.php'); -require_once ($config['homedir'] . '/include/functions_agents.php'); -require_once ($config['homedir'] . '/include/functions_servers.php'); +enterprise_include('godmode/agentes/module_manager.php'); +$isFunctionPolicies = enterprise_include_once('include/functions_policies.php'); +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_servers.php'; -$search_string = io_safe_output(urldecode(trim(get_parameter ("search_string", "")))); +$search_string = io_safe_output(urldecode(trim(get_parameter('search_string', '')))); global $policy_page; -if (!isset($policy_page)) - $policy_page = false; +if (!isset($policy_page)) { + $policy_page = false; +} // Search string filter form -if (($policy_page) || (isset($agent))) - echo '
    '; -else - echo ''; +if (($policy_page) || (isset($agent))) { + echo ''; +} else { + echo ''; +} + echo ''; echo ""; +echo __('Search').' '.html_print_input_text('search_string', $search_string, '', 15, 255, true); + html_print_input_hidden('search', 1); +echo ''; echo ""; +html_print_submit_button(__('Filter'), 'filter', false, 'class="sub search"'); +echo ''; echo ""; echo ''; // Check if there is at least one server of each type available to assign that // kind of modules. If not, do not show server type in combo - -$network_available = db_get_sql ("SELECT count(*) +$network_available = db_get_sql( + 'SELECT count(*) FROM tserver - WHERE server_type = 1"); //POSTGRESQL AND ORACLE COMPATIBLE -$wmi_available = db_get_sql ("SELECT count(*) + WHERE server_type = 1' +); +// POSTGRESQL AND ORACLE COMPATIBLE +$wmi_available = db_get_sql( + 'SELECT count(*) FROM tserver - WHERE server_type = 6"); //POSTGRESQL AND ORACLE COMPATIBLE -$plugin_available = db_get_sql ("SELECT count(*) + WHERE server_type = 6' +); +// POSTGRESQL AND ORACLE COMPATIBLE +$plugin_available = db_get_sql( + 'SELECT count(*) FROM tserver - WHERE server_type = 4"); //POSTGRESQL AND ORACLE COMPATIBLE -$prediction_available = db_get_sql ("SELECT count(*) + WHERE server_type = 4' +); +// POSTGRESQL AND ORACLE COMPATIBLE +$prediction_available = db_get_sql( + 'SELECT count(*) FROM tserver - WHERE server_type = 5"); //POSTGRESQL AND ORACLE COMPATIBLE - + WHERE server_type = 5' +); +// POSTGRESQL AND ORACLE COMPATIBLE // Development mode to use all servers if ($develop_bypass || is_metaconsole()) { - $network_available = 1; - $wmi_available = 1; - $plugin_available = 1; - // FIXME when prediction predictions server modules can be configured - // on metaconsole - $prediction_available = is_metaconsole() ? 0 : 1; + $network_available = 1; + $wmi_available = 1; + $plugin_available = 1; + // FIXME when prediction predictions server modules can be configured + // on metaconsole + $prediction_available = is_metaconsole() ? 0 : 1; } -$modules = array (); +$modules = []; $modules['dataserver'] = __('Create a new data server module'); -if ($network_available) - $modules['networkserver'] = __('Create a new network server module'); -if ($plugin_available) - $modules['pluginserver'] = __('Create a new plugin server module'); -if ($wmi_available) - $modules['wmiserver'] = __('Create a new WMI server module'); -if ($prediction_available) - $modules['predictionserver'] = __('Create a new prediction server module'); +if ($network_available) { + $modules['networkserver'] = __('Create a new network server module'); +} + +if ($plugin_available) { + $modules['pluginserver'] = __('Create a new plugin server module'); +} + +if ($wmi_available) { + $modules['wmiserver'] = __('Create a new WMI server module'); +} + +if ($prediction_available) { + $modules['predictionserver'] = __('Create a new prediction server module'); +} if (enterprise_installed()) { - set_enterprise_module_types($modules); + set_enterprise_module_types($modules); } $sec2 = get_parameter('sec2', ''); -if (strstr($sec2, "enterprise/godmode/policies/policies") !== false) { - //It is unset because the policies haven't a table tmodule_synth and the - //some part of code to apply this kind of modules in policy agents. - - //But in the future maybe will be good to make this feature, but remember - //the modules to show in syntetic module policy form must be the policy - //modules from the same policy. - unset($modules['predictionserver']); - if (enterprise_installed()){ - unset($modules['webux']); - } +if (strstr($sec2, 'enterprise/godmode/policies/policies') !== false) { + // It is unset because the policies haven't a table tmodule_synth and the + // some part of code to apply this kind of modules in policy agents. + // But in the future maybe will be good to make this feature, but remember + // the modules to show in syntetic module policy form must be the policy + // modules from the same policy. + unset($modules['predictionserver']); + if (enterprise_installed()) { + unset($modules['webux']); + } } $show_creation = false; -$checked = get_parameter("checked"); +$checked = get_parameter('checked'); if (($policy_page) || (isset($agent))) { - if ($policy_page) { - $show_creation = !is_central_policies_on_node(); - } - else { - if (!isset($all_groups)) { - $all_groups = agents_get_all_groups_agent ( - $agent['id_agente'], - $agent['id_grupo'] - ); - } - if (check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) - $show_creation = true; - } - - if ($show_creation) { - // Create module/type combo - echo ''; - if (!$policy_page) { - echo ''; - } - echo ''; - echo ''; - echo ''; - echo ""; - } + if ($policy_page) { + $show_creation = !is_central_policies_on_node(); + } else { + if (!isset($all_groups)) { + $all_groups = agents_get_all_groups_agent( + $agent['id_agente'], + $agent['id_grupo'] + ); + } + + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + $show_creation = true; + } + } + + if ($show_creation) { + // Create module/type combo + echo ''; + if (!$policy_page) { + echo ''; + } + + echo ''; + echo ''; + echo ''; + echo ''; + } } -echo "
    "; -echo __('Search') . ' ' . - html_print_input_text ('search_string', $search_string, '', 15, 255, true); - html_print_input_hidden ('search', 1); -echo ""; -html_print_submit_button (__('Filter'), 'filter', false, 'class="sub search"'); -echo "
    '; - echo __('Show in hierachy mode'); - if ($checked == "true") { - $checked = true; - } - else { - $checked = false; - } - html_print_checkbox ('status_hierachy_mode', "", $checked, false, false, "onChange=change_mod_filter();"); - echo ''; - echo __("

    Type

    "); - html_print_select ($modules, 'moduletype', '', '', '', '', false, false, false, '', false, 'max-width:300px;' ); - html_print_input_hidden ('edit_module', 1); - echo '
    '; - echo ''; - echo '
    '; + echo __('Show in hierachy mode'); + if ($checked == 'true') { + $checked = true; + } else { + $checked = false; + } + + html_print_checkbox('status_hierachy_mode', '', $checked, false, false, 'onChange=change_mod_filter();'); + echo ''; + echo __('

    Type

    '); + html_print_select($modules, 'moduletype', '', '', '', '', false, false, false, '', false, 'max-width:300px;'); + html_print_input_hidden('edit_module', 1); + echo '
    '; + echo ''; + echo '
    "; +echo ''; if (!$config['disable_help']) { - echo '
    '; - echo ""; - echo "".__("Get more modules on Monitoring Library").""; - echo ""; - echo '
    '; + echo '
    '; + echo ''; + echo "".__('Get more modules on Monitoring Library').''; + echo ''; + echo '
    '; } -if (! isset ($id_agente)) - return; +if (! isset($id_agente)) { + return; +} $multiple_delete = (bool) get_parameter('multiple_delete'); if ($multiple_delete) { - $id_agent_modules_delete = (array)get_parameter('id_delete'); - - $count_correct_delete_modules = 0; - foreach($id_agent_modules_delete as $id_agent_module_del) { - $id_grupo = (int) agents_get_agent_group($id_agente); - $all_groups = agents_get_all_groups_agent($id_agente, $id_grupo); - - if (! check_acl_one_of_groups ($config["id_user"], $all_groups, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to delete a module without admin rights"); - require ("general/noaccess.php"); - exit; - } - - if ($id_agent_module_del < 1) { - db_pandora_audit("HACK Attempt", - "Expected variable from form is not correct"); - die (__("Nice try buddy")); - exit; - } - - enterprise_include_once('include/functions_config_agents.php'); - enterprise_hook('config_agents_delete_module_in_conf', array(modules_get_agentmodule_agent($id_agent_module_del), modules_get_agentmodule_name($id_agent_module_del))); - - $error = 0; - - // First delete from tagente_modulo -> if not successful, increment - // error. NOTICE that we don't delete all data here, just marking for deletion - // and delete some simple data. - $status = ''; - $agent_id_of_module = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', (int)$id_agent_module_del); - - if (db_process_sql("UPDATE tagente_modulo + $id_agent_modules_delete = (array) get_parameter('id_delete'); + + $count_correct_delete_modules = 0; + foreach ($id_agent_modules_delete as $id_agent_module_del) { + $id_grupo = (int) agents_get_agent_group($id_agente); + $all_groups = agents_get_all_groups_agent($id_agente, $id_grupo); + + if (! check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to delete a module without admin rights' + ); + include 'general/noaccess.php'; + exit; + } + + if ($id_agent_module_del < 1) { + db_pandora_audit( + 'HACK Attempt', + 'Expected variable from form is not correct' + ); + die(__('Nice try buddy')); + exit; + } + + enterprise_include_once('include/functions_config_agents.php'); + enterprise_hook('config_agents_delete_module_in_conf', [modules_get_agentmodule_agent($id_agent_module_del), modules_get_agentmodule_name($id_agent_module_del)]); + + $error = 0; + + // First delete from tagente_modulo -> if not successful, increment + // error. NOTICE that we don't delete all data here, just marking for deletion + // and delete some simple data. + $status = ''; + $agent_id_of_module = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', (int) $id_agent_module_del); + + if (db_process_sql( + "UPDATE tagente_modulo SET nombre = 'pendingdelete', disabled = 1, delete_pending = 1 - WHERE id_agente_modulo = " . $id_agent_module_del, "affected_rows", '', true, $status, false) === false) { - $error++; - } - else { - // Set flag to update module status count - if ($agent_id_of_module !== false) { - db_process_sql ('UPDATE tagente + WHERE id_agente_modulo = ".$id_agent_module_del, + 'affected_rows', + '', + true, + $status, + false + ) === false + ) { + $error++; + } else { + // Set flag to update module status count + if ($agent_id_of_module !== false) { + db_process_sql( + 'UPDATE tagente SET update_module_count = 1, update_alert_count = 1 - WHERE id_agente = ' . $agent_id_of_module); - } - } - - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $result = db_process_sql_delete('tagente_estado', - array('id_agente_modulo' => $id_agent_module_del)); - if ($result === false) - $error++; - - $result = db_process_sql_delete('tagente_datos_inc', - array('id_agente_modulo' => $id_agent_module_del)); - if ($result === false) - $error++; - break; - case "oracle": - $result = db_process_delete_temp('tagente_estado', - 'id_agente_modulo', $id_agent_module_del); - if ($result === false) - $error++; - $result = db_process_delete_temp('tagente_datos_inc', - 'id_agente_modulo', $id_agent_module_del); - if ($result === false) - $error++; - break; - } - - // Trick to detect if we are deleting a synthetic module (avg or arithmetic) - // If result is empty then module doesn't have this type of submodules - $ops_json = enterprise_hook('modules_get_synthetic_operations', array($id_agent_module_del)); - $result_ops_synthetic = json_decode($ops_json); - if (!empty($result_ops_synthetic)) { - $result = enterprise_hook('modules_delete_synthetic_operations', array($id_agent_module_del)); - if ($result === false) - $error++; - } // Trick to detect if we are deleting components of synthetics modules (avg or arithmetic) - else { - $result_components = enterprise_hook('modules_get_synthetic_components', array($id_agent_module_del)); - $count_components = 1; - if (!empty($result_components)) { - // Get number of components pending to delete to know when it's needed to update orders - $num_components = count($result_components); - $last_target_module = 0; - foreach ($result_components as $id_target_module) { - // Detects change of component or last component to update orders - if (($count_components == $num_components) or ($last_target_module != $id_target_module)) - $update_orders = true; - else - $update_orders = false; - $result = enterprise_hook('modules_delete_synthetic_operations', array($id_target_module, $id_agent_module_del, $update_orders)); - if ($result === false) - $error++; - $count_components++; - $last_target_module = $id_target_module; - } - } - } - - - //Check for errors - if ($error != 0) { - } - else { - $count_correct_delete_modules++; - } - } - - $count_modules_to_delete = count($id_agent_modules_delete); - if ($count_correct_delete_modules == 0) { - ui_print_error_message( - sprintf(__('There was a problem deleting %s modules, none deleted.'), - $count_modules_to_delete)); - } - else { - if ($count_correct_delete_modules == $count_modules_to_delete) { - ui_print_success_message (__('All Modules deleted succesfully')); - } - else { - ui_print_error_message( - sprintf(__('There was a problem only deleted %s modules of %s total.'), - count_correct_delete_modules, $count_modules_to_delete)); - } - } + WHERE id_agente = '.$agent_id_of_module + ); + } + } + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $result = db_process_sql_delete( + 'tagente_estado', + ['id_agente_modulo' => $id_agent_module_del] + ); + if ($result === false) { + $error++; + } + + $result = db_process_sql_delete( + 'tagente_datos_inc', + ['id_agente_modulo' => $id_agent_module_del] + ); + if ($result === false) { + $error++; + } + break; + + case 'oracle': + $result = db_process_delete_temp( + 'tagente_estado', + 'id_agente_modulo', + $id_agent_module_del + ); + if ($result === false) { + $error++; + } + + $result = db_process_delete_temp( + 'tagente_datos_inc', + 'id_agente_modulo', + $id_agent_module_del + ); + if ($result === false) { + $error++; + } + break; + } + + // Trick to detect if we are deleting a synthetic module (avg or arithmetic) + // If result is empty then module doesn't have this type of submodules + $ops_json = enterprise_hook('modules_get_synthetic_operations', [$id_agent_module_del]); + $result_ops_synthetic = json_decode($ops_json); + if (!empty($result_ops_synthetic)) { + $result = enterprise_hook('modules_delete_synthetic_operations', [$id_agent_module_del]); + if ($result === false) { + $error++; + } + } //end if + else { + $result_components = enterprise_hook('modules_get_synthetic_components', [$id_agent_module_del]); + $count_components = 1; + if (!empty($result_components)) { + // Get number of components pending to delete to know when it's needed to update orders + $num_components = count($result_components); + $last_target_module = 0; + foreach ($result_components as $id_target_module) { + // Detects change of component or last component to update orders + if (($count_components == $num_components) or ($last_target_module != $id_target_module)) { + $update_orders = true; + } else { + $update_orders = false; + } + + $result = enterprise_hook('modules_delete_synthetic_operations', [$id_target_module, $id_agent_module_del, $update_orders]); + if ($result === false) { + $error++; + } + + $count_components++; + $last_target_module = $id_target_module; + } + } + } + + + // Check for errors + if ($error != 0) { + } else { + $count_correct_delete_modules++; + } + } + + $count_modules_to_delete = count($id_agent_modules_delete); + if ($count_correct_delete_modules == 0) { + ui_print_error_message( + sprintf( + __('There was a problem deleting %s modules, none deleted.'), + $count_modules_to_delete + ) + ); + } else { + if ($count_correct_delete_modules == $count_modules_to_delete) { + ui_print_success_message(__('All Modules deleted succesfully')); + } else { + ui_print_error_message( + sprintf( + __('There was a problem only deleted %s modules of %s total.'), + count_correct_delete_modules, + $count_modules_to_delete + ) + ); + } + } } // ================== // TABLE LIST MODULES // ================== - -$url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=module&id_agente=' . $id_agente; +$url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=module&id_agente='.$id_agente; $selectNameUp = ''; $selectNameDown = ''; $selectServerUp = ''; @@ -315,141 +370,192 @@ $sortField = get_parameter('sort_field'); $sort = get_parameter('sort', 'none'); $selected = ''; -$order[] = array('field' => 'tmodule_group.name', 'order' => 'ASC'); +$order[] = [ + 'field' => 'tmodule_group.name', + 'order' => 'ASC', +]; switch ($sortField) { - case 'name': - switch ($sort) { - case 'up': - $selectNameUp = $selected; - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $order[] = array('field' => 'tagente_modulo.nombre', 'order' => 'ASC'); - break; - case "oracle": - $order[] = array('field' => 'dbms_lob.substr(tagente_modulo.nombre,4000,1)', 'order' => 'ASC'); - break; - } - break; - case 'down': - $selectNameDown = $selected; - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $order[] = array('field' => 'tagente_modulo.nombre', 'order' => 'DESC'); - break; - case "oracle": - $order[] = array('field' => 'dbms_lob.substr(tagente_modulo.nombre,4000,1)', 'order' => 'DESC'); - break; - } - break; - } - break; - case 'server': - switch ($sort) { - case 'up': - $selectServerUp = $selected; - $order[] = array('field' => 'id_modulo', 'order' => 'ASC'); - break; - case 'down': - $selectServerDown = $selected; - $order[] = array('field' => 'id_modulo', 'order' => 'DESC'); - break; - } - break; - case 'type': - switch ($sort) { - case 'up': - $selectTypeUp = $selected; - $order[] = array('field' => 'id_tipo_modulo', 'order' => 'ASC'); - break; - case 'down': - $selectTypeDown = $selected; - $order[] = array('field' => 'id_tipo_modulo', 'order' => 'DESC'); - break; - } - break; - case 'interval': - switch ($sort) { - case 'up': - $selectIntervalUp = $selected; - $order[] = array('field' => 'module_interval', 'order' => 'ASC'); - break; - case 'down': - $selectIntervalDown = $selected; - $order[] = array('field' => 'module_interval', 'order' => 'DESC'); - break; - } - break; - default: - $selectNameUp = $selected; - $selectNameDown = ''; - $selectServerUp = ''; - $selectServerDown = ''; - $selectTypeUp = ''; - $selectTypeDown = ''; - $selectIntervalUp = ''; - $selectIntervalDown = ''; - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $order[] = array('field' => 'nombre', 'order' => 'ASC'); - break; - case "oracle": - $order[] = array('field' => 'dbms_lob.substr(nombre,4000,1)', 'order' => 'ASC'); - break; - } - break; + case 'name': + switch ($sort) { + case 'up': + $selectNameUp = $selected; + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $order[] = [ + 'field' => 'tagente_modulo.nombre', + 'order' => 'ASC', + ]; + break; + + case 'oracle': + $order[] = [ + 'field' => 'dbms_lob.substr(tagente_modulo.nombre,4000,1)', + 'order' => 'ASC', + ]; + break; + } + break; + + case 'down': + $selectNameDown = $selected; + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $order[] = [ + 'field' => 'tagente_modulo.nombre', + 'order' => 'DESC', + ]; + break; + + case 'oracle': + $order[] = [ + 'field' => 'dbms_lob.substr(tagente_modulo.nombre,4000,1)', + 'order' => 'DESC', + ]; + break; + } + break; + } + break; + + case 'server': + switch ($sort) { + case 'up': + $selectServerUp = $selected; + $order[] = [ + 'field' => 'id_modulo', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectServerDown = $selected; + $order[] = [ + 'field' => 'id_modulo', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'type': + switch ($sort) { + case 'up': + $selectTypeUp = $selected; + $order[] = [ + 'field' => 'id_tipo_modulo', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectTypeDown = $selected; + $order[] = [ + 'field' => 'id_tipo_modulo', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'interval': + switch ($sort) { + case 'up': + $selectIntervalUp = $selected; + $order[] = [ + 'field' => 'module_interval', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectIntervalDown = $selected; + $order[] = [ + 'field' => 'module_interval', + 'order' => 'DESC', + ]; + break; + } + break; + + default: + $selectNameUp = $selected; + $selectNameDown = ''; + $selectServerUp = ''; + $selectServerDown = ''; + $selectTypeUp = ''; + $selectTypeDown = ''; + $selectIntervalUp = ''; + $selectIntervalDown = ''; + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $order[] = [ + 'field' => 'nombre', + 'order' => 'ASC', + ]; + break; + + case 'oracle': + $order[] = [ + 'field' => 'dbms_lob.substr(nombre,4000,1)', + 'order' => 'ASC', + ]; + break; + } + break; } // Build the order sql if (!empty($order)) { - $order_sql = ' ORDER BY '; + $order_sql = ' ORDER BY '; } + $first = true; foreach ($order as $ord) { - if ($first) { - $first = false; - } - else { - $order_sql .= ','; - } - - $order_sql .= $ord['field'].' '.$ord['order']; + if ($first) { + $first = false; + } else { + $order_sql .= ','; + } + + $order_sql .= $ord['field'].' '.$ord['order']; } // Get limit and offset parameters -$limit = (int) $config["block_size"]; -$offset = (int) get_parameter ('offset'); +$limit = (int) $config['block_size']; +$offset = (int) get_parameter('offset'); -$params = ($checked) - ? "tagente_modulo.*, tmodule_group.*" - : implode(',', - array( - 'tagente_modulo.id_agente_modulo', - 'id_tipo_modulo', - 'descripcion', - 'nombre', - 'max', - 'min', - 'module_interval', - 'id_modulo', - 'id_module_group', - 'disabled', - 'max_warning', - 'min_warning', - 'str_warning', - 'max_critical', - 'min_critical', - 'str_critical', - 'quiet', - 'critical_inverse', - 'warning_inverse', - 'id_policy_module')); +$params = ($checked) ? 'tagente_modulo.*, tmodule_group.*' : implode( + ',', + [ + 'tagente_modulo.id_agente_modulo', + 'id_tipo_modulo', + 'descripcion', + 'nombre', + 'max', + 'min', + 'module_interval', + 'id_modulo', + 'id_module_group', + 'disabled', + 'max_warning', + 'min_warning', + 'str_warning', + 'max_critical', + 'min_critical', + 'str_critical', + 'quiet', + 'critical_inverse', + 'warning_inverse', + 'id_policy_module', + ] +); -$where = sprintf("delete_pending = 0 AND id_agente = %s", $id_agente); +$where = sprintf('delete_pending = 0 AND id_agente = %s', $id_agente); $search_string_entities = io_safe_input($search_string); @@ -458,22 +564,24 @@ $basic_where = sprintf("(nombre LIKE '%%%s%%' OR nombre LIKE '%%%s%%' OR descrip // Tags acl $agent_tags = tags_get_user_applied_agent_tags($id_agente); if ($agent_tags !== true) { - $where_tags = " AND ttag_module.id_tag IN (" . implode(',', $agent_tags) . ")"; + $where_tags = ' AND ttag_module.id_tag IN ('.implode(',', $agent_tags).')'; } $paginate_module = false; -if (isset($config['paginate_module'])) - $paginate_module = $config['paginate_module']; +if (isset($config['paginate_module'])) { + $paginate_module = $config['paginate_module']; +} if ($paginate_module) { - if (!isset($limit_sql)) { - $limit_sql = " LIMIT $offset, $limit "; - } + if (!isset($limit_sql)) { + $limit_sql = " LIMIT $offset, $limit "; + } +} else { + $limit_sql = ''; } -else { - $limit_sql = ''; -} -$sql = sprintf("SELECT tagente_modulo.*, tmodule_group.* + +$sql = sprintf( + 'SELECT tagente_modulo.*, tmodule_group.* FROM tagente_modulo LEFT JOIN tmodule_group ON tagente_modulo.id_module_group = tmodule_group.id_mg @@ -481,375 +589,399 @@ $sql = sprintf("SELECT tagente_modulo.*, tmodule_group.* ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo WHERE %s %s %s GROUP BY tagente_modulo.id_agente_modulo - %s %s", - $basic_where, $where, $where_tags, - $order_sql, $limit_sql + %s %s', + $basic_where, + $where, + $where_tags, + $order_sql, + $limit_sql ); $modules = db_get_all_rows_sql($sql); $sql_total_modules = sprintf( - "SELECT count(DISTINCT(tagente_modulo.id_agente_modulo)) + 'SELECT count(DISTINCT(tagente_modulo.id_agente_modulo)) FROM tagente_modulo LEFT JOIN ttag_module ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo - WHERE %s %s %s", $basic_where, $where, $where_tags + WHERE %s %s %s', + $basic_where, + $where, + $where_tags ); $total_modules = db_get_value_sql($sql_total_modules); -$total_modules = isset ($total_modules) ? $total_modules : 0; +$total_modules = isset($total_modules) ? $total_modules : 0; if ($modules === false) { - ui_print_empty_data ( __('No available data to show') ); - return; + ui_print_empty_data(__('No available data to show')); + return; } // Prepare pagination -$url = "?" . - "sec=gagente&" . - "tab=module&" . - "sec2=godmode/agentes/configurar_agente&" . - "id_agente=" . $id_agente . "&" . - "sort_field=" . $sortField ."&" . - "&sort=" . $sort . "&" . - "search_string=" . urlencode($search_string); +$url = '?'.'sec=gagente&'.'tab=module&'.'sec2=godmode/agentes/configurar_agente&'.'id_agente='.$id_agente.'&'.'sort_field='.$sortField.'&'.'&sort='.$sort.'&'.'search_string='.urlencode($search_string); if ($paginate_module) { - ui_pagination($total_modules, $url); + ui_pagination($total_modules, $url); } $table = new stdClass(); $table->width = '100%'; $table->class = 'databox data'; -$table->head = array (); -$table->head[0] = __('Name') . ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectNameUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectNameDown)) . ''; +$table->head = []; +$table->head[0] = __('Name').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectNameUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectNameDown]).''; // The access to the policy is granted only with AW permission -if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK && check_acl ($config['id_user'], $agent['id_grupo'], "AW")) { - $table->head[1] = "" . __('P.') . ""; +if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK && check_acl($config['id_user'], $agent['id_grupo'], 'AW')) { + $table->head[1] = "".__('P.').''; } -$table->head[2] = "" . __('S.') . "" . ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectServerUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectServerDown)) . ''; -$table->head[3] = __('Type') . ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectTypeUp)) .'' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectTypeDown)) . ''; -$table->head[4] = __('Interval') . ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectIntervalUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectIntervalDown)) . ''; +$table->head[2] = "".__('S.').''.' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectServerUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectServerDown]).''; +$table->head[3] = __('Type').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectTypeUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectTypeDown]).''; +$table->head[4] = __('Interval').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectIntervalUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectIntervalDown]).''; $table->head[5] = __('Description'); $table->head[6] = __('Status'); $table->head[7] = __('Warn'); $table->head[8] = __('Action'); -$table->head[9] = '' . __('Del.') . ''. - html_print_checkbox('all_delete', 0, false, true, false); +$table->head[9] = ''.__('Del.').''.html_print_checkbox('all_delete', 0, false, true, false); -$table->rowstyle = array(); -$table->style = array (); +$table->rowstyle = []; +$table->style = []; $table->style[0] = 'font-weight: bold'; -$table->size = array (); +$table->size = []; $table->size[2] = '70px'; -$table->align = array (); +$table->align = []; $table->align[2] = 'left'; $table->align[8] = 'left'; $table->align[9] = 'left'; -$table->data = array (); +$table->data = []; -$agent_interval = agents_get_interval ($id_agente); -$last_modulegroup = "0"; +$agent_interval = agents_get_interval($id_agente); +$last_modulegroup = '0'; -//Extract the ids only numeric modules for after show the normalize link. -$tempRows = db_get_all_rows_sql("SELECT * +// Extract the ids only numeric modules for after show the normalize link. +$tempRows = db_get_all_rows_sql( + "SELECT * FROM ttipo_modulo - WHERE nombre NOT LIKE '%string%' AND nombre NOT LIKE '%proc%'"); -$numericModules = array(); -foreach($tempRows as $row) { - $numericModules[$row['id_tipo']] = true; + WHERE nombre NOT LIKE '%string%' AND nombre NOT LIKE '%proc%'" +); +$numericModules = []; +foreach ($tempRows as $row) { + $numericModules[$row['id_tipo']] = true; } if ($checked) { - $modules_hierachy = array(); - $modules_hierachy = get_hierachy_modules_tree($modules); + $modules_hierachy = []; + $modules_hierachy = get_hierachy_modules_tree($modules); - $modules_dt = get_dt_from_modules_tree($modules_hierachy); + $modules_dt = get_dt_from_modules_tree($modules_hierachy); - $modules = $modules_dt; + $modules = $modules_dt; } foreach ($modules as $module) { - if (! check_acl_one_of_groups ($config["id_user"], $all_groups, "AW") && ! check_acl_one_of_groups ($config["id_user"], $all_groups, "AD")) { - continue; - } - - $type = $module["id_tipo_modulo"]; - $id_module = $module["id_modulo"]; - $nombre_modulo = $module["nombre"]; - $descripcion = $module["descripcion"]; - $module_max = $module["max"]; - $module_min = $module["min"]; - $module_interval2 = $module["module_interval"]; - $module_group2 = $module["id_module_group"]; - - $data = array (); + if (! check_acl_one_of_groups($config['id_user'], $all_groups, 'AW') && ! check_acl_one_of_groups($config['id_user'], $all_groups, 'AD')) { + continue; + } - if (!$checked) { - if ($module['id_module_group'] != $last_modulegroup) { - $last_modulegroup = $module['id_module_group']; - $data[0] = ''.modules_get_modulegroup_name ($last_modulegroup).''; - $i = array_push ($table->data, $data); - $table->rowstyle[$i - 1] = 'text-align: center'; - $table->rowclass[$i - 1] = 'datos3'; - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) - $table->colspan[$i - 1][0] = 10; - else - $table->colspan[$i - 1][0] = 9; - - $data = array (); - } - } - $data[0] = ""; + $type = $module['id_tipo_modulo']; + $id_module = $module['id_modulo']; + $nombre_modulo = $module['nombre']; + $descripcion = $module['descripcion']; + $module_max = $module['max']; + $module_min = $module['min']; + $module_interval2 = $module['module_interval']; + $module_group2 = $module['id_module_group']; - if (isset($module['deep']) && ($module['deep'] != 0)) { - $data[0] .= str_repeat('    ', $module['deep']); - $data[0] .= html_print_image("images/icono_escuadra.png", true, array("style" => 'padding-bottom: inherit;')) . "  "; - } + $data = []; - if ($module['quiet']) { - $data[0] .= html_print_image("images/dot_blue.png", - true, array("border" => '0', "title" => __('Quiet'), - "alt" => "")) . " "; - } - - if (check_acl_one_of_groups ($config["id_user"], $all_groups, "AW")) { - $data[0] .= ''; - } - - if ($module["disabled"]) { - $data[0] .= '' . - ui_print_truncate_text($module['nombre'], 'module_medium', false, true, true, '[…]', 'font-size: 7.2pt').''; - } - else { - $data[0] .= ui_print_truncate_text($module['nombre'], 'module_medium', false, true, true, '[…]', 'font-size: 7.2pt'); - } - - if (check_acl_one_of_groups ($config["id_user"], $all_groups, "AW")) { - $data[0] .= ''; - } - - // The access to the policy is granted only with AW permission - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK && check_acl ($config['id_user'], $agent['id_grupo'], "AW")) { - $policyInfo = policies_info_module_policy($module['id_agente_modulo']); - if ($policyInfo === false) - $data[1] = ''; - else { - $linked = policies_is_module_linked($module['id_agente_modulo']); - - $adopt = false; - if (policies_is_module_adopt($module['id_agente_modulo'])) { - $adopt = true; - } - - if ($linked) { - if ($adopt) { - $img = 'images/policies_brick.png'; - $title = '(' . __('Adopted') . ') ' . $policyInfo['name_policy']; - } - else { - $img = 'images/policies.png'; - $title = $policyInfo['name_policy']; - } - } - else { - if ($adopt) { - $img = 'images/policies_not_brick.png'; - $title = '(' . __('Unlinked') . ') (' . __('Adopted') . ') ' . $policyInfo['name_policy']; - } - else { - $img = 'images/unlinkpolicy.png'; - $title = '(' . __('Unlinked') . ') ' . $policyInfo['name_policy']; - } - } - - $data[1] = '' . - html_print_image($img,true, array('title' => $title)) . - ''; - } - } - - // Module type (by server type ) - $data[2] = ''; - if ($module['id_modulo'] > 0) { - $data[2] = servers_show_type ($module['id_modulo']); - } - - $module_status = db_get_row('tagente_estado', 'id_agente_modulo', $module['id_agente_modulo']); - - modules_get_status($module['id_agente_modulo'], $module_status['estado'], $module_status['datos'], $status, $title); - - // This module is initialized ? (has real data) - if ($status == STATUS_MODULE_NO_DATA) - $data[2] .= html_print_image('images/error.png', true, - array ('title' => __('Non initialized module'))); - - // Module type (by data type) - $data[3] = ''; - if ($type) { - $data[3] = ui_print_moduletype_icon($type, true); - } - - // Module interval - if ($module['module_interval']) { - $data[4] = human_time_description_raw($module['module_interval']); - } - else { - $data[4] = human_time_description_raw($agent_interval); - } - - if ($module['id_modulo'] == MODULE_DATA && $module['id_policy_module'] != 0) { - $data[4] .= ui_print_help_tip(__('The policy modules of data type will only update their intervals when policy is applied.'), true); - } - - $data[5] = ui_print_truncate_text($module['descripcion'], 'description', false); - - $data[6] = ui_print_status_image($status, $title, true); - - // MAX / MIN values - if($module['id_tipo_modulo'] != 25){ - $data[7] = ui_print_module_warn_value ($module["max_warning"], - $module["min_warning"], $module["str_warning"], - $module["max_critical"], $module["min_critical"], - $module["str_critical"]); - } - else{ - $data[7] = ""; - } - - if ($module['disabled']) { - $data[8] = "". - html_print_image('images/lightbulb_off.png', true, - array('alt' => __('Enable module'), 'title' => __('Enable module'))) .""; - } - else { - $data[8] = "". - html_print_image('images/lightbulb.png', true, - array('alt' => __('Disable module'), 'title' => __('Disable module'))) .""; - } + if (!$checked) { + if ($module['id_module_group'] != $last_modulegroup) { + $last_modulegroup = $module['id_module_group']; + $data[0] = ''.modules_get_modulegroup_name($last_modulegroup).''; + $i = array_push($table->data, $data); + $table->rowstyle[($i - 1)] = 'text-align: center'; + $table->rowclass[($i - 1)] = 'datos3'; + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { + $table->colspan[($i - 1)][0] = 10; + } else { + $table->colspan[($i - 1)][0] = 9; + } - if (check_acl_one_of_groups ($config['id_user'], $all_groups, "AW") && $module['id_tipo_modulo'] != 25) { - $data[8] .= ' '; - $data[8] .= html_print_image ('images/copy.png', true, - array ('title' => __('Duplicate'))); - $data[8] .= ' '; - - // Make a data normalization - if (isset($numericModules[$type])) { - if ($numericModules[$type] === true) { - $data[8] .= ' '; - $data[8] .= html_print_image ('images/chart_curve.png', true, - array('title' => __('Normalize'))); - $data[8] .= ''; - } - } - else { - $data[8] .= " " . html_print_image ('images/chart_curve.disabled.png', true, - array('title' => __('Normalize (Disabled)'))); - } - - //create network component action - if ((is_user_admin($config['id_user'])) && - ($module['id_modulo'] == MODULE_NETWORK)) { - $data[8] .= ' '; - $data[8] .= html_print_image ('images/network.png', true, - array ('title' => __('Create network component'))); - $data[8] .= ' '; - } - else { - $data[8] .= ' ' . html_print_image ('images/network.disabled.png', true, - array ('title' => __('Create network component (Disabled)'))); - } - } - - if (check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) { - // Delete module - - $data[9] = ' 'padding-bottom: inherit;']).'  '; + } + + if ($module['quiet']) { + $data[0] .= html_print_image( + 'images/dot_blue.png', + true, + [ + 'border' => '0', + 'title' => __('Quiet'), + 'alt' => '', + ] + ).' '; + } + + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + $data[0] .= ''; + } + + if ($module['disabled']) { + $data[0] .= ''.ui_print_truncate_text($module['nombre'], 'module_medium', false, true, true, '[…]', 'font-size: 7.2pt').''; + } else { + $data[0] .= ui_print_truncate_text($module['nombre'], 'module_medium', false, true, true, '[…]', 'font-size: 7.2pt'); + } + + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + $data[0] .= ''; + } + + // The access to the policy is granted only with AW permission + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK && check_acl($config['id_user'], $agent['id_grupo'], 'AW')) { + $policyInfo = policies_info_module_policy($module['id_agente_modulo']); + if ($policyInfo === false) { + $data[1] = ''; + } else { + $linked = policies_is_module_linked($module['id_agente_modulo']); + + $adopt = false; + if (policies_is_module_adopt($module['id_agente_modulo'])) { + $adopt = true; + } + + if ($linked) { + if ($adopt) { + $img = 'images/policies_brick.png'; + $title = '('.__('Adopted').') '.$policyInfo['name_policy']; + } else { + $img = 'images/policies.png'; + $title = $policyInfo['name_policy']; + } + } else { + if ($adopt) { + $img = 'images/policies_not_brick.png'; + $title = '('.__('Unlinked').') ('.__('Adopted').') '.$policyInfo['name_policy']; + } else { + $img = 'images/unlinkpolicy.png'; + $title = '('.__('Unlinked').') '.$policyInfo['name_policy']; + } + } + + $data[1] = ''.html_print_image($img, true, ['title' => $title]).''; + } + } + + // Module type (by server type ) + $data[2] = ''; + if ($module['id_modulo'] > 0) { + $data[2] = servers_show_type($module['id_modulo']); + } + + $module_status = db_get_row('tagente_estado', 'id_agente_modulo', $module['id_agente_modulo']); + + modules_get_status($module['id_agente_modulo'], $module_status['estado'], $module_status['datos'], $status, $title); + + // This module is initialized ? (has real data) + if ($status == STATUS_MODULE_NO_DATA) { + $data[2] .= html_print_image( + 'images/error.png', + true, + ['title' => __('Non initialized module')] + ); + } + + // Module type (by data type) + $data[3] = ''; + if ($type) { + $data[3] = ui_print_moduletype_icon($type, true); + } + + // Module interval + if ($module['module_interval']) { + $data[4] = human_time_description_raw($module['module_interval']); + } else { + $data[4] = human_time_description_raw($agent_interval); + } + + if ($module['id_modulo'] == MODULE_DATA && $module['id_policy_module'] != 0) { + $data[4] .= ui_print_help_tip(__('The policy modules of data type will only update their intervals when policy is applied.'), true); + } + + $data[5] = ui_print_truncate_text($module['descripcion'], 'description', false); + + $data[6] = ui_print_status_image($status, $title, true); + + // MAX / MIN values + if ($module['id_tipo_modulo'] != 25) { + $data[7] = ui_print_module_warn_value( + $module['max_warning'], + $module['min_warning'], + $module['str_warning'], + $module['max_critical'], + $module['min_critical'], + $module['str_critical'] + ); + } else { + $data[7] = ''; + } + + if ($module['disabled']) { + $data[8] = "".html_print_image( + 'images/lightbulb_off.png', + true, + [ + 'alt' => __('Enable module'), + 'title' => __('Enable module'), + ] + ).''; + } else { + $data[8] = "".html_print_image( + 'images/lightbulb.png', + true, + [ + 'alt' => __('Disable module'), + 'title' => __('Disable module'), + ] + ).''; + } + + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW') && $module['id_tipo_modulo'] != 25) { + $data[8] .= ' '; - $data[9] .= html_print_image ('images/cross.png', true, - array ('title' => __('Delete'))); - $data[9] .= ' '; - $data[9] .= html_print_checkbox('id_delete[]', $module['id_agente_modulo'], false, true); - } - - array_push ($table->data, $data); + $data[8] .= html_print_image( + 'images/copy.png', + true, + ['title' => __('Duplicate')] + ); + $data[8] .= ' '; + + // Make a data normalization + if (isset($numericModules[$type])) { + if ($numericModules[$type] === true) { + $data[8] .= ' '; + $data[8] .= html_print_image( + 'images/chart_curve.png', + true, + ['title' => __('Normalize')] + ); + $data[8] .= ''; + } + } else { + $data[8] .= ' '.html_print_image( + 'images/chart_curve.disabled.png', + true, + ['title' => __('Normalize (Disabled)')] + ); + } + + // create network component action + if ((is_user_admin($config['id_user'])) + && ($module['id_modulo'] == MODULE_NETWORK) + ) { + $data[8] .= ' '; + $data[8] .= html_print_image( + 'images/network.png', + true, + ['title' => __('Create network component')] + ); + $data[8] .= ' '; + } else { + $data[8] .= ' '.html_print_image( + 'images/network.disabled.png', + true, + ['title' => __('Create network component (Disabled)')] + ); + } + } + + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + // Delete module + $data[9] = ''; + $data[9] .= html_print_image( + 'images/cross.png', + true, + ['title' => __('Delete')] + ); + $data[9] .= ' '; + $data[9] .= html_print_checkbox('id_delete[]', $module['id_agente_modulo'], false, true); + } + + array_push($table->data, $data); } -if (check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) { - echo '
    '; +if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + echo ''; } -html_print_table ($table); +html_print_table($table); -if (check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) { - echo '
    '; - html_print_input_hidden ('multiple_delete', 1); - html_print_submit_button (__('Delete'), 'multiple_delete', false, 'class="sub delete"'); - echo '
    '; - echo '
    '; +if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + echo '
    '; + html_print_input_hidden('multiple_delete', 1); + html_print_submit_button(__('Delete'), 'multiple_delete', false, 'class="sub delete"'); + echo '
    '; + echo ''; } ?> diff --git a/pandora_console/godmode/agentes/module_manager_editor.php b/pandora_console/godmode/agentes/module_manager_editor.php index f9347c8b9b..aaa2078479 100644 --- a/pandora_console/godmode/agentes/module_manager_editor.php +++ b/pandora_console/godmode/agentes/module_manager_editor.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,505 +11,569 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -require_once ('include/functions_network_components.php'); +require_once 'include/functions_network_components.php'; enterprise_include_once('include/functions_local_components.php'); -if (is_ajax ()) { - $get_network_component = (bool) get_parameter ('get_network_component'); - $snmp_walk = (bool) get_parameter ('snmp_walk'); - $get_module_component = (bool) get_parameter ('get_module_component'); - $get_module_components = (bool) get_parameter ('get_module_components'); - $get_module_local_components = (bool) get_parameter('get_module_local_components'); - $get_module_local_component = (bool) get_parameter('get_module_local_component'); - - if ($get_module_component) { - $id_component = (int) get_parameter ('id_module_component'); - - $component = db_get_row ('tnetwork_component', 'id_nc', $id_component); - - $component['throw_unknown_events'] = - network_components_is_disable_type_event($id_component, EVENTS_GOING_UNKNOWN); - - // Decrypt passwords in the component. - $component['plugin_pass'] = io_output_password($component['plugin_pass']); +if (is_ajax()) { + $get_network_component = (bool) get_parameter('get_network_component'); + $snmp_walk = (bool) get_parameter('snmp_walk'); + $get_module_component = (bool) get_parameter('get_module_component'); + $get_module_components = (bool) get_parameter('get_module_components'); + $get_module_local_components = (bool) get_parameter('get_module_local_components'); + $get_module_local_component = (bool) get_parameter('get_module_local_component'); - $component['str_warning'] = io_safe_output($component['str_warning']); - $component['str_critical'] = io_safe_output($component['str_critical']); - $component['warning_inverse'] = (bool)$component['warning_inverse']; - $component['critical_inverse'] = (bool)$component['critical_inverse']; - - echo io_json_mb_encode ($component); - return; - } - - if ($get_module_components) { - require_once ('include/functions_modules.php'); - $id_module_group = (int) get_parameter ('id_module_component_group'); - $id_module_component = (int) get_parameter ('id_module_component_type'); - - $components = network_components_get_network_components ($id_module_component, - array ('id_group' => $id_module_group, - 'order' => 'name ASC'), - array ('id_nc', 'name')); - - echo io_json_mb_encode ($components); - return; - } - - if ($get_module_local_components) { - require_once ($config['homedir'] . '/' . ENTERPRISE_DIR . - '/include/functions_local_components.php'); - - $id_module_group = (int) get_parameter ('id_module_component_group'); - $localComponents = local_components_get_local_components( - array('id_network_component_group' => $id_module_group), - array('id', 'name')); - - echo io_json_mb_encode($localComponents); - return; - } - - if ($get_module_local_component) { - $id_component = (int) get_parameter ('id_module_component'); - - $component = db_get_row ('tlocal_component', 'id', $id_component); - foreach ($component as $index => $element) { - $component[$index] = html_entity_decode($element, ENT_QUOTES, "UTF-8"); - } - - $typeName = local_components_parse_module_extract_value('module_type',$component['data']); - - switch ($config["dbtype"]) { - case "mysql": - $component['type'] = db_get_value_sql(' + if ($get_module_component) { + $id_component = (int) get_parameter('id_module_component'); + + $component = db_get_row('tnetwork_component', 'id_nc', $id_component); + + $component['throw_unknown_events'] = network_components_is_disable_type_event($id_component, EVENTS_GOING_UNKNOWN); + + // Decrypt passwords in the component. + $component['plugin_pass'] = io_output_password($component['plugin_pass']); + + $component['str_warning'] = io_safe_output($component['str_warning']); + $component['str_critical'] = io_safe_output($component['str_critical']); + $component['warning_inverse'] = (bool) $component['warning_inverse']; + $component['critical_inverse'] = (bool) $component['critical_inverse']; + + echo io_json_mb_encode($component); + return; + } + + if ($get_module_components) { + include_once 'include/functions_modules.php'; + $id_module_group = (int) get_parameter('id_module_component_group'); + $id_module_component = (int) get_parameter('id_module_component_type'); + + $components = network_components_get_network_components( + $id_module_component, + [ + 'id_group' => $id_module_group, + 'order' => 'name ASC', + ], + [ + 'id_nc', + 'name', + ] + ); + + echo io_json_mb_encode($components); + return; + } + + if ($get_module_local_components) { + include_once $config['homedir'].'/'.ENTERPRISE_DIR.'/include/functions_local_components.php'; + + $id_module_group = (int) get_parameter('id_module_component_group'); + $localComponents = local_components_get_local_components( + ['id_network_component_group' => $id_module_group], + [ + 'id', + 'name', + ] + ); + + echo io_json_mb_encode($localComponents); + return; + } + + if ($get_module_local_component) { + $id_component = (int) get_parameter('id_module_component'); + + $component = db_get_row('tlocal_component', 'id', $id_component); + foreach ($component as $index => $element) { + $component[$index] = html_entity_decode($element, ENT_QUOTES, 'UTF-8'); + } + + $typeName = local_components_parse_module_extract_value('module_type', $component['data']); + + switch ($config['dbtype']) { + case 'mysql': + $component['type'] = db_get_value_sql( + ' SELECT id_tipo FROM ttipo_modulo - WHERE nombre LIKE "' . $typeName . '"'); - break; - case "postgresql": - case "oracle": - $component['type'] = db_get_value_sql(' + WHERE nombre LIKE "'.$typeName.'"' + ); + break; + + case 'postgresql': + case 'oracle': + $component['type'] = db_get_value_sql( + ' SELECT id_tipo FROM ttipo_modulo - WHERE nombre LIKE \'' . $typeName . '\''); - break; - } - - $component['throw_unknown_events'] = - !local_components_is_disable_type_event($id_component, EVENTS_GOING_UNKNOWN); - - echo io_json_mb_encode ($component); - return; - } - - if ($snmp_walk) { - $test_ip_type = get_parameter ('ip_target'); - if (is_array($test_ip_type)) - $ip_target = (string)array_shift($test_ip_type); - else - $ip_target = (string) get_parameter ('ip_target'); - $test_snmp_community = get_parameter ('snmp_community'); - if (is_array($test_snmp_community)) - $snmp_community = (string)array_shift($test_snmp_community); - else - $snmp_community = (string) get_parameter ('snmp_community'); - $snmp_version = get_parameter('snmp_version'); - $snmp3_auth_user = io_safe_output(get_parameter('snmp3_auth_user')); - $snmp3_security_level = get_parameter('snmp3_security_level'); - $snmp3_auth_method = get_parameter('snmp3_auth_method'); - $snmp3_auth_pass = io_safe_output(get_parameter('snmp3_auth_pass')); - $snmp3_privacy_method = get_parameter('snmp3_privacy_method'); - $snmp3_privacy_pass = io_safe_output(get_parameter('snmp3_privacy_pass')); - $snmp_port = get_parameter('snmp_port'); - - $snmpwalk = get_snmpwalk($ip_target, $snmp_version, $snmp_community, - $snmp3_auth_user, $snmp3_security_level, $snmp3_auth_method, - $snmp3_auth_pass, $snmp3_privacy_method, $snmp3_privacy_pass, - 1, "", $snmp_port); - - if ($snmpwalk === false) { - echo io_json_mb_encode ($snmpwalk); - return; - } - - $result = array (); - foreach ($snmpwalk as $id => $value) { - $value = substr ($id, 0, 35)." - ".substr ($value, 0, 20); - $result[$id] = substr ($value, 0, 55); - } - asort ($result); - echo io_json_mb_encode ($result); - return; - } - - return; + WHERE nombre LIKE \''.$typeName.'\'' + ); + break; + } + + $component['throw_unknown_events'] = !local_components_is_disable_type_event($id_component, EVENTS_GOING_UNKNOWN); + + echo io_json_mb_encode($component); + return; + } + + if ($snmp_walk) { + $test_ip_type = get_parameter('ip_target'); + if (is_array($test_ip_type)) { + $ip_target = (string) array_shift($test_ip_type); + } else { + $ip_target = (string) get_parameter('ip_target'); + } + + $test_snmp_community = get_parameter('snmp_community'); + if (is_array($test_snmp_community)) { + $snmp_community = (string) array_shift($test_snmp_community); + } else { + $snmp_community = (string) get_parameter('snmp_community'); + } + + $snmp_version = get_parameter('snmp_version'); + $snmp3_auth_user = io_safe_output(get_parameter('snmp3_auth_user')); + $snmp3_security_level = get_parameter('snmp3_security_level'); + $snmp3_auth_method = get_parameter('snmp3_auth_method'); + $snmp3_auth_pass = io_safe_output(get_parameter('snmp3_auth_pass')); + $snmp3_privacy_method = get_parameter('snmp3_privacy_method'); + $snmp3_privacy_pass = io_safe_output(get_parameter('snmp3_privacy_pass')); + $snmp_port = get_parameter('snmp_port'); + + $snmpwalk = get_snmpwalk( + $ip_target, + $snmp_version, + $snmp_community, + $snmp3_auth_user, + $snmp3_security_level, + $snmp3_auth_method, + $snmp3_auth_pass, + $snmp3_privacy_method, + $snmp3_privacy_pass, + 1, + '', + $snmp_port + ); + + if ($snmpwalk === false) { + echo io_json_mb_encode($snmpwalk); + return; + } + + $result = []; + foreach ($snmpwalk as $id => $value) { + $value = substr($id, 0, 35).' - '.substr($value, 0, 20); + $result[$id] = substr($value, 0, 55); + } + + asort($result); + echo io_json_mb_encode($result); + return; + } + + return; } -require_once ("include/functions_exportserver.php"); -require_once($config['homedir'] . "/include/functions_modules.php"); -require_once($config['homedir'] . "/include/functions_agents.php"); +require_once 'include/functions_exportserver.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_agents.php'; // Reading a module if ($id_agent_module) { - $module = modules_get_agentmodule ($id_agent_module); - $moduletype = $module['id_modulo']; - $name = $module['nombre']; - $description = $module['descripcion']; - $id_module_group = $module['id_module_group']; - $id_module_type = $module['id_tipo_modulo']; - $max = $module['max']; - $min = $module['min']; - $interval = $module['module_interval']; - if ($interval == 0) { - $interval = agents_get_interval ($id_agente); - } - $ff_interval = $module['module_ff_interval']; - $quiet_module = $module['quiet']; - $cps_module = $module['cps']; - $unit = $module['unit']; - $tcp_port = $module['tcp_port']; - $tcp_send = $module['tcp_send']; - $tcp_rcv = $module['tcp_rcv']; - $snmp_community = $module['snmp_community']; - $snmp_oid = $module['snmp_oid']; - - // New support for snmp v3 - $snmp_version = $module['tcp_send']; - $snmp3_auth_user = $module["plugin_user"]; - $snmp3_auth_pass = io_output_password($module["plugin_pass"]); - - // Auth method could be MD5 or SHA - $snmp3_auth_method = $module["plugin_parameter"]; - - // Privacy method could be DES or AES - $snmp3_privacy_method = $module["custom_string_1"]; - $snmp3_privacy_pass = io_output_password($module["custom_string_2"]); - - // Security level Could be noAuthNoPriv | authNoPriv | authPriv - $snmp3_security_level = $module["custom_string_3"]; + $module = modules_get_agentmodule($id_agent_module); + $moduletype = $module['id_modulo']; + $name = $module['nombre']; + $description = $module['descripcion']; + $id_module_group = $module['id_module_group']; + $id_module_type = $module['id_tipo_modulo']; + $max = $module['max']; + $min = $module['min']; + $interval = $module['module_interval']; + if ($interval == 0) { + $interval = agents_get_interval($id_agente); + } - $ip_target = $module['ip_target']; - $disabled = $module['disabled']; - $id_export = $module['id_export']; - $plugin_user = $module['plugin_user']; - $plugin_pass = io_output_password($module['plugin_pass']); - $plugin_parameter = $module['plugin_parameter']; - $id_plugin = $module['id_plugin']; - $post_process = $module['post_process']; - $prediction_module = $module['prediction_module']; - $custom_integer_1 = $module ['custom_integer_1']; - $custom_integer_2 = $module ['custom_integer_2']; - $custom_string_1 = $module ['custom_string_1']; - $custom_string_2 = $module ['custom_string_2']; - $max_timeout = $module['max_timeout']; - $max_retries = $module['max_retries']; - $custom_id = $module['custom_id']; - $history_data = $module['history_data']; - $dynamic_interval = $module['dynamic_interval']; - $dynamic_max = $module['dynamic_max']; - $dynamic_min = $module['dynamic_min']; - $parent_module_id = $module['parent_module_id']; - $dynamic_two_tailed = $module['dynamic_two_tailed']; - $min_warning = $module['min_warning']; - $max_warning = $module['max_warning']; - $str_warning = $module['str_warning']; - $min_critical = $module['min_critical']; - $max_critical = $module['max_critical']; - $str_critical = $module['str_critical']; - $ff_event = $module['min_ff_event']; - $ff_event_normal = $module['min_ff_event_normal']; - $ff_event_warning = $module['min_ff_event_warning']; - $ff_event_critical = $module['min_ff_event_critical']; - $each_ff = $module['each_ff']; - $ff_timeout = $module['ff_timeout']; - // Select tag info. - $id_tag = tags_get_module_tags ($id_agent_module); - - $critical_instructions = $module['critical_instructions']; - $warning_instructions = $module['warning_instructions']; - $unknown_instructions = $module['unknown_instructions']; - - $critical_inverse = $module['critical_inverse']; - $warning_inverse = $module['warning_inverse']; - - $id_category = $module['id_category']; - - $cron_interval = explode (" ", $module['cron_interval']); - if (isset ($cron_interval[4])) { - $minute_from = $cron_interval[0]; - $min = explode("-", $minute_from); - $minute_from = $min[0]; - if (isset($min[1])) { - $minute_to = $min[1]; - } + $ff_interval = $module['module_ff_interval']; + $quiet_module = $module['quiet']; + $cps_module = $module['cps']; + $unit = $module['unit']; + $tcp_port = $module['tcp_port']; + $tcp_send = $module['tcp_send']; + $tcp_rcv = $module['tcp_rcv']; + $snmp_community = $module['snmp_community']; + $snmp_oid = $module['snmp_oid']; - $hour_from = $cron_interval[1]; - $h = explode("-", $hour_from); - $hour_from = $h[0]; - if (isset($h[1])) { - $hour_to = $h[1]; - } + // New support for snmp v3 + $snmp_version = $module['tcp_send']; + $snmp3_auth_user = $module['plugin_user']; + $snmp3_auth_pass = io_output_password($module['plugin_pass']); - $mday_from = $cron_interval[2]; - $md = explode("-", $mday_from); - $mday_from = $md[0]; - if (isset($md[1])) { - $mday_to = $md[1]; - } - - $month_from = $cron_interval[3]; - $m = explode("-", $month_from); - $month_from = $m[0]; - if (isset($m[1])) { - $month_to = $m[1]; - } + // Auth method could be MD5 or SHA + $snmp3_auth_method = $module['plugin_parameter']; - $wday_from = $cron_interval[4]; - $wd = explode("-", $wday_from); - $wday_from = $wd[0]; - if (isset($wd[1])) { - $wday_to = $wd[1]; - } - } - else { - $minute_from = '*'; - $hour_from = '*'; - $mday_from = '*'; - $month_from = '*'; - $wday_from = '*'; + // Privacy method could be DES or AES + $snmp3_privacy_method = $module['custom_string_1']; + $snmp3_privacy_pass = io_output_password($module['custom_string_2']); - $minute_to = '*'; - $hour_to = '*'; - $mday_to = '*'; - $month_to = '*'; - $wday_to = '*'; - } - - $module_macros = null; - if (isset($module['module_macros'])) { - $module_macros = json_decode(base64_decode($module['module_macros']), true); - } -} -else { - if (!isset ($moduletype)) { - $moduletype = (string) get_parameter ('moduletype'); + // Security level Could be noAuthNoPriv | authNoPriv | authPriv + $snmp3_security_level = $module['custom_string_3']; - // Clean up specific network modules fields - $name = ''; - $description = ''; - $id_module_group = 1; - $id_module_type = 1; - $post_process = ''; - $max_timeout = 0; - $max_retries = 0; - $min = ''; - $max = ''; - $interval = ''; - $quiet_module = 0; - $cps_module = 0; - $unit = ''; - $prediction_module = ''; - $custom_integer_1 = 0; - $custom_integer_2 = 0; - $custom_string_1 = ''; - $custom_string_2 = ''; - $id_plugin = ''; - $id_export = ''; - $disabled = "0"; - $tcp_send = ''; - $tcp_rcv = ''; - $tcp_port = ''; + $ip_target = $module['ip_target']; + $disabled = $module['disabled']; + $id_export = $module['id_export']; + $plugin_user = $module['plugin_user']; + $plugin_pass = io_output_password($module['plugin_pass']); + $plugin_parameter = $module['plugin_parameter']; + $id_plugin = $module['id_plugin']; + $post_process = $module['post_process']; + $prediction_module = $module['prediction_module']; + $custom_integer_1 = $module['custom_integer_1']; + $custom_integer_2 = $module['custom_integer_2']; + $custom_string_1 = $module['custom_string_1']; + $custom_string_2 = $module['custom_string_2']; + $max_timeout = $module['max_timeout']; + $max_retries = $module['max_retries']; + $custom_id = $module['custom_id']; + $history_data = $module['history_data']; + $dynamic_interval = $module['dynamic_interval']; + $dynamic_max = $module['dynamic_max']; + $dynamic_min = $module['dynamic_min']; + $parent_module_id = $module['parent_module_id']; + $dynamic_two_tailed = $module['dynamic_two_tailed']; + $min_warning = $module['min_warning']; + $max_warning = $module['max_warning']; + $str_warning = $module['str_warning']; + $min_critical = $module['min_critical']; + $max_critical = $module['max_critical']; + $str_critical = $module['str_critical']; + $ff_event = $module['min_ff_event']; + $ff_event_normal = $module['min_ff_event_normal']; + $ff_event_warning = $module['min_ff_event_warning']; + $ff_event_critical = $module['min_ff_event_critical']; + $each_ff = $module['each_ff']; + $ff_timeout = $module['ff_timeout']; + // Select tag info. + $id_tag = tags_get_module_tags($id_agent_module); - if ($moduletype == "wmiserver") - $snmp_community = ''; - else - $snmp_community = "public"; - $snmp_oid = ''; - $ip_target = agents_get_address ($id_agente); - $plugin_user = ''; - $plugin_pass = ''; - $plugin_parameter = ''; - $custom_id = ''; - $history_data = 1; - $dynamic_interval = 0; - $dynamic_min = 0; - $dynamic_max = 0; - $parent_module_id = 0; - $dynamic_two_tailed = 0; - $min_warning = 0; - $max_warning = 0; - $str_warning = ''; - $min_critical = 0; - $max_critical = 0; - $str_critical = ''; - $ff_event = 0; - - // New support for snmp v3 - $snmp_version = 1; - $snmp3_auth_user = ""; - $snmp3_auth_pass = ""; - $snmp3_auth_method = ""; - $snmp3_privacy_method = ""; - $snmp3_privacy_pass = ""; - $snmp3_security_level = ""; - - $critical_instructions = ''; - $warning_instructions = ''; - $unknown_instructions = ''; - - $critical_inverse = ''; - $warning_inverse = ''; - - $each_ff = 0; - $ff_event_normal = ''; - $ff_event_warning = ''; - $ff_event_critical = ''; - - $id_category = 0; - - $cron_interval = '* * * * *'; - $hour_from = '*'; - $minute_from = '*'; - $mday_from = '*'; - $month_from = '*'; - $wday_from = '*'; - $hour_to = '*'; - $minute_to = '*'; - $mday_to = '*'; - $month_to = '*'; - $wday_to = '*'; - - $ff_interval = 0; + $critical_instructions = $module['critical_instructions']; + $warning_instructions = $module['warning_instructions']; + $unknown_instructions = $module['unknown_instructions']; - $ff_timeout = 0; - - $module_macros = array (); - } + $critical_inverse = $module['critical_inverse']; + $warning_inverse = $module['warning_inverse']; + + $id_category = $module['id_category']; + + $cron_interval = explode(' ', $module['cron_interval']); + if (isset($cron_interval[4])) { + $minute_from = $cron_interval[0]; + $min = explode('-', $minute_from); + $minute_from = $min[0]; + if (isset($min[1])) { + $minute_to = $min[1]; + } + + $hour_from = $cron_interval[1]; + $h = explode('-', $hour_from); + $hour_from = $h[0]; + if (isset($h[1])) { + $hour_to = $h[1]; + } + + $mday_from = $cron_interval[2]; + $md = explode('-', $mday_from); + $mday_from = $md[0]; + if (isset($md[1])) { + $mday_to = $md[1]; + } + + $month_from = $cron_interval[3]; + $m = explode('-', $month_from); + $month_from = $m[0]; + if (isset($m[1])) { + $month_to = $m[1]; + } + + $wday_from = $cron_interval[4]; + $wd = explode('-', $wday_from); + $wday_from = $wd[0]; + if (isset($wd[1])) { + $wday_to = $wd[1]; + } + } else { + $minute_from = '*'; + $hour_from = '*'; + $mday_from = '*'; + $month_from = '*'; + $wday_from = '*'; + + $minute_to = '*'; + $hour_to = '*'; + $mday_to = '*'; + $month_to = '*'; + $wday_to = '*'; + } + + $module_macros = null; + if (isset($module['module_macros'])) { + $module_macros = json_decode(base64_decode($module['module_macros']), true); + } +} else { + if (!isset($moduletype)) { + $moduletype = (string) get_parameter('moduletype'); + + // Clean up specific network modules fields + $name = ''; + $description = ''; + $id_module_group = 1; + $id_module_type = 1; + $post_process = ''; + $max_timeout = 0; + $max_retries = 0; + $min = ''; + $max = ''; + $interval = ''; + $quiet_module = 0; + $cps_module = 0; + $unit = ''; + $prediction_module = ''; + $custom_integer_1 = 0; + $custom_integer_2 = 0; + $custom_string_1 = ''; + $custom_string_2 = ''; + $id_plugin = ''; + $id_export = ''; + $disabled = '0'; + $tcp_send = ''; + $tcp_rcv = ''; + $tcp_port = ''; + + if ($moduletype == 'wmiserver') { + $snmp_community = ''; + } else { + $snmp_community = 'public'; + } + + $snmp_oid = ''; + $ip_target = agents_get_address($id_agente); + $plugin_user = ''; + $plugin_pass = ''; + $plugin_parameter = ''; + $custom_id = ''; + $history_data = 1; + $dynamic_interval = 0; + $dynamic_min = 0; + $dynamic_max = 0; + $parent_module_id = 0; + $dynamic_two_tailed = 0; + $min_warning = 0; + $max_warning = 0; + $str_warning = ''; + $min_critical = 0; + $max_critical = 0; + $str_critical = ''; + $ff_event = 0; + + // New support for snmp v3 + $snmp_version = 1; + $snmp3_auth_user = ''; + $snmp3_auth_pass = ''; + $snmp3_auth_method = ''; + $snmp3_privacy_method = ''; + $snmp3_privacy_pass = ''; + $snmp3_security_level = ''; + + $critical_instructions = ''; + $warning_instructions = ''; + $unknown_instructions = ''; + + $critical_inverse = ''; + $warning_inverse = ''; + + $each_ff = 0; + $ff_event_normal = ''; + $ff_event_warning = ''; + $ff_event_critical = ''; + + $id_category = 0; + + $cron_interval = '* * * * *'; + $hour_from = '*'; + $minute_from = '*'; + $mday_from = '*'; + $month_from = '*'; + $wday_from = '*'; + $hour_to = '*'; + $minute_to = '*'; + $mday_to = '*'; + $month_to = '*'; + $wday_to = '*'; + + $ff_interval = 0; + + $ff_timeout = 0; + + $module_macros = []; + } } $is_function_policies = enterprise_include_once('include/functions_policies.php'); if ($is_function_policies !== ENTERPRISE_NOT_HOOK) { - $relink_policy = get_parameter('relink_policy', 0); - $unlink_policy = get_parameter('unlink_policy', 0); - - if ($relink_policy) { - $policy_info = policies_info_module_policy($id_agent_module); - $policy_id = $policy_info['id_policy']; - - if ($relink_policy && policies_get_policy_queue_status ($policy_id) == STATUS_IN_QUEUE_APPLYING) { - ui_print_error_message(__('This policy is applying and cannot be modified')); - } - else { - $result = policies_relink_module($id_agent_module); - ui_print_result_message($result, __('Module will be linked in the next application')); - - db_pandora_audit("Agent management", "Re-link module " . $id_agent_module); - } - } - - if ($unlink_policy) { - $result = policies_unlink_module($id_agent_module); - ui_print_result_message($result, __('Module will be unlinked in the next application')); - - db_pandora_audit("Agent management", "Unlink module " . $id_agent_module); - } + $relink_policy = get_parameter('relink_policy', 0); + $unlink_policy = get_parameter('unlink_policy', 0); + if ($relink_policy) { + $policy_info = policies_info_module_policy($id_agent_module); + $policy_id = $policy_info['id_policy']; + + if ($relink_policy && policies_get_policy_queue_status($policy_id) == STATUS_IN_QUEUE_APPLYING) { + ui_print_error_message(__('This policy is applying and cannot be modified')); + } else { + $result = policies_relink_module($id_agent_module); + ui_print_result_message($result, __('Module will be linked in the next application')); + + db_pandora_audit('Agent management', 'Re-link module '.$id_agent_module); + } + } + + if ($unlink_policy) { + $result = policies_unlink_module($id_agent_module); + ui_print_result_message($result, __('Module will be unlinked in the next application')); + + db_pandora_audit('Agent management', 'Unlink module '.$id_agent_module); + } } + global $__code_from; $__code_from = 'modules'; $remote_conf = false; if ($__code_from !== 'policies') { - //Only check in the module editor. - - //Check ACL tags - $tag_acl = true; - - // If edit a existing module. - if (!empty($id_agent_module)) - $tag_acl = tags_check_acl_by_module($id_agent_module); - - if (!$tag_acl) { - db_pandora_audit("ACL Violation", - "Trying to access agent manager"); - require ("general/noaccess.php"); - return; - } + // Only check in the module editor. + // Check ACL tags + $tag_acl = true; + + // If edit a existing module. + if (!empty($id_agent_module)) { + $tag_acl = tags_check_acl_by_module($id_agent_module); + } + + if (!$tag_acl) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access agent manager' + ); + include 'general/noaccess.php'; + return; + } } switch ($moduletype) { - case "dataserver": - case MODULE_DATA: - $moduletype = MODULE_DATA; - // Has remote configuration ? - $remote_conf = false; - if (enterprise_installed()) { - enterprise_include_once('include/functions_config_agents.php'); - $remote_conf = enterprise_hook('config_agents_has_remote_configuration',array($id_agente)); - } - - /* Categories is an array containing the allowed module types - (generic_data, generic_string, etc) from ttipo_modulo (field categoria) */ - $categories = array (0, 1, 2, 6, 7, 8, -1); - require ('module_manager_editor_common.php'); - require ('module_manager_editor_data.php'); - if ($config['enterprise_installed'] && $remote_conf) { - if($id_agent_module) { - enterprise_include_once('include/functions_config_agents.php'); - $configuration_data = enterprise_hook('config_agents_get_module_from_conf', - array($id_agente, io_safe_output(modules_get_agentmodule_name($id_agent_module)))); - } - enterprise_include ('godmode/agentes/module_manager_editor_data.php'); - } - break; - case "networkserver": - case MODULE_NETWORK: - $moduletype = MODULE_NETWORK; - $categories = array (3, 4, 5); - require ('module_manager_editor_common.php'); - require ('module_manager_editor_network.php'); - break; - case "pluginserver": - case MODULE_PLUGIN: - $moduletype = MODULE_PLUGIN; - - $categories = array (0, 1, 2); - require ('module_manager_editor_common.php'); - require ('module_manager_editor_plugin.php'); - break; - case "predictionserver": - case MODULE_PREDICTION: - $moduletype = MODULE_PREDICTION; - - $categories = array (0, 1); - require ('module_manager_editor_common.php'); - require ('module_manager_editor_prediction.php'); - break; - case "wmiserver": - case MODULE_WMI: - $moduletype = MODULE_WMI; - - $categories = array (0, 1, 2); - require ('module_manager_editor_common.php'); - require ('module_manager_editor_wmi.php'); - break; - /* WARNING: type 7 is reserved on enterprise */ - default: - if (enterprise_include ('godmode/agentes/module_manager_editor.php') === ENTERPRISE_NOT_HOOK) { - ui_print_error_message(sprintf(__('Invalid module type'))); - return; - } - break; + case 'dataserver': + case MODULE_DATA: + $moduletype = MODULE_DATA; + // Has remote configuration ? + $remote_conf = false; + if (enterprise_installed()) { + enterprise_include_once('include/functions_config_agents.php'); + $remote_conf = enterprise_hook('config_agents_has_remote_configuration', [$id_agente]); + } + + /* + Categories is an array containing the allowed module types + (generic_data, generic_string, etc) from ttipo_modulo (field categoria) */ + $categories = [ + 0, + 1, + 2, + 6, + 7, + 8, + -1, + ]; + include 'module_manager_editor_common.php'; + include 'module_manager_editor_data.php'; + if ($config['enterprise_installed'] && $remote_conf) { + if ($id_agent_module) { + enterprise_include_once('include/functions_config_agents.php'); + $configuration_data = enterprise_hook( + 'config_agents_get_module_from_conf', + [ + $id_agente, + io_safe_output(modules_get_agentmodule_name($id_agent_module)), + ] + ); + } + + enterprise_include('godmode/agentes/module_manager_editor_data.php'); + } + break; + + case 'networkserver': + case MODULE_NETWORK: + $moduletype = MODULE_NETWORK; + $categories = [ + 3, + 4, + 5, + ]; + include 'module_manager_editor_common.php'; + include 'module_manager_editor_network.php'; + break; + + case 'pluginserver': + case MODULE_PLUGIN: + $moduletype = MODULE_PLUGIN; + + $categories = [ + 0, + 1, + 2, + ]; + include 'module_manager_editor_common.php'; + include 'module_manager_editor_plugin.php'; + break; + + case 'predictionserver': + case MODULE_PREDICTION: + $moduletype = MODULE_PREDICTION; + + $categories = [ + 0, + 1, + ]; + include 'module_manager_editor_common.php'; + include 'module_manager_editor_prediction.php'; + break; + + case 'wmiserver': + case MODULE_WMI: + $moduletype = MODULE_WMI; + + $categories = [ + 0, + 1, + 2, + ]; + include 'module_manager_editor_common.php'; + include 'module_manager_editor_wmi.php'; + break; + + // WARNING: type 7 is reserved on enterprise + default: + if (enterprise_include('godmode/agentes/module_manager_editor.php') === ENTERPRISE_NOT_HOOK) { + ui_print_error_message(sprintf(__('Invalid module type'))); + return; + } + break; } if ($config['enterprise_installed'] && $id_agent_module) { - if (policies_is_module_in_policy($id_agent_module)) { - policies_add_policy_linkation($id_agent_module); - } + if (policies_is_module_in_policy($id_agent_module)) { + policies_add_policy_linkation($id_agent_module); + } } echo ''; @@ -518,162 +581,185 @@ echo ''; // TODO: Change to the ui_print_error system echo '
    '; -html_print_table ($table_simple); +html_print_table($table_simple); -ui_toggle(html_print_table ($table_advanced, true), - __('Advanced options')); -ui_toggle(html_print_table ($table_macros, true), - __('Custom macros') . ui_print_help_icon ('module_macros', true)); +ui_toggle( + html_print_table($table_advanced, true), + __('Advanced options') +); +ui_toggle( + html_print_table($table_macros, true), + __('Custom macros').ui_print_help_icon('module_macros', true) +); -if($moduletype != 13){ - ui_toggle(html_print_table ($table_new_relations, true) . - html_print_table ($table_relations, true), __('Module relations')); +if ($moduletype != 13) { + ui_toggle( + html_print_table($table_new_relations, true).html_print_table($table_relations, true), + __('Module relations') + ); } // Submit echo '
    '; if ($id_agent_module) { - html_print_submit_button(__('Update'), 'updbutton', false, - 'class="sub upd"'); - html_print_input_hidden('update_module', 1); - html_print_input_hidden('id_agent_module', $id_agent_module); - html_print_input_hidden('id_module_type', $id_module_type); - - if ($config['enterprise_installed'] && $remote_conf) { - ?> - - - - + + + + '; echo ''; -ui_require_jquery_file ('ui'); -ui_require_jquery_file ('form'); -ui_require_jquery_file ('pandora'); -ui_require_jquery_file ('pandora.controls'); +ui_require_jquery_file('ui'); +ui_require_jquery_file('form'); +ui_require_jquery_file('pandora'); +ui_require_jquery_file('pandora.controls'); -ui_require_javascript_file ('pandora_modules'); +ui_require_javascript_file('pandora_modules'); ?> diff --git a/pandora_console/godmode/agentes/module_manager_editor_common.php b/pandora_console/godmode/agentes/module_manager_editor_common.php index 0527bea08d..9f321bff59 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_common.php +++ b/pandora_console/godmode/agentes/module_manager_editor_common.php @@ -5,7 +5,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -13,89 +12,118 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -include_once($config['homedir'] . "/include/functions_modules.php"); -include_once($config['homedir'] . "/include/functions_categories.php"); -include_once($config['homedir'] . "/include/graphs/functions_d3.php"); +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_categories.php'; +require_once $config['homedir'].'/include/graphs/functions_d3.php'; include_javascript_d3(); -function prepend_table_simple ($row, $id = false) { - global $table_simple; - - if ($id) - $data = array ($id => $row); - else - $data = array ($row); - - $table_simple->data = array_merge ($data, $table_simple->data); + +function prepend_table_simple($row, $id=false) +{ + global $table_simple; + + if ($id) { + $data = [$id => $row]; + } else { + $data = [$row]; + } + + $table_simple->data = array_merge($data, $table_simple->data); } -function push_table_simple ($row, $id = false) { - global $table_simple; - - if ($id) - $data = array ($id => $row); - else - $data = array ($row); - - $table_simple->data = array_merge ($table_simple->data, $data); + +function push_table_simple($row, $id=false) +{ + global $table_simple; + + if ($id) { + $data = [$id => $row]; + } else { + $data = [$row]; + } + + $table_simple->data = array_merge($table_simple->data, $data); } -function prepend_table_advanced ($row, $id = false) { - global $table_advanced; - - if ($id) - $data = array ($id => $row); - else - $data = array ($row); - - $table_advanced->data = array_merge ($data, $table_advanced->data); + +function prepend_table_advanced($row, $id=false) +{ + global $table_advanced; + + if ($id) { + $data = [$id => $row]; + } else { + $data = [$row]; + } + + $table_advanced->data = array_merge($data, $table_advanced->data); } -function push_table_advanced ($row, $id = false) { - global $table_advanced; - - if ($id) - $data = array ($id => $row); - else - $data = array ($row); - - $table_advanced->data = array_merge ($table_advanced->data, $data); + +function push_table_advanced($row, $id=false) +{ + global $table_advanced; + + if ($id) { + $data = [$id => $row]; + } else { + $data = [$row]; + } + + $table_advanced->data = array_merge($table_advanced->data, $data); } -function add_component_selection ($id_network_component_type) { - global $table_simple; - - $data = array (); - $data[0] = __('Using module component').' '; - $data[0] .= ui_print_help_icon ('network_component', true); - - $component_groups = network_components_get_groups ($id_network_component_type); - $data[1] = ''; - $data[1] .= html_print_select ($component_groups, - 'network_component_group', '', '', '--'.__('Manual setup').'--', 0, - true, false, false); - $data[1] .= ''; - $data[1] .= html_print_input_hidden ('id_module_component_type', $id_network_component_type, true); - $data[1] .= ''; - $data[1] .= ''; - $data[1] .= ' '; - - $table_simple->colspan['module_component'][1] = 3; - $table_simple->rowstyle['module_component'] = 'background-color: #cfcfcf'; - - prepend_table_simple ($data, 'module_component'); + +function add_component_selection($id_network_component_type) +{ + global $table_simple; + + $data = []; + $data[0] = __('Using module component').' '; + $data[0] .= ui_print_help_icon('network_component', true); + + $component_groups = network_components_get_groups($id_network_component_type); + $data[1] = ''; + $data[1] .= html_print_select( + $component_groups, + 'network_component_group', + '', + '', + '--'.__('Manual setup').'--', + 0, + true, + false, + false + ); + $data[1] .= ''; + $data[1] .= html_print_input_hidden('id_module_component_type', $id_network_component_type, true); + $data[1] .= ''; + $data[1] .= ''; + $data[1] .= ' '; + + $table_simple->colspan['module_component'][1] = 3; + $table_simple->rowstyle['module_component'] = 'background-color: #cfcfcf'; + + prepend_table_simple($data, 'module_component'); } -require_once ('include/functions_network_components.php'); + +require_once 'include/functions_network_components.php'; enterprise_include_once('include/functions_policies.php'); // If code comes from policies disable export select @@ -107,348 +135,545 @@ $largeClassDisabledBecauseInPolicy = ''; $page = get_parameter('page', ''); -if (strstr($page, "policy_modules") === false && $id_agent_module) { - if ($config['enterprise_installed']) - if(policies_is_module_linked($id_agent_module) == 1){ - $disabledBecauseInPolicy = 1; - } - else{ - $disabledBecauseInPolicy = 0; - } - else - $disabledBecauseInPolicy = false; - if ($disabledBecauseInPolicy) - $disabledTextBecauseInPolicy = 'readonly = "readonly"'; +if (strstr($page, 'policy_modules') === false && $id_agent_module) { + if ($config['enterprise_installed']) { + if (policies_is_module_linked($id_agent_module) == 1) { + $disabledBecauseInPolicy = 1; + } else { + $disabledBecauseInPolicy = 0; + } + } else { + $disabledBecauseInPolicy = false; + } + + if ($disabledBecauseInPolicy) { + $disabledTextBecauseInPolicy = 'readonly = "readonly"'; + } } -if($disabledBecauseInPolicy){ - $classdisabledBecauseInPolicy = 'readonly'; - $largeClassDisabledBecauseInPolicy = 'class=readonly'; +if ($disabledBecauseInPolicy) { + $classdisabledBecauseInPolicy = 'readonly'; + $largeClassDisabledBecauseInPolicy = 'class=readonly'; } else { - $classdisabledBecauseInPolicy = ''; + $classdisabledBecauseInPolicy = ''; } -$update_module_id = (int) get_parameter_get ('update_module'); +$update_module_id = (int) get_parameter_get('update_module'); $table_simple = new stdClass(); $table_simple->id = 'simple'; $table_simple->width = '100%'; $table_simple->class = 'databox'; -$table_simple->data = array (); -$table_simple->style = array (); +$table_simple->data = []; +$table_simple->style = []; $table_simple->style[0] = 'font-weight: bold; width: 25%;'; $table_simple->style[1] = 'width: 25%'; $table_simple->style[2] = 'font-weight: bold; width: 25%;'; $table_simple->style[3] = 'width: 25%'; -$table_simple->cellclass = array(); +$table_simple->cellclass = []; -$table_simple->colspan = array (); +$table_simple->colspan = []; $table_simple->colspan[6][1] = 3; -$table_simple->rowspan = array (); -if(strstr($page, "policy_modules")){ - $table_simple->rowspan[3][2] = 3; - $table_simple->colspan[3][2] = 2; -} -else{ - $table_simple->rowspan[4][2] = 3; - $table_simple->colspan[4][2] = 2; - $table_simple->colspan[5][1] = 3; +$table_simple->rowspan = []; +if (strstr($page, 'policy_modules')) { + $table_simple->rowspan[3][2] = 3; + $table_simple->colspan[3][2] = 2; +} else { + $table_simple->rowspan[4][2] = 3; + $table_simple->colspan[4][2] = 2; + $table_simple->colspan[5][1] = 3; } $table_simple->data[0][0] = __('Name'); -$table_simple->data[0][1] = html_print_input_text_extended ('name', - io_safe_input(html_entity_decode($name, ENT_QUOTES, "UTF-8")), 'text-name', '', 45, 100, $disabledBecauseInPolicy, '', $largeClassDisabledBecauseInPolicy, true); -//$table_simple->data[0][1] = html_print_input_text ('name', -// io_safe_output($name), '', 45, 100, true, $disabledBecauseInPolicy); - +$table_simple->data[0][1] = html_print_input_text_extended( + 'name', + io_safe_input(html_entity_decode($name, ENT_QUOTES, 'UTF-8')), + 'text-name', + '', + 45, + 100, + $disabledBecauseInPolicy, + '', + $largeClassDisabledBecauseInPolicy, + true +); +// $table_simple->data[0][1] = html_print_input_text ('name', +// io_safe_output($name), '', 45, 100, true, $disabledBecauseInPolicy); if (!empty($id_agent_module) && isset($id_agente)) { - $table_simple->data[0][1] .= ' ' . __('ID') . '  ' . $id_agent_module . ' '; + $table_simple->data[0][1] .= ' '.__('ID').'  '.$id_agent_module.' '; - $table_simple->data[0][1] .= ' data[0][1] .= ' '; - $table_simple->data[0][1] .= html_print_image ('images/cross.png', true, - array ('title' => __('Delete module'))); - $table_simple->data[0][1] .= ' '; + $table_simple->data[0][1] .= html_print_image( + 'images/cross.png', + true, + ['title' => __('Delete module')] + ); + $table_simple->data[0][1] .= ' '; } $disabled_enable = 0; -$policy_link = db_get_value('policy_linked', 'tagente_modulo', - 'id_agente_modulo', $id_agent_module); +$policy_link = db_get_value( + 'policy_linked', + 'tagente_modulo', + 'id_agente_modulo', + $id_agent_module +); if ($policy_link != 0) { - $disabled_enable = 1; + $disabled_enable = 1; } + $table_simple->data[0][2] = __('Disabled'); -$table_simple->data[0][2] .= html_print_checkbox ("disabled", 1, $disabled, true, $disabled_enable); +$table_simple->data[0][2] .= html_print_checkbox('disabled', 1, $disabled, true, $disabled_enable); $table_simple->data[0][3] = __('Module group'); -$table_simple->data[0][3] .= html_print_select_from_sql ('SELECT id_mg, name FROM tmodule_group ORDER BY name', - 'id_module_group', $id_module_group, '', __('Not assigned'), '0', true, false, true, $disabledBecauseInPolicy); +$table_simple->data[0][3] .= html_print_select_from_sql( + 'SELECT id_mg, name FROM tmodule_group ORDER BY name', + 'id_module_group', + $id_module_group, + '', + __('Not assigned'), + '0', + true, + false, + true, + $disabledBecauseInPolicy +); -$in_policy = strstr($page, "policy_modules"); +$in_policy = strstr($page, 'policy_modules'); if (!$in_policy) { - // Cannot select the current module to be itself parent - $module_parent_filter = $id_agent_module - ? array("tagente_modulo.id_agente_modulo" => "<>$id_agent_module") - : ""; - $table_simple->data[1][0] = __('Module parent'); - $modules_can_be_parent = agents_get_modules($id_agente, false, $module_parent_filter); - // If the user cannot have access to parent module, only print the name - if ($parent_module_id != 0 && !in_array($parent_module_id, array_keys($modules_can_be_parent))) { - $table_simple->data[1][1] = db_get_value( - 'nombre', 'tagente_modulo', 'id_agente_modulo', $parent_module_id - ); - } else { - $table_simple->data[1][1] = html_print_select ( - $modules_can_be_parent, 'parent_module_id', $parent_module_id, '', - __('Not assigned'), '0', true - ); - } + // Cannot select the current module to be itself parent + $module_parent_filter = $id_agent_module ? ['tagente_modulo.id_agente_modulo' => "<>$id_agent_module"] : ''; + $table_simple->data[1][0] = __('Module parent'); + $modules_can_be_parent = agents_get_modules($id_agente, false, $module_parent_filter); + // If the user cannot have access to parent module, only print the name + if ($parent_module_id != 0 && !in_array($parent_module_id, array_keys($modules_can_be_parent))) { + $table_simple->data[1][1] = db_get_value( + 'nombre', + 'tagente_modulo', + 'id_agente_modulo', + $parent_module_id + ); + } else { + $table_simple->data[1][1] = html_print_select( + $modules_can_be_parent, + 'parent_module_id', + $parent_module_id, + '', + __('Not assigned'), + '0', + true + ); + } } -$table_simple->data[2][0] = __('Type').' ' . ui_print_help_icon ('module_type', true); -$table_simple->data[2][0] .= html_print_input_hidden ('id_module_type_hidden', $id_module_type, true); +$table_simple->data[2][0] = __('Type').' '.ui_print_help_icon('module_type', true); +$table_simple->data[2][0] .= html_print_input_hidden('id_module_type_hidden', $id_module_type, true); if (isset($id_agent_module)) { - if ($id_agent_module) { - $edit = false; - } - else { - $edit = true; - } -} -else { - //Run into a policy - $edit = true; + if ($id_agent_module) { + $edit = false; + } else { + $edit = true; + } +} else { + // Run into a policy + $edit = true; } if (!$edit) { - $sql = sprintf ('SELECT id_tipo, nombre + $sql = sprintf( + 'SELECT id_tipo, nombre FROM ttipo_modulo WHERE id_tipo = %s ORDER BY descripcion', - $id_module_type); + $id_module_type + ); - $type_names = db_get_all_rows_sql($sql); + $type_names = db_get_all_rows_sql($sql); - $type_names_hash = array(); - foreach ($type_names as $tn) { - $type_names_hash[$tn['id_tipo']] = $tn['nombre']; - } + $type_names_hash = []; + foreach ($type_names as $tn) { + $type_names_hash[$tn['id_tipo']] = $tn['nombre']; + } - $table_simple->data[2][1] = ''.modules_get_moduletype_description ($id_module_type).' ('.$type_names_hash[$id_module_type].')'; - $table_simple->data[2][1] .= html_print_input_hidden('type_names',base64_encode(io_json_mb_encode($type_names_hash)),true); -} -else { - if (isset($id_module_type)) { - $idModuleType = $id_module_type; - } - else { - $idModuleType = ''; - } + $table_simple->data[2][1] = ''.modules_get_moduletype_description($id_module_type).' ('.$type_names_hash[$id_module_type].')'; + $table_simple->data[2][1] .= html_print_input_hidden('type_names', base64_encode(io_json_mb_encode($type_names_hash)), true); +} else { + if (isset($id_module_type)) { + $idModuleType = $id_module_type; + } else { + $idModuleType = ''; + } - $sql = sprintf ('SELECT id_tipo, descripcion + // Removed web analysis and log4x from select + $sql = sprintf( + 'SELECT id_tipo, descripcion, nombre FROM ttipo_modulo - WHERE categoria IN (%s) + WHERE categoria IN (%s) AND id_tipo NOT IN (24, 25) ORDER BY descripcion', - implode (',', $categories)); + implode(',', $categories) + ); - $table_simple->data[2][1] = html_print_select_from_sql ($sql, 'id_module_type', - $idModuleType, '', '', '', true, false, false, $disabledBecauseInPolicy, false, false, 100); + $type_names = db_get_all_rows_sql($sql); - // Store the relation between id and name of the types on a hidden field - $sql = sprintf ('SELECT id_tipo, nombre - FROM ttipo_modulo - WHERE categoria IN (%s) - ORDER BY descripcion', - implode (',', $categories)); + $type_names_hash = []; + $type_description_hash = []; + if (isset($type_names) && is_array($type_names)) { + foreach ($type_names as $tn) { + $type_names_hash[$tn['id_tipo']] = $tn['nombre']; + $type_description_hash[$tn['id_tipo']] = $tn['descripcion']; + } + } - $type_names = db_get_all_rows_sql($sql); + $table_simple->data[2][1] = html_print_select( + $type_description_hash, + 'id_module_type', + $idModuleType, + $disabledBecauseInPolicy, + '', + 0, + true, + false, + true, + '', + false, + false, + false, + 100 + ); - $type_names_hash = array(); - foreach ($type_names as $tn) { - $type_names_hash[$tn['id_tipo']] = $tn['nombre']; - } - - $table_simple->data[2][1] .= html_print_input_hidden('type_names',base64_encode(io_json_mb_encode($type_names_hash)),true); + // Store the relation between id and name of the types on a hidden field + $table_simple->data[2][1] .= html_print_input_hidden('type_names', base64_encode(io_json_mb_encode($type_names_hash)), true); } -if($disabledBecauseInPolicy){ - $table_simple->data[2][3] .= html_print_input_hidden ('id_module_group', $id_module_group, true); +if ($disabledBecauseInPolicy) { + $table_simple->data[2][3] .= html_print_input_hidden('id_module_group', $id_module_group, true); } -$table_simple->data[3][0] = __('Dynamic Threshold Interval') .' ' . ui_print_help_icon ('dynamic_threshold', true); -$table_simple->data[3][1] = html_print_extended_select_for_time ('dynamic_interval', $dynamic_interval, '', 'None', '0', 10, true, 'width:150px',false, $classdisabledBecauseInPolicy, $disabledBecauseInPolicy); -$table_simple->data[3][1] .= '' . html_print_image('images/cog.png', true, array('title' => __('Advanced options Dynamic Threshold'))) . ''; -if($in_policy){ - $table_simple->cellclass[2][2] = 'hide_dinamic'; - $table_simple->cellclass[2][3] = 'hide_dinamic'; -} -else{ - $table_simple->cellclass[3][2] = 'hide_dinamic'; - $table_simple->cellclass[3][3] = 'hide_dinamic'; + +$table_simple->data[3][0] = __('Dynamic Threshold Interval').' '.ui_print_help_icon('dynamic_threshold', true); +$table_simple->data[3][1] = html_print_extended_select_for_time('dynamic_interval', $dynamic_interval, '', 'None', '0', 10, true, 'width:150px', false, $classdisabledBecauseInPolicy, $disabledBecauseInPolicy); +$table_simple->data[3][1] .= ''.html_print_image('images/cog.png', true, ['title' => __('Advanced options Dynamic Threshold')]).''; +if ($in_policy) { + $table_simple->cellclass[2][2] = 'hide_dinamic'; + $table_simple->cellclass[2][3] = 'hide_dinamic'; +} else { + $table_simple->cellclass[3][2] = 'hide_dinamic'; + $table_simple->cellclass[3][3] = 'hide_dinamic'; } $table_simple->data[3][2] = ''.__('Dynamic Threshold Min. ').''; -$table_simple->data[3][2] .= html_print_input_text ('dynamic_min', $dynamic_min, '', 10, 255, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); +$table_simple->data[3][2] .= html_print_input_text( + 'dynamic_min', + $dynamic_min, + '', + 10, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); $table_simple->data[3][2] .= '
    '.__('Dynamic Threshold Max. ').''; -$table_simple->data[3][2] .= html_print_input_text ('dynamic_max', $dynamic_max, '', 10, 255, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); +$table_simple->data[3][2] .= html_print_input_text( + 'dynamic_max', + $dynamic_max, + '', + 10, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); $table_simple->data[3][3] = ''.__('Dynamic Threshold Two Tailed: ').''; -$table_simple->data[3][3] .= html_print_checkbox ("dynamic_two_tailed", 1, $dynamic_two_tailed, true, $disabledBecauseInPolicy); +$table_simple->data[3][3] .= html_print_checkbox('dynamic_two_tailed', 1, $dynamic_two_tailed, true, $disabledBecauseInPolicy); -$table_simple->data[4][0] = __('Warning status').' ' . ui_print_help_icon ('warning_status', true); +$table_simple->data[4][0] = __('Warning status').' '.ui_print_help_icon('warning_status', true); if (!modules_is_string_type($id_module_type) || $edit) { - $table_simple->data[4][1] .= ''.__('Min. ').''; - $table_simple->data[4][1] .= html_print_input_text ('min_warning', $min_warning, '', 10, 255, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); - $table_simple->data[4][1] .= '
    '.__('Max.').''; - $table_simple->data[4][1] .= html_print_input_text ('max_warning', $max_warning, '', 10, 255, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy).'
    '; + $table_simple->data[4][1] .= ''.__('Min. ').''; + $table_simple->data[4][1] .= html_print_input_text( + 'min_warning', + $min_warning, + '', + 10, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ); + $table_simple->data[4][1] .= '
    '.__('Max.').''; + $table_simple->data[4][1] .= html_print_input_text( + 'max_warning', + $max_warning, + '', + 10, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ).'
    '; } + if (modules_is_string_type($id_module_type) || $edit) { - $table_simple->data[4][1] .= ''.__('Str.').''; - $table_simple->data[4][1] .= html_print_input_text ('str_warning', str_replace("\"","",$str_warning), - '', 10, 255, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy).''; -} - $table_simple->data[4][1] .= '
    '.__('Inverse interval').''; - $table_simple->data[4][1] .= html_print_checkbox ("warning_inverse", 1, $warning_inverse, true, $disabledBecauseInPolicy); - -if (!modules_is_string_type($id_module_type) || $edit) { - $table_simple->data[4][2] = ' '; + $table_simple->data[4][1] .= ''.__('Str.').''; + $table_simple->data[4][1] .= html_print_input_text( + 'str_warning', + str_replace('"', '', $str_warning), + '', + 10, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ).''; } -$table_simple->data[5][0] = __('Critical status').' ' . ui_print_help_icon ('critical_status', true); + $table_simple->data[4][1] .= '
    '.__('Inverse interval').''; + $table_simple->data[4][1] .= html_print_checkbox('warning_inverse', 1, $warning_inverse, true, $disabledBecauseInPolicy); + if (!modules_is_string_type($id_module_type) || $edit) { - $table_simple->data[5][1] .= ''.__('Min. ').''; - $table_simple->data[5][1] .= html_print_input_text ('min_critical', $min_critical, '', 10, 255, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); - $table_simple->data[5][1] .= '
    '.__('Max.').''; - $table_simple->data[5][1] .= html_print_input_text ('max_critical', $max_critical, '', 10, 255, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy).'
    '; + $table_simple->data[4][2] = ' '; } + +$table_simple->data[5][0] = __('Critical status').' '.ui_print_help_icon('critical_status', true); +if (!modules_is_string_type($id_module_type) || $edit) { + $table_simple->data[5][1] .= ''.__('Min. ').''; + $table_simple->data[5][1] .= html_print_input_text( + 'min_critical', + $min_critical, + '', + 10, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ); + $table_simple->data[5][1] .= '
    '.__('Max.').''; + $table_simple->data[5][1] .= html_print_input_text( + 'max_critical', + $max_critical, + '', + 10, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ).'
    '; +} + if (modules_is_string_type($id_module_type) || $edit) { - $table_simple->data[5][1] .= ''.__('Str.').''; - $table_simple->data[5][1] .= html_print_input_text ('str_critical', str_replace("\"","",$str_critical), - '', 10, 255, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy).''; + $table_simple->data[5][1] .= ''.__('Str.').''; + $table_simple->data[5][1] .= html_print_input_text( + 'str_critical', + str_replace('"', '', $str_critical), + '', + 10, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ).''; } $table_simple->data[5][1] .= '
    '.__('Inverse interval').''; -$table_simple->data[5][1] .= html_print_checkbox ("critical_inverse", 1, $critical_inverse, true, $disabledBecauseInPolicy); +$table_simple->data[5][1] .= html_print_checkbox('critical_inverse', 1, $critical_inverse, true, $disabledBecauseInPolicy); -//FF stands for Flip-flop -$table_simple->data[6][0] = __('FF threshold').' ' . ui_print_help_icon ('ff_threshold', true); +// FF stands for Flip-flop +$table_simple->data[6][0] = __('FF threshold').' '.ui_print_help_icon('ff_threshold', true); -$table_simple->data[6][1] = html_print_radio_button ('each_ff', 0, '', $each_ff, true, $disabledBecauseInPolicy) . ' ' . __('All state changing') . ' : '; -$table_simple->data[6][1] .= html_print_input_text ('ff_event', $ff_event, '', 5, 15, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy) . '
    '; -$table_simple->data[6][1] .= html_print_radio_button ('each_ff', 1, '', $each_ff, true, $disabledBecauseInPolicy) . ' ' . __('Each state changing') . ' : '; +$table_simple->data[6][1] = html_print_radio_button('each_ff', 0, '', $each_ff, true, $disabledBecauseInPolicy).' '.__('All state changing').' : '; +$table_simple->data[6][1] .= html_print_input_text( + 'ff_event', + $ff_event, + '', + 5, + 15, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +).'
    '; +$table_simple->data[6][1] .= html_print_radio_button('each_ff', 1, '', $each_ff, true, $disabledBecauseInPolicy).' '.__('Each state changing').' : '; $table_simple->data[6][1] .= __('To normal'); -$table_simple->data[6][1] .= html_print_input_text ('ff_event_normal', $ff_event_normal, '', 5, 15, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy) . ' '; +$table_simple->data[6][1] .= html_print_input_text( + 'ff_event_normal', + $ff_event_normal, + '', + 5, + 15, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +).' '; $table_simple->data[6][1] .= __('To warning'); -$table_simple->data[6][1] .= html_print_input_text ('ff_event_warning', $ff_event_warning, '', 5, 15, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy) . ' '; +$table_simple->data[6][1] .= html_print_input_text( + 'ff_event_warning', + $ff_event_warning, + '', + 5, + 15, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +).' '; $table_simple->data[6][1] .= __('To critical'); -$table_simple->data[6][1] .= html_print_input_text ('ff_event_critical', $ff_event_critical, '', 5, 15, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); +$table_simple->data[6][1] .= html_print_input_text( + 'ff_event_critical', + $ff_event_critical, + '', + 5, + 15, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); $table_simple->data[7][0] = __('Historical data'); -if($disabledBecauseInPolicy) { - // If is disabled, we send a hidden in his place and print a false checkbox because HTML dont send disabled fields and could be disabled by error - $table_simple->data[7][1] = html_print_checkbox ("history_data_fake", 1, $history_data, true, $disabledBecauseInPolicy); - $table_simple->data[7][1] .= ''; -} -else { - $table_simple->data[7][1] = html_print_checkbox ("history_data", 1, $history_data, true, $disabledBecauseInPolicy); +if ($disabledBecauseInPolicy) { + // If is disabled, we send a hidden in his place and print a false checkbox because HTML dont send disabled fields and could be disabled by error + $table_simple->data[7][1] = html_print_checkbox('history_data_fake', 1, $history_data, true, $disabledBecauseInPolicy); + $table_simple->data[7][1] .= ''; +} else { + $table_simple->data[7][1] = html_print_checkbox('history_data', 1, $history_data, true, $disabledBecauseInPolicy); } -//Advanced form part +// Advanced form part $table_advanced = new stdClass(); $table_advanced->id = 'advanced'; $table_advanced->width = '100%'; $table_advanced->class = 'databox filters'; -$table_advanced->data = array (); -$table_advanced->style = array (); -$table_advanced->style[0] = - $table_advanced->style[3] = - $table_advanced->style[5] = 'font-weight: bold;'; -$table_advanced->colspan = array (); +$table_advanced->data = []; +$table_advanced->style = []; +$table_advanced->style[0] = $table_advanced->style[3] = $table_advanced->style[5] = 'font-weight: bold;'; +$table_advanced->colspan = []; $table_advanced->data[0][0] = __('Description'); $table_advanced->colspan[0][1] = 6; -$table_advanced->data[0][1] = html_print_textarea ('description', 2, 65, - $description, $disabledTextBecauseInPolicy, true, $largeClassDisabledBecauseInPolicy); +$table_advanced->data[0][1] = html_print_textarea( + 'description', + 2, + 65, + $description, + $disabledTextBecauseInPolicy, + true, + $largeClassDisabledBecauseInPolicy +); $table_advanced->data[1][0] = __('Custom ID'); $table_advanced->colspan[1][1] = 2; -$table_advanced->data[1][1] = html_print_input_text ('custom_id', $custom_id, '', 20, 65, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); +$table_advanced->data[1][1] = html_print_input_text( + 'custom_id', + $custom_id, + '', + 20, + 65, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); $table_advanced->data[1][3] = __('Unit'); // $table_advanced->data[1][4] = html_print_input_text ('unit', $unit, '', 20, 65, true, -// $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); +// $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); // $table_advanced->colspan[1][4] = 3; -$table_advanced->data[1][4] = - html_print_extended_select_for_unit('unit', - $unit, '', '', '0', false, true, false, false); +$table_advanced->data[1][4] = html_print_extended_select_for_unit( + 'unit', + $unit, + '', + '', + '0', + false, + true, + false, + false +); $table_advanced->colspan[1][4] = 3; $module_id_policy_module = 0; if (isset($module['id_policy_module'])) { - $module_id_policy_module = $module['id_policy_module']; + $module_id_policy_module = $module['id_policy_module']; } -// In the data modules, the interval is not in seconds. It is a factor +// In the data modules, the interval is not in seconds. It is a factor // to be multiplied for the agent interval if ($moduletype == MODULE_DATA) { - $table_advanced->data[2][0] = __('Interval'); - $table_advanced->colspan[2][1] = 2; - $interval_factor = 1; - if (isset($id_agente)) { - $agent_interval = agents_get_interval ($id_agente); - $interval_factor = $interval / $agent_interval; - $table_advanced->data[2][1] = human_time_description_raw($interval) . ' (' . sprintf(__('Agent interval x %s'), $interval_factor) . ') ' . ui_print_help_icon ('module_interval_factor', true); - } - else { - $table_advanced->data[2][1] = sprintf(__('Agent interval x %s'), $interval_factor) . ui_print_help_icon ('module_interval_factor', true); - } - - if ($__code_from == 'policies') { - // If is the policy form, module_interval will store the factor (not the seconds). - // So server will transform it to interval in seconds - $table_advanced->data[2][1] = sprintf(__('Default') . ': 1' , $interval_factor) . ui_print_help_icon ('module_interval_factor', true); - $table_advanced->data[2][1] .= html_print_input_hidden('module_interval', $interval_factor, true); - } - else if ($module_id_policy_module != 0) { - $table_advanced->data[2][1] .= ui_print_help_tip(__('The policy modules of data type will only update their intervals when policy is applied.'), true); - } - - // If it is a non policy form, the module_interval will not provided and will - // be taken the agent interval (this code is at configurar_agente.php) -} -else { - $table_advanced->data[2][0] = __('Interval') . ui_print_help_icon ('module_interval', true); - $table_advanced->colspan[2][1] = 2; - $table_advanced->data[2][1] = html_print_extended_select_for_time ('module_interval' , $interval, '', '', '0', false, true, false, false, $classdisabledBecauseInPolicy, $disabledBecauseInPolicy); + $table_advanced->data[2][0] = __('Interval'); + $table_advanced->colspan[2][1] = 2; + $interval_factor = 1; + if (isset($id_agente)) { + $agent_interval = agents_get_interval($id_agente); + $interval_factor = ($interval / $agent_interval); + $table_advanced->data[2][1] = human_time_description_raw($interval).' ('.sprintf(__('Agent interval x %s'), $interval_factor).') '.ui_print_help_icon('module_interval_factor', true); + } else { + $table_advanced->data[2][1] = sprintf(__('Agent interval x %s'), $interval_factor).ui_print_help_icon('module_interval_factor', true); + } + + if ($__code_from == 'policies') { + // If is the policy form, module_interval will store the factor (not the seconds). + // So server will transform it to interval in seconds + $table_advanced->data[2][1] = sprintf(__('Default').': 1', $interval_factor).ui_print_help_icon('module_interval_factor', true); + $table_advanced->data[2][1] .= html_print_input_hidden('module_interval', $interval_factor, true); + } else if ($module_id_policy_module != 0) { + $table_advanced->data[2][1] .= ui_print_help_tip(__('The policy modules of data type will only update their intervals when policy is applied.'), true); + } + + // If it is a non policy form, the module_interval will not provided and will + // be taken the agent interval (this code is at configurar_agente.php) +} else { + $table_advanced->data[2][0] = __('Interval').ui_print_help_icon('module_interval', true); + $table_advanced->colspan[2][1] = 2; + $table_advanced->data[2][1] = html_print_extended_select_for_time('module_interval', $interval, '', '', '0', false, true, false, false, $classdisabledBecauseInPolicy, $disabledBecauseInPolicy); } -$table_advanced->data[2][1] .= html_print_input_hidden ('moduletype', $moduletype, true); +$table_advanced->data[2][1] .= html_print_input_hidden('moduletype', $moduletype, true); -$table_advanced->data[2][3] = __('Post process').' ' . ui_print_help_icon ('postprocess', true); -$table_advanced->data[2][4] = - html_print_extended_select_for_post_process('post_process', - $post_process, '', '', '0', false, true, false, true, - $disabledBecauseInPolicy); +$table_advanced->data[2][3] = __('Post process').' '.ui_print_help_icon('postprocess', true); +$table_advanced->data[2][4] = html_print_extended_select_for_post_process( + 'post_process', + $post_process, + '', + '', + '0', + false, + true, + false, + false, + $disabledBecauseInPolicy +); $table_advanced->colspan[2][4] = 3; $table_advanced->data[3][0] = __('Min. Value'); $table_advanced->colspan[3][1] = 2; -$table_advanced->data[3][1] = html_print_input_text ('min', $min, '', 5, 15, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy). ' ' . ui_print_help_tip (__('Any value below this number is discarted.'), true); +$table_advanced->data[3][1] = html_print_input_text('min', $min, '', 5, 15, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy).' '.ui_print_help_tip(__('Any value below this number is discarted.'), true); $table_advanced->data[3][3] = __('Max. Value'); -$table_advanced->data[3][4] = html_print_input_text ('max', $max, '', 5, 15, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy). ' ' . ui_print_help_tip (__('Any value over this number is discarted.'), true); +$table_advanced->data[3][4] = html_print_input_text('max', $max, '', 5, 15, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy).' '.ui_print_help_tip(__('Any value over this number is discarted.'), true); $table_advanced->colspan[3][4] = 3; $table_advanced->data[4][0] = __('Export target'); @@ -457,136 +682,218 @@ $none_text = __('None'); $disabled_export = false; if ($__code_from == 'policies') { - $none_text = __('Not needed'); - $disabled_export = true; -} -$table_advanced->data[4][1] = html_print_select_from_sql ('SELECT id, name FROM tserver_export ORDER BY name', - 'id_export', $id_export, '', $none_text, '0', true, false, false, $disabled_export).ui_print_help_tip (__('In case you use an Export server you can link this module and export data to one these.'), true); + $none_text = __('Not needed'); + $disabled_export = true; +} + +$table_advanced->data[4][1] = html_print_select_from_sql( + 'SELECT id, name FROM tserver_export ORDER BY name', + 'id_export', + $id_export, + '', + $none_text, + '0', + true, + false, + false, + $disabled_export +).ui_print_help_tip(__('In case you use an Export server you can link this module and export data to one these.'), true); $table_advanced->colspan[4][1] = 2; // Code comes from module_editor if ($__code_from == 'modules') { - $throw_unknown_events_check = - modules_is_disable_type_event($id_agent_module, EVENTS_GOING_UNKNOWN); -} -else { - global $__id_pol_mod; - - $throw_unknown_events_check = - policy_module_is_disable_type_event($__id_pol_mod, EVENTS_GOING_UNKNOWN); + $throw_unknown_events_check = modules_is_disable_type_event($id_agent_module, EVENTS_GOING_UNKNOWN); +} else { + global $__id_pol_mod; + + $throw_unknown_events_check = policy_module_is_disable_type_event($__id_pol_mod, EVENTS_GOING_UNKNOWN); } + $table_advanced->data[4][3] = __('Discard unknown events'); -$table_advanced->data[4][4] = html_print_checkbox('throw_unknown_events', - 1, $throw_unknown_events_check, true, $disabledBecauseInPolicy); +$table_advanced->data[4][4] = html_print_checkbox( + 'throw_unknown_events', + 1, + $throw_unknown_events_check, + true, + $disabledBecauseInPolicy +); $table_advanced->colspan[4][4] = 3; -$table_advanced->data[5][0] = __('FF interval') . ' ' . ui_print_help_icon ('ff_interval', true); -$table_advanced->data[5][1] = html_print_input_text ('module_ff_interval', $ff_interval, - '', 5, 10, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy) . - ui_print_help_tip (__('Module execution flip flop time interval (in secs).'), true); +$table_advanced->data[5][0] = __('FF interval').' '.ui_print_help_icon('ff_interval', true); +$table_advanced->data[5][1] = html_print_input_text( + 'module_ff_interval', + $ff_interval, + '', + 5, + 10, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +).ui_print_help_tip(__('Module execution flip flop time interval (in secs).'), true); $table_advanced->colspan[5][1] = 2; -$table_advanced->data[5][3] = __('FF timeout') . ' ' . ui_print_help_icon ('ff_timeout', true); +$table_advanced->data[5][3] = __('FF timeout').' '.ui_print_help_icon('ff_timeout', true); $module_type_name = modules_get_type_name($id_module_type); $table_advanced->data[5][4] = ''; -if (preg_match ('/async/', $module_type_name) || $edit) { - $table_advanced->data[5][4] .= '' . html_print_input_text ('ff_timeout', $ff_timeout, - '', 5, 10, true, $disabledBecauseInPolicy).ui_print_help_tip (__('Timeout in secs from start of flip flop counting. If this value is exceeded, FF counter is reset. Set to 0 for no timeout.'), true) . ''; +if (preg_match('/async/', $module_type_name) || $edit) { + $table_advanced->data[5][4] .= ''.html_print_input_text( + 'ff_timeout', + $ff_timeout, + '', + 5, + 10, + true, + $disabledBecauseInPolicy + ).ui_print_help_tip(__('Timeout in secs from start of flip flop counting. If this value is exceeded, FF counter is reset. Set to 0 for no timeout.'), true).''; } -if (!preg_match ('/async/', $module_type_name) || $edit) { - $table_advanced->data[5][4] .= '' . __('Disabled') . ui_print_help_tip (__('This value can be set only in the async modules.'), true) . ''; + +if (!preg_match('/async/', $module_type_name) || $edit) { + $table_advanced->data[5][4] .= ''.__('Disabled').ui_print_help_tip(__('This value can be set only in the async modules.'), true).''; } + $table_advanced->colspan[5][4] = 3; -/* Tags */ +/* + Tags */ // This var comes from module_manager_editor.php or policy_modules.php global $__code_from; -$table_advanced->data[6][0] = __('Tags available'); +$table_advanced->data[6][0] = __('Tags available'); // Code comes from module_editor if ($__code_from == 'modules') { - $__table_modules = 'ttag_module'; - $__id_where = 'b.id_agente_modulo'; - $__id = (int)$id_agent_module; - - $__sql = " AND b.id_policy_module = 0"; - $__sql_policy = " AND b.id_policy_module != 0"; - -} -else { - // Code comes from policy module editor - - global $__id_pol_mod; - $__table_modules= 'ttag_policy_module'; - $__id_where = 'b.id_policy_module'; - $__id = $__id_pol_mod; - - $__sql = ""; - + $__table_modules = 'ttag_module'; + $__id_where = 'b.id_agente_modulo'; + $__id = (int) $id_agent_module; + + $__sql = ' AND b.id_policy_module = 0'; + $__sql_policy = ' AND b.id_policy_module != 0'; +} else { + // Code comes from policy module editor + global $__id_pol_mod; + $__table_modules = 'ttag_policy_module'; + $__id_where = 'b.id_policy_module'; + $__id = $__id_pol_mod; + + $__sql = ''; } -if (!tags_has_user_acl_tags($config["id_user"])) { - $table_advanced->data[6][1] = html_print_select_from_sql ( - "SELECT id_tag, name +if (!tags_has_user_acl_tags($config['id_user'])) { + $table_advanced->data[6][1] = html_print_select_from_sql( + "SELECT id_tag, name FROM ttag WHERE id_tag NOT IN ( SELECT a.id_tag FROM ttag a, $__table_modules b WHERE a.id_tag = b.id_tag AND $__id_where = $__id ) - ORDER BY name", 'id_tag_available[]', '', '','','', - true, true, false, $disabledBecauseInPolicy, 'width: 200px', '5'); -} -else { - $user_tags = tags_get_user_tags($config["id_user"], "AW"); - if (!empty($user_tags)) { - $id_user_tags = array_keys($user_tags); - - $table_advanced->data[6][1] = html_print_select_from_sql ( - "SELECT id_tag, name + ORDER BY name", + 'id_tag_available[]', + '', + '', + '', + '', + true, + true, + false, + $disabledBecauseInPolicy, + 'width: 200px', + '5' + ); +} else { + $user_tags = tags_get_user_tags($config['id_user'], 'AW'); + if (!empty($user_tags)) { + $id_user_tags = array_keys($user_tags); + + $table_advanced->data[6][1] = html_print_select_from_sql( + 'SELECT id_tag, name FROM ttag - WHERE id_tag IN (" . implode(',', $id_user_tags) . ") AND + WHERE id_tag IN ('.implode(',', $id_user_tags).") AND id_tag NOT IN ( SELECT a.id_tag FROM ttag a, $__table_modules b WHERE a.id_tag = b.id_tag AND $__id_where = $__id ) - ORDER BY name", 'id_tag_available[]', '', '','','', - true, true, false, $disabledBecauseInPolicy, 'width: 200px', '5'); - } - else { - $table_advanced->data[6][1] = html_print_select_from_sql ( - "SELECT id_tag, name + ORDER BY name", + 'id_tag_available[]', + '', + '', + '', + '', + true, + true, + false, + $disabledBecauseInPolicy, + 'width: 200px', + '5' + ); + } else { + $table_advanced->data[6][1] = html_print_select_from_sql( + "SELECT id_tag, name FROM ttag WHERE id_tag NOT IN ( SELECT a.id_tag FROM ttag a, $__table_modules b WHERE a.id_tag = b.id_tag AND $__id_where = $__id ) - ORDER BY name", 'id_tag_available[]', '', '','','', - true, true, false, $disabledBecauseInPolicy, 'width: 200px', '5'); - } + ORDER BY name", + 'id_tag_available[]', + '', + '', + '', + '', + true, + true, + false, + $disabledBecauseInPolicy, + 'width: 200px', + '5' + ); + } } -$table_advanced->data[6][2] = html_print_image('images/darrowright.png', true, array('id' => 'right', 'title' => __('Add tags to module'))); //html_print_input_image ('add', 'images/darrowright.png', 1, '', true, array ('title' => __('Add tags to module'))); -$table_advanced->data[6][2] .= '



    ' . html_print_image('images/darrowleft.png', true, array('id' => 'left', 'title' => __('Delete tags to module'))); //html_print_input_image ('add', 'images/darrowleft.png', 1, '', true, array ('title' => __('Delete tags to module'))); -$table_advanced->data[6][3] = '' . __('Tags selected') . ''; -$table_advanced->data[6][4] = html_print_select_from_sql ( - "SELECT a.id_tag, name +$table_advanced->data[6][2] = html_print_image('images/darrowright.png', true, ['id' => 'right', 'title' => __('Add tags to module')]); +// html_print_input_image ('add', 'images/darrowright.png', 1, '', true, array ('title' => __('Add tags to module'))); +$table_advanced->data[6][2] .= '



    '.html_print_image('images/darrowleft.png', true, ['id' => 'left', 'title' => __('Delete tags to module')]); +// html_print_input_image ('add', 'images/darrowleft.png', 1, '', true, array ('title' => __('Delete tags to module'))); +$table_advanced->data[6][3] = ''.__('Tags selected').''; +$table_advanced->data[6][4] = html_print_select_from_sql( + "SELECT a.id_tag, name FROM ttag a, $__table_modules b WHERE a.id_tag = b.id_tag AND $__id_where = $__id $__sql ORDER BY name", - 'id_tag_selected[]', '', '','','', true, true, false, - $disabledBecauseInPolicy, 'width: 200px', '5'); + 'id_tag_selected[]', + '', + '', + '', + '', + true, + true, + false, + $disabledBecauseInPolicy, + 'width: 200px', + '5' +); if ($__code_from == 'modules') { - $table_advanced->data[6][5] = '' . __('Tags from policy') . ''; - $table_advanced->data[6][6] = html_print_select_from_sql ( - "SELECT a.id_tag, name + $table_advanced->data[6][5] = ''.__('Tags from policy').''; + $table_advanced->data[6][6] = html_print_select_from_sql( + "SELECT a.id_tag, name FROM ttag a, $__table_modules b WHERE a.id_tag = b.id_tag AND $__id_where = $__id $__sql_policy ORDER BY name", - 'id_tag_policy[]', '', '','','', true, true, false, - $disabledBecauseInPolicy, 'width: 200px', '5'); + 'id_tag_policy[]', + '', + '', + '', + '', + true, + true, + false, + $disabledBecauseInPolicy, + 'width: 200px', + '5' + ); } $table_advanced->data[7][0] = __('Quiet'); @@ -594,130 +901,143 @@ $table_advanced->data[7][0] .= ui_print_help_tip(__('The module still stores dat $table_advanced->data[7][1] = html_print_checkbox('quiet_module', 1, $quiet_module, true, $disabledBecauseInPolicy); $cps_array[-1] = __('Disabled'); -if($cps_module > 0){ - $cps_array[$cps_module] = __('Enabled'); -} -else{ - $cps_inc = 0; - if($id_agent_module){ - $cps_inc = enterprise_hook('service_modules_cps', array($id_agent_module)); - if ($cps_inc === ENTERPRISE_NOT_HOOK) $cps_inc = 0; - } - $cps_array[$cps_inc] = __('Enabled'); +if ($cps_module > 0) { + $cps_array[$cps_module] = __('Enabled'); +} else { + $cps_inc = 0; + if ($id_agent_module) { + $cps_inc = enterprise_hook('service_modules_cps', [$id_agent_module]); + if ($cps_inc === ENTERPRISE_NOT_HOOK) { + $cps_inc = 0; + } + } + + $cps_array[$cps_inc] = __('Enabled'); } + $table_advanced->data[7][2] = __('Cascade Protection Services'); $table_advanced->data[7][2] .= ui_print_help_tip(__('Disable the alerts and events of the elements that belong to this service'), true); $table_advanced->colspan[7][3] = 5; -$table_advanced->data[7][3] = html_print_select($cps_array, 'cps_module', $cps_module, '', '', 0, true, false, true, "", $disabledBecauseInPolicy); +$table_advanced->data[7][3] = html_print_select($cps_array, 'cps_module', $cps_module, '', '', 0, true, false, true, '', $disabledBecauseInPolicy); -$table_advanced->data[8][0] = __('Critical instructions') . - ui_print_help_tip(__("Instructions when the status is critical"), true); -$table_advanced->data[8][1] = html_print_textarea ('critical_instructions', 2, 65, $critical_instructions, $disabledTextBecauseInPolicy, true, $largeClassDisabledBecauseInPolicy); +$table_advanced->data[8][0] = __('Critical instructions').ui_print_help_tip(__('Instructions when the status is critical'), true); +$table_advanced->data[8][1] = html_print_textarea('critical_instructions', 2, 65, $critical_instructions, $disabledTextBecauseInPolicy, true, $largeClassDisabledBecauseInPolicy); $table_advanced->colspan[8][1] = 6; -$table_advanced->data[9][0] = __('Warning instructions') . - ui_print_help_tip(__("Instructions when the status is warning"), true); -$table_advanced->data[9][1] = html_print_textarea ('warning_instructions', 2, 65, $warning_instructions, $disabledTextBecauseInPolicy, true, $largeClassDisabledBecauseInPolicy); +$table_advanced->data[9][0] = __('Warning instructions').ui_print_help_tip(__('Instructions when the status is warning'), true); +$table_advanced->data[9][1] = html_print_textarea('warning_instructions', 2, 65, $warning_instructions, $disabledTextBecauseInPolicy, true, $largeClassDisabledBecauseInPolicy); $table_advanced->colspan[9][1] = 6; -$table_advanced->data[10][0] = __('Unknown instructions'). ui_print_help_tip(__("Instructions when the status is unknown"), true); -$table_advanced->data[10][1] = html_print_textarea ('unknown_instructions', 2, 65, $unknown_instructions, $disabledTextBecauseInPolicy, true, $largeClassDisabledBecauseInPolicy); +$table_advanced->data[10][0] = __('Unknown instructions').ui_print_help_tip(__('Instructions when the status is unknown'), true); +$table_advanced->data[10][1] = html_print_textarea('unknown_instructions', 2, 65, $unknown_instructions, $disabledTextBecauseInPolicy, true, $largeClassDisabledBecauseInPolicy); $table_advanced->colspan[10][1] = 6; if (isset($id_agente) && $moduletype == MODULE_DATA) { - $has_remote_conf = enterprise_hook('config_agents_has_remote_configuration',array($agent["id_agente"])); - if ($has_remote_conf) { - $table_advanced->data[11][0] = __('Cron from') . ui_print_help_icon ('cron', true); - $table_advanced->data[11][1] = html_print_extended_select_for_cron ($hour_from, $minute_from, $mday_from, $month_from, $wday_from, true, $disabledBecauseInPolicy); - $table_advanced->colspan[11][1] = 6; + $has_remote_conf = enterprise_hook('config_agents_has_remote_configuration', [$agent['id_agente']]); + if ($has_remote_conf) { + $table_advanced->data[11][0] = __('Cron from').ui_print_help_icon('cron', true); + $table_advanced->data[11][1] = html_print_extended_select_for_cron($hour_from, $minute_from, $mday_from, $month_from, $wday_from, true, $disabledBecauseInPolicy); + $table_advanced->colspan[11][1] = 6; - $table_advanced->data[12][0] = __('Cron to'); - $table_advanced->data[12][1] = html_print_extended_select_for_cron ($hour_to, $minute_to, $mday_to, $month_to, $wday_to, true, $disabledBecauseInPolicy, true); - $table_advanced->colspan[12][1] = 6; - } - else { - $table_advanced->data[11][0] = __('Cron from') . ui_print_help_icon ('cron', true); - $table_advanced->data[11][1] = html_print_extended_select_for_cron ($hour_from, $minute_from, $mday_from, $month_from, $wday_from, true, true); - $table_advanced->colspan[11][1] = 6; + $table_advanced->data[12][0] = __('Cron to'); + $table_advanced->data[12][1] = html_print_extended_select_for_cron($hour_to, $minute_to, $mday_to, $month_to, $wday_to, true, $disabledBecauseInPolicy, true); + $table_advanced->colspan[12][1] = 6; + } else { + $table_advanced->data[11][0] = __('Cron from').ui_print_help_icon('cron', true); + $table_advanced->data[11][1] = html_print_extended_select_for_cron($hour_from, $minute_from, $mday_from, $month_from, $wday_from, true, true); + $table_advanced->colspan[11][1] = 6; - $table_advanced->data[12][0] = __('Cron to'); - $table_advanced->data[12][1] = html_print_extended_select_for_cron ($hour_to, $minute_to, $mday_to, $month_to, $wday_to, true, true, true); - $table_advanced->colspan[12][1] = 6; - } -} -else { - $table_advanced->data[11][0] = __('Cron from') . ui_print_help_icon ('cron', true); - $table_advanced->data[11][1] = html_print_extended_select_for_cron ($hour_from, $minute_from, $mday_from, $month_from, $wday_from, true, $disabledBecauseInPolicy); - $table_advanced->colspan[11][1] = 6; + $table_advanced->data[12][0] = __('Cron to'); + $table_advanced->data[12][1] = html_print_extended_select_for_cron($hour_to, $minute_to, $mday_to, $month_to, $wday_to, true, true, true); + $table_advanced->colspan[12][1] = 6; + } +} else { + $table_advanced->data[11][0] = __('Cron from').ui_print_help_icon('cron', true); + $table_advanced->data[11][1] = html_print_extended_select_for_cron($hour_from, $minute_from, $mday_from, $month_from, $wday_from, true, $disabledBecauseInPolicy); + $table_advanced->colspan[11][1] = 6; - $table_advanced->data[12][0] = __('Cron to'); - $table_advanced->data[12][1] = html_print_extended_select_for_cron ($hour_to, $minute_to, $mday_to, $month_to, $wday_to, true, $disabledBecauseInPolicy, true); - $table_advanced->colspan[12][1] = 6; + $table_advanced->data[12][0] = __('Cron to'); + $table_advanced->data[12][1] = html_print_extended_select_for_cron($hour_to, $minute_to, $mday_to, $month_to, $wday_to, true, $disabledBecauseInPolicy, true); + $table_advanced->colspan[12][1] = 6; } $table_advanced->data[13][0] = __('Timeout'); -$table_advanced->data[13][1] = html_print_input_text ('max_timeout', $max_timeout, '', 5, 10, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy). ' ' . ui_print_help_tip (__('Seconds that agent will wait for the execution of the module.'), true); +$table_advanced->data[13][1] = html_print_input_text('max_timeout', $max_timeout, '', 5, 10, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy).' '.ui_print_help_tip(__('Seconds that agent will wait for the execution of the module.'), true); $table_advanced->data[13][2] = ''; $table_advanced->data[13][3] = __('Retries'); -$table_advanced->data[13][4] = html_print_input_text ('max_retries', $max_retries, '', 5, 10, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy). ' ' . ui_print_help_tip (__('Number of retries that the module will attempt to run.'), true); +$table_advanced->data[13][4] = html_print_input_text('max_retries', $max_retries, '', 5, 10, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy).' '.ui_print_help_tip(__('Number of retries that the module will attempt to run.'), true); $table_advanced->colspan[13][4] = 3; -if (check_acl ($config['id_user'], 0, "PM")) { - $table_advanced->data[14][0] = __('Category'); - $table_advanced->data[14][1] = html_print_select( - categories_get_all_categories('forselect'), 'id_category', $id_category, '', __('None'), 0, true, false, true, "", $disabledBecauseInPolicy); - $table_advanced->colspan[14][1] = 6; -} -else { - // Store in a hidden field if is not visible to avoid delete the value - $table_advanced->data[13][4] .= html_print_input_hidden ('id_category', $id_category, true); +if (check_acl($config['id_user'], 0, 'PM')) { + $table_advanced->data[14][0] = __('Category'); + $table_advanced->data[14][1] = html_print_select( + categories_get_all_categories('forselect'), + 'id_category', + $id_category, + '', + __('None'), + 0, + true, + false, + true, + '', + $disabledBecauseInPolicy + ); + $table_advanced->colspan[14][1] = 6; +} else { + // Store in a hidden field if is not visible to avoid delete the value + $table_advanced->data[13][4] .= html_print_input_hidden('id_category', $id_category, true); } -/* Advanced form part */ +// Advanced form part $table_macros = new stdClass(); $table_macros->id = 'module_macros'; $table_macros->width = '100%'; $table_macros->class = 'databox filters'; -$table_macros->data = array (); -$table_macros->style = array (); +$table_macros->data = []; +$table_macros->style = []; $table_macros->style[0] = 'font-weight: bold;'; $table_macros->style[2] = 'font-weight: bold;'; $table_macros->style[5] = 'width: 10px'; -$table_macros->colspan = array (); +$table_macros->colspan = []; $macro_count = 0; if (isset($module_macros)) { - if (is_array($module_macros)) { - foreach ($module_macros as $macro_name => $macro_value) { - $table_macros->data[$macro_count][0] = __('Name'); - $table_macros->data[$macro_count][1] = html_print_input_text ('module_macro_names[]', $macro_name, '', 50, 60, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); - $table_macros->data[$macro_count][2] = __('Value'); - $table_macros->data[$macro_count][3] = html_print_input_text ('module_macro_values[]', $macro_value, '', 50, 60, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); - if(!$disabledBecauseInPolicy){ - $table_macros->data[$macro_count][4] = '' . html_print_image('images/cross.png', true) . ''; - } - $macro_count++; - } - } -} -if(!$disabledBecauseInPolicy){ - $table_macros->data[$macro_count][0] = ''.__('Custom macros').' '.html_print_image('images/add.png',true).''; + if (is_array($module_macros)) { + foreach ($module_macros as $macro_name => $macro_value) { + $table_macros->data[$macro_count][0] = __('Name'); + $table_macros->data[$macro_count][1] = html_print_input_text('module_macro_names[]', $macro_name, '', 50, 60, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); + $table_macros->data[$macro_count][2] = __('Value'); + $table_macros->data[$macro_count][3] = html_print_input_text('module_macro_values[]', $macro_value, '', 50, 60, true, $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); + if (!$disabledBecauseInPolicy) { + $table_macros->data[$macro_count][4] = ''.html_print_image('images/cross.png', true).''; + } - $table_macros->colspan[$macro_count][0] = 5; + $macro_count++; + } + } } + +if (!$disabledBecauseInPolicy) { + $table_macros->data[$macro_count][0] = ''.__('Custom macros').' '.html_print_image('images/add.png', true).''; + + $table_macros->colspan[$macro_count][0] = 5; +} + $macro_count++; -html_print_input_hidden ('module_macro_count', $macro_count); +html_print_input_hidden('module_macro_count', $macro_count); -/* Advanced form part */ +/* + Advanced form part */ // Add relationships $table_new_relations = new stdClass(); $table_new_relations->id = 'module_new_relations'; $table_new_relations->width = '100%'; $table_new_relations->class = 'databox filters'; -$table_new_relations->data = array (); -$table_new_relations->style = array (); +$table_new_relations->data = []; +$table_new_relations->style = []; $table_new_relations->style[0] = 'width: 10%; font-weight: bold;'; $table_new_relations->style[1] = 'width: 25%; text-align: center;'; $table_new_relations->style[2] = 'width: 10%; font-weight: bold;'; @@ -725,7 +1045,7 @@ $table_new_relations->style[3] = 'width: 25%; text-align: center;'; $table_new_relations->style[4] = 'width: 30%; text-align: center;'; $table_new_relations->data[0][0] = __('Agent'); -$params = array(); +$params = []; $params['return'] = true; $params['show_helptip'] = true; $params['input_name'] = 'autocomplete_agent_name'; @@ -736,7 +1056,7 @@ $params['javascript_function_action_after_select_js_call'] = 'change_modules_aut $table_new_relations->data[0][1] = ui_print_agent_autocomplete_input($params); $table_new_relations->data[0][2] = __('Module'); $table_new_relations->data[0][3] = "
    "; -$table_new_relations->data[0][4] = html_print_button (__('Add relationship'), 'add_relation', false, 'javascript: add_new_relation();', 'class="sub add"', true); +$table_new_relations->data[0][4] = html_print_button(__('Add relationship'), 'add_relation', false, 'javascript: add_new_relation();', 'class="sub add"', true); $table_new_relations->data[0][4] .= "  
    "; // Relationship list @@ -744,76 +1064,65 @@ $table_relations = new stdClass(); $table_relations->id = 'module_relations'; $table_relations->width = '100%'; $table_relations->class = 'databox data'; -$table_relations->head = array (); -$table_relations->data = array (); -$table_relations->rowstyle = array (); +$table_relations->head = []; +$table_relations->data = []; +$table_relations->rowstyle = []; $table_relations->rowstyle[-1] = 'display: none;'; -$table_relations->style = array (); +$table_relations->style = []; $table_relations->style[2] = 'width: 10%; text-align: center;'; $table_relations->style[3] = 'width: 10%; text-align: center;'; $table_relations->head[0] = __('Agent'); $table_relations->head[1] = __('Module'); -$table_relations->head[2] = __('Changes'). ui_print_help_tip(__("Activate this to prevent the relation from being updated or deleted"), true); +$table_relations->head[2] = __('Changes').ui_print_help_tip(__('Activate this to prevent the relation from being updated or deleted'), true); $table_relations->head[3] = __('Delete'); // Create an invisible row to use their html to add new rows -$table_relations->data[-1][0] = ""; -$table_relations->data[-1][1] = ""; -$table_relations->data[-1][2] = '' . html_print_image('images/lock.png', true) . ''; -$table_relations->data[-1][3] = '' . html_print_image('images/cross.png', true) . ''; +$table_relations->data[-1][0] = ''; +$table_relations->data[-1][1] = ''; +$table_relations->data[-1][2] = ''.html_print_image('images/lock.png', true).''; +$table_relations->data[-1][3] = ''.html_print_image('images/cross.png', true).''; -$module_relations = modules_get_relations(array('id_module' => $id_agent_module)); +$module_relations = modules_get_relations(['id_module' => $id_agent_module]); if (!$module_relations) { - $module_relations = array(); + $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']); - } - - $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, '[…]') . ""; - // Lock relationship updates - $table_relations->data[$relations_count][2] = - '' . - html_print_image('images/lock.png', true) . ''; - // Delete relationship - $table_relations->data[$relations_count][3] = - '' . - html_print_image('images/cross.png', true) . ''; - $relations_count++; + 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']); + } + + $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, '[…]').''; + // Lock relationship updates + $table_relations->data[$relations_count][2] = ''.html_print_image('images/lock.png', true).''; + // Delete relationship + $table_relations->data[$relations_count][3] = ''.html_print_image('images/cross.png', true).''; + $relations_count++; } -html_print_input_hidden ('module_relations_count', $relations_count); +html_print_input_hidden('module_relations_count', $relations_count); ui_require_jquery_file('json'); @@ -822,449 +1131,449 @@ ui_require_jquery_file('json'); "; -//This line does not run with the dinamic loader editor in policies. -//ui_require_javascript_file ('pandora_snmp_browser'); - -//WARNING REPEAT input hidden errors in console +// This line does not run with the dinamic loader editor in policies. +// ui_require_javascript_file ('pandora_snmp_browser'); +// WARNING REPEAT input hidden errors in console // Save some variables for javascript functions -//html_print_input_hidden ('ajax_url', ui_get_full_url("ajax.php"), false); -//html_print_input_hidden ('search_matches_translation', __("Search matches"), false); - - - +// html_print_input_hidden ('ajax_url', ui_get_full_url("ajax.php"), false); +// html_print_input_hidden ('search_matches_translation', __("Search matches"), false); // Define a custom action to save the OID selected in the SNMP browser to the form -html_print_input_hidden ('custom_action', urlencode (base64_encode(' ')), false); +html_print_input_hidden('custom_action', urlencode(base64_encode(' ')), false); $isFunctionPolicies = enterprise_include_once('include/functions_policies.php'); @@ -39,400 +33,518 @@ $disabledTextBecauseInPolicy = ''; $classdisabledBecauseInPolicy = ''; $largeclassdisabledBecauseInPolicy = ''; $page = get_parameter('page', ''); -if (strstr($page, "policy_modules") === false) { - if ($config['enterprise_installed']) { - $disabledBecauseInPolicy = policies_is_module_in_policy($id_agent_module) && policies_is_module_linked($id_agent_module); - } - else { - $disabledBecauseInPolicy = false; - } - if ($disabledBecauseInPolicy){ - $disabledTextBecauseInPolicy = 'readonly = "yes"'; - $classdisabledBecauseInPolicy = 'readonly'; - $largeclassdisabledBecauseInPolicy = 'class = readonly'; - } +if (strstr($page, 'policy_modules') === false) { + if ($config['enterprise_installed']) { + $disabledBecauseInPolicy = policies_is_module_in_policy($id_agent_module) && policies_is_module_linked($id_agent_module); + } else { + $disabledBecauseInPolicy = false; + } + if ($disabledBecauseInPolicy) { + $disabledTextBecauseInPolicy = 'readonly = "yes"'; + $classdisabledBecauseInPolicy = 'readonly'; + $largeclassdisabledBecauseInPolicy = 'class = readonly'; + } } -define ('ID_NETWORK_COMPONENT_TYPE', 2); +define('ID_NETWORK_COMPONENT_TYPE', 2); -if (empty ($update_module_id)) { - /* Function in module_manager_editor_common.php */ - add_component_selection (ID_NETWORK_COMPONENT_TYPE); -} -else { - /* TODO: Print network component if available */ +if (empty($update_module_id)) { + // Function in module_manager_editor_common.php + add_component_selection(ID_NETWORK_COMPONENT_TYPE); +} else { + // TODO: Print network component if available } $extra_title = __('Network server module'); -$data = array (); +$data = []; $data[0] = __('Target IP'); -//show agent_for defect; +// show agent_for defect; +if ($page == 'enterprise/godmode/policies/policy_modules') { + if ($ip_target != 'auto' && $ip_target != '') { + $custom_ip_target = $ip_target; + $ip_target = 'custom'; + } else if ($ip_target == '') { + $ip_target = 'force_pri'; + $custom_ip_target = ''; + } else { + $custom_ip_target = ''; + } -if($page == 'enterprise/godmode/policies/policy_modules'){ - - if($ip_target != 'auto' && $ip_target != ''){ - $custom_ip_target = $ip_target; - $ip_target = 'custom'; - } - elseif($ip_target == ''){ - $ip_target = 'force_pri'; - $custom_ip_target = ''; - } - else{ - $custom_ip_target = ''; - } + $target_ip_values = []; + $target_ip_values['auto'] = __('Auto'); + $target_ip_values['force_pri'] = __('Force primary key'); + $target_ip_values['custom'] = __('Custom'); - $target_ip_values = array(); - $target_ip_values['auto'] = __('Auto'); - $target_ip_values['force_pri'] = __('Force primary key'); - $target_ip_values['custom'] = __('Custom'); + $data[1] = html_print_select( + $target_ip_values, + 'ip_target', + $ip_target, + '', + '', + '', + true, + false, + false, + '', + false, + 'width:200px;' + ); + $data[1] .= html_print_input_text('custom_ip_target', $custom_ip_target, '', 15, 60, true); +} else { + if ($ip_target == 'auto') { + $ip_target = agents_get_address($id_agente); + } - $data[1] = html_print_select ($target_ip_values, 'ip_target', $ip_target, '', '', '', - true, false, false, '', false, 'width:200px;'); - $data[1] .= html_print_input_text ('custom_ip_target', $custom_ip_target, '', 15, 60, true); -} -else{ - if($ip_target == 'auto'){ - $ip_target = agents_get_address ($id_agente); - } - $data[1] = html_print_input_text ('ip_target', $ip_target, '', 15, 60, true); + $data[1] = html_print_input_text('ip_target', $ip_target, '', 15, 60, true); } // In ICMP modules, port is not configurable if ($id_module_type >= 6 && $id_module_type <= 7) { - $data[2] = ''; - $data[3] = ''; -} -else { - $data[2] = __('Port'); - $data[3] = html_print_input_text ('tcp_port', $tcp_port, '', 5, 20, true, $disabledBecauseInPolicy, - false, '', $classdisabledBecauseInPolicy); + $data[2] = ''; + $data[3] = ''; +} else { + $data[2] = __('Port'); + $data[3] = html_print_input_text( + 'tcp_port', + $tcp_port, + '', + 5, + 20, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ); } -push_table_simple ($data, 'target_ip'); +push_table_simple($data, 'target_ip'); $snmp_versions['1'] = 'v. 1'; $snmp_versions['2'] = 'v. 2'; $snmp_versions['2c'] = 'v. 2c'; $snmp_versions['3'] = 'v. 3'; -$data = array (); +$data = []; $data[0] = __('SNMP community'); $adopt = false; if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK && isset($id_agent_module)) { - $adopt = policies_is_module_adopt($id_agent_module); + $adopt = policies_is_module_adopt($id_agent_module); } + if (!$adopt) { - $data[1] = html_print_input_text ('snmp_community', $snmp_community, '', 15, 60, true, $disabledBecauseInPolicy, - false, '', $classdisabledBecauseInPolicy); -} -else { - $data[1] = html_print_input_text ('snmp_community', $snmp_community, '', 15, 60, true, false); + $data[1] = html_print_input_text( + 'snmp_community', + $snmp_community, + '', + 15, + 60, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ); +} else { + $data[1] = html_print_input_text('snmp_community', $snmp_community, '', 15, 60, true, false); } $data[2] = _('SNMP version'); if ($id_module_type >= 15 && $id_module_type <= 18) { - $data[3] = html_print_select ($snmp_versions, 'snmp_version', $tcp_send, - '', '', '', true, false, false, '', $disabledBecauseInPolicy, - false, '', $classdisabledBecauseInPolicy); + $data[3] = html_print_select( + $snmp_versions, + 'snmp_version', + $tcp_send, + '', + '', + '', + true, + false, + false, + '', + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ); +} else { + $data[3] = html_print_select( + $snmp_versions, + 'snmp_version', + 0, + '', + '', + '', + true, + false, + false, + '', + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ); } -else { - $data[3] = html_print_select ($snmp_versions, 'snmp_version', 0, '', '', - '', true, false, false, '', $disabledBecauseInPolicy, - false, '', $classdisabledBecauseInPolicy); -} -if($disabledBecauseInPolicy){ - if ($id_module_type >= 15 && $id_module_type <= 18) { - $data[3] .= html_print_input_hidden ('snmp_version', $tcp_send, true); - } -} -push_table_simple ($data, 'snmp_1'); -$data = array (); +if ($disabledBecauseInPolicy) { + if ($id_module_type >= 15 && $id_module_type <= 18) { + $data[3] .= html_print_input_hidden('snmp_version', $tcp_send, true); + } +} + +push_table_simple($data, 'snmp_1'); + +$data = []; $data[0] = __('SNMP OID'); $data[1] = ''; -$data[1] .= html_print_input_text ('snmp_oid', $snmp_oid, '', 30, 255, true, $disabledBecauseInPolicy, - false, '', $classdisabledBecauseInPolicy); +$data[1] .= html_print_input_text( + 'snmp_oid', + $snmp_oid, + '', + 30, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); $data[1] .= ''; $data[1] .= ''; -$data[1] .= html_print_button (__('SNMP walk'), 'snmp_walk', false, 'snmpBrowserWindow()', - 'class="sub next"', true); -$data[1] .= ui_print_help_icon ('snmpwalk', true); +$data[1] .= html_print_button( + __('SNMP walk'), + 'snmp_walk', + false, + 'snmpBrowserWindow()', + 'class="sub next"', + true +); +$data[1] .= ui_print_help_icon('snmpwalk', true); $data[1] .= ''; $table_simple->colspan['snmp_2'][1] = 3; -push_table_simple ($data, 'snmp_2'); +push_table_simple($data, 'snmp_2'); -/* Advanced stuff */ -$data = array (); -$data[0] = __('TCP send') . ' ' . ui_print_help_icon ("tcp_send", true); -$data[1] = html_print_textarea ('tcp_send', 2, 65, $tcp_send, $disabledTextBecauseInPolicy, true, $largeclassdisabledBecauseInPolicy); +// Advanced stuff +$data = []; +$data[0] = __('TCP send').' '.ui_print_help_icon('tcp_send', true); +$data[1] = html_print_textarea('tcp_send', 2, 65, $tcp_send, $disabledTextBecauseInPolicy, true, $largeclassdisabledBecauseInPolicy); $table_simple->colspan['tcp_send'][1] = 3; -push_table_simple ($data, 'tcp_send'); +push_table_simple($data, 'tcp_send'); $data[0] = __('TCP receive'); -$data[1] = html_print_textarea ('tcp_rcv', 2, 65, $tcp_rcv, $disabledTextBecauseInPolicy, true, $largeclassdisabledBecauseInPolicy); +$data[1] = html_print_textarea('tcp_rcv', 2, 65, $tcp_rcv, $disabledTextBecauseInPolicy, true, $largeclassdisabledBecauseInPolicy); $table_simple->colspan['tcp_receive'][1] = 3; -push_table_simple ($data, 'tcp_receive'); +push_table_simple($data, 'tcp_receive'); if ($id_module_type < 8 || $id_module_type > 11) { - /* NOT TCP */ - $table_simple->rowstyle['tcp_send'] = 'display: none;'; - $table_simple->rowstyle['tcp_receive'] = 'display: none;'; + // NOT TCP + $table_simple->rowstyle['tcp_send'] = 'display: none;'; + $table_simple->rowstyle['tcp_receive'] = 'display: none;'; } if ($id_module_type < 15 || $id_module_type > 18) { - /* NOT SNMP */ - $table_simple->rowstyle['snmp_1'] = 'display: none'; - $table_simple->rowstyle['snmp_2'] = 'display: none'; + // NOT SNMP + $table_simple->rowstyle['snmp_1'] = 'display: none'; + $table_simple->rowstyle['snmp_2'] = 'display: none'; } -//For a policy +// For a policy if (!isset($id_agent_module)) { - $snmp3_auth_user = ''; - $snmp3_auth_pass = ''; - $snmp_version = 1; - $snmp3_privacy_method = ''; - $snmp3_privacy_pass = ''; - $snmp3_auth_method = ''; - $snmp3_security_level = ''; -} -else if ($id_agent_module === false) { - $snmp3_auth_user = ''; - $snmp3_auth_pass = ''; - $snmp_version = 1; - $snmp3_privacy_method = ''; - $snmp3_privacy_pass = ''; - $snmp3_auth_method = ''; - $snmp3_security_level = ''; + $snmp3_auth_user = ''; + $snmp3_auth_pass = ''; + $snmp_version = 1; + $snmp3_privacy_method = ''; + $snmp3_privacy_pass = ''; + $snmp3_auth_method = ''; + $snmp3_security_level = ''; +} else if ($id_agent_module === false) { + $snmp3_auth_user = ''; + $snmp3_auth_pass = ''; + $snmp_version = 1; + $snmp3_privacy_method = ''; + $snmp3_privacy_pass = ''; + $snmp3_auth_method = ''; + $snmp3_security_level = ''; } -$data = array(); +$data = []; $data[0] = __('Auth user'); -$data[1] = html_print_input_text ('snmp3_auth_user', $snmp3_auth_user, '', 15, 60, true, $disabledBecauseInPolicy, - false, '', $classdisabledBecauseInPolicy); -$data[2] = __('Auth password') . ui_print_help_tip(__("The pass length must be eight character minimum."), true); -$data[3] = html_print_input_password ('snmp3_auth_pass', $snmp3_auth_pass, '', 15, 60, true, $disabledBecauseInPolicy, - false, $largeclassdisabledBecauseInPolicy); +$data[1] = html_print_input_text( + 'snmp3_auth_user', + $snmp3_auth_user, + '', + 15, + 60, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); +$data[2] = __('Auth password').ui_print_help_tip(__('The pass length must be eight character minimum.'), true); +$data[3] = html_print_input_password( + 'snmp3_auth_pass', + $snmp3_auth_pass, + '', + 15, + 60, + true, + $disabledBecauseInPolicy, + false, + $largeclassdisabledBecauseInPolicy +); $data[3] .= html_print_input_hidden_extended('active_snmp_v3', 0, 'active_snmp_v3_mmen', true); -if ($snmp_version != 3) $table_simple->rowstyle['field_snmpv3_row1'] = 'display: none;'; +if ($snmp_version != 3) { + $table_simple->rowstyle['field_snmpv3_row1'] = 'display: none;'; +} + push_table_simple($data, 'field_snmpv3_row1'); -$data = array(); +$data = []; $data[0] = __('Privacy method'); -$data[1] = html_print_select(array('DES' => __('DES'), 'AES' => __('AES')), 'snmp3_privacy_method', $snmp3_privacy_method, '', '', '', true, false, false, '', $disabledBecauseInPolicy); -$data[2] = __('Privacy pass') . ui_print_help_tip(__("The pass length must be eight character minimum."), true); -$data[3] = html_print_input_password ('snmp3_privacy_pass', $snmp3_privacy_pass, '', 15, 60, true, $disabledBecauseInPolicy, - false, $largeclassdisabledBecauseInPolicy); +$data[1] = html_print_select(['DES' => __('DES'), 'AES' => __('AES')], 'snmp3_privacy_method', $snmp3_privacy_method, '', '', '', true, false, false, '', $disabledBecauseInPolicy); +$data[2] = __('Privacy pass').ui_print_help_tip(__('The pass length must be eight character minimum.'), true); +$data[3] = html_print_input_password( + 'snmp3_privacy_pass', + $snmp3_privacy_pass, + '', + 15, + 60, + true, + $disabledBecauseInPolicy, + false, + $largeclassdisabledBecauseInPolicy +); + +if ($snmp_version != 3) { + $table_simple->rowstyle['field_snmpv3_row2'] = 'display: none;'; +} -if ($snmp_version != 3) $table_simple->rowstyle['field_snmpv3_row2'] = 'display: none;'; push_table_simple($data, 'field_snmpv3_row2'); -$data = array(); +$data = []; $data[0] = __('Auth method'); -$data[1] = html_print_select(array('MD5' => __('MD5'), 'SHA' => __('SHA')), 'snmp3_auth_method', $snmp3_auth_method, '', '', '', true, false, false, '', $disabledBecauseInPolicy); +$data[1] = html_print_select(['MD5' => __('MD5'), 'SHA' => __('SHA')], 'snmp3_auth_method', $snmp3_auth_method, '', '', '', true, false, false, '', $disabledBecauseInPolicy); $data[2] = __('Security level'); -$data[3] = html_print_select(array('noAuthNoPriv' => __('Not auth and not privacy method'), - 'authNoPriv' => __('Auth and not privacy method'), 'authPriv' => __('Auth and privacy method')), 'snmp3_security_level', $snmp3_security_level, '', '', '', true, false, false, '', $disabledBecauseInPolicy); -if ($snmp_version != 3) - $table_simple->rowstyle['field_snmpv3_row3'] = 'display: none;'; +$data[3] = html_print_select( + [ + 'noAuthNoPriv' => __('Not auth and not privacy method'), + 'authNoPriv' => __('Auth and not privacy method'), + 'authPriv' => __('Auth and privacy method'), + ], + 'snmp3_security_level', + $snmp3_security_level, + '', + '', + '', + true, + false, + false, + '', + $disabledBecauseInPolicy +); +if ($snmp_version != 3) { + $table_simple->rowstyle['field_snmpv3_row3'] = 'display: none;'; +} + push_table_simple($data, 'field_snmpv3_row3'); -snmp_browser_print_container (false, '100%', '60%', 'none'); +snmp_browser_print_container(false, '100%', '60%', 'none'); ?> diff --git a/pandora_console/godmode/agentes/module_manager_editor_plugin.php b/pandora_console/godmode/agentes/module_manager_editor_plugin.php index a5085122d0..6b39172bca 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_plugin.php +++ b/pandora_console/godmode/agentes/module_manager_editor_plugin.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,7 +11,6 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - enterprise_include_once('include/functions_policies.php'); global $module; @@ -23,102 +21,123 @@ $disabledBecauseInPolicy = false; $disabledTextBecauseInPolicy = ''; $classdisabledBecauseInPolicy = ''; $page = get_parameter('page', ''); -if (strstr($page, "policy_modules") === false) { - if ($config['enterprise_installed']) - $disabledBecauseInPolicy = policies_is_module_in_policy($id_agent_module) && policies_is_module_linked($id_agent_module); - else - $disabledBecauseInPolicy = false; - if ($disabledBecauseInPolicy){ - $disabledTextBecauseInPolicy = 'readonly = "readonly"'; - $classdisabledBecauseInPolicy = 'readonly'; - } +if (strstr($page, 'policy_modules') === false) { + if ($config['enterprise_installed']) { + $disabledBecauseInPolicy = policies_is_module_in_policy($id_agent_module) && policies_is_module_linked($id_agent_module); + } else { + $disabledBecauseInPolicy = false; + } + + if ($disabledBecauseInPolicy) { + $disabledTextBecauseInPolicy = 'readonly = "readonly"'; + $classdisabledBecauseInPolicy = 'readonly'; + } } -define ('ID_NETWORK_COMPONENT_TYPE', 4); +define('ID_NETWORK_COMPONENT_TYPE', 4); -if (empty ($update_module_id)) { - /* Function in module_manager_editor_common.php */ - add_component_selection (ID_NETWORK_COMPONENT_TYPE); -} -else { - /* TODO: Print network component if available */ +if (empty($update_module_id)) { + // Function in module_manager_editor_common.php + add_component_selection(ID_NETWORK_COMPONENT_TYPE); +} else { + // TODO: Print network component if available } $extra_title = __('Plugin server module'); -$data = array (); -$data[0] = __('Plugin') . ui_print_help_icon ('plugin_macros', true); -$data[1] = html_print_select_from_sql ('SELECT id, name FROM tplugin ORDER BY name', - 'id_plugin', $id_plugin, 'changePluginSelect();', __('None'), 0, true, false, false, $disabledBecauseInPolicy); +$data = []; +$data[0] = __('Plugin').ui_print_help_icon('plugin_macros', true); +$data[1] = html_print_select_from_sql( + 'SELECT id, name FROM tplugin ORDER BY name', + 'id_plugin', + $id_plugin, + 'changePluginSelect();', + __('None'), + 0, + true, + false, + false, + $disabledBecauseInPolicy +); // Store the macros in base64 into a hidden control to move between pages -$data[1] .= html_print_input_hidden('macros',base64_encode($macros),true); +$data[1] .= html_print_input_hidden('macros', base64_encode($macros), true); $table_simple->colspan['plugin_1'][2] = 2; if (!empty($id_plugin)) { - $preload = db_get_sql ("SELECT description FROM tplugin WHERE id = $id_plugin"); - $preload = io_safe_output ($preload); - $preload = str_replace ("\n", "
    ", $preload); -} -else { - $preload = ""; + $preload = db_get_sql("SELECT description FROM tplugin WHERE id = $id_plugin"); + $preload = io_safe_output($preload); + $preload = str_replace("\n", '
    ', $preload); +} else { + $preload = ''; } $data[2] = ''.$preload.''; -push_table_simple ($data, 'plugin_1'); +push_table_simple($data, 'plugin_1'); // A hidden "model row" to clone it from javascript to add fields dynamicly -$data = array (); +$data = []; $data[0] = 'macro_desc'; -$data[0] .= ui_print_help_tip ('macro_help', true); -$data[1] = html_print_input_text ('macro_name', 'macro_value', '', 100, 1024, true); +$data[0] .= ui_print_help_tip('macro_help', true); +$data[1] = html_print_input_text('macro_name', 'macro_value', '', 100, 1024, true); $table_simple->colspan['macro_field'][1] = 3; $table_simple->rowstyle['macro_field'] = 'display:none'; -push_table_simple ($data, 'macro_field'); +push_table_simple($data, 'macro_field'); // If there are $macros, we create the form fields if (!empty($macros)) { - $macros = json_decode($macros, true); - - foreach ($macros as $k => $m) { - $data = array (); - $data[0] = $m['desc']; - if (!empty($m['help'])) { - $data[0] .= ui_print_help_tip ($m['help'], true); - } - - $m_hide = false; - if (isset($m['hide'])) - $m_hide = $m['hide']; - - if ($m_hide) { - $data[1] = html_print_input_password($m['macro'], io_output_password($m['value']), '', 100, 1024, true); - } - else { - $data[1] = html_print_input_text($m['macro'], $m['value'], '', 100, 1024, true, - $disabledBecauseInPolicy, false, '', $classdisabledBecauseInPolicy); - } - $table_simple->colspan['macro'.$m['macro']][1] = 3; - $table_simple->rowclass['macro'.$m['macro']] = 'macro_field'; - - push_table_simple ($data, 'macro'.$m['macro']); - } + $macros = json_decode($macros, true); + + foreach ($macros as $k => $m) { + $data = []; + $data[0] = $m['desc']; + if (!empty($m['help'])) { + $data[0] .= ui_print_help_tip($m['help'], true); + } + + $m_hide = false; + if (isset($m['hide'])) { + $m_hide = $m['hide']; + } + + if ($m_hide) { + $data[1] = html_print_input_password($m['macro'], io_output_password($m['value']), '', 100, 1024, true); + } else { + $data[1] = html_print_input_text( + $m['macro'], + $m['value'], + '', + 100, + 1024, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy + ); + } + + $table_simple->colspan['macro'.$m['macro']][1] = 3; + $table_simple->rowclass['macro'.$m['macro']] = 'macro_field'; + + push_table_simple($data, 'macro'.$m['macro']); + } } ?> diff --git a/pandora_console/godmode/agentes/module_manager_editor_prediction.php b/pandora_console/godmode/agentes/module_manager_editor_prediction.php index f8a4622ffe..b571335f7b 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_prediction.php +++ b/pandora_console/godmode/agentes/module_manager_editor_prediction.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -14,15 +13,15 @@ // GNU General Public License for more details. enterprise_include_once('include/functions_policies.php'); enterprise_include_once('godmode/agentes/module_manager_editor_prediction.php'); -require_once ('include/functions_agents.php'); +require_once 'include/functions_agents.php'; $disabledBecauseInPolicy = false; $disabledTextBecauseInPolicy = ''; $page = get_parameter('page', ''); $id_agente = get_parameter('id_agente', ''); $agent_name = get_parameter('agent_name', agents_get_alias($id_agente)); -$id_agente_modulo= get_parameter('id_agent_module',0); -$custom_integer_2 = get_parameter ('custom_integer_2', 0); +$id_agente_modulo = get_parameter('id_agent_module', 0); +$custom_integer_2 = get_parameter('custom_integer_2', 0); $sql = 'SELECT * FROM tagente_modulo WHERE id_agente_modulo = '.$id_agente_modulo; @@ -32,93 +31,99 @@ $is_synthetic = false; $is_synthetic_avg = false; $ops = false; if ($row !== false && is_array($row)) { - $prediction_module = $row['prediction_module']; - $custom_integer_2 = $row ['custom_integer_2']; - // Services are an Enterprise feature. - $custom_integer_1 = $row['custom_integer_1']; - - switch ($prediction_module) { - case MODULE_PREDICTION_SERVICE: - $is_service = true; - $custom_integer_2 = 0; - break; - case MODULE_PREDICTION_SYNTHETIC: - $ops_json = enterprise_hook('modules_get_synthetic_operations', - array($id_agente_modulo)); - - - $ops = json_decode($ops_json, true); - - - - //Erase the key of array serialize as ** - $chunks = explode('**', reset(array_keys($ops))); - - $first_op = explode('_', $chunks[1]); - - - - if (isset($first_op[1]) && $first_op[1] == 'avg') { - $is_synthetic_avg = true; - } - else { - $is_synthetic = true; - } - - $custom_integer_1 = 0; - $custom_integer_2 = 0; - break; - default: - $prediction_module = $custom_integer_1; - break; - } + $prediction_module = $row['prediction_module']; + $custom_integer_2 = $row['custom_integer_2']; + // Services are an Enterprise feature. + $custom_integer_1 = $row['custom_integer_1']; + + switch ($prediction_module) { + case MODULE_PREDICTION_SERVICE: + $is_service = true; + $custom_integer_2 = 0; + break; + + case MODULE_PREDICTION_SYNTHETIC: + $ops_json = enterprise_hook( + 'modules_get_synthetic_operations', + [$id_agente_modulo] + ); + + + $ops = json_decode($ops_json, true); + + + + // Erase the key of array serialize as ** + $chunks = explode('**', reset(array_keys($ops))); + + $first_op = explode('_', $chunks[1]); + + + + if (isset($first_op[1]) && $first_op[1] == 'avg') { + $is_synthetic_avg = true; + } else { + $is_synthetic = true; + } + + $custom_integer_1 = 0; + $custom_integer_2 = 0; + break; + + default: + $prediction_module = $custom_integer_1; + break; + } +} else { + $custom_integer_1 = 0; } -else { - $custom_integer_1 = 0; -} -if (strstr($page, "policy_modules") === false) { - if ($config['enterprise_installed']) - $disabledBecauseInPolicy = policies_is_module_in_policy($id_agent_module) && policies_is_module_linked($id_agent_module); - else - $disabledBecauseInPolicy = false; - if ($disabledBecauseInPolicy) - $disabledTextBecauseInPolicy = 'disabled = "disabled"'; + +if (strstr($page, 'policy_modules') === false) { + if ($config['enterprise_installed']) { + $disabledBecauseInPolicy = policies_is_module_in_policy($id_agent_module) && policies_is_module_linked($id_agent_module); + } else { + $disabledBecauseInPolicy = false; + } + + if ($disabledBecauseInPolicy) { + $disabledTextBecauseInPolicy = 'disabled = "disabled"'; + } } $extra_title = __('Prediction server module'); -$data = array (); +$data = []; $data[0] = __('Source module'); -$data[0] .= ui_print_help_icon ('prediction_source_module', true); +$data[0] .= ui_print_help_icon('prediction_source_module', true); $data[1] = ''; // Services and Synthetic are an Enterprise feature. -$module_service_synthetic_selector = enterprise_hook('get_module_service_synthetic_selector', array($is_service, $is_synthetic, $is_synthetic_avg)); +$module_service_synthetic_selector = enterprise_hook('get_module_service_synthetic_selector', [$is_service, $is_synthetic, $is_synthetic_avg]); if ($module_service_synthetic_selector !== ENTERPRISE_NOT_HOOK) { - $data[1] = $module_service_synthetic_selector; - - $table_simple->colspan['module_service_synthetic_selector'][1] = 3; - push_table_simple ($data, 'module_service_synthetic_selector'); - - $data = array(); - $data[0] = ''; + $data[1] = $module_service_synthetic_selector; + + $table_simple->colspan['module_service_synthetic_selector'][1] = 3; + push_table_simple($data, 'module_service_synthetic_selector'); + + $data = []; + $data[0] = ''; } $data[1] = '
    '; -$data[1] .= html_print_label(__("Agent"),'agent_name', true)."
    "; +$data[1] .= html_print_label(__('Agent'), 'agent_name', true).'
    '; // Get module and agent of the target prediction module if (!empty($prediction_module)) { - $id_agente_clean = modules_get_agentmodule_agent($prediction_module); - $prediction_module_agent = modules_get_agentmodule_agent_name($prediction_module); - $agent_name_clean = $prediction_module_agent; -} -else { - $id_agente_clean = $id_agente; - $agent_name_clean = $agent_name; + $id_agente_clean = modules_get_agentmodule_agent($prediction_module); + $prediction_module_agent = modules_get_agentmodule_agent_name($prediction_module); + $agent_name_clean = $prediction_module_agent; +} else { + $id_agente_clean = $id_agente; + $agent_name_clean = $agent_name; } + $agent_alias = agents_get_alias($id_agente_clean); -$params = array(); +$params = []; $params['return'] = true; $params['show_helptip'] = true; $params['input_name'] = 'agent_name'; @@ -130,78 +135,92 @@ $params['use_hidden_input_idagent'] = true; $params['hidden_input_idagent_id'] = 'hidden-id_agente_module_prediction'; $data[1] .= ui_print_agent_autocomplete_input($params); -$data[1] .= html_print_label(__("Module"),'prediction_module',true); +$data[1] .= html_print_label(__('Module'), 'prediction_module', true); if ($id_agente) { - $sql = "SELECT id_agente_modulo, nombre + $sql = 'SELECT id_agente_modulo, nombre FROM tagente_modulo WHERE delete_pending = 0 AND history_data = 1 - AND id_agente = " . $id_agente_clean . " - AND id_agente_modulo <> " . $id_agente_modulo; - $data[1] .= html_print_select_from_sql($sql, 'prediction_module', - $prediction_module, false, __('Select Module'), 0, true); -} -else { - $data[1] .= ''; + AND id_agente = '.$id_agente_clean.' + AND id_agente_modulo <> '.$id_agente_modulo; + $data[1] .= html_print_select_from_sql( + $sql, + 'prediction_module', + $prediction_module, + false, + __('Select Module'), + 0, + true + ); +} else { + $data[1] .= ''; } -$data[1] .= html_print_label(__("Period"), 'custom_integer_2', true)."
    "; +$data[1] .= html_print_label(__('Period'), 'custom_integer_2', true).'
    '; -$periods [0] = __('Weekly'); -$periods [1] = __('Monthly'); -$periods [2] = __('Daily'); -$data[1] .= html_print_select ($periods, 'custom_integer_2', $custom_integer_2, '', '', 0, true); +$periods[0] = __('Weekly'); +$periods[1] = __('Monthly'); +$periods[2] = __('Daily'); +$data[1] .= html_print_select($periods, 'custom_integer_2', $custom_integer_2, '', '', 0, true); -$data[1] .= html_print_input_hidden ('id_agente_module_prediction', $id_agente, true); +$data[1] .= html_print_input_hidden('id_agente_module_prediction', $id_agente, true); $data[1] .= '
    '; $table_simple->colspan['prediction_module'][1] = 3; -push_table_simple ($data, 'prediction_module'); +push_table_simple($data, 'prediction_module'); // Services are an Enterprise feature. -$selector_form = enterprise_hook('get_selector_form', array($custom_integer_1)); +$selector_form = enterprise_hook('get_selector_form', [$custom_integer_1]); if ($selector_form !== ENTERPRISE_NOT_HOOK) { - $data = array(); - $data[0] = ''; - $data[1] = $selector_form; - - $table_simple->colspan['service_module'][1] = 3; - push_table_simple ($data, 'service_module'); + $data = []; + $data[0] = ''; + $data[1] = $selector_form; + + $table_simple->colspan['service_module'][1] = 3; + push_table_simple($data, 'service_module'); } // Synthetic modules are an Enterprise feature. -$synthetic_module_form = enterprise_hook ('get_synthetic_module_form'); +$synthetic_module_form = enterprise_hook('get_synthetic_module_form'); if ($synthetic_module_form !== ENTERPRISE_NOT_HOOK) { - $data = array(); - $data[0] = ''; - $data[1] = $synthetic_module_form; - - $table_simple->colspan['synthetic_module'][1] = 3; - push_table_simple ($data, 'synthetic_module'); + $data = []; + $data[0] = ''; + $data[1] = $synthetic_module_form; + + $table_simple->colspan['synthetic_module'][1] = 3; + push_table_simple($data, 'synthetic_module'); } // Netflow modules are an Enterprise feature. -$netflow_module_form = enterprise_hook ('get_netflow_module_form', array($custom_integer_1)); +$netflow_module_form = enterprise_hook('get_netflow_module_form', [$custom_integer_1]); if ($netflow_module_form !== ENTERPRISE_NOT_HOOK) { - $data = array(); - $data[0] = ''; - $data[1] = $netflow_module_form; - - $table_simple->colspan['netflow_module_form'][1] = 3; - push_table_simple ($data, 'netflow_module'); + $data = []; + $data[0] = ''; + $data[1] = $netflow_module_form; + + $table_simple->colspan['netflow_module_form'][1] = 3; + push_table_simple($data, 'netflow_module'); } -/* Removed common useless parameter */ -unset ($table_advanced->data[3]); +// Removed common useless parameter +unset($table_advanced->data[3]); ?> \ No newline at end of file diff --git a/pandora_console/godmode/agentes/module_manager_editor_wmi.php b/pandora_console/godmode/agentes/module_manager_editor_wmi.php index c177db7790..e7f38447cf 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_wmi.php +++ b/pandora_console/godmode/agentes/module_manager_editor_wmi.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -18,66 +17,123 @@ $disabledBecauseInPolicy = false; $disabledTextBecauseInPolicy = ''; $classdisabledBecauseInPolicy = ''; $page = get_parameter('page', ''); -if (strstr($page, "policy_modules") === false) { - if ($config['enterprise_installed']) - $disabledBecauseInPolicy = policies_is_module_in_policy($id_agent_module) && policies_is_module_linked($id_agent_module); - else - $disabledBecauseInPolicy = false; - if ($disabledBecauseInPolicy){ - $disabledTextBecauseInPolicy = 'readonly = "readonly"'; - $classdisabledBecauseInPolicy = 'readonly'; - } +if (strstr($page, 'policy_modules') === false) { + if ($config['enterprise_installed']) { + $disabledBecauseInPolicy = policies_is_module_in_policy($id_agent_module) && policies_is_module_linked($id_agent_module); + } else { + $disabledBecauseInPolicy = false; + } + + if ($disabledBecauseInPolicy) { + $disabledTextBecauseInPolicy = 'readonly = "readonly"'; + $classdisabledBecauseInPolicy = 'readonly'; + } } $extra_title = __('WMI server module'); -define ('ID_NETWORK_COMPONENT_TYPE', 6); +define('ID_NETWORK_COMPONENT_TYPE', 6); -if (empty ($update_module_id)) { - /* Function in module_manager_editor_common.php */ - add_component_selection (ID_NETWORK_COMPONENT_TYPE); -} -else { - /* TODO: Print network component if available */ +if (empty($update_module_id)) { + // Function in module_manager_editor_common.php + add_component_selection(ID_NETWORK_COMPONENT_TYPE); +} else { + // TODO: Print network component if available } -$data = array (); +$data = []; $data[0] = __('Target IP'); -$data[1] = html_print_input_text ('ip_target', $ip_target, '', 15, 60, true); -$data[2] = __('Namespace'); -$data[2] .= ui_print_help_icon ('wminamespace', true); -$data[3] = html_print_input_text ('tcp_send', $tcp_send, '', 5, 20, true, $disabledBecauseInPolicy, false, - '', $classdisabledBecauseInPolicy); -push_table_simple ($data, 'target_ip'); +$data[1] = html_print_input_text('ip_target', $ip_target, '', 15, 60, true); +$data[2] = __('Namespace').ui_print_help_tip(__('Optional. WMI namespace. If unsure leave blank.'), true); +$data[3] = html_print_input_text( + 'tcp_send', + $tcp_send, + '', + 5, + 20, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); +push_table_simple($data, 'target_ip'); -$data = array (); +$data = []; $data[0] = __('Username'); -$data[1] = html_print_input_text ('plugin_user', $plugin_user, '', 15, 60, true, $disabledBecauseInPolicy, false, - '', $classdisabledBecauseInPolicy); +$data[1] = html_print_input_text( + 'plugin_user', + $plugin_user, + '', + 15, + 60, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); $data[2] = __('Password'); -$data[3] = html_print_input_password ('plugin_pass', $plugin_pass, '', 15, 60, true, $disabledBecauseInPolicy, false, - '', $classdisabledBecauseInPolicy); +$data[3] = html_print_input_password( + 'plugin_pass', + $plugin_pass, + '', + 15, + 60, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); -push_table_simple ($data, 'user_pass'); +push_table_simple($data, 'user_pass'); -$data = array (); +$data = []; $data[0] = __('WMI query'); -$data[0] .= ui_print_help_icon ('wmiquery', true); -$data[1] = html_print_input_text ('snmp_oid', $snmp_oid, '', 35, 255, true, $disabledBecauseInPolicy, false, - '', $classdisabledBecauseInPolicy); +$data[0] .= ui_print_help_icon('wmiquery', true); +$data[1] = html_print_input_text( + 'snmp_oid', + $snmp_oid, + '', + 35, + 255, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); $table_simple->colspan['wmi_query'][1] = 3; -push_table_simple ($data, 'wmi_query'); +push_table_simple($data, 'wmi_query'); -$data = array (); -$data[0] = __('Key string'); -$data[0] .= ui_print_help_icon ('wmikey', true); -$data[1] = html_print_input_text ('snmp_community', $snmp_community, '', 20, 60, true, $disabledBecauseInPolicy, false, - '', $classdisabledBecauseInPolicy); -$data[2] = __('Field number'); -$data[2] .= ui_print_help_icon ('wmifield', true); -$data[3] = html_print_input_text ('tcp_port', $tcp_port, '', 5, 15, true, $disabledBecauseInPolicy, false, - '', $classdisabledBecauseInPolicy); +$data = []; +$data[0] = __('Key string').ui_print_help_tip(__('Optional. Substring to look for in the WQL query result. The module returns 1 if found, 0 if not.'), true); +$data[1] = html_print_input_text( + 'snmp_community', + $snmp_community, + '', + 20, + 60, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); +$data[2] = __('Field number').ui_print_help_tip(__('Column number to retrieve from the WQL query result (starting from zero).'), true); +$data[3] = html_print_input_text( + 'tcp_port', + $tcp_port, + '', + 5, + 15, + true, + $disabledBecauseInPolicy, + false, + '', + $classdisabledBecauseInPolicy +); -push_table_simple ($data, 'key_field'); -?> +push_table_simple($data, 'key_field'); diff --git a/pandora_console/godmode/agentes/planned_downtime.editor.php b/pandora_console/godmode/agentes/planned_downtime.editor.php index a2aac419bd..bc5ac2a09c 100644 --- a/pandora_console/godmode/agentes/planned_downtime.editor.php +++ b/pandora_console/godmode/agentes/planned_downtime.editor.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,86 +10,87 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; check_login(); -$agent_d = check_acl ($config['id_user'], 0, "AD"); -$agent_w = check_acl ($config['id_user'], 0, "AW"); +$agent_d = check_acl($config['id_user'], 0, 'AD'); +$agent_w = check_acl($config['id_user'], 0, 'AW'); $access = ($agent_d == true) ? 'AD' : (($agent_w == true) ? 'AW' : 'AD'); if (!$agent_d && !$agent_w) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; } // Default -set_unless_defined ($config["past_planned_downtimes"], 1); +set_unless_defined($config['past_planned_downtimes'], 1); -require_once ('include/functions_users.php'); +require_once 'include/functions_users.php'; // Buttons -$buttons = array( - 'text' => "" - . html_print_image ("images/list.png", true, array ("title" =>__('List'))) . "" - ); +$buttons = [ + 'text' => "".html_print_image('images/list.png', true, ['title' => __('List')]).'', +]; // Header ui_print_page_header( - __("Planned Downtime"), - "images/gm_monitoring.png", - false, - "planned_downtime", - true, - $buttons); + __('Planned Downtime'), + 'images/gm_monitoring.png', + false, + 'planned_downtime', + true, + $buttons +); -//recursion group filter +// recursion group filter $recursion = get_parameter('recursion', $_POST['recursion']); -//Initialize data -$id_group = (int) get_parameter ('id_group'); -$name = (string) get_parameter ('name'); -$description = (string) get_parameter ('description'); +// Initialize data +$id_group = (int) get_parameter('id_group'); +$name = (string) get_parameter('name'); +$description = (string) get_parameter('description'); -$type_downtime = (string) get_parameter('type_downtime', 'quiet'); -$type_execution = (string) get_parameter('type_execution', 'once'); -$type_periodicity = (string) get_parameter('type_periodicity', 'weekly'); +$type_downtime = (string) get_parameter('type_downtime', 'quiet'); +$type_execution = (string) get_parameter('type_execution', 'once'); +$type_periodicity = (string) get_parameter('type_periodicity', 'weekly'); $utimestamp = get_system_time(); // Fake utimestamp to retrieve the string date of the system -$system_time = $utimestamp - get_fixed_offset(); +$system_time = ($utimestamp - get_fixed_offset()); -$once_date_from = (string) get_parameter ('once_date_from', date(DATE_FORMAT, $utimestamp)); -$once_time_from = (string) get_parameter ('once_time_from', date(TIME_FORMAT, $utimestamp)); -$once_date_to = (string) get_parameter ('once_date_to', date(DATE_FORMAT, $utimestamp)); -$once_time_to = (string) get_parameter ('once_time_to', date(TIME_FORMAT, $utimestamp + SECONDS_1HOUR)); +$once_date_from = (string) get_parameter('once_date_from', date(DATE_FORMAT, $utimestamp)); +$once_time_from = (string) get_parameter('once_time_from', date(TIME_FORMAT, $utimestamp)); +$once_date_to = (string) get_parameter('once_date_to', date(DATE_FORMAT, $utimestamp)); +$once_time_to = (string) get_parameter('once_time_to', date(TIME_FORMAT, ($utimestamp + SECONDS_1HOUR))); -$periodically_day_from = (int) get_parameter ('periodically_day_from', 1); -$periodically_day_to = (int) get_parameter ('periodically_day_to', 31); -$periodically_time_from = (string) get_parameter ('periodically_time_from', date(TIME_FORMAT, $system_time)); -$periodically_time_to = (string) get_parameter ('periodically_time_to', date(TIME_FORMAT, $system_time + SECONDS_1HOUR)); +$periodically_day_from = (int) get_parameter('periodically_day_from', 1); +$periodically_day_to = (int) get_parameter('periodically_day_to', 31); +$periodically_time_from = (string) get_parameter('periodically_time_from', date(TIME_FORMAT, $system_time)); +$periodically_time_to = (string) get_parameter('periodically_time_to', date(TIME_FORMAT, ($system_time + SECONDS_1HOUR))); -$monday = (bool) get_parameter ('monday'); -$tuesday = (bool) get_parameter ('tuesday'); -$wednesday = (bool) get_parameter ('wednesday'); -$thursday = (bool) get_parameter ('thursday'); -$friday = (bool) get_parameter ('friday'); -$saturday = (bool) get_parameter ('saturday'); -$sunday = (bool) get_parameter ('sunday'); +$monday = (bool) get_parameter('monday'); +$tuesday = (bool) get_parameter('tuesday'); +$wednesday = (bool) get_parameter('wednesday'); +$thursday = (bool) get_parameter('thursday'); +$friday = (bool) get_parameter('friday'); +$saturday = (bool) get_parameter('saturday'); +$sunday = (bool) get_parameter('sunday'); -$first_create = (int) get_parameter ('first_create'); -$create_downtime = (int) get_parameter ('create_downtime'); -$update_downtime = (int) get_parameter ('update_downtime'); -$edit_downtime = (int) get_parameter ('edit_downtime'); -$id_downtime = (int) get_parameter ('id_downtime'); +$first_create = (int) get_parameter('first_create'); +$create_downtime = (int) get_parameter('create_downtime'); +$update_downtime = (int) get_parameter('update_downtime'); +$edit_downtime = (int) get_parameter('edit_downtime'); +$id_downtime = (int) get_parameter('id_downtime'); -$id_agent = (int) get_parameter ('id_agent'); -$insert_downtime_agent = (int) get_parameter ('insert_downtime_agent'); -$delete_downtime_agent = (int) get_parameter ('delete_downtime_agent'); +$id_agent = (int) get_parameter('id_agent'); +$insert_downtime_agent = (int) get_parameter('insert_downtime_agent'); +$delete_downtime_agent = (int) get_parameter('delete_downtime_agent'); $modules_selection_mode = (string) get_parameter('modules_selection_mode'); @@ -99,392 +99,405 @@ $user_groups_ad = array_keys(users_get_groups($config['id_user'], $access)); // INSERT A NEW DOWNTIME_AGENT ASSOCIATION if ($insert_downtime_agent === 1) { - - // Check AD permission on downtime - $downtime_group = db_get_value('id_group', 'tplanned_downtime', 'id', $id_downtime); - - if ($downtime_group === false || !in_array($downtime_group, $user_groups_ad)) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - $agents = (array) get_parameter ('id_agents'); - $module_names = (array) get_parameter ('module'); - - $all_modules = (empty($module_names) || ($module_names[0] === "0")); - - // 'Is running' check - $is_running = (bool) db_get_value ('executed', 'tplanned_downtime', 'id', $id_downtime); - if ($is_running) { - ui_print_error_message(__("This elements cannot be modified while the downtime is being executed")); - } - else { - foreach ($agents as $agent_id) { - //check module belongs to the agent - if($modules_selection_mode == 'all'){ - $check = false; - foreach ($module_names as $module_name) { - $check_module = modules_get_agentmodule_id($module_name, $agent_id); - if (!empty($check_module)){ - $check = true; - } - } + // Check AD permission on downtime + $downtime_group = db_get_value('id_group', 'tplanned_downtime', 'id', $id_downtime); - if (!$check){ - continue; - } - } - // Check AD permission on agent - $agent_group = db_get_value('id_grupo', 'tagente', 'id_agente', $agent_id); - - if ($agent_group === false || !in_array($agent_group, $user_groups_ad)) { - continue; - } - - $values = array( - 'id_downtime' => $id_downtime, - 'id_agent' => $agent_id, - 'all_modules' => $all_modules - ); - $result = db_process_sql_insert('tplanned_downtime_agents', $values); - - if ($result && !$all_modules) { - foreach ($module_names as $module_name) { - $module = modules_get_agentmodule_id($module_name, $agent_id); - - if (empty($module)) - continue; - - $values = array( - 'id_downtime' => $id_downtime, - 'id_agent' => $agent_id, - 'id_agent_module' => $module["id_agente_modulo"] - ); - $result = db_process_sql_insert('tplanned_downtime_modules', $values); - - if ($result) { - $values = array('id_user' => $config['id_user']); - $result = db_process_sql_update('tplanned_downtime', - $values, array('id' => $id_downtime)); - } - } - } - } - } + if ($downtime_group === false || !in_array($downtime_group, $user_groups_ad)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + $agents = (array) get_parameter('id_agents'); + $module_names = (array) get_parameter('module'); + + $all_modules = (empty($module_names) || ($module_names[0] === '0')); + + // 'Is running' check + $is_running = (bool) db_get_value('executed', 'tplanned_downtime', 'id', $id_downtime); + if ($is_running) { + ui_print_error_message(__('This elements cannot be modified while the downtime is being executed')); + } else { + foreach ($agents as $agent_id) { + // check module belongs to the agent + if ($modules_selection_mode == 'all') { + $check = false; + foreach ($module_names as $module_name) { + $check_module = modules_get_agentmodule_id($module_name, $agent_id); + if (!empty($check_module)) { + $check = true; + } + } + + if (!$check) { + continue; + } + } + + // Check AD permission on agent + $agent_group = db_get_value('id_grupo', 'tagente', 'id_agente', $agent_id); + + if ($agent_group === false || !in_array($agent_group, $user_groups_ad)) { + continue; + } + + $values = [ + 'id_downtime' => $id_downtime, + 'id_agent' => $agent_id, + 'all_modules' => $all_modules, + ]; + $result = db_process_sql_insert('tplanned_downtime_agents', $values); + + if ($result && !$all_modules) { + foreach ($module_names as $module_name) { + $module = modules_get_agentmodule_id($module_name, $agent_id); + + if (empty($module)) { + continue; + } + + $values = [ + 'id_downtime' => $id_downtime, + 'id_agent' => $agent_id, + 'id_agent_module' => $module['id_agente_modulo'], + ]; + $result = db_process_sql_insert('tplanned_downtime_modules', $values); + + if ($result) { + $values = ['id_user' => $config['id_user']]; + $result = db_process_sql_update( + 'tplanned_downtime', + $values, + ['id' => $id_downtime] + ); + } + } + } + } + } } // DELETE A DOWNTIME_AGENT ASSOCIATION if ($delete_downtime_agent === 1) { - - $id_da = (int) get_parameter ('id_downtime_agent'); - - // Check AD permission on downtime - $downtime_group = db_get_value('id_group', 'tplanned_downtime', 'id', $id_downtime); - - if ($downtime_group === false || !in_array($downtime_group, $user_groups_ad)) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - // Check AD permission on agent - $agent_group = db_get_value('id_grupo', 'tagente', 'id_agente', $id_agent); - - if ($agent_group === false || !in_array($agent_group, $user_groups_ad)) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - // 'Is running' check - $is_running = (bool) db_get_value ('executed', 'tplanned_downtime', 'id', $id_downtime); - if ($is_running) { - ui_print_error_message(__("This elements cannot be modified while the downtime is being executed")); - } - else { - $row_to_delete = db_get_row('tplanned_downtime_agents', 'id', $id_da); - - $result = db_process_sql_delete('tplanned_downtime_agents', array('id' => $id_da)); - - if ($result) { - //Delete modules in downtime - db_process_sql_delete('tplanned_downtime_modules', - array('id_downtime' => $row_to_delete['id_downtime'], - 'id_agent' => $id_agent)); - } - } + $id_da = (int) get_parameter('id_downtime_agent'); + + // Check AD permission on downtime + $downtime_group = db_get_value('id_group', 'tplanned_downtime', 'id', $id_downtime); + + if ($downtime_group === false || !in_array($downtime_group, $user_groups_ad)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + // Check AD permission on agent + $agent_group = db_get_value('id_grupo', 'tagente', 'id_agente', $id_agent); + + if ($agent_group === false || !in_array($agent_group, $user_groups_ad)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + // 'Is running' check + $is_running = (bool) db_get_value('executed', 'tplanned_downtime', 'id', $id_downtime); + if ($is_running) { + ui_print_error_message(__('This elements cannot be modified while the downtime is being executed')); + } else { + $row_to_delete = db_get_row('tplanned_downtime_agents', 'id', $id_da); + + $result = db_process_sql_delete('tplanned_downtime_agents', ['id' => $id_da]); + + if ($result) { + // Delete modules in downtime + db_process_sql_delete( + 'tplanned_downtime_modules', + [ + 'id_downtime' => $row_to_delete['id_downtime'], + 'id_agent' => $id_agent, + ] + ); + } + } } // UPDATE OR CREATE A DOWNTIME (MAIN DATA, NOT AGENT ASSOCIATION) if ($create_downtime || $update_downtime) { - $check = (bool) db_get_value ('name', 'tplanned_downtime', 'name', $name); - - $datetime_from = strtotime ($once_date_from . ' ' . $once_time_from); - $datetime_to = strtotime ($once_date_to . ' ' . $once_time_to); - $now = time(); - - if ($type_execution == 'once' && !$config["past_planned_downtimes"] && $datetime_from < $now) { - ui_print_error_message(__('Not created. Error inserting data. Start time must be higher than the current time' )); - } - else if ($type_execution == 'once' && $datetime_from >= $datetime_to) { - ui_print_error_message(__('Not created. Error inserting data') . ". " .__('The end date must be higher than the start date')); - } - else if ($type_execution == 'once' && $datetime_to <= $now && !$config["past_planned_downtimes"]) { - ui_print_error_message(__('Not created. Error inserting data') . ". " .__('The end date must be higher than the current time')); - } - else if ($type_execution == 'periodically' - && (($type_periodicity == 'weekly' && $periodically_time_from >= $periodically_time_to) - || ($type_periodicity == 'monthly' && $periodically_day_from == $periodically_day_to && $periodically_time_from >= $periodically_time_to))) { - ui_print_error_message(__('Not created. Error inserting data') . ". " .__('The end time must be higher than the start time')); - } - else if ($type_execution == 'periodically' && $type_periodicity == 'monthly' && $periodically_day_from > $periodically_day_to) { - ui_print_error_message(__('Not created. Error inserting data') . ". " .__('The end day must be higher than the start day')); - } - else { - $sql = ''; - if ($create_downtime) { - - // Check AD permission on new downtime - if (!in_array($id_group, $user_groups_ad)) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - if (trim(io_safe_output($name)) != '') { - if (!$check) { - $values = array( - 'name' => $name, - 'description' => $description, - 'date_from' => $datetime_from, - 'date_to' => $datetime_to, - 'executed' => 0, - 'id_group' => $id_group, - 'only_alerts' => 0, - 'monday' => $monday, - 'tuesday' => $tuesday, - 'wednesday' => $wednesday, - 'thursday' => $thursday, - 'friday' => $friday, - 'saturday' => $saturday, - 'sunday' => $sunday, - 'periodically_time_from' => $periodically_time_from, - 'periodically_time_to' => $periodically_time_to, - 'periodically_day_from' => $periodically_day_from, - 'periodically_day_to' => $periodically_day_to, - 'type_downtime' => $type_downtime, - 'type_execution' => $type_execution, - 'type_periodicity' => $type_periodicity, - 'id_user' => $config['id_user'] - ); - if ($config["dbtype"] == 'oracle') { - $values['periodically_time_from'] = '1970/01/01 ' . $values['periodically_time_from']; - $values['periodically_time_to'] = '1970/01/01 ' . $values['periodically_time_to']; - } - - $result = db_process_sql_insert('tplanned_downtime', $values); - } - else { - ui_print_error_message( - __('Each planned downtime must have a different name')); - } - } - else { - ui_print_error_message( - __('Planned downtime must have a name')); - } - } - else if ($update_downtime) { - $old_downtime = db_get_row('tplanned_downtime', 'id', $id_downtime); - - // Check AD permission on OLD downtime - if (empty($old_downtime) || !in_array($old_downtime['id_group'], $user_groups_ad)) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - // Check AD permission on NEW downtime group - if (!in_array($id_group, $user_groups_ad)) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - // 'Is running' check - $is_running = (bool) $old_downtime['executed']; - - $values = array(); - if (trim(io_safe_output($name)) == '') { - ui_print_error_message(__('Planned downtime must have a name')); - } - // When running only certain items can be modified for the 'once' type - else if ($is_running && $type_execution == 'once') { - $values = array( - 'description' => $description, - 'date_to' => $datetime_to, - 'id_user' => $config['id_user'] - ); - } - else if ($is_running) { - ui_print_error_message(__('Cannot be modified while the downtime is being executed')); - } - else { - $values = array( - 'name' => $name, - 'description' => $description, - 'date_from' => $datetime_from, - 'date_to' => $datetime_to, - 'id_group' => $id_group, - 'only_alerts' => 0, - 'monday' => $monday, - 'tuesday' => $tuesday, - 'wednesday' => $wednesday, - 'thursday' => $thursday, - 'friday' => $friday, - 'saturday' => $saturday, - 'sunday' => $sunday, - 'periodically_time_from' => $periodically_time_from, - 'periodically_time_to' => $periodically_time_to, - 'periodically_day_from' => $periodically_day_from, - 'periodically_day_to' => $periodically_day_to, - 'type_downtime' => $type_downtime, - 'type_execution' => $type_execution, - 'type_periodicity' => $type_periodicity, - 'id_user' => $config['id_user'] - ); - if ($config["dbtype"] == 'oracle') { - $values['periodically_time_from'] = '1970/01/01 ' . $values['periodically_time_from']; - $values['periodically_time_to'] = '1970/01/01 ' . $values['periodically_time_to']; - } - } - if (!empty($values)) { - $result = db_process_sql_update('tplanned_downtime', $values, array('id' => $id_downtime)); - } - } - - if ($result === false) { - if ($create_downtime) { - ui_print_error_message(__('Could not be created')); - } - else { - ui_print_error_message(__('Could not be updated')); - } - } - else { - if ($create_downtime && $name && !$check) { - $id_downtime = $result; - ui_print_success_message(__('Successfully created')); - } - else if ($update_downtime && $name) { - ui_print_success_message(__('Successfully updated')); - } - } - } + $check = (bool) db_get_value('name', 'tplanned_downtime', 'name', $name); + + $datetime_from = strtotime($once_date_from.' '.$once_time_from); + $datetime_to = strtotime($once_date_to.' '.$once_time_to); + $now = time(); + + if ($type_execution == 'once' && !$config['past_planned_downtimes'] && $datetime_from < $now) { + ui_print_error_message(__('Not created. Error inserting data. Start time must be higher than the current time')); + } else if ($type_execution == 'once' && $datetime_from >= $datetime_to) { + ui_print_error_message(__('Not created. Error inserting data').'. '.__('The end date must be higher than the start date')); + } else if ($type_execution == 'once' && $datetime_to <= $now && !$config['past_planned_downtimes']) { + ui_print_error_message(__('Not created. Error inserting data').'. '.__('The end date must be higher than the current time')); + } else if ($type_execution == 'periodically' + && (($type_periodicity == 'weekly' && $periodically_time_from >= $periodically_time_to) + || ($type_periodicity == 'monthly' && $periodically_day_from == $periodically_day_to && $periodically_time_from >= $periodically_time_to)) + ) { + ui_print_error_message(__('Not created. Error inserting data').'. '.__('The end time must be higher than the start time')); + } else if ($type_execution == 'periodically' && $type_periodicity == 'monthly' && $periodically_day_from > $periodically_day_to) { + ui_print_error_message(__('Not created. Error inserting data').'. '.__('The end day must be higher than the start day')); + } else { + $sql = ''; + if ($create_downtime) { + // Check AD permission on new downtime + if (!in_array($id_group, $user_groups_ad)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + if (trim(io_safe_output($name)) != '') { + if (!$check) { + $values = [ + 'name' => $name, + 'description' => $description, + 'date_from' => $datetime_from, + 'date_to' => $datetime_to, + 'executed' => 0, + 'id_group' => $id_group, + 'only_alerts' => 0, + 'monday' => $monday, + 'tuesday' => $tuesday, + 'wednesday' => $wednesday, + 'thursday' => $thursday, + 'friday' => $friday, + 'saturday' => $saturday, + 'sunday' => $sunday, + 'periodically_time_from' => $periodically_time_from, + 'periodically_time_to' => $periodically_time_to, + 'periodically_day_from' => $periodically_day_from, + 'periodically_day_to' => $periodically_day_to, + 'type_downtime' => $type_downtime, + 'type_execution' => $type_execution, + 'type_periodicity' => $type_periodicity, + 'id_user' => $config['id_user'], + ]; + if ($config['dbtype'] == 'oracle') { + $values['periodically_time_from'] = '1970/01/01 '.$values['periodically_time_from']; + $values['periodically_time_to'] = '1970/01/01 '.$values['periodically_time_to']; + } + + $result = db_process_sql_insert('tplanned_downtime', $values); + } else { + ui_print_error_message( + __('Each planned downtime must have a different name') + ); + } + } else { + ui_print_error_message( + __('Planned downtime must have a name') + ); + } + } else if ($update_downtime) { + $old_downtime = db_get_row('tplanned_downtime', 'id', $id_downtime); + + // Check AD permission on OLD downtime + if (empty($old_downtime) || !in_array($old_downtime['id_group'], $user_groups_ad)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + // Check AD permission on NEW downtime group + if (!in_array($id_group, $user_groups_ad)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + // 'Is running' check + $is_running = (bool) $old_downtime['executed']; + + $values = []; + if (trim(io_safe_output($name)) == '') { + ui_print_error_message(__('Planned downtime must have a name')); + } + // When running only certain items can be modified for the 'once' type + else if ($is_running && $type_execution == 'once') { + $values = [ + 'description' => $description, + 'date_to' => $datetime_to, + 'id_user' => $config['id_user'], + ]; + } else if ($is_running) { + ui_print_error_message(__('Cannot be modified while the downtime is being executed')); + } else { + $values = [ + 'name' => $name, + 'description' => $description, + 'date_from' => $datetime_from, + 'date_to' => $datetime_to, + 'id_group' => $id_group, + 'only_alerts' => 0, + 'monday' => $monday, + 'tuesday' => $tuesday, + 'wednesday' => $wednesday, + 'thursday' => $thursday, + 'friday' => $friday, + 'saturday' => $saturday, + 'sunday' => $sunday, + 'periodically_time_from' => $periodically_time_from, + 'periodically_time_to' => $periodically_time_to, + 'periodically_day_from' => $periodically_day_from, + 'periodically_day_to' => $periodically_day_to, + 'type_downtime' => $type_downtime, + 'type_execution' => $type_execution, + 'type_periodicity' => $type_periodicity, + 'id_user' => $config['id_user'], + ]; + if ($config['dbtype'] == 'oracle') { + $values['periodically_time_from'] = '1970/01/01 '.$values['periodically_time_from']; + $values['periodically_time_to'] = '1970/01/01 '.$values['periodically_time_to']; + } + } + + if (!empty($values)) { + $result = db_process_sql_update('tplanned_downtime', $values, ['id' => $id_downtime]); + } + } + + if ($result === false) { + if ($create_downtime) { + ui_print_error_message(__('Could not be created')); + } else { + ui_print_error_message(__('Could not be updated')); + } + } else { + if ($create_downtime && $name && !$check) { + $id_downtime = $result; + ui_print_success_message(__('Successfully created')); + } else if ($update_downtime && $name) { + ui_print_success_message(__('Successfully updated')); + } + } + } } // Have any data to show ? if ($id_downtime > 0) { - // Columns of the table tplanned_downtime - $columns = array( - 'id', - 'name', - 'description', - 'date_from', - 'date_to', - 'executed', - 'id_group', - 'only_alerts', - 'monday', - 'tuesday', - 'wednesday', - 'thursday', - 'friday', - 'saturday', - 'sunday', - 'periodically_time_from', - 'periodically_time_to', - 'periodically_day_from', - 'periodically_day_to', - 'type_downtime', - 'type_execution', - 'type_periodicity', - 'id_user', - ); - - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $columns_str = implode(',', $columns); - $sql = "SELECT $columns_str - FROM tplanned_downtime - WHERE id = $id_downtime"; - break; - case "oracle": - // Oracle doesn't have TIME type, so we should transform the DATE value - $new_time_from = "TO_CHAR(periodically_time_from, 'HH24:MI:SS') AS periodically_time_from"; - $new_time_to = "TO_CHAR(periodically_time_to, 'HH24:MI:SS') AS periodically_time_to"; - - $time_from_key = array_search('periodically_time_from', $columns); - $time_to_key = array_search('periodically_time_to', $columns); - - if ($time_from_key !== false) - $columns[$time_from_key] = $new_time_from; - if ($time_to_key !== false) - $columns[$time_to_key] = $new_time_to; - - $columns_str = implode(',', $columns); - $sql = "SELECT $columns_str - FROM tplanned_downtime - WHERE id = $id_downtime"; - break; - } - - $result = db_get_row_sql ($sql); - - // Permission check for the downtime with the AD user groups - if (empty($result) || !in_array($result['id_group'], $user_groups_ad) ){ - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - $name = (string) $result["name"]; - $id_group = (int) $result['id_group']; + // Columns of the table tplanned_downtime + $columns = [ + 'id', + 'name', + 'description', + 'date_from', + 'date_to', + 'executed', + 'id_group', + 'only_alerts', + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday', + 'periodically_time_from', + 'periodically_time_to', + 'periodically_day_from', + 'periodically_day_to', + 'type_downtime', + 'type_execution', + 'type_periodicity', + 'id_user', + ]; - $description = (string) $result["description"]; - - $type_downtime = (string) $result['type_downtime']; - $type_execution = (string) $result['type_execution']; - $type_periodicity = (string) $result['type_periodicity']; - - $once_date_from = date(DATE_FORMAT, $result["date_from"]); - $once_date_to = date(DATE_FORMAT, $result["date_to"]); - $once_time_from = date(TIME_FORMAT, $result["date_from"]); - $once_time_to = date(TIME_FORMAT, $result["date_to"]); - - $periodically_time_from = (string) $result['periodically_time_from']; - $periodically_time_to = (string) $result['periodically_time_to']; - $periodically_day_from = (int) $result['periodically_day_from']; - $periodically_day_to = (int) $result['periodically_day_to']; - - $monday = (bool) $result['monday']; - $tuesday = (bool) $result['tuesday']; - $wednesday = (bool) $result['wednesday']; - $thursday = (bool) $result['thursday']; - $friday = (bool) $result['friday']; - $saturday = (bool) $result['saturday']; - $sunday = (bool) $result['sunday']; - - $running = (bool) $result['executed']; + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $columns_str = implode(',', $columns); + $sql = "SELECT $columns_str + FROM tplanned_downtime + WHERE id = $id_downtime"; + break; + + case 'oracle': + // Oracle doesn't have TIME type, so we should transform the DATE value + $new_time_from = "TO_CHAR(periodically_time_from, 'HH24:MI:SS') AS periodically_time_from"; + $new_time_to = "TO_CHAR(periodically_time_to, 'HH24:MI:SS') AS periodically_time_to"; + + $time_from_key = array_search('periodically_time_from', $columns); + $time_to_key = array_search('periodically_time_to', $columns); + + if ($time_from_key !== false) { + $columns[$time_from_key] = $new_time_from; + } + + if ($time_to_key !== false) { + $columns[$time_to_key] = $new_time_to; + } + + $columns_str = implode(',', $columns); + $sql = "SELECT $columns_str + FROM tplanned_downtime + WHERE id = $id_downtime"; + break; + } + + $result = db_get_row_sql($sql); + + // Permission check for the downtime with the AD user groups + if (empty($result) || !in_array($result['id_group'], $user_groups_ad)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + $name = (string) $result['name']; + $id_group = (int) $result['id_group']; + + $description = (string) $result['description']; + + $type_downtime = (string) $result['type_downtime']; + $type_execution = (string) $result['type_execution']; + $type_periodicity = (string) $result['type_periodicity']; + + $once_date_from = date(DATE_FORMAT, $result['date_from']); + $once_date_to = date(DATE_FORMAT, $result['date_to']); + $once_time_from = date(TIME_FORMAT, $result['date_from']); + $once_time_to = date(TIME_FORMAT, $result['date_to']); + + $periodically_time_from = (string) $result['periodically_time_from']; + $periodically_time_to = (string) $result['periodically_time_to']; + $periodically_day_from = (int) $result['periodically_day_from']; + $periodically_day_to = (int) $result['periodically_day_to']; + + $monday = (bool) $result['monday']; + $tuesday = (bool) $result['tuesday']; + $wednesday = (bool) $result['wednesday']; + $thursday = (bool) $result['thursday']; + $friday = (bool) $result['friday']; + $saturday = (bool) $result['saturday']; + $sunday = (bool) $result['sunday']; + + $running = (bool) $result['executed']; } // when the planned downtime is in execution, only action to postpone on once type is enabled and the other are disabled. @@ -493,204 +506,232 @@ $disabled_in_execution = (int) $running; $table = new StdClass(); $table->class = 'databox filters'; $table->width = '100%'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Name'); -$table->data[0][1] = html_print_input_text ('name', $name, '', 25, 40, true, $disabled_in_execution); +$table->data[0][1] = html_print_input_text('name', $name, '', 25, 40, true, $disabled_in_execution); $table->data[1][0] = __('Group'); $table->data[1][1] = html_print_select_groups(false, $access, true, 'id_group', $id_group, '', '', 0, true, false, true, '', $disabled_in_execution); $table->data[2][0] = __('Description'); -$table->data[2][1] = html_print_textarea ('description', 3, 35, $description, '', true); +$table->data[2][1] = html_print_textarea('description', 3, 35, $description, '', true); -$table->data[3][0] = __('Type').ui_print_help_tip(__("Quiet: Modules will not generate events or fire alerts.").'
    '. - __("Disable Agents: Disables the selected agents.").'
    '. - __("Disable Alerts: Disable alerts for the selected agents."), true); -$table->data[3][1] = html_print_select(array('quiet' => __('Quiet'), - 'disable_agents' => __('Disabled Agents'), - 'disable_agents_alerts' => __('Disabled only Alerts')), - 'type_downtime', $type_downtime, 'change_type_downtime()', '', 0, true, false, true, - '', $disabled_in_execution); +$table->data[3][0] = __('Type').ui_print_help_tip( + __('Quiet: Modules will not generate events or fire alerts.').'
    '.__('Disable Agents: Disables the selected agents.').'
    '.__('Disable Alerts: Disable alerts for the selected agents.'), + true +); +$table->data[3][1] = html_print_select( + [ + 'quiet' => __('Quiet'), + 'disable_agents' => __('Disabled Agents'), + 'disable_agents_alerts' => __('Disabled only Alerts'), + ], + 'type_downtime', + $type_downtime, + 'change_type_downtime()', + '', + 0, + true, + false, + true, + '', + $disabled_in_execution +); $table->data[4][0] = __('Execution'); -$table->data[4][1] = html_print_select(array('once' => __('Once'), - 'periodically' => __('Periodically')), - 'type_execution', $type_execution, 'change_type_execution();', '', 0, true, - false, true, '', $disabled_in_execution); +$table->data[4][1] = html_print_select( + [ + 'once' => __('Once'), + 'periodically' => __('Periodically'), + ], + 'type_execution', + $type_execution, + 'change_type_execution();', + '', + 0, + true, + false, + true, + '', + $disabled_in_execution +); $days = array_combine(range(1, 31), range(1, 31)); -$table->data[5][0] = __('Configure the time') . " " . ui_print_help_icon ('planned_downtime_time', true);; +$table->data[5][0] = __('Configure the time').' '.ui_print_help_icon('planned_downtime_time', true); +; $table->data[5][1] = " "; +
    '; echo '
    '; if ($id_downtime > 0) { - echo ""; - echo "
    "; + echo ''; + echo "
    "; } -//Editor form -html_print_table ($table); +// Editor form +html_print_table($table); -html_print_input_hidden ('id_agent', $id_agent); +html_print_input_hidden('id_agent', $id_agent); echo '
    '; if ($id_downtime > 0) { - html_print_input_hidden ('update_downtime', 1); - html_print_input_hidden ('id_downtime', $id_downtime); - html_print_submit_button (__('Update'), 'updbutton', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create_downtime', 1); - html_print_submit_button (__('Add'), 'crtbutton', false, 'class="sub wand"'); + html_print_input_hidden('update_downtime', 1); + html_print_input_hidden('id_downtime', $id_downtime); + html_print_submit_button(__('Update'), 'updbutton', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create_downtime', 1); + html_print_submit_button(__('Add'), 'crtbutton', false, 'class="sub wand"'); } + echo '
    '; echo ''; if ($id_downtime > 0) { - - echo "
    "; - - $filter_group = (int) get_parameter("filter_group", 0); - - // User AD groups to str for the filter - $id_groups_str = implode(",", $user_groups_ad); - - if (empty($id_groups_str)) { - // Restrictive filter on error. This will filter all the downtimes - $id_groups_str = '-1'; - } - - $filter_cond = ''; - if ($filter_group > 0){ - if($recursion){ - $rg = groups_get_id_recursive($filter_group, true); - $filter_cond .= " AND id_grupo IN ("; - - $i = 0; - $len = count($rg); - - foreach ($rg as $key) { - - if ($i == $len - 1) { - $filter_cond .= $key.")"; - }else{ - $i++; - $filter_cond .= $key.","; - } - } - - } - else{ - $filter_cond = " AND id_grupo = $filter_group "; - } - - } + echo ""; - $sql = sprintf("SELECT tagente.id_agente, tagente.alias + $filter_group = (int) get_parameter('filter_group', 0); + + // User AD groups to str for the filter + $id_groups_str = implode(',', $user_groups_ad); + + if (empty($id_groups_str)) { + // Restrictive filter on error. This will filter all the downtimes + $id_groups_str = '-1'; + } + + $filter_cond = ''; + if ($filter_group > 0) { + if ($recursion) { + $rg = groups_get_id_recursive($filter_group, true); + $filter_cond .= ' AND id_grupo IN ('; + + $i = 0; + $len = count($rg); + + foreach ($rg as $key) { + if ($i == ($len - 1)) { + $filter_cond .= $key.')'; + } else { + $i++; + $filter_cond .= $key.','; + } + } + } else { + $filter_cond = " AND id_grupo = $filter_group "; + } + } + + $sql = sprintf( + 'SELECT tagente.id_agente, tagente.alias FROM tagente WHERE tagente.id_agente NOT IN ( SELECT tagente.id_agente @@ -699,145 +740,165 @@ if ($id_downtime > 0) { AND tplanned_downtime_agents.id_downtime = %d ) AND disabled = 0 %s AND tagente.id_grupo IN (%s) - ORDER BY tagente.nombre", $id_downtime, $filter_cond, $id_groups_str); - $agents = db_get_all_rows_sql ($sql); - if (empty($agents)) - $agents = array(); - - $agent_ids = extract_column($agents, 'id_agente'); - $agent_names = extract_column($agents, 'alias'); - // item[] = ; - $agents = array_combine($agent_ids, $agent_names); - if ($agents === false) - $agents = array(); - - $disabled_add_button = false; - if (empty($agents) || $disabled_in_execution) { - $disabled_add_button = true; - } - - - 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, ''); - echo __('Recursion') . ' '; - echo "

    "; - html_print_submit_button (__('Filter by group'), '', false, 'class="sub next"',false); - echo "
    "; - // Show available agents to include into downtime - echo '

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

    '; - echo "
    "; - - echo html_print_select ($agents, "id_agents[]", -1, '', _("Any"), -2, false, true, true, '', false, 'width: 180px;'); - - if ($type_downtime != 'quiet'){ - echo '
    "; - - //Start Overview of existing planned downtime - echo '

    '.__('Agents planned for this downtime').':

    '; - - // User the $id_groups_str built before - $sql = sprintf("SELECT ta.nombre, tpda.id, + ORDER BY tagente.nombre', + $id_downtime, + $filter_cond, + $id_groups_str + ); + $agents = db_get_all_rows_sql($sql); + if (empty($agents)) { + $agents = []; + } + + $agent_ids = extract_column($agents, 'id_agente'); + $agent_names = extract_column($agents, 'alias'); + // item[] = ; + $agents = array_combine($agent_ids, $agent_names); + if ($agents === false) { + $agents = []; + } + + $disabled_add_button = false; + if (empty($agents) || $disabled_in_execution) { + $disabled_add_button = true; + } + + + 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, ''); + echo __('Recursion').' '; + echo '

    '; + html_print_submit_button(__('Filter by group'), '', false, 'class="sub next"', false); + echo '
    '; + // Show available agents to include into downtime + echo '

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

    '; + echo "
    "; + + echo html_print_select($agents, 'id_agents[]', -1, '', _('Any'), -2, false, true, true, '', false, 'width: 180px;'); + + if ($type_downtime != 'quiet') { + echo '
    '; + + // Start Overview of existing planned downtime + echo '

    '.__('Agents planned for this downtime').':

    '; + + // User the $id_groups_str built before + $sql = sprintf( + 'SELECT ta.nombre, tpda.id, ta.id_os, ta.id_agente, ta.id_grupo, ta.ultimo_contacto, tpda.all_modules FROM tagente ta INNER JOIN tplanned_downtime_agents tpda ON ta.id_agente = tpda.id_agent AND tpda.id_downtime = %d - WHERE ta.id_grupo IN (%s)", - $id_downtime, $id_groups_str); - $downtimes_agents = db_get_all_rows_sql ($sql); - - if (empty($downtimes_agents)) { - echo '
    ' . __('There are no agents') . '
    '; - } - else { - $table = new stdClass(); - $table->id = 'list'; - $table->class = 'databox data'; - $table->width = '100%'; - $table->data = array (); - $table->head = array (); - $table->head[0] = __('Name'); - $table->head[1] = __('Group'); - $table->head[2] = __('OS'); - $table->head[3] = __('Last contact'); - $table->head['count_modules'] = __('Modules'); - - if (!$running) { - $table->head[5] = __('Actions'); - $table->align[5] = "center"; - $table->size[5] = "5%"; - } - - foreach ($downtimes_agents as $downtime_agent) { - $data = array (); - - $alias = db_get_value("alias","tagente","id_agente",$downtime_agent['id_agente']); - $data[0] = $alias; - - $data[1] = db_get_sql ("SELECT nombre + WHERE ta.id_grupo IN (%s)', + $id_downtime, + $id_groups_str + ); + $downtimes_agents = db_get_all_rows_sql($sql); + + if (empty($downtimes_agents)) { + echo '
    '.__('There are no agents').'
    '; + } else { + $table = new stdClass(); + $table->id = 'list'; + $table->class = 'databox data'; + $table->width = '100%'; + $table->data = []; + $table->head = []; + $table->head[0] = __('Name'); + $table->head[1] = __('Group'); + $table->head[2] = __('OS'); + $table->head[3] = __('Last contact'); + $table->head['count_modules'] = __('Modules'); + + if (!$running) { + $table->head[5] = __('Actions'); + $table->align[5] = 'center'; + $table->size[5] = '5%'; + } + + foreach ($downtimes_agents as $downtime_agent) { + $data = []; + + $alias = db_get_value('alias', 'tagente', 'id_agente', $downtime_agent['id_agente']); + $data[0] = $alias; + + $data[1] = db_get_sql( + 'SELECT nombre FROM tgrupo - WHERE id_grupo = " . $downtime_agent["id_grupo"]); - - $data[2] = ui_print_os_icon($downtime_agent["id_os"], true, true); - - $data[3] = $downtime_agent["ultimo_contacto"]; - - if ($type_downtime == 'disable_agents_alerts') { - $data['count_modules'] = __("All alerts"); - } - elseif ($type_downtime == 'disable_agents') { - $data['count_modules'] = __("Entire agent"); - } - else { - if ($downtime_agent["all_modules"]) { - $data['count_modules'] = __("All modules"); - } - else { - $data['count_modules'] = __("Some modules"); - } - } - - if (!$running) { - $data[5] = ''; - if ($type_downtime != 'disable_agents_alerts' && $type_downtime != 'disable_agents') { - $data[5] = '' . - html_print_image("images/config.png", true, array("border" => '0', "alt" => __('Delete'))) . ""; - } - - $data[5] .= '' . - html_print_image("images/cross.png", true, array("border" => '0', "alt" => __('Delete'))) . ""; - } - - $table->data['agent_' . $downtime_agent["id_agente"]] = $data; - } - html_print_table ($table); - } + WHERE id_grupo = '.$downtime_agent['id_grupo'] + ); + + $data[2] = ui_print_os_icon($downtime_agent['id_os'], true, true); + + $data[3] = $downtime_agent['ultimo_contacto']; + + if ($type_downtime == 'disable_agents_alerts') { + $data['count_modules'] = __('All alerts'); + } else if ($type_downtime == 'disable_agents') { + $data['count_modules'] = __('Entire agent'); + } else { + if ($downtime_agent['all_modules']) { + $data['count_modules'] = __('All modules'); + } else { + $data['count_modules'] = __('Some modules'); + } + } + + if (!$running) { + $data[5] = ''; + if ($type_downtime != 'disable_agents_alerts' && $type_downtime != 'disable_agents') { + $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')]).''; + } + + $table->data['agent_'.$downtime_agent['id_agente']] = $data; + } + + html_print_table($table); + } } $table = new stdClass(); @@ -845,402 +906,407 @@ $table->id = 'loading'; $table->width = '100%'; $table->colspan['loading'][0] = '6'; $table->style[0] = 'text-align: center;'; -$table->data = array(); -$table->data['loading'] = array(); -$table->data['loading'][0] = html_print_image("images/spinner.gif", true); +$table->data = []; +$table->data['loading'] = []; +$table->data['loading'][0] = html_print_image('images/spinner.gif', true); echo "
    "; -html_print_table ($table); -echo "
    "; +html_print_table($table); +echo '
    '; $table = new stdClass(); $table->id = 'editor'; $table->width = '100%'; $table->colspan['module'][1] = '5'; -$table->data = array(); -$table->data['module'] = array(); +$table->data = []; +$table->data['module'] = []; $table->data['module'][0] = ''; -$table->data['module'][1] = "

    " . __('Modules') . "

    "; +$table->data['module'][1] = '

    '.__('Modules').'

    '; -//List of modules, empty, it is populated by javascript. +// List of modules, empty, it is populated by javascript. $table->data['module'][1] = " - - + + - + - - + + -
    " . __('Module') . "" . __('Action') . "".__('Module')."".__('Action')."
    " - . __("Add Module:") . ' ' - . html_print_select(array(), - 'modules', '', '', '', 0, true) - . "" - . '' - . "" - . "".__('Add Module:').' '.html_print_select( + [], + 'modules', + '', + '', + '', + 0, + true +)."".''."'.'
    "; + '; echo "
    "; -html_print_table ($table); -echo "
    "; +html_print_table($table); +echo '
    '; echo "
    "; echo "
    "; -html_print_image("images/spinner.gif"); -echo "
    "; -echo "
    "; +html_print_image('images/spinner.gif'); +echo '
    '; +echo ''; echo ""; +echo ''; echo ""; +echo ''; echo ""; +echo __('All modules'); +echo ''; ui_include_time_picker(); -ui_require_jquery_file("ui.datepicker-" . get_user_language(), "include/javascript/i18n/"); +ui_require_jquery_file('ui.datepicker-'.get_user_language(), 'include/javascript/i18n/'); ?> diff --git a/pandora_console/godmode/agentes/planned_downtime.export_csv.php b/pandora_console/godmode/agentes/planned_downtime.export_csv.php index bdac1eca41..605b00f95f 100644 --- a/pandora_console/godmode/agentes/planned_downtime.export_csv.php +++ b/pandora_console/godmode/agentes/planned_downtime.export_csv.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,22 +11,21 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Don't start a session before this import. // The session is configured and started inside the config process. -require_once ("../../include/config.php"); +require_once '../../include/config.php'; -require_once ("../../include/functions.php"); -require_once ("../../include/functions_db.php"); -require_once ("../../include/functions_users.php"); -require_once ("../../include/functions_groups.php"); -require_once ("../../include/functions_reporting.php"); +require_once '../../include/functions.php'; +require_once '../../include/functions_db.php'; +require_once '../../include/functions_users.php'; +require_once '../../include/functions_groups.php'; +require_once '../../include/functions_reporting.php'; -$config["id_user"] = $_SESSION["id_usuario"]; -if (! check_acl ($config['id_user'], 0, "AR")) { - db_pandora_audit("ACL Violation", "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; +$config['id_user'] = $_SESSION['id_usuario']; +if (! check_acl($config['id_user'], 0, 'AR')) { + db_pandora_audit('ACL Violation', 'Trying to access downtime scheduler'); + include 'general/noaccess.php'; + return; } // Filter parameters @@ -38,72 +36,72 @@ $date_to = (string) get_parameter('date_to'); $execution_type = (string) get_parameter('execution_type'); $show_archived = (bool) get_parameter('archived'); $agent_id = (int) get_parameter('agent_id'); -$agent_name = !empty($agent_id) ? (string) get_parameter('agent_name') : ""; +$agent_name = !empty($agent_id) ? (string) get_parameter('agent_name') : ''; $module_id = (int) get_parameter('module_name_hidden'); -$module_name = !empty($module_id) ? (string) get_parameter('module_name') : ""; +$module_name = !empty($module_id) ? (string) get_parameter('module_name') : ''; -$separator = (string) get_parameter("separator", ";"); -$items_separator = (string) get_parameter("items_separator", ","); +$separator = (string) get_parameter('separator', ';'); +$items_separator = (string) get_parameter('items_separator', ','); $groups = users_get_groups(); if (!empty($groups)) { - // SQL QUERY CREATION - $where_values = "1=1"; + // SQL QUERY CREATION + $where_values = '1=1'; - $groups_string = implode (",", array_keys ($groups)); - $where_values .= " AND id_group IN ($groups_string)"; + $groups_string = implode(',', array_keys($groups)); + $where_values .= " AND id_group IN ($groups_string)"; - if (!empty($search_text)) { - $where_values .= " AND (name LIKE '%$search_text%' OR description LIKE '%$search_text%')"; - } + if (!empty($search_text)) { + $where_values .= " AND (name LIKE '%$search_text%' OR description LIKE '%$search_text%')"; + } - if (!empty($execution_type)) { - $where_values .= " AND type_execution = '$execution_type'"; - } + if (!empty($execution_type)) { + $where_values .= " AND type_execution = '$execution_type'"; + } - if (!empty($date_from)) { - $where_values .= " AND (type_execution = 'periodically' OR (type_execution = 'once' AND date_from >= '".strtotime("$date_from 00:00:00")."'))"; - } + if (!empty($date_from)) { + $where_values .= " AND (type_execution = 'periodically' OR (type_execution = 'once' AND date_from >= '".strtotime("$date_from 00:00:00")."'))"; + } - if (!empty($date_to)) { - $periodically_monthly_w = "type_periodicity = 'monthly' + if (!empty($date_to)) { + $periodically_monthly_w = "type_periodicity = 'monthly' AND ((periodically_day_from <= '".date('d', strtotime($date_from))."' AND periodically_day_to >= '".date('d', strtotime($date_to))."') OR (periodically_day_from > periodically_day_to AND (periodically_day_from <= '".date('d', strtotime($date_from))."' OR periodically_day_to >= '".date('d', strtotime($date_to))."')))"; - - $periodically_weekly_days = array(); - $date_from_aux = strtotime($date_from); - $date_end = strtotime($date_to); - $days_number = 0; - while ($date_from_aux <= $date_end && $days_number < 7) { - $weekday_actual = strtolower(date('l', $date_from_aux)); - - $periodically_weekly_days[] = "$weekday_actual = 1"; + $periodically_weekly_days = []; + $date_from_aux = strtotime($date_from); + $date_end = strtotime($date_to); + $days_number = 0; - $date_from_aux = $date_from_aux + SECONDS_1DAY; - $days_number++; - } + while ($date_from_aux <= $date_end && $days_number < 7) { + $weekday_actual = strtolower(date('l', $date_from_aux)); - $periodically_weekly_w = "type_periodicity = 'weekly' AND (".implode(" OR ", $periodically_weekly_days).")"; - - $periodically_w = "type_execution = 'periodically' AND (($periodically_monthly_w) OR ($periodically_weekly_w))"; - - $once_w = "type_execution = 'once' AND date_to <= '".strtotime("$date_to 23:59:59")."'"; - - $where_values .= " AND (($periodically_w) OR ($once_w))"; - } + $periodically_weekly_days[] = "$weekday_actual = 1"; - if (!$show_archived) { - $where_values .= " AND (type_execution = 'periodically' OR (type_execution = 'once' AND date_to >= '".time()."'))"; - } + $date_from_aux = ($date_from_aux + SECONDS_1DAY); + $days_number++; + } - if (!empty($agent_id)) { - $where_values .= " AND id IN (SELECT id_downtime FROM tplanned_downtime_agents WHERE id_agent = $agent_id)"; - } + $periodically_weekly_w = "type_periodicity = 'weekly' AND (".implode(' OR ', $periodically_weekly_days).')'; - if (!empty($module_id)) { - $where_values .= " AND (id IN (SELECT id_downtime + $periodically_w = "type_execution = 'periodically' AND (($periodically_monthly_w) OR ($periodically_weekly_w))"; + + $once_w = "type_execution = 'once' AND date_to <= '".strtotime("$date_to 23:59:59")."'"; + + $where_values .= " AND (($periodically_w) OR ($once_w))"; + } + + if (!$show_archived) { + $where_values .= " AND (type_execution = 'periodically' OR (type_execution = 'once' AND date_to >= '".time()."'))"; + } + + if (!empty($agent_id)) { + $where_values .= " AND id IN (SELECT id_downtime FROM tplanned_downtime_agents WHERE id_agent = $agent_id)"; + } + + if (!empty($module_id)) { + $where_values .= " AND (id IN (SELECT id_downtime FROM tplanned_downtime_modules WHERE id_agent_module = $module_id) OR id IN (SELECT id_downtime @@ -111,92 +109,92 @@ if (!empty($groups)) { WHERE tpda.id_agent = tam.id_agente AND tam.id_agente_modulo = $module_id AND tpda.all_modules = 1))"; - } + } - $sql = "SELECT * + $sql = "SELECT * FROM tplanned_downtime WHERE $where_values ORDER BY type_execution DESC, date_from DESC"; - $downtimes = @db_get_all_rows_sql($sql); + $downtimes = @db_get_all_rows_sql($sql); } if (!empty($downtimes)) { - ob_clean(); - // Show contentype header - Header("Content-type: text/csv"); - header('Content-Disposition: attachment; filename="pandora_planned_downtime_'.date("Y/m/d H:i:s").'.csv"'); + ob_clean(); + // Show contentype header + header('Content-type: text/csv'); + header('Content-Disposition: attachment; filename="pandora_planned_downtime_'.date('Y/m/d H:i:s').'.csv"'); - $titles = array(); - $titles[] = "id"; - $titles[] = "name"; - $titles[] = "description"; - $titles[] = "group"; - $titles[] = "type"; - $titles[] = "execution_type"; - $titles[] = "execution_date"; - $titles[] = "affected_items"; + $titles = []; + $titles[] = 'id'; + $titles[] = 'name'; + $titles[] = 'description'; + $titles[] = 'group'; + $titles[] = 'type'; + $titles[] = 'execution_type'; + $titles[] = 'execution_date'; + $titles[] = 'affected_items'; - echo implode($separator, $titles); - echo chr(13); + echo implode($separator, $titles); + echo chr(13); - foreach ($downtimes as $downtime) { - $id = $downtime['id']; - $name = io_safe_output($downtime['name']); - $description = io_safe_output($downtime['description']); - $group = ucfirst(io_safe_output(groups_get_name($downtime['id_group']))); - $type = ucfirst(io_safe_output($downtime['type_downtime'])); - $execution_type = ucfirst(io_safe_output($downtime['type_execution'])); - - $execution_date = io_safe_output(reporting_format_planned_downtime_dates($downtime)); + foreach ($downtimes as $downtime) { + $id = $downtime['id']; + $name = io_safe_output($downtime['name']); + $description = io_safe_output($downtime['description']); + $group = ucfirst(io_safe_output(groups_get_name($downtime['id_group']))); + $type = ucfirst(io_safe_output($downtime['type_downtime'])); + $execution_type = ucfirst(io_safe_output($downtime['type_execution'])); - $affected_items = array(); + $execution_date = io_safe_output(reporting_format_planned_downtime_dates($downtime)); - $sql_agents = "SELECT tpda.id_agent AS agent_id, tpda.all_modules AS all_modules, ta.nombre AS agent_name, ta.alias + $affected_items = []; + + $sql_agents = "SELECT tpda.id_agent AS agent_id, tpda.all_modules AS all_modules, ta.nombre AS agent_name, ta.alias FROM tplanned_downtime_agents tpda, tagente ta WHERE tpda.id_downtime = $id AND tpda.id_agent = ta.id_agente"; - $downtime_agents = @db_get_all_rows_sql($sql_agents); + $downtime_agents = @db_get_all_rows_sql($sql_agents); - if (!empty($downtime_agents)) { - foreach ($downtime_agents as $downtime_agent) { - $downtime_items = array(); - $downtime_items[] = $downtime_agent[alias]; + if (!empty($downtime_agents)) { + foreach ($downtime_agents as $downtime_agent) { + $downtime_items = []; + $downtime_items[] = $downtime_agent[alias]; - if (!$downtime_agent['all_modules']) { - $agent_id = $downtime_agent['agent_id']; - $sql_modules = "SELECT tpdm.id_agent_module AS module_id, tam.nombre AS module_name + if (!$downtime_agent['all_modules']) { + $agent_id = $downtime_agent['agent_id']; + $sql_modules = "SELECT tpdm.id_agent_module AS module_id, tam.nombre AS module_name FROM tplanned_downtime_modules tpdm, tagente_modulo tam WHERE tpdm.id_downtime = $id AND tpdm.id_agent = $agent_id AND tpdm.id_agent_module = tam.id_agente_modulo"; - $downtime_modules = @db_get_all_rows_sql($sql_modules); + $downtime_modules = @db_get_all_rows_sql($sql_modules); - if (!empty($downtime_modules)) { - foreach ($downtime_modules as $downtime_module) { - $downtime_items[] = $downtime_module['module_name']; - } - } - } - $affected_items[] = "[".implode("|", $downtime_items)."]"; - } - } - $affected_items = implode(",", $affected_items); + if (!empty($downtime_modules)) { + foreach ($downtime_modules as $downtime_module) { + $downtime_items[] = $downtime_module['module_name']; + } + } + } - $values = array(); - $values[] = $id; - $values[] = $name; - $values[] = $description; - $values[] = $group; - $values[] = $type; - $values[] = $execution_type; - $values[] = $execution_date; - $values[] = $affected_items; + $affected_items[] = '['.implode('|', $downtime_items).']'; + } + } - echo implode($separator, $values); - echo chr(13); - } + $affected_items = implode(',', $affected_items); + + $values = []; + $values[] = $id; + $values[] = $name; + $values[] = $description; + $values[] = $group; + $values[] = $type; + $values[] = $execution_type; + $values[] = $execution_date; + $values[] = $affected_items; + + echo implode($separator, $values); + echo chr(13); + } +} else { + echo '
    '.__('No planned downtime').'
    '; } -else { - echo '
    '.__('No planned downtime').'
    '; -} -?> \ No newline at end of file diff --git a/pandora_console/godmode/agentes/planned_downtime.list.php b/pandora_console/godmode/agentes/planned_downtime.list.php index 0e42cb3930..790944b472 100755 --- a/pandora_console/godmode/agentes/planned_downtime.list.php +++ b/pandora_console/godmode/agentes/planned_downtime.list.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,116 +11,123 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; check_login(); -$read_permisson = check_acl ($config['id_user'], 0, "AR"); -$write_permisson = check_acl ($config['id_user'], 0, "AD"); -$manage_permisson = check_acl ($config['id_user'], 0, "AW"); +$read_permisson = check_acl($config['id_user'], 0, 'AR'); +$write_permisson = check_acl($config['id_user'], 0, 'AD'); +$manage_permisson = check_acl($config['id_user'], 0, 'AW'); $access = ($read_permisson == true) ? 'AR' : (($write_permisson == true) ? 'AD' : (($manage_permisson == true) ? 'AW' : 'AR')); if (! $read_permisson && !$manage_permisson) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_users.php'); -require_once ('include/functions_events.php'); -require_once ('include/functions_planned_downtimes.php'); -require_once ('include/functions_reporting.php'); +require_once 'include/functions_users.php'; +require_once 'include/functions_events.php'; +require_once 'include/functions_planned_downtimes.php'; +require_once 'include/functions_reporting.php'; $malformed_downtimes = planned_downtimes_get_malformed(); $malformed_downtimes_exist = !empty($malformed_downtimes) ? true : false; -$migrate_malformed = (bool) get_parameter("migrate_malformed"); +$migrate_malformed = (bool) get_parameter('migrate_malformed'); if ($migrate_malformed) { - $migration_result = planned_downtimes_migrate_malformed_downtimes(); + $migration_result = planned_downtimes_migrate_malformed_downtimes(); - if ($migration_result['status'] == false) { - ui_print_error_message(__('An error occurred while migrating the malformed planned downtimes') . ". " - . __('Please run the migration again or contact with the administrator')); - echo "
    "; - } + if ($migration_result['status'] == false) { + ui_print_error_message( + __('An error occurred while migrating the malformed planned downtimes').'. '.__('Please run the migration again or contact with the administrator') + ); + echo '
    '; + } } // Header ui_print_page_header( - __("Planned Downtime"), - "images/gm_monitoring.png", - false, - "planned_downtime", - true, - ""); + __('Planned Downtime'), + 'images/gm_monitoring.png', + false, + 'planned_downtime', + true, + '' +); -$id_downtime = (int) get_parameter ('id_downtime', 0); +$id_downtime = (int) get_parameter('id_downtime', 0); -$stop_downtime = (bool) get_parameter ('stop_downtime'); +$stop_downtime = (bool) get_parameter('stop_downtime'); // STOP DOWNTIME if ($stop_downtime) { - $downtime = db_get_row('tplanned_downtime', 'id', $id_downtime); - - // Check AD permission on the downtime - if (empty($downtime) || (! check_acl ($config['id_user'], $downtime['id_group'], "AD") && ! check_acl ($config['id_user'], $downtime['id_group'], "AW"))) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - $result = planned_downtimes_stop($downtime); - - if ($result === false) { - ui_print_error_message(__('An error occurred stopping the planned downtime')); - } - else { - echo $result['message']; - } + $downtime = db_get_row('tplanned_downtime', 'id', $id_downtime); + + // Check AD permission on the downtime + if (empty($downtime) || (! check_acl($config['id_user'], $downtime['id_group'], 'AD') && ! check_acl($config['id_user'], $downtime['id_group'], 'AW'))) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + $result = planned_downtimes_stop($downtime); + + if ($result === false) { + ui_print_error_message(__('An error occurred stopping the planned downtime')); + } else { + echo $result['message']; + } } -$delete_downtime = (int) get_parameter ('delete_downtime'); +$delete_downtime = (int) get_parameter('delete_downtime'); // DELETE WHOLE DOWNTIME! if ($delete_downtime) { - $downtime = db_get_row('tplanned_downtime', 'id', $id_downtime); - - // Check AD permission on the downtime - if (empty($downtime) || (! check_acl ($config['id_user'], $downtime['id_group'], "AD") && ! check_acl ($config['id_user'], $downtime['id_group'], "AW"))) { - db_pandora_audit("ACL Violation", - "Trying to access downtime scheduler"); - require ("general/noaccess.php"); - return; - } - - // The downtime shouldn't be running!! - if ($downtime['executed']) { - ui_print_error_message(__('This planned downtime is running')); - } - else { - $result = db_process_sql_delete('tplanned_downtime', array('id' => $id_downtime)); - - ui_print_result_message($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); - } + $downtime = db_get_row('tplanned_downtime', 'id', $id_downtime); + + // Check AD permission on the downtime + if (empty($downtime) || (! check_acl($config['id_user'], $downtime['id_group'], 'AD') && ! check_acl($config['id_user'], $downtime['id_group'], 'AW'))) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access downtime scheduler' + ); + include 'general/noaccess.php'; + return; + } + + // The downtime shouldn't be running!! + if ($downtime['executed']) { + ui_print_error_message(__('This planned downtime is running')); + } else { + $result = db_process_sql_delete('tplanned_downtime', ['id' => $id_downtime]); + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); + } } // Filter parameters $offset = (int) get_parameter('offset'); -$filter_params = array(); +$filter_params = []; -$search_text = $filter_params['search_text'] = (string) get_parameter('search_text'); -$date_from = $filter_params['date_from'] = (string) get_parameter('date_from'); -$date_to = $filter_params['date_to'] = (string) get_parameter('date_to'); -$execution_type = $filter_params['execution_type'] = (string) get_parameter('execution_type'); -$show_archived = $filter_params['archived'] = (bool) get_parameter('archived'); -$agent_id = $filter_params['agent_id'] = (int) get_parameter('agent_id'); -$agent_name = $filter_params['agent_name'] = (string) (!empty($agent_id) ? get_parameter('agent_name') : ''); -$module_id = $filter_params['module_id'] = (int) get_parameter('module_name_hidden'); -$module_name = $filter_params['module_name'] = (string) (!empty($module_id) ? get_parameter('module_name') : ''); +$search_text = $filter_params['search_text'] = (string) get_parameter('search_text'); +$date_from = $filter_params['date_from'] = (string) get_parameter('date_from'); +$date_to = $filter_params['date_to'] = (string) get_parameter('date_to'); +$execution_type = $filter_params['execution_type'] = (string) get_parameter('execution_type'); +$show_archived = $filter_params['archived'] = (bool) get_parameter('archived'); +$agent_id = $filter_params['agent_id'] = (int) get_parameter('agent_id'); +$agent_name = $filter_params['agent_name'] = (string) (!empty($agent_id) ? get_parameter('agent_name') : ''); +$module_id = $filter_params['module_id'] = (int) get_parameter('module_name_hidden'); +$module_name = $filter_params['module_name'] = (string) (!empty($module_id) ? get_parameter('module_name') : ''); $filter_params_str = http_build_query($filter_params); @@ -129,38 +135,41 @@ $filter_params_str = http_build_query($filter_params); $table_form = new StdClass(); $table_form->class = 'databox filters'; $table_form->width = '100%'; -$table_form->rowstyle = array(); -$table_form->rowstyle[0] = "background-color: #f9faf9;"; -$table_form->rowstyle[1] = "background-color: #f9faf9;"; -$table_form->rowstyle[2] = "background-color: #f9faf9;"; -$table_form->data = array(); +$table_form->rowstyle = []; +$table_form->rowstyle[0] = 'background-color: #f9faf9;'; +$table_form->rowstyle[1] = 'background-color: #f9faf9;'; +$table_form->rowstyle[2] = 'background-color: #f9faf9;'; +$table_form->data = []; -$row = array(); +$row = []; // Search text -$row[] = __('Search') . ' ' . html_print_input_text("search_text", $search_text, '', 50, 250, true); +$row[] = __('Search').' '.html_print_input_text('search_text', $search_text, '', 50, 250, true); // Dates -$date_inputs = __('From') . ' ' . html_print_input_text('date_from', $date_from, '', 10, 10, true); -$date_inputs .= "  "; -$date_inputs .= __('To') . ' ' . html_print_input_text('date_to', $date_to, '', 10, 10, true); +$date_inputs = __('From').' '.html_print_input_text('date_from', $date_from, '', 10, 10, true); +$date_inputs .= '  '; +$date_inputs .= __('To').' '.html_print_input_text('date_to', $date_to, '', 10, 10, true); $row[] = $date_inputs; $table_form->data[] = $row; -$row = array(); +$row = []; // Execution type -$execution_type_fields = array('once' => __('Once'), 'periodically' => __('Periodically')); -$row[] = __('Execution type') . ' ' . html_print_select($execution_type_fields, 'execution_type', $execution_type, '', __('Any'), '', true, false, false); +$execution_type_fields = [ + 'once' => __('Once'), + 'periodically' => __('Periodically'), +]; +$row[] = __('Execution type').' '.html_print_select($execution_type_fields, 'execution_type', $execution_type, '', __('Any'), '', true, false, false); // Show past downtimes -$row[] = __('Show past downtimes') . ' ' . html_print_checkbox ("archived", 1, $show_archived, true); +$row[] = __('Show past downtimes').' '.html_print_checkbox('archived', 1, $show_archived, true); $table_form->data[] = $row; -$row = array(); +$row = []; // Agent -$params = array(); +$params = []; $params['show_helptip'] = true; $params['input_name'] = 'agent_name'; $params['value'] = $agent_name; @@ -168,94 +177,92 @@ $params['return'] = true; $params['print_hidden_input_idagent'] = true; $params['hidden_input_idagent_name'] = 'agent_id'; $params['hidden_input_idagent_value'] = $agent_id; -$agent_input = __('Agent') . ' ' . ui_print_agent_autocomplete_input($params); +$agent_input = __('Agent').' '.ui_print_agent_autocomplete_input($params); $row[] = $agent_input; // Module -$row[] = __('Module') . ' ' . html_print_autocomplete_modules('module_name', $module_name, false, true, '', array(), true); +$row[] = __('Module').' '.html_print_autocomplete_modules('module_name', $module_name, false, true, '', [], true); $row[] = html_print_submit_button(__('Search'), 'search', false, 'class="sub search"', true); $table_form->data[] = $row; // End of table filter - // Useful to know if the user has done a form filtering $filter_performed = false; -$groups = users_get_groups (false, $access); +$groups = users_get_groups(false, $access); if (!empty($groups)) { - $where_values = "1=1"; + $where_values = '1=1'; - $groups_string = implode (",", array_keys ($groups)); - $where_values .= " AND id_group IN ($groups_string)"; - - // WARNING: add $filter_performed = true; to any future filter + $groups_string = implode(',', array_keys($groups)); + $where_values .= " AND id_group IN ($groups_string)"; - if (!empty($search_text)) { - $filter_performed = true; - - $where_values .= " AND (name LIKE '%$search_text%' OR description LIKE '%$search_text%')"; - } + // WARNING: add $filter_performed = true; to any future filter + if (!empty($search_text)) { + $filter_performed = true; - if (!empty($execution_type)) { - $filter_performed = true; - - $where_values .= " AND type_execution = '$execution_type'"; - } + $where_values .= " AND (name LIKE '%$search_text%' OR description LIKE '%$search_text%')"; + } - if (!empty($date_from)) { - $filter_performed = true; - - $where_values .= " AND (type_execution = 'periodically' OR (type_execution = 'once' AND date_from >= '".strtotime("$date_from 00:00:00")."'))"; - } + if (!empty($execution_type)) { + $filter_performed = true; - if (!empty($date_to)) { - $filter_performed = true; - - $periodically_monthly_w = "type_periodicity = 'monthly' + $where_values .= " AND type_execution = '$execution_type'"; + } + + if (!empty($date_from)) { + $filter_performed = true; + + $where_values .= " AND (type_execution = 'periodically' OR (type_execution = 'once' AND date_from >= '".strtotime("$date_from 00:00:00")."'))"; + } + + if (!empty($date_to)) { + $filter_performed = true; + + $periodically_monthly_w = "type_periodicity = 'monthly' AND ((periodically_day_from <= '".date('d', strtotime($date_from))."' AND periodically_day_to >= '".date('d', strtotime($date_to))."') OR (periodically_day_from > periodically_day_to AND (periodically_day_from <= '".date('d', strtotime($date_from))."' OR periodically_day_to >= '".date('d', strtotime($date_to))."')))"; - - $periodically_weekly_days = array(); - $date_from_aux = strtotime($date_from); - $date_end = strtotime($date_to); - $days_number = 0; - while ($date_from_aux <= $date_end && $days_number < 7) { - $weekday_actual = strtolower(date('l', $date_from_aux)); - - $periodically_weekly_days[] = "$weekday_actual = 1"; + $periodically_weekly_days = []; + $date_from_aux = strtotime($date_from); + $date_end = strtotime($date_to); + $days_number = 0; - $date_from_aux = $date_from_aux + SECONDS_1DAY; - $days_number++; - } + while ($date_from_aux <= $date_end && $days_number < 7) { + $weekday_actual = strtolower(date('l', $date_from_aux)); - $periodically_weekly_w = "type_periodicity = 'weekly' AND (".implode(" OR ", $periodically_weekly_days).")"; - - $periodically_w = "type_execution = 'periodically' AND (($periodically_monthly_w) OR ($periodically_weekly_w))"; - - $once_w = "type_execution = 'once' AND date_to <= '".strtotime("$date_to 23:59:59")."'"; - - $where_values .= " AND (($periodically_w) OR ($once_w))"; - } + $periodically_weekly_days[] = "$weekday_actual = 1"; - if (!$show_archived) { - $filter_performed = true; - - $where_values .= " AND (type_execution = 'periodically' OR (type_execution = 'once' AND date_to >= '".time()."'))"; - } + $date_from_aux = ($date_from_aux + SECONDS_1DAY); + $days_number++; + } - if (!empty($agent_id)) { - $filter_performed = true; - - $where_values .= " AND id IN (SELECT id_downtime FROM tplanned_downtime_agents WHERE id_agent = $agent_id)"; - } + $periodically_weekly_w = "type_periodicity = 'weekly' AND (".implode(' OR ', $periodically_weekly_days).')'; - if (!empty($module_id)) { - $filter_performed = true; - - $where_values .= " AND (id IN (SELECT id_downtime + $periodically_w = "type_execution = 'periodically' AND (($periodically_monthly_w) OR ($periodically_weekly_w))"; + + $once_w = "type_execution = 'once' AND date_to <= '".strtotime("$date_to 23:59:59")."'"; + + $where_values .= " AND (($periodically_w) OR ($once_w))"; + } + + if (!$show_archived) { + $filter_performed = true; + + $where_values .= " AND (type_execution = 'periodically' OR (type_execution = 'once' AND date_to >= '".time()."'))"; + } + + if (!empty($agent_id)) { + $filter_performed = true; + + $where_values .= " AND id IN (SELECT id_downtime FROM tplanned_downtime_agents WHERE id_agent = $agent_id)"; + } + + if (!empty($module_id)) { + $filter_performed = true; + + $where_values .= " AND (id IN (SELECT id_downtime FROM tplanned_downtime_modules WHERE id_agent_module = $module_id) OR id IN (SELECT id_downtime @@ -263,285 +270,301 @@ if (!empty($groups)) { WHERE tpda.id_agent = tam.id_agente AND tam.id_agente_modulo = $module_id AND tpda.all_modules = 1))"; - } - - // Columns of the table tplanned_downtime - $columns = array( - 'id', - 'name', - 'description', - 'date_from', - 'date_to', - 'executed', - 'id_group', - 'only_alerts', - 'monday', - 'tuesday', - 'wednesday', - 'thursday', - 'friday', - 'saturday', - 'sunday', - 'periodically_time_from', - 'periodically_time_to', - 'periodically_day_from', - 'periodically_day_to', - 'type_downtime', - 'type_execution', - 'type_periodicity', - 'id_user', - ); - - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $columns_str = implode(',', $columns); - $sql = "SELECT $columns_str + } + + // Columns of the table tplanned_downtime + $columns = [ + 'id', + 'name', + 'description', + 'date_from', + 'date_to', + 'executed', + 'id_group', + 'only_alerts', + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday', + 'periodically_time_from', + 'periodically_time_to', + 'periodically_day_from', + 'periodically_day_to', + 'type_downtime', + 'type_execution', + 'type_periodicity', + 'id_user', + ]; + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $columns_str = implode(',', $columns); + $sql = "SELECT $columns_str FROM tplanned_downtime WHERE $where_values ORDER BY type_execution DESC, date_from DESC - LIMIT ".$config["block_size"]." + LIMIT ".$config['block_size']." OFFSET $offset"; - break; - case "oracle": - // Oracle doesn't have TIME type, so we should transform the DATE value - $new_time_from = "TO_CHAR(periodically_time_from, 'HH24:MI:SS') AS periodically_time_from"; - $new_time_to = "TO_CHAR(periodically_time_to, 'HH24:MI:SS') AS periodically_time_to"; - - $time_from_key = array_search('periodically_time_from', $columns); - $time_to_key = array_search('periodically_time_to', $columns); - - if ($time_from_key !== false) - $columns[$time_from_key] = $new_time_from; - if ($time_to_key !== false) - $columns[$time_to_key] = $new_time_to; - - $columns_str = implode(',', $columns); - - $set = array (); - $set['limit'] = $config["block_size"]; - $set['offset'] = $offset; - - $sql = "SELECT $columns_str + break; + + case 'oracle': + // Oracle doesn't have TIME type, so we should transform the DATE value + $new_time_from = "TO_CHAR(periodically_time_from, 'HH24:MI:SS') AS periodically_time_from"; + $new_time_to = "TO_CHAR(periodically_time_to, 'HH24:MI:SS') AS periodically_time_to"; + + $time_from_key = array_search('periodically_time_from', $columns); + $time_to_key = array_search('periodically_time_to', $columns); + + if ($time_from_key !== false) { + $columns[$time_from_key] = $new_time_from; + } + + if ($time_to_key !== false) { + $columns[$time_to_key] = $new_time_to; + } + + $columns_str = implode(',', $columns); + + $set = []; + $set['limit'] = $config['block_size']; + $set['offset'] = $offset; + + $sql = "SELECT $columns_str FROM tplanned_downtime WHERE $where_values ORDER BY type_execution DESC, date_from DESC"; - - $sql = oracle_recode_query ($sql, $set); - break; - } - $sql_count = "SELECT COUNT(id) AS num + $sql = oracle_recode_query($sql, $set); + break; + } + + $sql_count = "SELECT COUNT(id) AS num FROM tplanned_downtime WHERE $where_values"; - - $downtimes = db_get_all_rows_sql ($sql); - $downtimes_number_res = db_get_all_rows_sql($sql_count); - $downtimes_number = $downtimes_number_res != false ? $downtimes_number_res[0]['num'] : 0; -} -else { - $downtimes = array(); + + $downtimes = db_get_all_rows_sql($sql); + $downtimes_number_res = db_get_all_rows_sql($sql_count); + $downtimes_number = $downtimes_number_res != false ? $downtimes_number_res[0]['num'] : 0; +} else { + $downtimes = []; } // No downtimes cause the user has not anyone if (!$downtimes && !$filter_performed) { - require_once ($config['homedir'] . "/general/firts_task/planned_downtime.php"); + include_once $config['homedir'].'/general/firts_task/planned_downtime.php'; } // No downtimes cause the user performed a search else if (!$downtimes) { - // Filter form - echo "
    "; - html_print_table($table_form); - echo "
    "; - - // Info message - echo '
    '.__('No planned downtime').'
    '; - - echo '
    '; + // Filter form + echo "
    "; + html_print_table($table_form); + echo '
    '; - // Create button - if ($write_permisson) { - echo ' '; - echo '
    '; - html_print_submit_button (__('Create'), 'create', false, 'class="sub next"'); - echo '
    '; - } - - echo '
    '; + // Info message + echo '
    '.__('No planned downtime').'
    '; + + echo '
    '; + + // Create button + if ($write_permisson) { + echo ' '; + echo '
    '; + html_print_submit_button(__('Create'), 'create', false, 'class="sub next"'); + echo '
    '; + } + + echo '
    '; } // Has downtimes else { - 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); - - // User groups with AR, AD or AW permission - $groupsAD = users_get_groups($config['id_user'], $access); - $groupsAD = array_keys($groupsAD); - - // View available downtimes present in database (if any of them) - $table = new StdClass(); - $table->class = 'databox data'; - $table->width = '100%'; - $table->cellstyle = array(); - - $table->head = array(); - $table->head['name'] = __('Name #Ag.'); - $table->head['description'] = __('Description'); - $table->head['group'] = __('Group'); - $table->head['type'] = __('Type'); - $table->head['execution'] = __('Execution'); - $table->head['configuration'] = __('Configuration'); - $table->head['running'] = __('Running'); - - if ($write_permisson || $manage_permisson) { - $table->head['stop'] = __('Stop downtime'); - $table->head['edit'] = __('Edit'); - $table->head['delete'] = __('Delete'); - } - - $table->align = array(); - $table->align['group'] = "center"; - $table->align['running'] = "center"; - - if ($write_permisson || $manage_permisson) { - $table->align['stop'] = "center"; - $table->align['edit'] = "center"; - $table->align['delete'] = "center"; - } - - $table->data = array(); - - foreach ($downtimes as $downtime) { - $data = array(); - $total = db_get_sql ("SELECT COUNT(id_agent) + 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); + + // User groups with AR, AD or AW permission + $groupsAD = users_get_groups($config['id_user'], $access); + $groupsAD = array_keys($groupsAD); + + // View available downtimes present in database (if any of them) + $table = new StdClass(); + $table->class = 'databox data'; + $table->width = '100%'; + $table->cellstyle = []; + + $table->head = []; + $table->head['name'] = __('Name #Ag.'); + $table->head['description'] = __('Description'); + $table->head['group'] = __('Group'); + $table->head['type'] = __('Type'); + $table->head['execution'] = __('Execution'); + $table->head['configuration'] = __('Configuration'); + $table->head['running'] = __('Running'); + + if ($write_permisson || $manage_permisson) { + $table->head['stop'] = __('Stop downtime'); + $table->head['edit'] = __('Edit'); + $table->head['delete'] = __('Delete'); + } + + $table->align = []; + $table->align['group'] = 'center'; + $table->align['running'] = 'center'; + + if ($write_permisson || $manage_permisson) { + $table->align['stop'] = 'center'; + $table->align['edit'] = 'center'; + $table->align['delete'] = 'center'; + } + + $table->data = []; + + foreach ($downtimes as $downtime) { + $data = []; + $total = db_get_sql( + 'SELECT COUNT(id_agent) FROM tplanned_downtime_agents - WHERE id_downtime = ".$downtime["id"]); - - $data['name'] = $downtime['name']. " ($total)"; - $data['description'] = $downtime['description']; - $data['group'] = ui_print_group_icon ($downtime['id_group'], true); - - $type_text = array('quiet' => __('Quiet'), - 'disable_agents' => __('Disabled Agents'), - 'disable_agents_alerts' => __('Disabled only Alerts')); - - $data['type'] = $type_text[$downtime['type_downtime']]; - - $execution_text = array('once' => __('once'), - 'periodically' => __('Periodically')); - - $data['execution'] = $execution_text[$downtime['type_execution']]; - - $data['configuration'] = reporting_format_planned_downtime_dates($downtime); - - if ($downtime["executed"] == 0) { - $data['running'] = html_print_image ("images/pixel_red.png", true, - array ('width' => 20, 'height' => 20, 'title' => __('Not running'))); - } - else { - $data['running'] = html_print_image ("images/pixel_green.png", true, - array ('width' => 20, 'height' => 20, 'title' => __('Running'))); - } - - // If user have writting permissions - 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, array("title" => __('Stop downtime'))); - } - else { - $data['stop'] = ""; - } - - // Edit & delete buttons - if ($downtime["executed"] == 0) { - // Edit - $data['edit'] = '' . - html_print_image("images/config.png", true, array("title" => __('Update'))) . ''; - // Delete - $data['delete'] = '' . - html_print_image("images/cross.png", true, array("title" => __('Delete'))); - } - else if ($downtime["executed"] == 1 && $downtime['type_execution'] == 'once') { - // Edit - $data['edit'] = '' . - html_print_image("images/config.png", true, array("title" => __('Update'))) . ''; - // Delete - $data['delete']= __('N/A'); - } - else { - $data['edit']= ''; - $data['delete']= ''; - } - } - else { - $data['stop'] = ''; - $data['edit'] = ''; - $data['delete'] = ''; - } + WHERE id_downtime = '.$downtime['id'] + ); - if (!empty($malformed_downtimes_exist) && isset($malformed_downtimes[$downtime['id']])) { - $next_row_num = count($table->data); - $table->cellstyle[$next_row_num][0] = 'color: red'; - $table->cellstyle[$next_row_num][1] = 'color: red'; - $table->cellstyle[$next_row_num][3] = 'color: red'; - $table->cellstyle[$next_row_num][4] = 'color: red'; - $table->cellstyle[$next_row_num][5] = 'color: red'; - } + $data['name'] = $downtime['name']." ($total)"; + $data['description'] = $downtime['description']; + $data['group'] = ui_print_group_icon($downtime['id_group'], true); - array_push ($table->data, $data); - } - - html_print_table ($table); - echo '
    '; + $type_text = [ + 'quiet' => __('Quiet'), + 'disable_agents' => __('Disabled Agents'), + 'disable_agents_alerts' => __('Disabled only Alerts'), + ]; - echo '
    '; - // CSV export button - echo '
    '; - html_print_button(__('Export to CSV'), 'csv_export', false, - "location.href='godmode/agentes/planned_downtime.export_csv.php?$filter_params_str'", 'class="sub next"'); - echo '
    '; - - // Create button - if ($write_permisson) { - echo ' '; - echo '
    '; - html_print_submit_button (__('Create'), 'create', false, 'class="sub next"'); - echo '
    '; - } - - echo '
    '; + $data['type'] = $type_text[$downtime['type_downtime']]; + + $execution_text = [ + 'once' => __('once'), + 'periodically' => __('Periodically'), + ]; + + $data['execution'] = $execution_text[$downtime['type_execution']]; + + $data['configuration'] = reporting_format_planned_downtime_dates($downtime); + + if ($downtime['executed'] == 0) { + $data['running'] = html_print_image( + 'images/pixel_red.png', + true, + [ + 'width' => 20, + 'height' => 20, + 'title' => __('Not running'), + ] + ); + } else { + $data['running'] = html_print_image( + 'images/pixel_green.png', + true, + [ + 'width' => 20, + 'height' => 20, + 'title' => __('Running'), + ] + ); + } + + // If user have writting permissions + 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')]); + } else { + $data['stop'] = ''; + } + + // Edit & delete buttons + if ($downtime['executed'] == 0) { + // Edit + $data['edit'] = ''.html_print_image('images/config.png', true, ['title' => __('Update')]).''; + // 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')]).''; + // Delete + $data['delete'] = __('N/A'); + } else { + $data['edit'] = ''; + $data['delete'] = ''; + } + } else { + $data['stop'] = ''; + $data['edit'] = ''; + $data['delete'] = ''; + } + + if (!empty($malformed_downtimes_exist) && isset($malformed_downtimes[$downtime['id']])) { + $next_row_num = count($table->data); + $table->cellstyle[$next_row_num][0] = 'color: red'; + $table->cellstyle[$next_row_num][1] = 'color: red'; + $table->cellstyle[$next_row_num][3] = 'color: red'; + $table->cellstyle[$next_row_num][4] = 'color: red'; + $table->cellstyle[$next_row_num][5] = 'color: red'; + } + + array_push($table->data, $data); + } + + html_print_table($table); + echo '
    '; + + echo '
    '; + // CSV export button + echo '
    '; + html_print_button( + __('Export to CSV'), + 'csv_export', + false, + "location.href='godmode/agentes/planned_downtime.export_csv.php?$filter_params_str'", + 'class="sub next"' + ); + echo '
    '; + + // Create button + if ($write_permisson) { + echo ' '; + echo '
    '; + html_print_submit_button(__('Create'), 'create', false, 'class="sub next"'); + echo '
    '; + } + + echo '
    '; } -ui_require_jquery_file("ui.datepicker-" . get_user_language(), "include/javascript/i18n/"); +ui_require_jquery_file('ui.datepicker-'.get_user_language(), 'include/javascript/i18n/'); ?> diff --git a/pandora_console/godmode/alerts/alert_actions.php b/pandora_console/godmode/alerts/alert_actions.php index a1ae9afca5..6140d5407a 100644 --- a/pandora_console/godmode/alerts/alert_actions.php +++ b/pandora_console/godmode/alerts/alert_actions.php @@ -1,10 +1,9 @@ -width = '100%'; $table->class = 'databox data'; -$table->data = array (); -$table->head = array (); +$table->data = []; +$table->head = []; $table->head[0] = __('Name'); $table->head[1] = __('Group'); $table->head[2] = __('Copy'); $table->head[3] = __('Delete'); -$table->style = array (); +$table->style = []; $table->style[0] = 'font-weight: bold'; -$table->size = array (); +$table->size = []; $table->size[1] = '200px'; $table->size[2] = '40px'; $table->size[3] = '40px'; -$table->align = array (); +$table->align = []; $table->align[1] = 'left'; $table->align[2] = 'left'; $table->align[3] = 'left'; -$filter = array(); -if (!is_user_admin($config['id_user'])) - $filter['talert_actions.id_group'] = array_keys(users_get_groups(false, "LM")); +$filter = []; +if (!is_user_admin($config['id_user'])) { + $filter['talert_actions.id_group'] = array_keys(users_get_groups(false, 'LM')); +} -$actions = db_get_all_rows_filter ( - 'talert_actions INNER JOIN talert_commands ON talert_actions.id_alert_command = talert_commands.id', - $filter, - 'talert_actions.* , talert_commands.id_group AS command_group' +$actions = db_get_all_rows_filter( + 'talert_actions INNER JOIN talert_commands ON talert_actions.id_alert_command = talert_commands.id', + $filter, + 'talert_actions.* , talert_commands.id_group AS command_group' ); -if ($actions === false) - $actions = array (); +if ($actions === false) { + $actions = []; +} $rowPair = true; $iterator = 0; foreach ($actions as $action) { - if ($rowPair) - $table->rowclass[$iterator] = 'rowPair'; - else - $table->rowclass[$iterator] = 'rowOdd'; - $rowPair = !$rowPair; - $iterator++; - - $data = array (); + if ($rowPair) { + $table->rowclass[$iterator] = 'rowPair'; + } else { + $table->rowclass[$iterator] = 'rowOdd'; + } - $data[0] = ''. - $action['name'].''; - $data[1] = ui_print_group_icon ($action["id_group"], true) .' '; - if (!alerts_validate_command_to_action($action["id_group"], $action["command_group"])) { - $data[1].= html_print_image( - "images/error.png", - true, - // FIXME: Translation. - array("title" => __("The action and the command associated with it do not have the same group. Please contact an administrator to fix it.") - )); - } + $rowPair = !$rowPair; + $iterator++; - if (check_acl($config['id_user'], $action["id_group"], "LM")) { - $data[2] = '' . - html_print_image("images/copy.png", true) . ''; - $data[3] = ''. - html_print_image("images/cross.png", true) . ''; - } + $data = []; - array_push ($table->data, $data); + $data[0] = ''.$action['name'].''; + $data[1] = ui_print_group_icon($action['id_group'], true).' '; + if (!alerts_validate_command_to_action($action['id_group'], $action['command_group'])) { + $data[1] .= html_print_image( + 'images/error.png', + true, + // FIXME: Translation. + [ + 'title' => __('The action and the command associated with it do not have the same group. Please contact an administrator to fix it.'), + ] + ); + } + + if (check_acl($config['id_user'], $action['id_group'], 'LM')) { + $data[2] = ''.html_print_image('images/copy.png', true).''; + $data[3] = ''.html_print_image('images/cross.png', true).''; + } + + array_push($table->data, $data); } + if (isset($data)) { - html_print_table ($table); -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('No alert actions configured') ) ); + html_print_table($table); +} else { + ui_print_info_message(['no_close' => true, 'message' => __('No alert actions configured') ]); } echo '
    '; echo '
    '; -html_print_submit_button (__('Create'), 'create', false, 'class="sub next"'); -html_print_input_hidden ('create_alert', 1); +html_print_submit_button(__('Create'), 'create', false, 'class="sub next"'); +html_print_input_hidden('create_alert', 1); echo '
    '; echo '
    '; enterprise_hook('close_meta_frame'); - -?> diff --git a/pandora_console/godmode/alerts/alert_commands.php b/pandora_console/godmode/alerts/alert_commands.php index 3f890e1190..455ae72d73 100644 --- a/pandora_console/godmode/alerts/alert_commands.php +++ b/pandora_console/godmode/alerts/alert_commands.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,408 +11,449 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars global $config; -require_once ($config['homedir'] . "/include/functions_alerts.php"); -enterprise_include_once ('meta/include/functions_alerts_meta.php'); +require_once $config['homedir'].'/include/functions_alerts.php'; +enterprise_include_once('meta/include/functions_alerts_meta.php'); -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "LM")) { - db_pandora_audit("ACL Violation", - "Trying to access Alert Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'LM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Alert Management' + ); + include 'general/noaccess.php'; + exit; } -if (is_metaconsole()) - $sec = 'advanced'; -else - $sec = 'galertas'; +if (is_metaconsole()) { + $sec = 'advanced'; +} else { + $sec = 'galertas'; +} -$pure = (int)get_parameter('pure', 0); -$update_command = (bool) get_parameter ('update_command'); -$create_command = (bool) get_parameter ('create_command'); -$delete_command = (bool) get_parameter ('delete_command'); -$copy_command = (bool) get_parameter ('copy_command'); +$pure = (int) get_parameter('pure', 0); +$update_command = (bool) get_parameter('update_command'); +$create_command = (bool) get_parameter('create_command'); +$delete_command = (bool) get_parameter('delete_command'); +$copy_command = (bool) get_parameter('copy_command'); -if (is_ajax ()) { - $get_alert_command = (bool) get_parameter ('get_alert_command'); - if ($get_alert_command) { - $id = (int) get_parameter ('id', 0); - $get_recovery_fields = (int) get_parameter('get_recovery_fields', 1); - - // If command ID is not provided, check for action id - if ($id == 0) { - $id_action = (int) get_parameter ('id_action'); - $id = alerts_get_alert_action_alert_command_id($id_action); - } - - $command = alerts_get_alert_command ($id); - - // If is setted a description, we change the carriage return by
    tags - if (isset($command['description'])) { - $command['description'] = io_safe_input(str_replace("\r\n","
    ", io_safe_output($command['description']))); - } - // Descriptions are stored in json - $fields_descriptions = empty($command['fields_descriptions']) ? - '' : json_decode(io_safe_output($command['fields_descriptions']), true); - // Fields values are stored in json - $fields_values = empty($command['fields_values']) ? - '' : io_safe_output(json_decode($command['fields_values'], true)); +if (is_ajax()) { + $get_alert_command = (bool) get_parameter('get_alert_command'); + if ($get_alert_command) { + $id = (int) get_parameter('id', 0); + $get_recovery_fields = (int) get_parameter('get_recovery_fields', 1); - $fields_rows = array(); - for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + // If command ID is not provided, check for action id + if ($id == 0) { + $id_action = (int) get_parameter('id_action'); + $id = alerts_get_alert_action_alert_command_id($id_action); + } - if (($i == 5) && ($command['id'] == 3)){ - continue; - } + $command = alerts_get_alert_command($id); - $field_description = $fields_descriptions[$i - 1]; - $field_value = $fields_values[$i - 1]; - - if (!empty($field_description)) { - //If the value is 5, this because severity in snmp alerts is not permit to show - if (($i > 5) && ($command['id'] == 3)){ - $fdesc = $field_description . - '
    ' . sprintf(__('Field %s'), $i - 1) . ''; - } - else{ - $fdesc = $field_description . - '
    ' . sprintf(__('Field %s'), $i) . ''; - } - //If the field is the number one, print the help message - if ($i == 1) { - // If our context is snmpconsole, show snmp_alert helps - if ((isset ($_SERVER["HTTP_REFERER"])) && ( preg_match ("/snmp_alert/", $_SERVER["HTTP_REFERER"]) > 0 )){ - $fdesc .= ui_print_help_icon ('snmp_alert_field1',true); + // If is setted a description, we change the carriage return by
    tags + if (isset($command['description'])) { + $command['description'] = io_safe_input(str_replace("\r\n", '
    ', io_safe_output($command['description']))); + } + + // Descriptions are stored in json + $fields_descriptions = empty($command['fields_descriptions']) ? '' : json_decode(io_safe_output($command['fields_descriptions']), true); + // Fields values are stored in json + $fields_values = empty($command['fields_values']) ? '' : io_safe_output(json_decode($command['fields_values'], true)); + + $fields_rows = []; + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + if (($i == 5) && ($command['id'] == 3)) { + continue; + } + + $field_description = $fields_descriptions[($i - 1)]; + $field_value = $fields_values[($i - 1)]; + + if (!empty($field_description)) { + // If the value is 5, this because severity in snmp alerts is not permit to show + if (($i > 5) && ($command['id'] == 3)) { + $fdesc = $field_description.'
    '.sprintf(__('Field %s'), ($i - 1)).''; + } else { + $fdesc = $field_description.'
    '.sprintf(__('Field %s'), $i).''; + } + + // If the field is the number one, print the help message + if ($i == 1) { + // If our context is snmpconsole, show snmp_alert helps + if ((isset($_SERVER['HTTP_REFERER'])) && ( preg_match('/snmp_alert/', $_SERVER['HTTP_REFERER']) > 0 )) { + $fdesc .= ui_print_help_icon('snmp_alert_field1', true); + } else { + $fdesc .= ui_print_help_icon('alert_config', true); } - else { - $fdesc .= ui_print_help_icon ('alert_config', true); + } + } else { + // If the macro hasn't description and doesnt appear in command, set with empty description to dont show it + if (($i > 5) && ($command['id'] == 3)) { + if (substr_count($command['command'], '_field'.($i - 1).'_') > 0) { + $fdesc = sprintf(__('Field %s'), ($i - 1)); + } else { + $fdesc = ''; } + } else { + if (substr_count($command['command'], '_field'.$i.'_') > 0) { + $fdesc = sprintf(__('Field %s'), $i); + } else { + $fdesc = ''; + } + } + } - } - } - else { - // If the macro hasn't description and doesnt appear in command, set with empty description to dont show it - if (($i > 5) && ($command['id'] == 3)){ - if (substr_count($command['command'], "_field" . $i - 1 . "_") > 0) { - $fdesc = sprintf(__('Field %s'), $i - 1); - } - else { - $fdesc = ''; - } - } - else{ - if (substr_count($command['command'], "_field" . $i . "_") > 0) { - $fdesc = sprintf(__('Field %s'), $i); - } - else { - $fdesc = ''; - } - } - } - - if (!empty($field_value)) { - $field_value = io_safe_output($field_value); - // HTML type - if (preg_match ("/^_html_editor_$/i", $field_value)) { - - $editor_type_chkbx = "
    "; - $editor_type_chkbx .= __('Basic') . ui_print_help_tip (__("For sending emails, text must be HTML format, if you want to use plain text, type it between the following labels:
    "), true);
    -					$editor_type_chkbx .= html_print_radio_button_extended ('editor_type_value_'.$i, 0, '', false, false, "removeTinyMCE('textarea_field".$i."_value')", '', true);
    -					$editor_type_chkbx .= "    ";
    -					$editor_type_chkbx .= __('Advanced') . "  ";
    -					$editor_type_chkbx .= html_print_radio_button_extended ('editor_type_value_'.$i, 0, '', true, false, "addTinyMCE('textarea_field".$i."_value')", '', true);
    -					$editor_type_chkbx .= "
    "; - $ffield = $editor_type_chkbx; - $ffield .= html_print_textarea ('field'.$i.'_value', 1, 1, '', 'class="fields"', true); - - $editor_type_chkbx = "
    "; - $editor_type_chkbx .= __('Basic') . "  "; - $editor_type_chkbx .= html_print_radio_button_extended ('editor_type_recovery_value_'.$i, 0, '', false, false, "removeTinyMCE('textarea_field".$i."_recovery_value')", '', true); - $editor_type_chkbx .= "    "; - $editor_type_chkbx .= __('Advanced') . "  "; - $editor_type_chkbx .= html_print_radio_button_extended ('editor_type_recovery_value_'.$i, 0, '', true, false, "addTinyMCE('textarea_field".$i."_recovery_value')", '', true); - $editor_type_chkbx .= "
    "; - $rfield = $editor_type_chkbx; - $rfield .= html_print_textarea ('field'.$i.'_recovery_value', 1, 1, '', 'class="fields_recovery"', true); - } - elseif(preg_match ("/^_content_type_$/i", $field_value)){ - $editor_type_chkbx = "
    "; - $editor_type_chkbx .= __('Text/plain') . ui_print_help_tip (__("For sending emails only text plain"), true); - $editor_type_chkbx .= html_print_radio_button_extended ('field'.$i.'_value', 'text/plain', '', '', false, '', '', true); - $editor_type_chkbx .= "    "; - $editor_type_chkbx .= __('Text/html') . "  "; - $editor_type_chkbx .= html_print_radio_button_extended ('field'.$i.'_value', 'text/html', '', 'text/html', false, '', '', true); - $editor_type_chkbx .= "
    "; - $ffield = $editor_type_chkbx; + if (!empty($field_value)) { + $field_value = io_safe_output($field_value); + // HTML type + if (preg_match('/^_html_editor_$/i', $field_value)) { + $editor_type_chkbx = '
    '; + $editor_type_chkbx .= __('Basic').ui_print_help_tip(__('For sending emails, text must be HTML format, if you want to use plain text, type it between the following labels:
    '), true);
    +                    $editor_type_chkbx .= html_print_radio_button_extended('editor_type_value_'.$i, 0, '', false, false, "removeTinyMCE('textarea_field".$i."_value')", '', true);
    +                    $editor_type_chkbx .= '    ';
    +                    $editor_type_chkbx .= __('Advanced').'  ';
    +                    $editor_type_chkbx .= html_print_radio_button_extended('editor_type_value_'.$i, 0, '', true, false, "addTinyMCE('textarea_field".$i."_value')", '', true);
    +                    $editor_type_chkbx .= '
    '; + $ffield = $editor_type_chkbx; + $ffield .= html_print_textarea('field'.$i.'_value', 1, 1, '', 'class="fields"', true); - $editor_type_chkbx = "
    "; - $editor_type_chkbx .= __('Text/plain') . ui_print_help_tip (__("For sending emails only text plain"), true); - $editor_type_chkbx .= html_print_radio_button_extended ('field'.$i.'_recovery_value', 'text/plain', '', '', false, '', '', true); - $editor_type_chkbx .= "    "; - $editor_type_chkbx .= __('Text/html') . "  "; - $editor_type_chkbx .= html_print_radio_button_extended ('field'.$i.'_recovery_value', 'text/html', '', 'text/html', false, '', '', true); - $editor_type_chkbx .= "
    "; - $rfield = $editor_type_chkbx; - // Select type - }else { - $fields_value_select = array(); - $fv = explode(';', $field_value); - - if (count($fv) > 1) { - if (!empty($fv)) { - foreach ($fv as $fv_option) { - $fv_option = explode(',', $fv_option); - - if (empty($fv_option)) - continue; - - if (!isset($fv_option[1])) - $fv_option[1] = $fv_option[0]; - - $fields_value_select[$fv_option[0]] = $fv_option[1]; - } - } - - $ffield = html_print_select($fields_value_select, - 'field'.$i.'_value', '', '', '', 0, true, false, false, 'fields'); - $rfield = html_print_select($fields_value_select, - 'field'.$i.'_recovery_value', '', '', '', 0, true, false, false, 'fields_recovery'); - } - else { - $ffield = html_print_textarea ('field' . $i . '_value',1, 1, $fv[0], - 'style="min-height:40px" class="fields"', true); - $rfield = html_print_textarea ('field' . $i . '_recovery_value', 1, 1, $fv[0], - 'style="min-height:40px" class="fields_recovery"', true); - } - } - } - else { - $ffield = html_print_textarea ('field' . $i . '_value', - 1, 1, '', 'style="min-height:40px" class="fields"', true); - $rfield = html_print_textarea ( - 'field' . $i . '_recovery_value', 1, 1, '', - 'style="min-height:40px" class="fields_recovery"', true); - } - - - // The empty descriptions will be ignored - if ($fdesc == '') { - $fields_rows[$i] = ''; - } - else { - $fields_rows[$i] = - ''; - $fields_rows[$i] .= '' . $fdesc . ''; - $fields_rows[$i] .= '' . $ffield . ''; - if ($get_recovery_fields) { - $fields_rows[$i] .= '' . $rfield . ''; - } - $fields_rows[$i] .= ''; - } - } + $editor_type_chkbx = '
    '; + $editor_type_chkbx .= __('Basic').'  '; + $editor_type_chkbx .= html_print_radio_button_extended('editor_type_recovery_value_'.$i, 0, '', false, false, "removeTinyMCE('textarea_field".$i."_recovery_value')", '', true); + $editor_type_chkbx .= '    '; + $editor_type_chkbx .= __('Advanced').'  '; + $editor_type_chkbx .= html_print_radio_button_extended('editor_type_recovery_value_'.$i, 0, '', true, false, "addTinyMCE('textarea_field".$i."_recovery_value')", '', true); + $editor_type_chkbx .= '
    '; + $rfield = $editor_type_chkbx; + $rfield .= html_print_textarea('field'.$i.'_recovery_value', 1, 1, '', 'class="fields_recovery"', true); + } else if (preg_match('/^_content_type_$/i', $field_value)) { + $editor_type_chkbx = '
    '; + $editor_type_chkbx .= __('Text/plain').ui_print_help_tip(__('For sending emails only text plain'), true); + $editor_type_chkbx .= html_print_radio_button_extended('field'.$i.'_value', 'text/plain', '', '', false, '', '', true); + $editor_type_chkbx .= '    '; + $editor_type_chkbx .= __('Text/html').'  '; + $editor_type_chkbx .= html_print_radio_button_extended('field'.$i.'_value', 'text/html', '', 'text/html', false, '', '', true); + $editor_type_chkbx .= '
    '; + $ffield = $editor_type_chkbx; - //If command is PandoraFMS event, field 5 must be empty because "severity" must be set by the alert - if ($command['id'] == 3){ - $fields_rows[5] = ''; - } + $editor_type_chkbx = '
    '; + $editor_type_chkbx .= __('Text/plain').ui_print_help_tip(__('For sending emails only text plain'), true); + $editor_type_chkbx .= html_print_radio_button_extended('field'.$i.'_recovery_value', 'text/plain', '', '', false, '', '', true); + $editor_type_chkbx .= '    '; + $editor_type_chkbx .= __('Text/html').'  '; + $editor_type_chkbx .= html_print_radio_button_extended('field'.$i.'_recovery_value', 'text/html', '', 'text/html', false, '', '', true); + $editor_type_chkbx .= '
    '; + $rfield = $editor_type_chkbx; + // Select type + } else { + $fields_value_select = []; + $fv = explode(';', $field_value); - $command['fields_rows'] = $fields_rows; - - echo json_encode ($command); - } - return; + if (count($fv) > 1) { + if (!empty($fv)) { + foreach ($fv as $fv_option) { + $fv_option = explode(',', $fv_option); + + if (empty($fv_option)) { + continue; + } + + if (!isset($fv_option[1])) { + $fv_option[1] = $fv_option[0]; + } + + $fields_value_select[$fv_option[0]] = $fv_option[1]; + } + } + + $ffield = html_print_select( + $fields_value_select, + 'field'.$i.'_value', + '', + '', + '', + 0, + true, + false, + false, + 'fields' + ); + $rfield = html_print_select( + $fields_value_select, + 'field'.$i.'_recovery_value', + '', + '', + '', + 0, + true, + false, + false, + 'fields_recovery' + ); + } else { + $ffield = html_print_textarea( + 'field'.$i.'_value', + 1, + 1, + $fv[0], + 'style="min-height:40px" class="fields"', + true + ); + $rfield = html_print_textarea( + 'field'.$i.'_recovery_value', + 1, + 1, + $fv[0], + 'style="min-height:40px" class="fields_recovery"', + true + ); + } + } + } else { + $ffield = html_print_textarea( + 'field'.$i.'_value', + 1, + 1, + '', + 'style="min-height:40px" class="fields"', + true + ); + $rfield = html_print_textarea( + 'field'.$i.'_recovery_value', + 1, + 1, + '', + 'style="min-height:40px" class="fields_recovery"', + true + ); + } + + + // The empty descriptions will be ignored + if ($fdesc == '') { + $fields_rows[$i] = ''; + } else { + $fields_rows[$i] = ''; + $fields_rows[$i] .= ''.$fdesc.''; + $fields_rows[$i] .= ''.$ffield.''; + if ($get_recovery_fields) { + $fields_rows[$i] .= ''.$rfield.''; + } + + $fields_rows[$i] .= ''; + } + } + + // If command is PandoraFMS event, field 5 must be empty because "severity" must be set by the alert + if ($command['id'] == 3) { + $fields_rows[5] = ''; + } + + $command['fields_rows'] = $fields_rows; + + echo json_encode($command); + } + + return; } enterprise_hook('open_meta_frame'); if ($update_command) { - require_once("configure_alert_command.php"); - return; + include_once 'configure_alert_command.php'; + return; } // Header -if (defined('METACONSOLE')) - alerts_meta_print_header(); -else - ui_print_page_header (__('Alerts').' » '.__('Alert commands'), "images/gm_alerts.png", false, "alerts_config", true); +if (defined('METACONSOLE')) { + alerts_meta_print_header(); +} else { + ui_print_page_header(__('Alerts').' » '.__('Alert commands'), 'images/gm_alerts.png', false, 'alerts_config', true); +} if ($create_command) { - $name = (string) get_parameter ('name'); - $command = (string) get_parameter ('command'); - $description = (string) get_parameter ('description'); - $id_group = (string) get_parameter ('id_group', 0); - - $fields_descriptions = array(); - $fields_values = array(); - $info_fields = ''; - $values = array(); - for ($i=1;$i<=$config['max_macro_fields'];$i++) { - $fields_descriptions[] = (string) get_parameter ('field'.$i.'_description'); - $fields_values[] = (string) get_parameter ('field'.$i.'_values'); - $info_fields .= ' Field'.$i.': ' . $fields_values[$i - 1]; - } - - $values['fields_values'] = io_json_mb_encode($fields_values); - $values['fields_descriptions'] = io_json_mb_encode($fields_descriptions); - $values['description'] = $description; - $values['id_group'] = $id_group; + $name = (string) get_parameter('name'); + $command = (string) get_parameter('command'); + $description = (string) get_parameter('description'); + $id_group = (string) get_parameter('id_group', 0); - $name_check = db_get_value ('name', 'talert_commands', 'name', $name); - - if (!$name_check) { - $result = alerts_create_alert_command ($name, $command, - $values); - - $info = '{"Name":"'.$name.'","Command":"'.$command.'","Description":"'.$description. ' '.$info_fields.'"}'; - } - else { - $result = ''; - } - - if ($result) { - db_pandora_audit("Command management", "Create alert command #" . $result, false, false, $info); - } - else { - db_pandora_audit("Command management", "Fail try to create alert command", false, false); - } - - /* Show errors */ - if (!isset($messageAction)) { - $messageAction = __('Could not be created'); - } - - if ($name == "") { - $messageAction = __('No name specified'); - } + $fields_descriptions = []; + $fields_values = []; + $info_fields = ''; + $values = []; + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + $fields_descriptions[] = (string) get_parameter('field'.$i.'_description'); + $fields_values[] = (string) get_parameter('field'.$i.'_values'); + $info_fields .= ' Field'.$i.': '.$fields_values[($i - 1)]; + } - if ($command == "") { - $messageAction = __('No command specified'); - } + $values['fields_values'] = io_json_mb_encode($fields_values); + $values['fields_descriptions'] = io_json_mb_encode($fields_descriptions); + $values['description'] = $description; + $values['id_group'] = $id_group; - $messageAction = ui_print_result_message ($result, - __('Successfully created'), - $messageAction); + $name_check = db_get_value('name', 'talert_commands', 'name', $name); + + if (!$name_check) { + $result = alerts_create_alert_command( + $name, + $command, + $values + ); + + $info = '{"Name":"'.$name.'","Command":"'.$command.'","Description":"'.$description.' '.$info_fields.'"}'; + } else { + $result = ''; + } + + if ($result) { + db_pandora_audit('Command management', 'Create alert command #'.$result, false, false, $info); + } else { + db_pandora_audit('Command management', 'Fail try to create alert command', false, false); + } + + // Show errors + if (!isset($messageAction)) { + $messageAction = __('Could not be created'); + } + + if ($name == '') { + $messageAction = __('No name specified'); + } + + if ($command == '') { + $messageAction = __('No command specified'); + } + + $messageAction = ui_print_result_message( + $result, + __('Successfully created'), + $messageAction + ); } if ($delete_command) { - $id = (int) get_parameter ('id'); - - // Internal commands cannot be deleted - if (alerts_get_alert_command_internal ($id)) { - db_pandora_audit("ACL Violation", - "Trying to access Alert Management"); - require ("general/noaccess.php"); - return; - } - - $result = alerts_delete_alert_command ($id); - - if ($result) { - db_pandora_audit("Command management", "Delete alert command #" . $id); - } - else { - db_pandora_audit("Command management", "Fail try to delete alert command #" . $id); - } - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Could not be deleted')); + $id = (int) get_parameter('id'); + + // Internal commands cannot be deleted + if (alerts_get_alert_command_internal($id)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Alert Management' + ); + include 'general/noaccess.php'; + return; + } + + $result = alerts_delete_alert_command($id); + + if ($result) { + db_pandora_audit('Command management', 'Delete alert command #'.$id); + } else { + db_pandora_audit('Command management', 'Fail try to delete alert command #'.$id); + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Could not be deleted') + ); } if ($copy_command) { - $id = (int) get_parameter ('id'); + $id = (int) get_parameter('id'); - // Get the info from the source command - $command_to_copy = db_get_row('talert_commands', 'id', $id); - if ($command_to_copy === false) { - ui_print_error_message(__("Command with id $id does not found.")); - } else { - // Prepare to insert the copy with same values - unset ($command_to_copy['id']); - $command_to_copy['name'].= __(' (copy)'); - $result = db_process_sql_insert('talert_commands', $command_to_copy); + // Get the info from the source command + $command_to_copy = db_get_row('talert_commands', 'id', $id); + if ($command_to_copy === false) { + ui_print_error_message(__("Command with id $id does not found.")); + } else { + // Prepare to insert the copy with same values + unset($command_to_copy['id']); + $command_to_copy['name'] .= __(' (copy)'); + $result = db_process_sql_insert('talert_commands', $command_to_copy); - // Print the result - ui_print_result_message ($result, - __('Successfully copied'), - __('Could not be copied') - ); - } + // Print the result + ui_print_result_message( + $result, + __('Successfully copied'), + __('Could not be copied') + ); + } } $table->width = '100%'; $table->class = 'databox data'; -$table->data = array (); -$table->head = array (); +$table->data = []; +$table->head = []; $table->head['name'] = __('Name'); $table->head['id'] = __('ID'); $table->head['group'] = __('Group'); $table->head['description'] = __('Description'); $table->head['action'] = __('Actions'); -$table->style = array (); +$table->style = []; $table->style['name'] = 'font-weight: bold'; -$table->size = array (); +$table->size = []; $table->size['action'] = '40px'; -$table->align = array (); +$table->align = []; $table->align['action'] = 'left'; $commands = db_get_all_rows_filter( - 'talert_commands', - array('id_group' => array_keys(users_get_groups(false, "LM"))) + 'talert_commands', + ['id_group' => array_keys(users_get_groups(false, 'LM'))] ); -if ($commands === false) $commands = array (); +if ($commands === false) { + $commands = []; +} foreach ($commands as $command) { - $data = array (); + $data = []; - $data['name'] = ''; - if (! $command['internal']) - $data['name'] .= ''. - $command['name'].''; - else - $data['name'] .= $command['name']; - $data['name'] .= ''; - $data['id'] = $command['id']; - $data['group'] = ui_print_group_icon ($command["id_group"], true); - $data['description'] = str_replace("\r\n","
    ", - io_safe_output($command['description'])); - $data['action'] = ''; - if (! $command['internal']) { - $data['action'] = ''; - $data['action'].= ''. - html_print_image("images/copy.png", true) . ''; - $data['action'].= ''. - html_print_image("images/cross.png", true) . ''; - $data['action'].= ''; - } + $data['name'] = ''; + if (! $command['internal']) { + $data['name'] .= ''.$command['name'].''; + } else { + $data['name'] .= $command['name']; + } - array_push ($table->data, $data); + $data['name'] .= ''; + $data['id'] = $command['id']; + $data['group'] = ui_print_group_icon($command['id_group'], true); + $data['description'] = str_replace( + "\r\n", + '
    ', + io_safe_output($command['description']) + ); + $data['action'] = ''; + if (! $command['internal']) { + $data['action'] = ''; + $data['action'] .= ''.html_print_image('images/copy.png', true).''; + $data['action'] .= ''.html_print_image('images/cross.png', true).''; + $data['action'] .= ''; + } + + array_push($table->data, $data); } if (count($table->data) > 0) { - html_print_table ($table); -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('No alert commands configured') ) ); + html_print_table($table); +} else { + ui_print_info_message(['no_close' => true, 'message' => __('No alert commands configured') ]); } -echo '
    '; -echo '
    '; -html_print_submit_button (__('Create'), 'create', false, 'class="sub next"'); -html_print_input_hidden ('create_alert', 1); +echo '
    '; +echo ''; +html_print_submit_button(__('Create'), 'create', false, 'class="sub next"'); +html_print_input_hidden('create_alert', 1); echo ''; echo '
    '; enterprise_hook('close_meta_frame'); - -?> diff --git a/pandora_console/godmode/alerts/alert_list.builder.php b/pandora_console/godmode/alerts/alert_list.builder.php index d32ab3ed48..97d4c951bc 100644 --- a/pandora_console/godmode/alerts/alert_list.builder.php +++ b/pandora_console/godmode/alerts/alert_list.builder.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,31 +11,32 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; // Login check -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "LW")) { - db_pandora_audit("ACL Violation", - "Trying to access Alert Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'LW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Alert Management' + ); + include 'general/noaccess.php'; + exit; } -include_once($config['homedir'] . "/include/functions_agents.php"); -include_once($config['homedir'] . '/include/functions_users.php'); +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_users.php'; $pure = get_parameter('pure', 0); $table->id = 'add_alert_table'; $table->class = 'databox filters'; $table->width = '100%'; -$table->head = array (); -$table->data = array (); -$table->size = array (); -$table->size = array (); +$table->head = []; +$table->data = []; +$table->size = []; +$table->size = []; $table->size[0] = '5%'; $table->size[1] = '25%'; $table->size[2] = '5%'; @@ -46,7 +46,7 @@ $table->style[1] = 'font-weight: bold; '; $table->style[2] = 'font-weight: bold; '; $table->style[3] = 'font-weight: bold; '; -// This is because if this view is reused after list alert view then +// This is because if this view is reused after list alert view then // styles in the previous view can affect this table. $table->rowstyle[0] = ''; $table->rowstyle[1] = ''; @@ -54,183 +54,219 @@ $table->rowstyle[2] = ''; $table->rowstyle[3] = ''; -/* Add an agent selector */ +// Add an agent selector if (! $id_agente) { - $table->data['agent'][0] = __('Agent'); - - $params = array(); - $params['return'] = true; - $params['show_helptip'] = true; - $params['input_name'] = 'id_agent'; - $params['selectbox_id'] = 'id_agent_module'; - $params['javascript_is_function_select'] = true; - $params['metaconsole_enabled'] = false; - $table->data['agent'][1] = ui_print_agent_autocomplete_input($params); + $table->data['agent'][0] = __('Agent'); + + $params = []; + $params['return'] = true; + $params['show_helptip'] = true; + $params['input_name'] = 'id_agent'; + $params['selectbox_id'] = 'id_agent_module'; + $params['javascript_is_function_select'] = true; + $params['metaconsole_enabled'] = false; + $params['use_hidden_input_idagent'] = true; + $params['print_hidden_input_idagent'] = true; + $table->data['agent'][1] = ui_print_agent_autocomplete_input($params); } $table->data[0][0] = __('Module'); -$modules = array (); +$modules = []; -if ($id_agente) - $modules = agents_get_modules ($id_agente, false, array("delete_pending" => 0)); +if ($id_agente) { + $modules = agents_get_modules($id_agente, false, ['delete_pending' => 0]); +} -$table->data[0][1] = html_print_select ($modules, 'id_agent_module', 0, true, - __('Select'), 0, true, false, true, '', ($id_agente == 0), 'width: 250px;'); +$table->data[0][1] = html_print_select( + $modules, + 'id_agent_module', + 0, + true, + __('Select'), + 0, + true, + false, + true, + '', + ($id_agente == 0), + 'width: 250px;' +); $table->data[0][1] .= ' '; $table->data[0][1] .= ' '; +$table->data[0][1] .= html_print_image('images/spinner.png', true).''; $table->data[1][0] = __('Actions'); -$groups_user = users_get_groups($config["id_user"]); +$groups_user = users_get_groups($config['id_user']); if (!empty($groups_user)) { - $groups = implode(',', array_keys($groups_user)); - $sql = "SELECT id, name FROM talert_actions WHERE id_group IN ($groups)"; - $actions = db_get_all_rows_sql($sql); + $groups = implode(',', array_keys($groups_user)); + $sql = "SELECT id, name FROM talert_actions WHERE id_group IN ($groups)"; + $actions = db_get_all_rows_sql($sql); } $table->data[1][1] = html_print_select( - index_array($actions, 'id', 'name'), 'action_select', '', '', - __('Default action'), '0', true, '', true, '', false, - 'width: 250px;'); + index_array($actions, 'id', 'name'), + 'action_select', + '', + '', + __('Default action'), + '0', + true, + '', + true, + '', + false, + 'width: 250px;' +); $table->data[1][1] .= ''; -if (check_acl ($config['id_user'], 0, "LM")) { - - - $table->data[1][1] .= ''; - $table->data[1][1] .= html_print_image ('images/add.png', true); - $table->data[1][1] .= ''.__('Create Action').''; - $table->data[1][1] .= ''; +if (check_acl($config['id_user'], 0, 'LM')) { + $table->data[1][1] .= ''; + $table->data[1][1] .= html_print_image('images/add.png', true); + $table->data[1][1] .= ''.__('Create Action').''; + $table->data[1][1] .= ''; } - $table->data[2][0] = __('Template'); - $own_info = get_user_info ($config['id_user']); - if ($own_info['is_admin'] || check_acl ($config['id_user'], 0, "PM")) - $templates = alerts_get_alert_templates (false, array ('id', 'name')); - else { - $usr_groups = users_get_groups($config['id_user'], 'LW', true); - $filter_groups = ''; - $filter_groups = implode(',', array_keys($usr_groups)); - $templates = alerts_get_alert_templates (array ('id_group IN (' . $filter_groups . ')'), array ('id', 'name')); - } - - $table->data[2][1] = html_print_select (index_array ($templates, 'id', 'name'), - 'template', '', '', __('Select'), 0, true, false, true, '', false, 'width: 250px;'); - $table->data[2][1] .= ' '; - if (check_acl ($config['id_user'], 0, "LM")) { - $table->data[2][1] .= ''; - $table->data[2][1] .= html_print_image ('images/add.png', true); - $table->data[2][1] .= ''.__('Create Template').''; - $table->data[2][1] .= ''; - } - $table->data[3][0] = __('Threshold'); - $table->data[3][1] = html_print_input_text ('module_action_threshold', '0', '', 5, 7, true); - $table->data[3][1] .= ' ' . __('seconds') . ui_print_help_icon ('action_threshold', true); - - -if (!isset($step) || $step!=5) { - echo '
    '; - html_print_table ($table); + $table->data[2][0] = __('Template'); + $own_info = get_user_info($config['id_user']); +if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { + $templates = alerts_get_alert_templates(false, ['id', 'name']); +} else { + $usr_groups = users_get_groups($config['id_user'], 'LW', true); + $filter_groups = ''; + $filter_groups = implode(',', array_keys($usr_groups)); + $templates = alerts_get_alert_templates(['id_group IN ('.$filter_groups.')'], ['id', 'name']); } -echo '
    '; + $table->data[2][1] = html_print_select( + index_array($templates, 'id', 'name'), + 'template', + '', + '', + __('Select'), + 0, + true, + false, + true, + '', + false, + 'width: 250px;' + ); + $table->data[2][1] .= ' '; + if (check_acl($config['id_user'], 0, 'LM')) { + $table->data[2][1] .= ''; + $table->data[2][1] .= html_print_image('images/add.png', true); + $table->data[2][1] .= ''.__('Create Template').''; + $table->data[2][1] .= ''; + } -if (!isset($step) || $step!=5) { - if($id_cluster){ - echo ""; - } + $table->data[3][0] = __('Threshold'); + $table->data[3][1] = html_print_input_text('module_action_threshold', '0', '', 5, 7, true); + $table->data[3][1] .= ' '.__('seconds').ui_print_help_icon('action_threshold', true); + if (!isset($step)) { + echo ''; + html_print_table($table); + } - html_print_submit_button (__('Add alert'), 'add', false, 'class="sub wand"'); - html_print_input_hidden ('create_alert', 1); - echo '
    '; -} + echo '
    '; -ui_require_css_file ('cluetip'); -ui_require_jquery_file ('cluetip'); -ui_require_jquery_file ('pandora.controls'); -ui_require_jquery_file ('bgiframe'); -?> + if (!isset($step)) { + if ($id_cluster) { + echo ""; + } + + html_print_submit_button(__('Add alert'), 'add', false, 'class="sub wand"'); + html_print_input_hidden('create_alert', 1); + echo '
    '; + } + + ui_require_css_file('cluetip', 'include/styles/js/'); + ui_require_jquery_file('cluetip'); + ui_require_jquery_file('pandora.controls'); + ui_require_jquery_file('bgiframe'); + ?> diff --git a/pandora_console/godmode/alerts/alert_list.list.php b/pandora_console/godmode/alerts/alert_list.list.php index 189507772b..77bb7067bb 100644 --- a/pandora_console/godmode/alerts/alert_list.list.php +++ b/pandora_console/godmode/alerts/alert_list.list.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,65 +11,63 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; // Login check -check_login (); +check_login(); -/* Check if this page is included from a agent edition */ - -if (! check_acl ($config['id_user'], 0, "LW") && - ! check_acl ($config['id_user'], 0, "AD") && - ! check_acl ($config['id_user'], 0, "LM")) { - db_pandora_audit("ACL Violation", - "Trying to access Alert Management"); - require ("general/noaccess.php"); - exit; +// Check if this page is included from a agent edition +if (! check_acl($config['id_user'], 0, 'LW') + && ! check_acl($config['id_user'], 0, 'AD') + && ! check_acl($config['id_user'], 0, 'LM') +) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Alert Management' + ); + include 'general/noaccess.php'; + exit; } -require_once ($config['homedir'].'/include/functions_agents.php'); -require_once ($config['homedir'].'/include/functions_modules.php'); -require_once ($config['homedir'].'/include/functions_users.php'); +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_users.php'; $pure = get_parameter('pure', 0); if (defined('METACONSOLE')) { - $sec = 'advanced'; -} -else { - $sec = 'galertas'; + $sec = 'advanced'; +} else { + $sec = 'galertas'; } if ($id_agente) { - $sec2 = 'godmode/agentes/configurar_agente&tab=alert&id_agente=' . $id_agente; -} -else { - $sec2 = 'godmode/alerts/alert_list'; + $sec2 = 'godmode/agentes/configurar_agente&tab=alert&id_agente='.$id_agente; +} else { + $sec2 = 'godmode/alerts/alert_list'; } // Table for filter controls -$form_filter = '
    '; +$form_filter = ''; $form_filter .= ""; $form_filter .= ''; -$form_filter .= ""; -$form_filter .= ""; +$form_filter .= ''; +$form_filter .= "'; $temp = agents_get_agents(); -$arrayAgents = array(); +$arrayAgents = []; -# Avoid empty arrays, warning messages are UGLY ! +// Avoid empty arrays, warning messages are UGLY ! if ($temp) { - foreach ($temp as $agentElement) { - $arrayAgents[$agentElement['id_agente']] = $agentElement['nombre']; - } + foreach ($temp as $agentElement) { + $arrayAgents[$agentElement['id_agente']] = $agentElement['nombre']; + } } -$form_filter .= ""; +$form_filter .= ''; -$form_filter .= ""; -$form_filter .= ""; +$form_filter .= "'; +$form_filter .= ''; $all_groups = db_get_value('is_admin', 'tusuario', 'id_user', $config['id_user']); -if (check_acl ($config['id_user'], 0, "AD")) - $groups_user = users_get_groups($config['id_user'], 'AD', $all_groups); -elseif (check_acl ($config['id_user'], 0, "LW")) - $groups_user = users_get_groups($config['id_user'], 'LW', $all_groups); -elseif (check_acl ($config['id_user'], 0, "LM")) - $groups_user = users_get_groups($config['id_user'], 'LM', $all_groups); -if ($groups_user === false) { - $groups_user = array(); +if (check_acl($config['id_user'], 0, 'AD')) { + $groups_user = users_get_groups($config['id_user'], 'AD', $all_groups); +} else if (check_acl($config['id_user'], 0, 'LW')) { + $groups_user = users_get_groups($config['id_user'], 'LW', $all_groups); +} else if (check_acl($config['id_user'], 0, 'LM')) { + $groups_user = users_get_groups($config['id_user'], 'LM', $all_groups); } + +if ($groups_user === false) { + $groups_user = []; +} + $groups_id = implode(',', array_keys($groups_user)); -$form_filter .= ""; +$form_filter .= ''; $temp = db_get_all_rows_sql("SELECT id, name FROM talert_actions WHERE id_group IN ($groups_id);"); -$arrayActions = array(); +$arrayActions = []; if (is_array($temp)) { - foreach ($temp as $actionElement) { - $arrayActions[$actionElement['id']] = $actionElement['name']; - } + foreach ($temp as $actionElement) { + $arrayActions[$actionElement['id']] = $actionElement['name']; + } } -$form_filter .= ""; -$form_filter .= ""; -$form_filter .= ""; -$form_filter .= ""; -$form_filter .= ""; -$form_filter .= "'; +$form_filter .= "'; +$form_filter .= ""; +$form_filter .= ''; + +$form_filter .= ''; +$form_filter .= ""; -if ( defined("METACONSOLE") ) { - $form_filter .= ""; - $form_filter .= ""; - $form_filter .= ""; - $form_filter .= "
    " . __('Template name') . ""; -$form_filter .= html_print_input_text ('template_name', $templateName, '', 12, 255, true); -$form_filter .= "
    ".__('Template name').''; +$form_filter .= html_print_input_text('template_name', $templateName, '', 12, 255, true); +$form_filter .= '".__('Agents').""; +$form_filter .= "".__('Agents').''; -$params = array(); +$params = []; $params['return'] = true; $params['show_helptip'] = true; $params['input_name'] = 'agent_name'; @@ -78,125 +75,152 @@ $params['value'] = $agentName; $params['size'] = 24; $params['metaconsole_enabled'] = false; -$form_filter .= ui_print_agent_autocomplete_input($params); +$form_filter .= ui_print_agent_autocomplete_input($params); -$form_filter .= "".__('Module name').""; -$form_filter .= html_print_input_text ('module_name', $moduleName, '', 12, 255, true); -$form_filter .= "
    ".__('Module name').''; +$form_filter .= html_print_input_text('module_name', $moduleName, '', 12, 255, true); +$form_filter .= '
    ".__('Actions').""; -$form_filter .= html_print_select ($arrayActions, "action_id", $actionID, '', __('All'), -1, true); -$form_filter .= "".__('Field content').""; -$form_filter .= html_print_input_text ('field_content', $fieldContent, '', 12, 255, true); -$form_filter .= "".__('Priority').""; -$form_filter .= html_print_select (get_priorities (), 'priority',$priority, '', __('All'), -1, true); -$form_filter .= "
    ".__('Enabled / Disabled').""; -$ed_list = array (); +$form_filter .= "".__('Actions').''; +$form_filter .= html_print_select($arrayActions, 'action_id', $actionID, '', __('All'), -1, true); +$form_filter .= '".__('Field content').''; +$form_filter .= html_print_input_text('field_content', $fieldContent, '', 12, 255, true); +$form_filter .= '".__('Priority').''; +$form_filter .= html_print_select(get_priorities(), 'priority', $priority, '', __('All'), -1, true); +$form_filter .= "
    ".__('Enabled / Disabled').''; +$ed_list = []; $ed_list[0] = __('Enabled'); $ed_list[1] = __('Disabled'); -$form_filter .= html_print_select ($ed_list, 'enabledisable', $enabledisable, '', __('All'), -1, true); -$form_filter .= "".__('Standby').""; -$sb_list = array (); +$form_filter .= html_print_select($ed_list, 'enabledisable', $enabledisable, '', __('All'), -1, true); +$form_filter .= "".__('Standby').''; +$sb_list = []; $sb_list[1] = __('Standby on'); $sb_list[0] = __('Standby off'); -$form_filter .= html_print_select ($sb_list, 'standby', $standby, '', __('All'), -1, true); -$form_filter .= "
    "; - $form_filter .= html_print_submit_button (__('Update'), '', false, 'class="sub upd"', true); - $form_filter .= "
    "; -} -else { - $form_filter .= ""; - $form_filter .= "
    "; - $form_filter .= html_print_submit_button (__('Update'), '', false, 'class="sub upd"', true); - $form_filter .= "
    "; +$form_filter .= html_print_select($sb_list, 'standby', $standby, '', __('All'), -1, true); +$form_filter .= ''; +if (defined('METACONSOLE')) { + $form_filter .= ''; + $form_filter .= ""; + $form_filter .= html_print_submit_button(__('Update'), '', false, 'class="sub upd"', true); + $form_filter .= ''; + $form_filter .= ''; + $form_filter .= ''; +} else { + $form_filter .= ''; + $form_filter .= "
    "; + $form_filter .= html_print_submit_button(__('Update'), '', false, 'class="sub upd"', true); + $form_filter .= '
    '; } -$form_filter .= "
    "; -if ( defined("METACONSOLE")) - echo "
    "; - -if(!$id_cluster){ - ui_toggle($form_filter, __('Alert control filter'), __('Toggle filter(s)')); -} -else{ - unset($form_filter); +$form_filter .= ''; +if (defined('METACONSOLE')) { + echo '
    '; +} + +if (!$id_cluster) { + ui_toggle($form_filter, __('Alert control filter'), __('Toggle filter(s)')); +} else { + unset($form_filter); } -$simple_alerts = array(); +$simple_alerts = []; $total = 0; $where = ''; if ($searchFlag) { - if ($priority != -1 && $priority != '') - $where .= " AND id_alert_template IN (SELECT id FROM talert_templates WHERE priority = " . $priority . ")"; - if (strlen(trim($templateName)) > 0) - $where .= " AND id_alert_template IN (SELECT id FROM talert_templates WHERE name LIKE '%" . trim($templateName) . "%')"; - if (strlen(trim($fieldContent)) > 0) - $where .= " AND id_alert_template IN (SELECT id FROM talert_templates - WHERE field1 LIKE '%" . trim($fieldContent) . "%' OR field2 LIKE '%" . trim($fieldContent) . "%' OR - field3 LIKE '%" . trim($fieldContent) . "%' OR - field2_recovery LIKE '%" . trim($fieldContent) . "%' OR - field3_recovery LIKE '%" . trim($fieldContent) . "%')"; - if (strlen(trim($moduleName)) > 0) - $where .= " AND id_agent_module IN (SELECT id_agente_modulo FROM tagente_modulo WHERE nombre LIKE '%" . trim($moduleName) . "%')"; - if (strlen(trim($agentName)) > 0) { - $where .= " AND id_agent_module IN (SELECT t2.id_agente_modulo + if ($priority != -1 && $priority != '') { + $where .= ' AND id_alert_template IN (SELECT id FROM talert_templates WHERE priority = '.$priority.')'; + } + + if (strlen(trim($templateName)) > 0) { + $where .= " AND id_alert_template IN (SELECT id FROM talert_templates WHERE name LIKE '%".trim($templateName)."%')"; + } + + if (strlen(trim($fieldContent)) > 0) { + $where .= " AND id_alert_template IN (SELECT id FROM talert_templates + WHERE field1 LIKE '%".trim($fieldContent)."%' OR field2 LIKE '%".trim($fieldContent)."%' OR + field3 LIKE '%".trim($fieldContent)."%' OR + field2_recovery LIKE '%".trim($fieldContent)."%' OR + field3_recovery LIKE '%".trim($fieldContent)."%')"; + } + + if (strlen(trim($moduleName)) > 0) { + $where .= " AND id_agent_module IN (SELECT id_agente_modulo FROM tagente_modulo WHERE nombre LIKE '%".trim($moduleName)."%')"; + } + + if (strlen(trim($agentName)) > 0) { + $where .= " AND id_agent_module IN (SELECT t2.id_agente_modulo FROM tagente t1 INNER JOIN tagente_modulo t2 ON t1.id_agente = t2.id_agente - WHERE t1.alias LIKE '" . trim($agentName) . "')"; - } - if ($actionID != -1 && $actionID != '') - $where .= " AND talert_template_modules.id IN (SELECT id_alert_template_module FROM talert_template_module_actions WHERE id_alert_action = " . $actionID . ")"; - if ($enabledisable != -1 && $enabledisable != '') - $where .= " AND talert_template_modules.disabled =" . $enabledisable; - if ($standby != -1 && $standby != '') - $where .= " AND talert_template_modules.standby = " . $standby; + WHERE t1.alias LIKE '".trim($agentName)."')"; + } + + if ($actionID != -1 && $actionID != '') { + $where .= ' AND talert_template_modules.id IN (SELECT id_alert_template_module FROM talert_template_module_actions WHERE id_alert_action = '.$actionID.')'; + } + + if ($enabledisable != -1 && $enabledisable != '') { + $where .= ' AND talert_template_modules.disabled ='.$enabledisable; + } + + if ($standby != -1 && $standby != '') { + $where .= ' AND talert_template_modules.standby = '.$standby; + } } -$id_agents = array_keys ($agents); +$id_agents = array_keys($agents); -$total = agents_get_alerts_simple ($id_agents, false, - false, $where, false, false, false, true); +$total = agents_get_alerts_simple( + $id_agents, + false, + false, + $where, + false, + false, + false, + true +); -if (empty($total)) $total = 0; +if (empty($total)) { + $total = 0; +} $order = null; @@ -215,176 +239,223 @@ $selectTemplateUp = ''; $selectTemplateDown = ''; switch ($sortField) { - case 'disabled': - switch ($sort) { - case 'up': - $selectDisabledUp = $selected; - $order = array('field' => 'disabled', 'order' => 'ASC'); - break; - case 'down': - $selectDisabledDown = $selected; - $order = array('field' => 'disabled', 'order' => 'DESC'); - break; - } - break; - case 'standby': - switch ($sort) { - case 'up': - $selectStandbyUp = $selected; - $order = array('field' => 'standby', 'order' => 'ASC'); - break; - case 'down': - $selectStandbyDown = $selected; - $order = array('field' => 'standby', 'order' => 'DESC'); - break; - } - break; - case 'agent': - switch ($sort) { - case 'up': - $selectAgentUp = $selected; - $order = array('field' => 'agent_name', 'order' => 'ASC'); - break; - case 'down': - $selectAgentDown = $selected; - $order = array('field' => 'agent_name', 'order' => 'DESC'); - break; - } - break; - case 'module': - switch ($sort) { - case 'up': - $selectModuleUp = $selected; - $order = array('field' => 'agent_module_name', 'order' => 'ASC'); - break; - case 'down': - $selectModuleDown = $selected; - $order = array('field' => 'agent_module_name', 'order' => 'DESC'); - break; - } - break; - case 'template': - switch ($sort) { - case 'up': - $selectTemplateUp = $selected; - $order = array('field' => 'template_name', 'order' => 'ASC'); - break; - case 'down': - $selectTemplateDown = $selected; - $order = array('field' => 'template_name', 'order' => 'DESC'); - break; - } - break; - default: - if (!$id_agente) { - $selectDisabledUp = ''; - $selectDisabledDown = ''; - $selectStandbyUp = ''; - $selectStandbyDown = ''; - $selectAgentUp = $selected; - $selectAgentDown = ''; - $selectModuleUp = ''; - $selectModuleDown = ''; - $selectTemplateUp = ''; - $selectTemplateDown = ''; - $order = array('field' => 'agent_name', 'order' => 'ASC'); - } - else { - $selectDisabledUp = ''; - $selectDisabledDown = ''; - $selectStandbyUp = ''; - $selectStandbyDown = ''; - $selectAgentUp = ''; - $selectAgentDown = ''; - $selectModuleUp = $selected; - $selectModuleDown = ''; - $selectTemplateUp = ''; - $selectTemplateDown = ''; - $order = array('field' => 'agent_module_name', 'order' => 'ASC'); - } - break; + case 'disabled': + switch ($sort) { + case 'up': + $selectDisabledUp = $selected; + $order = [ + 'field' => 'disabled', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectDisabledDown = $selected; + $order = [ + 'field' => 'disabled', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'standby': + switch ($sort) { + case 'up': + $selectStandbyUp = $selected; + $order = [ + 'field' => 'standby', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectStandbyDown = $selected; + $order = [ + 'field' => 'standby', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'agent': + switch ($sort) { + case 'up': + $selectAgentUp = $selected; + $order = [ + 'field' => 'agent_name', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectAgentDown = $selected; + $order = [ + 'field' => 'agent_name', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'module': + switch ($sort) { + case 'up': + $selectModuleUp = $selected; + $order = [ + 'field' => 'agent_module_name', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectModuleDown = $selected; + $order = [ + 'field' => 'agent_module_name', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'template': + switch ($sort) { + case 'up': + $selectTemplateUp = $selected; + $order = [ + 'field' => 'template_name', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectTemplateDown = $selected; + $order = [ + 'field' => 'template_name', + 'order' => 'DESC', + ]; + break; + } + break; + + default: + if (!$id_agente) { + $selectDisabledUp = ''; + $selectDisabledDown = ''; + $selectStandbyUp = ''; + $selectStandbyDown = ''; + $selectAgentUp = $selected; + $selectAgentDown = ''; + $selectModuleUp = ''; + $selectModuleDown = ''; + $selectTemplateUp = ''; + $selectTemplateDown = ''; + $order = [ + 'field' => 'agent_name', + 'order' => 'ASC', + ]; + } else { + $selectDisabledUp = ''; + $selectDisabledDown = ''; + $selectStandbyUp = ''; + $selectStandbyDown = ''; + $selectAgentUp = ''; + $selectAgentDown = ''; + $selectModuleUp = $selected; + $selectModuleDown = ''; + $selectTemplateUp = ''; + $selectTemplateDown = ''; + $order = [ + 'field' => 'agent_module_name', + 'order' => 'ASC', + ]; + } + break; } -$form_params = '&template_name=' . $templateName . '&agent_name=' . $agentName . '&module_name=' . $moduleName . '&action_id=' . $actionID . '&field_content=' . $fieldContent. '&priority=' . $priority . '&enabledisable=' . $enabledisable . '&standby=' . $standby; -$sort_params = '&sort_field=' . $sortField . '&sort=' . $sort; +$form_params = '&template_name='.$templateName.'&agent_name='.$agentName.'&module_name='.$moduleName.'&action_id='.$actionID.'&field_content='.$fieldContent.'&priority='.$priority.'&enabledisable='.$enabledisable.'&standby='.$standby; +$sort_params = '&sort_field='.$sortField.'&sort='.$sort; if ($id_agente) { - ui_pagination ($total, 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=alert&id_agente=' . $id_agente . $form_params . $sort_params); -} -else { - ui_pagination ($total, 'index.php?sec='.$sec.'&sec2=godmode/alerts/alert_list' . $form_params . $sort_params); + ui_pagination($total, 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&tab=alert&id_agente='.$id_agente.$form_params.$sort_params); +} else { + ui_pagination($total, 'index.php?sec='.$sec.'&sec2=godmode/alerts/alert_list'.$form_params.$sort_params); } $offset = (int) get_parameter('offset'); -$simple_alerts = agents_get_alerts_simple ($id_agents, false, - array ('offset' => $offset, - 'limit' => $config['block_size'], 'order' => $order), $where, false); +$simple_alerts = agents_get_alerts_simple( + $id_agents, + false, + [ + 'offset' => $offset, + 'limit' => $config['block_size'], + 'order' => $order, + ], + $where, + false +); if (!$id_agente) { - $url = 'index.php?sec='.$sec.'&sec2=godmode/alerts/alert_list&tab=list&pure='.$pure.'&offset=' . $offset . $form_params; -} -else { - $url = 'index.php?sec='.$sec.'&sec2=godmode/agentes/configurar_agente&pure='.$pure.'&tab=alert&id_agente=' . $id_agente . '&offset=' . $offset . $form_params; + $url = 'index.php?sec='.$sec.'&sec2=godmode/alerts/alert_list&tab=list&pure='.$pure.'&offset='.$offset.$form_params; +} else { + $url = 'index.php?sec='.$sec.'&sec2=godmode/agentes/configurar_agente&pure='.$pure.'&tab=alert&id_agente='.$id_agente.'&offset='.$offset.$form_params; } $table = new stdClass(); -if ( is_metaconsole() ) - $table->class = 'alert_list databox'; -else - $table->class = 'databox data'; +if (is_metaconsole()) { + $table->class = 'alert_list databox'; +} else { + $table->class = 'databox data'; +} $table->width = '100%'; $table->cellpadding = 0; $table->cellspacing = 0; -$table->size = array (); +$table->size = []; -$table->align = array (); +$table->align = []; $table->align[0] = 'left'; $table->align[1] = 'left'; $table->align[2] = 'left'; $table->align[3] = 'left'; $table->align[4] = 'left'; -$table->head = array (); +$table->head = []; if (! $id_agente) { - $table->style = array (); - $table->style[0] = 'font-weight: bold;'; - $table->head[0] = __('Agent') . ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectAgentUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectAgentDown)) . ''; - $table->size[0] = '4%'; - $table->size[1] = '8%'; - $table->size[2] = '8%'; - $table->size[3] = '4%'; - $table->size[4] = '4%'; + $table->style = []; + $table->style[0] = 'font-weight: bold;'; + $table->head[0] = __('Agent').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectAgentUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectAgentDown]).''; + $table->size[0] = '4%'; + $table->size[1] = '8%'; + $table->size[2] = '8%'; + $table->size[3] = '4%'; + $table->size[4] = '4%'; -/* if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { - $table->size[4] = '8%'; - }*/ -} -else { - $table->head[0] = __('Module') . ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectModuleUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectModuleDown)) . ''; - /* Different sizes or the layout screws up */ - $table->size[0] = '0%'; - $table->size[1] = '10%'; - $table->size[2] = '30%'; -/* if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { - $table->size[4] = '25%'; - } */ - $table->size[3] = '1%'; - $table->size[4] = '1%'; + /* + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { + $table->size[4] = '8%'; + }*/ +} else { + $table->head[0] = __('Module').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectModuleUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectModuleDown]).''; + // Different sizes or the layout screws up + $table->size[0] = '0%'; + $table->size[1] = '10%'; + $table->size[2] = '30%'; + /* + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { + $table->size[4] = '25%'; + } */ + $table->size[3] = '1%'; + $table->size[4] = '1%'; } -$table->head[1] = __('Template') . ' ' . - '' . html_print_image("images/sort_up.png", true, array("style" => $selectTemplateUp)) . '' . - '' . html_print_image("images/sort_down.png", true, array("style" => $selectTemplateDown)) . ''; +$table->head[1] = __('Template').' '.''.html_print_image('images/sort_up.png', true, ['style' => $selectTemplateUp]).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectTemplateDown]).''; $table->head[2] = __('Actions'); $table->head[3] = __('Status'); -$table->head[4] = "" . __('Op.') . ""; +$table->head[4] = "".__('Op.').''; $table->valign[0] = 'middle'; $table->valign[1] = 'middle'; @@ -392,9 +463,9 @@ $table->valign[2] = 'middle'; $table->valign[3] = 'middle'; $table->valign[4] = 'middle'; -$table->style[4] = "min-width:80px"; +$table->style[4] = 'min-width:80px'; -$table->data = array (); +$table->data = []; $url .= $sort_params; @@ -402,473 +473,506 @@ $rowPair = true; $iterator = 0; foreach ($simple_alerts as $alert) { - if ($alert['disabled']) { - $table->rowstyle[$iterator] = 'font-style: italic; color: #aaaaaa;'; - $table->style[$iterator][1] = 'font-style: italic; color: #aaaaaa;'; - } - - if ($rowPair) - $table->rowclass[$iterator] = 'rowPair'; - else - $table->rowclass[$iterator] = 'rowOdd'; - $rowPair = !$rowPair; - $iterator++; - - $data = array (); - - if (! $id_agente) { - $id_agent = modules_get_agentmodule_agent ($alert['id_agent_module']); - $all_groups = agents_get_all_groups_agent($id_agent); - - $data[0] = ''; - - if (check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) { - $main_tab = 'main'; - } - else { - $main_tab = 'module'; - } - - $data[0] = ''; - - if ($alert['disabled']) - $data[0] .= ''; - $alias = db_get_value ("alias","tagente","id_agente",$id_agent); - $data[0] .= $alias; - if ($alert['disabled']) - $data[0] .= ''; - - $data[0] .= ''; - } - else { - $all_groups = agents_get_all_groups_agent($id_agente); - } - - $module_name = modules_get_agentmodule_name ($alert['id_agent_module']); - $data[0] .= ui_print_truncate_text($module_name, 'module_medium', false, true, true, '[…]', 'display:block;font-size: 7.2pt') . '
    '; + if ($alert['disabled']) { + $table->rowstyle[$iterator] = 'font-style: italic; color: #aaaaaa;'; + $table->style[$iterator][1] = 'font-style: italic; color: #aaaaaa;'; + } + + if ($rowPair) { + $table->rowclass[$iterator] = 'rowPair'; + } else { + $table->rowclass[$iterator] = 'rowOdd'; + } + + $rowPair = !$rowPair; + $iterator++; + + $data = []; + + if (! $id_agente) { + $id_agent = modules_get_agentmodule_agent($alert['id_agent_module']); + $all_groups = agents_get_all_groups_agent($id_agent); + + $data[0] = ''; + + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + $main_tab = 'main'; + } else { + $main_tab = 'module'; + } + + $data[0] = ''; + + if ($alert['disabled']) { + $data[0] .= ''; + } + + $alias = db_get_value('alias', 'tagente', 'id_agente', $id_agent); + $data[0] .= $alias; + if ($alert['disabled']) { + $data[0] .= ''; + } + + $data[0] .= ''; + } else { + $all_groups = agents_get_all_groups_agent($id_agente); + } + + $module_name = modules_get_agentmodule_name($alert['id_agent_module']); + $data[0] .= ui_print_truncate_text($module_name, 'module_medium', false, true, true, '[…]', 'display:block;font-size: 7.2pt').'
    '; - $template_group = db_get_value('id_group', 'talert_templates', 'id', $alert['id_alert_template']); - - // The access to the template manage page is necessary have LW permissions on template group - if(check_acl ($config['id_user'], $template_group, "LW")) { - $data[1] .= ""; - } - - $data[1] .= ui_print_truncate_text( - alerts_get_alert_template_name ($alert['id_alert_template']), 'module_medium', false, true, true, '[…]', 'font-size: 7.1pt'); - $data[1] .= ' '; - $data[1] .= html_print_image("images/zoom.png", true, array("id" => 'template-details-'.$alert['id_alert_template'], "class" => "img_help")); - $data[1] .= ' '; - - if(check_acl ($config['id_user'], $template_group, "LW") || check_acl ($config['id_user'], $template_group, "LM")) { - $data[1] .= ""; - } - - $actions = alerts_get_alert_agent_module_actions ($alert['id']); + $template_group = db_get_value('id_group', 'talert_templates', 'id', $alert['id_alert_template']); - $data[2] = ""; - // Get and show default actions for this alert - $default_action = db_get_sql ("SELECT id_alert_action + // The access to the template manage page is necessary have LW permissions on template group + if (check_acl($config['id_user'], $template_group, 'LW')) { + $data[1] .= ""; + } + + $data[1] .= ui_print_truncate_text( + alerts_get_alert_template_name($alert['id_alert_template']), + 'module_medium', + false, + true, + true, + '[…]', + 'font-size: 7.1pt' + ); + $data[1] .= ' '; + $data[1] .= html_print_image('images/zoom.png', true, ['id' => 'template-details-'.$alert['id_alert_template'], 'class' => 'img_help']); + $data[1] .= ' '; + + if (check_acl($config['id_user'], $template_group, 'LW') || check_acl($config['id_user'], $template_group, 'LM')) { + $data[1] .= ''; + } + + $actions = alerts_get_alert_agent_module_actions($alert['id']); + + $data[2] = "
    "; + // Get and show default actions for this alert + $default_action = db_get_sql( + 'SELECT id_alert_action FROM talert_templates - WHERE id = ".$alert["id_alert_template"]); - if ($default_action != "") { - $data[2] .= ""; - $data[2] .= ""; - $data[2] .= ""; - } - - foreach ($actions as $action_id => $action) { - $data[2] .= ""; - $data[2] .= "'; + $data[2] .= ''; + $data[2] .= ''; + } - // Is possible manage actions if have LW permissions in the agent group of the alert module - if (check_acl_one_of_groups ($config['id_user'], $all_groups, "LW")) { - //~ $data[2] .= ''; - $data[2] .= ''; - $data[2] .= html_print_input_image ('delete', - 'images/cross.png', 1, 'padding:0px;', true, - array('title' => __('Delete action'))); - $data[2] .= html_print_input_hidden ('delete_action', 1, true); - $data[2] .= html_print_input_hidden ('id_alert', $alert['id'], true); - $data[2] .= html_print_input_hidden ('id_action', $action_id, true); - $data[2] .= ''; - $data[2] .= html_print_input_image ('update_action', - 'images/config.png', 1, 'padding:0px;', true, - array('title' => __('Update action'), - 'onclick' => 'show_display_update_action(\''.$action['id'].'\',\''.$alert['id'].'\',\''.$alert['id_agent_module'].'\',\''.$action_id.'\',\''.$alert['id_agent_module'].'\')')); - $data[2] .= html_print_input_hidden ('id_agent_module', $alert['id_agent_module'], true); - } + foreach ($actions as $action_id => $action) { + $data[2] .= ''; + $data[2] .= '"; - $data[2] .= ""; - } - $data[2] .= ''; - $data[2] .= '
    • "; - $data[2] .= db_get_sql ("SELECT name FROM talert_actions WHERE id = $default_action") . ' (' . __('Default') . ')'; - $data[2] .= ui_print_help_tip(__('The default actions will be executed every time that the alert is fired and no other action is executed'), true); - $data[2] .= "
    "; - $data[2] .= '
      '; - $data[2] .= '
    • '; - if ($alert['disabled']) - $data[2] .= ''; - else - $data[2] .= ''; - $data[2] .= ui_print_truncate_text($action['name'], (GENERIC_SIZE_TEXT+20), false); - $data[2] .= ' ('; - if ($action['fires_min'] == $action['fires_max']) { - if ($action['fires_min'] == 0) - $data[2] .= __('Always'); - else - $data[2] .= __('On').' '.$action['fires_min']; - } - else if ($action['fires_min'] < $action['fires_max']) { - if ($action['fires_min'] == 0) - $data[2] .= __('Until').' '.$action['fires_max']; - else - $data[2] .= __('From').' '.$action['fires_min']. - ' '.__('to').' '.$action['fires_max']; - } - else { - $data[2] .= __('From').' '.$action['fires_min']; - } - if ($action['module_action_threshold'] != 0) - $data[2] .= ' '.__('Threshold').' '.human_time_description_alerts ($action['module_action_threshold'], true, 'tiny'); - - $data[2] .= ')'; - $data[2] .= ''; - $data[2] .= '
    • '; - $data[2] .= '
    '; + WHERE id = '.$alert['id_alert_template'] + ); + if ($default_action != '') { + $data[2] .= "
    • "; + $data[2] .= db_get_sql("SELECT name FROM talert_actions WHERE id = $default_action").' ('.__('Default').')'; + $data[2] .= ui_print_help_tip(__('The default actions will be executed every time that the alert is fired and no other action is executed'), true); + $data[2] .= '
    '; + $data[2] .= '
      '; + $data[2] .= '
    • '; + if ($alert['disabled']) { + $data[2] .= ''; + } else { + $data[2] .= ''; + } - $data[2] .= "
    '; - // Is possible manage actions if have LW permissions in the agent group of the alert module - if (check_acl_one_of_groups ($config['id_user'], $all_groups, "LW") || check_acl ($config['id_user'], $template_group, "LM")) { - $own_info = get_user_info($config['id_user']); - if (check_acl ($config['id_user'], $template_group, "LW")) - $own_groups = users_get_groups($config['id_user'], 'LW', true); - elseif (check_acl ($config['id_user'], $template_group, "LM")) - $own_groups = users_get_groups($config['id_user'], 'LM', true); - $filter_groups = ''; - $filter_groups = implode(',', array_keys($own_groups)); - if($filter_groups != null){ - $actions = alerts_get_alert_actions_filter(true, 'id_group IN (' . $filter_groups . ')'); - } - $data[2] .= ''; - } - - $status = STATUS_ALERT_NOT_FIRED; - $title = ""; - - if ($alert["times_fired"] > 0) { - $status = STATUS_ALERT_FIRED; - $title = __('Alert fired').' '.$alert["internal_counter"].' '.__('time(s)'); - } - elseif ($alert["disabled"] > 0) { - $status = STATUS_ALERT_DISABLED; - $title = __('Alert disabled'); - } - else { - $status = STATUS_ALERT_NOT_FIRED; - $title = __('Alert not fired'); - } + $data[2] .= ui_print_truncate_text($action['name'], (GENERIC_SIZE_TEXT + 20), false); + $data[2] .= ' ('; + if ($action['fires_min'] == $action['fires_max']) { + if ($action['fires_min'] == 0) { + $data[2] .= __('Always'); + } else { + $data[2] .= __('On').' '.$action['fires_min']; + } + } else if ($action['fires_min'] < $action['fires_max']) { + if ($action['fires_min'] == 0) { + $data[2] .= __('Until').' '.$action['fires_max']; + } else { + $data[2] .= __('From').' '.$action['fires_min'].' '.__('to').' '.$action['fires_max']; + } + } else { + $data[2] .= __('From').' '.$action['fires_min']; + } - $data[3] = ui_print_status_image($status, $title, true); + if ($action['module_action_threshold'] != 0) { + $data[2] .= ' '.__('Threshold').' '.human_time_description_alerts($action['module_action_threshold'], true, 'tiny'); + } - $data[4] = '
    '; - if ($alert['disabled']) { - $data[4] .= html_print_input_image ('enable', 'images/lightbulb_off.png', 1, 'padding:0px', true); - $data[4] .= html_print_input_hidden ('enable_alert', 1, true); - } - else { - $data[4] .= html_print_input_image ('disable', 'images/lightbulb.png', 1, 'padding:0px;', true); - $data[4] .= html_print_input_hidden ('disable_alert', 1, true); - } - $data[4] .= html_print_input_hidden ('id_alert', $alert['id'], true); - $data[4] .= '
    '; + $data[2] .= ')
    '; + $data[2] .= ''; + $data[2] .= ''; + $data[2] .= ''; - // To manage alert is necessary LW permissions in the agent group - if(check_acl_one_of_groups ($config['id_user'], $all_groups, "LW")) { - $data[4] .= '  
    '; - if (!$alert['standby']) { - $data[4] .= html_print_input_image ('standby_off', 'images/bell.png', 1, 'padding:0px;', true); - $data[4] .= html_print_input_hidden ('standbyon_alert', 1, true); - } - else { - $data[4] .= html_print_input_image ('standby_on', 'images/bell_pause.png', 1, 'padding:0px;', true); - $data[4] .= html_print_input_hidden ('standbyoff_alert', 1, true); - } - $data[4] .= html_print_input_hidden ('id_alert', $alert['id'], true); - $data[4] .= '
    '; - } - - // To access to policy page is necessary have AW permissions in the agent - if(check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) { - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { - $policyInfo = policies_is_alert_in_policy2($alert['id'], false); - if ($policyInfo === false) - $data[3] .= ''; - else { - $img = 'images/policies.png'; + // Is possible manage actions if have LW permissions in the agent group of the alert module + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'LW')) { + // ~ $data[2] .= ''; + $data[2] .= html_print_input_image( + 'update_action', + 'images/config.png', + 1, + 'padding:0px;', + true, + [ + 'title' => __('Update action'), + 'onclick' => 'show_display_update_action(\''.$action['id'].'\',\''.$alert['id'].'\',\''.$alert['id_agent_module'].'\',\''.$action_id.'\',\''.$alert['id_agent_module'].'\')', + ] + ); + $data[2] .= html_print_input_hidden('id_agent_module', $alert['id_agent_module'], true); + } - $data[3] .= '  ' . - html_print_image($img, true, array('title' => $policyInfo['name'])) . - ''; - } - } - } - - // To manage alert is necessary LW permissions in the agent group - if(check_acl_one_of_groups ($config['id_user'], $all_groups, "LW")) { - $data[4] .= '  
    '; - $is_cluster = (bool)get_parameter('id_cluster'); - if (!$is_cluster) { - if ($alert['disabled']) { - $data[4] .= html_print_image('images/add.disabled.png', - true, array('title' => __("Add action"))); - } - else { - $data[4] .= ''; - $data[4] .= html_print_image('images/add.png', true, array('title' => __("Add action"))); - $data[4] .= ''; - } - } - $data[4] .= html_print_input_image ('delete', 'images/cross.png', 1, '', true, array('title' => __('Delete'))); - $data[4] .= html_print_input_hidden ('delete_alert', 1, true); - $data[4] .= html_print_input_hidden ('id_alert', $alert['id'], true); - $data[4] .= '
    '; + $data[2] .= ''; + $data[2] .= ''; + } - if ($is_cluster) { - $data[4] .= '
    '; + $data[2] .= ''; + $data[2] .= ''; + // Is possible manage actions if have LW permissions in the agent group of the alert module + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'LW') || check_acl($config['id_user'], $template_group, 'LM')) { + $own_info = get_user_info($config['id_user']); + if (check_acl($config['id_user'], $template_group, 'LW')) { + $own_groups = users_get_groups($config['id_user'], 'LW', true); + } else if (check_acl($config['id_user'], $template_group, 'LM')) { + $own_groups = users_get_groups($config['id_user'], 'LM', true); + } - $data[4] .= html_print_input_image ('update', 'images/builder.png', 1, '', true, array('title' => __('Update'))); - $data[4] .= html_print_input_hidden ('upd_alert', 1, true); - $data[4] .= html_print_input_hidden ('id_alert', $alert['id'], true); + $filter_groups = ''; + $filter_groups = implode(',', array_keys($own_groups)); + if ($filter_groups != null) { + $actions = alerts_get_alert_actions_filter(true, 'id_group IN ('.$filter_groups.')'); + } - $data[4] .= '
    '; - } - } - - if(check_acl_one_of_groups ($config['id_user'], $all_groups, "LM")) { - $data[4] .= '
    '; - $data[4] .= html_print_input_image ('view_alert', 'images/eye.png', 1, '', true, array('title' => __('View alert advanced details'))); - $data[4] .= html_print_input_hidden ('id_alert', $alert['id'], true); - $data[4] .= '
    '; - } - array_push ($table->data, $data); + $data[2] .= ''; + } + + $status = STATUS_ALERT_NOT_FIRED; + $title = ''; + + if ($alert['times_fired'] > 0) { + $status = STATUS_ALERT_FIRED; + $title = __('Alert fired').' '.$alert['internal_counter'].' '.__('time(s)'); + } else if ($alert['disabled'] > 0) { + $status = STATUS_ALERT_DISABLED; + $title = __('Alert disabled'); + } else { + $status = STATUS_ALERT_NOT_FIRED; + $title = __('Alert not fired'); + } + + $data[3] = ui_print_status_image($status, $title, true); + + $data[4] = '
    '; + if ($alert['disabled']) { + $data[4] .= html_print_input_image('enable', 'images/lightbulb_off.png', 1, 'padding:0px', true); + $data[4] .= html_print_input_hidden('enable_alert', 1, true); + } else { + $data[4] .= html_print_input_image('disable', 'images/lightbulb.png', 1, 'padding:0px;', true); + $data[4] .= html_print_input_hidden('disable_alert', 1, true); + } + + $data[4] .= html_print_input_hidden('id_alert', $alert['id'], true); + $data[4] .= '
    '; + + // To manage alert is necessary LW permissions in the agent group + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'LW')) { + $data[4] .= '  
    '; + if (!$alert['standby']) { + $data[4] .= html_print_input_image('standby_off', 'images/bell.png', 1, 'padding:0px;', true); + $data[4] .= html_print_input_hidden('standbyon_alert', 1, true); + } else { + $data[4] .= html_print_input_image('standby_on', 'images/bell_pause.png', 1, 'padding:0px;', true); + $data[4] .= html_print_input_hidden('standbyoff_alert', 1, true); + } + + $data[4] .= html_print_input_hidden('id_alert', $alert['id'], true); + $data[4] .= '
    '; + } + + // To access to policy page is necessary have AW permissions in the agent + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { + $policyInfo = policies_is_alert_in_policy2($alert['id'], false); + if ($policyInfo === false) { + $data[3] .= ''; + } else { + $img = 'images/policies.png'; + + $data[3] .= '  '.html_print_image($img, true, ['title' => $policyInfo['name']]).''; + } + } + } + + // To manage alert is necessary LW permissions in the agent group + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'LW')) { + $data[4] .= '  
    '; + $is_cluster = (bool) get_parameter('id_cluster'); + if (!$is_cluster) { + if ($alert['disabled']) { + $data[4] .= html_print_image( + 'images/add.disabled.png', + true, + ['title' => __('Add action')] + ); + } else { + $data[4] .= ''; + $data[4] .= html_print_image('images/add.png', true, ['title' => __('Add action')]); + $data[4] .= ''; + } + } + + $data[4] .= html_print_input_image('delete', 'images/cross.png', 1, '', true, ['title' => __('Delete')]); + $data[4] .= html_print_input_hidden('delete_alert', 1, true); + $data[4] .= html_print_input_hidden('id_alert', $alert['id'], true); + $data[4] .= '
    '; + + if ($is_cluster) { + $data[4] .= '
    '; + + $data[4] .= html_print_input_image('update', 'images/builder.png', 1, '', true, ['title' => __('Update')]); + $data[4] .= html_print_input_hidden('upd_alert', 1, true); + $data[4] .= html_print_input_hidden('id_alert', $alert['id'], true); + + $data[4] .= '
    '; + } + } + + if (check_acl_one_of_groups($config['id_user'], $all_groups, 'LM')) { + $data[4] .= '
    '; + $data[4] .= html_print_input_image('view_alert', 'images/eye.png', 1, '', true, ['title' => __('View alert advanced details')]); + $data[4] .= html_print_input_hidden('id_alert', $alert['id'], true); + $data[4] .= '
    '; + } + + array_push($table->data, $data); } if (isset($data)) { - html_print_table ($table); -} -else { - ui_print_info_message ( array('no_close' => true, 'message' => __('No alerts defined') ) ); + html_print_table($table); +} else { + ui_print_info_message(['no_close' => true, 'message' => __('No alerts defined') ]); } // Create alert button // $dont_display_alert_create_bttn is setted in configurar_agente.php in order to not display create button $display_create = true; -if (isset($dont_display_alert_create_bttn)) - if ($dont_display_alert_create_bttn) - $display_create = false; - -if ($display_create && (check_acl ($config['id_user'], 0, "LW") || check_acl ($config['id_user'], $template_group, "LM")) && !$id_cluster) { - echo '
    '; - echo '
    '; - html_print_submit_button (__('Create'), 'crtbtn', false, 'class="sub next"'); - echo '
    '; - echo '
    '; +if (isset($dont_display_alert_create_bttn)) { + if ($dont_display_alert_create_bttn) { + $display_create = false; + } } -ui_require_css_file ('cluetip'); -ui_require_jquery_file ('cluetip'); -ui_require_jquery_file ('pandora.controls'); -ui_require_jquery_file ('bgiframe'); +if ($display_create && (check_acl($config['id_user'], 0, 'LW') || check_acl($config['id_user'], $template_group, 'LM')) && !$id_cluster) { + echo '
    '; + echo '
    '; + html_print_submit_button(__('Create'), 'crtbtn', false, 'class="sub next"'); + echo '
    '; + echo '
    '; +} + +ui_require_css_file('cluetip', 'include/styles/js/'); +ui_require_jquery_file('cluetip'); +ui_require_jquery_file('pandora.controls'); +ui_require_jquery_file('bgiframe'); ?> diff --git a/pandora_console/godmode/alerts/configure_alert_action.php b/pandora_console/godmode/alerts/configure_alert_action.php index 46b1ce8a4c..c29cda623b 100644 --- a/pandora_console/godmode/alerts/configure_alert_action.php +++ b/pandora_console/godmode/alerts/configure_alert_action.php @@ -1,10 +1,9 @@ - 'help_alert_macros_hint', - 'content' => ui_print_help_icon ('alert_macros', true), - 'hidden' => true)); + [ + 'id' => 'help_alert_macros_hint', + 'content' => ui_print_help_icon('alert_macros', true), + 'hidden' => true, + ] +); $table = new stdClass(); $table->id = 'table_macros'; @@ -94,68 +110,81 @@ $table->width = '100%'; $table->class = 'databox filters'; if (defined('METACONSOLE')) { - if ($id) { - $table->head[0] = __('Update Action'); - } - else { - $table->head[0] = __('Create Action'); - } - - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; + if ($id) { + $table->head[0] = __('Update Action'); + } else { + $table->head[0] = __('Create Action'); + } + + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; } -$table->style = array (); + +$table->style = []; $table->style[0] = 'font-weight: bold'; -$table->size = array (); +$table->size = []; $table->size[0] = '20%'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Name'); -$table->data[0][1] = html_print_input_text ('name', $name, '', 35, 255, true); -if (io_safe_output($name) == "Monitoring Event") { - $table->data[0][1] .= '  ' . ui_print_help_tip( - __("This action may stop working, if you change its name."), - true, - "images/header_yellow.png" - ); +$table->data[0][1] = html_print_input_text('name', $name, '', 35, 255, true); +if (io_safe_output($name) == 'Monitoring Event') { + $table->data[0][1] .= '  '.ui_print_help_tip( + __('This action may stop working, if you change its name.'), + true, + 'images/header_yellow.png' + ); } + $table->colspan[0][1] = 2; $table->data[1][0] = __('Group'); -$own_info = get_user_info ($config['id_user']); +$own_info = get_user_info($config['id_user']); // Only display group "All" if user is administrator or has "PM" privileges -if ($own_info['is_admin'] || check_acl ($config['id_user'], 0, "PM")) - $display_all_group = true; -else - $display_all_group = false; -$table->data[1][1] = html_print_select_groups(false, "LW", $display_all_group, 'group', $group, '', '', 0, true); +if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { + $display_all_group = true; +} else { + $display_all_group = false; +} + +$table->data[1][1] = html_print_select_groups(false, 'LW', $display_all_group, 'group', $group, '', '', 0, true); $table->colspan[1][1] = 2; $table->data[2][0] = __('Command'); $commands_sql = db_get_all_rows_filter( - 'talert_commands', - array('id_group' => array_keys(users_get_groups(false, "LW"))), - array('id', 'name'), - 'AND', - false, - true + 'talert_commands', + ['id_group' => array_keys(users_get_groups(false, 'LW'))], + [ + 'id', + 'name', + ], + 'AND', + false, + true ); -$table->data[2][1] = html_print_select_from_sql ($commands_sql, 'id_command', $id_command, - '', __('None'), 0, true +$table->data[2][1] = html_print_select_from_sql( + $commands_sql, + 'id_command', + $id_command, + '', + __('None'), + 0, + true ); $table->data[2][1] .= ' '; -if (check_acl ($config['id_user'], 0, "PM")) { - $table->data[2][1] .= html_print_image ('images/add.png', true); - $table->data[2][1] .= ''; - $table->data[2][1] .= __('Create Command'); - $table->data[2][1] .= ''; +if (check_acl($config['id_user'], 0, 'PM')) { + $table->data[2][1] .= html_print_image('images/add.png', true); + $table->data[2][1] .= ''; + $table->data[2][1] .= __('Create Command'); + $table->data[2][1] .= ''; } + $table->data[2][1] .= '
    '; $table->colspan[2][1] = 2; $table->data[3][0] = __('Threshold'); -$table->data[3][1] = html_print_input_text ('action_threshold', $action_threshold, '', 5, 7, true); -$table->data[3][1] .= ' ' . __('seconds') . ui_print_help_icon ('action_threshold', true); +$table->data[3][1] = html_print_input_text('action_threshold', $action_threshold, '', 5, 7, true); +$table->data[3][1] .= ' '.__('seconds').ui_print_help_icon('action_threshold', true); $table->colspan[3][1] = 2; $table->data[4][0] = ''; @@ -165,261 +194,268 @@ $table->cellstyle[4][1] = 'font-weight: bold;'; $table->cellstyle[4][2] = 'font-weight: bold;'; $table->data[5][0] = __('Command preview'); -$table->data[5][1] = html_print_textarea ('command_preview', 5, 30, '', - 'disabled="disabled"', true); -$table->data[5][2] = html_print_textarea ('command_recovery_preview', 5, 30, '', - 'disabled="disabled"', true); +$table->data[5][1] = html_print_textarea( + 'command_preview', + 5, + 30, + '', + 'disabled="disabled"', + true +); +$table->data[5][2] = html_print_textarea( + 'command_recovery_preview', + 5, + 30, + '', + 'disabled="disabled"', + true +); for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - $table->data['field' . $i][0] = html_print_image( - 'images/spinner.gif', true); - $table->data['field' . $i][1] = html_print_image( - 'images/spinner.gif', true); - $table->data['field' . $i][2] = html_print_image( - 'images/spinner.gif', true); + $table->data['field'.$i][0] = html_print_image( + 'images/spinner.gif', + true + ); + $table->data['field'.$i][1] = html_print_image( + 'images/spinner.gif', + true + ); + $table->data['field'.$i][2] = html_print_image( + 'images/spinner.gif', + true + ); - // Store the value in a hidden to keep it on first execution - $table->data['field' . $i][1] .= html_print_input_hidden( - 'field' . $i . '_value', - !empty($action['field' . $i]) ? - $action['field' . $i] : '', - true); - $table->data['field' . $i][2] .= html_print_input_hidden( - 'field' . $i . '_recovery_value', - !empty($action['field' . $i . '_recovery']) ? - $action['field' . $i . '_recovery'] : '', - true); + // Store the value in a hidden to keep it on first execution + $table->data['field'.$i][1] .= html_print_input_hidden( + 'field'.$i.'_value', + !empty($action['field'.$i]) ? $action['field'.$i] : '', + true + ); + $table->data['field'.$i][2] .= html_print_input_hidden( + 'field'.$i.'_recovery_value', + !empty($action['field'.$i.'_recovery']) ? $action['field'.$i.'_recovery'] : '', + true + ); } -echo '
    '; -$table_html = html_print_table ($table, true); +echo ''; +$table_html = html_print_table($table, true); -//////////////////////////////////////////////////////////////////////// -//Hack to hook the bubble dialog of clippy in any place, the intro.js -//fails with new elements in the dom from javascript code -//---------------------------------------------------------------------- +// +// Hack to hook the bubble dialog of clippy in any place, the intro.js +// fails with new elements in the dom from javascript code +// ---------------------------------------------------------------------- /* -$table_html = str_replace( - "", - "
    ", - $table_html); -$table_html = str_replace( - '', - " -
    - - - ", - $table_html); + $table_html = str_replace( + "
    ", + "
    ", + $table_html); + $table_html = str_replace( + '', + " +
    + + + ", + $table_html); */ -//////////////////////////////////////////////////////////////////////// - +// echo $table_html; echo '
    '; if ($id) { - html_print_input_hidden ('id', $id); - if ($al_action['id_group'] == 0) { - // then must have "PM" access privileges - if (check_acl ($config['id_user'], 0, "PM")) { - html_print_input_hidden ('update_action', 1); - html_print_submit_button (__('Update'), 'create', false, 'class="sub upd"'); - } - } - else { - - html_print_input_hidden ('update_action', 1); - html_print_submit_button (__('Update'), 'create', false, 'class="sub upd"'); - } -} -else { - html_print_input_hidden ('create_action', 1); - html_print_submit_button (__('Create'), 'create', false, 'class="sub wand"'); + html_print_input_hidden('id', $id); + if ($al_action['id_group'] == 0) { + // then must have "PM" access privileges + if (check_acl($config['id_user'], 0, 'PM')) { + html_print_input_hidden('update_action', 1); + html_print_submit_button(__('Update'), 'create', false, 'class="sub upd"'); + } + } else { + html_print_input_hidden('update_action', 1); + html_print_submit_button(__('Update'), 'create', false, 'class="sub upd"'); + } +} else { + html_print_input_hidden('create_action', 1); + html_print_submit_button(__('Create'), 'create', false, 'class="sub wand"'); } + echo '
    '; echo ''; enterprise_hook('close_meta_frame'); -ui_require_javascript_file ('pandora_alerts'); +ui_require_javascript_file('pandora_alerts'); ui_require_javascript_file('tiny_mce', 'include/javascript/tiny_mce/'); ?> diff --git a/pandora_console/godmode/alerts/configure_alert_command.php b/pandora_console/godmode/alerts/configure_alert_command.php index 55254cdadf..7482c21f63 100644 --- a/pandora_console/godmode/alerts/configure_alert_command.php +++ b/pandora_console/godmode/alerts/configure_alert_command.php @@ -1,10 +1,9 @@ -width = '100%'; $table->class = 'databox filters'; if (defined('METACONSOLE')) { - $table->head[0] = ($id) ? __('Update Command') : __('Create Command'); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; + $table->head[0] = ($id) ? __('Update Command') : __('Create Command'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; } -$table->style = array (); + +$table->style = []; if (!defined('METACONSOLE')) { - $table->style[0] = 'font-weight: bold'; - $table->style[2] = 'font-weight: bold'; + $table->style[0] = 'font-weight: bold'; + $table->style[2] = 'font-weight: bold'; } -$table->size = array (); + +$table->size = []; $table->size[0] = '20%'; -$table->data = array (); +$table->data = []; $table->colspan['name'][1] = 3; $table->data['name'][0] = __('Name'); -$table->data['name'][2] = html_print_input_text ('name', $name, '', 35, 255, true); +$table->data['name'][2] = html_print_input_text('name', $name, '', 35, 255, true); $table->colspan['command'][1] = 3; $table->data['command'][0] = __('Command'); -$table->data['command'][0] .= ui_print_help_icon ('alert_macros', true); -$table->data['command'][1] = html_print_textarea ('command', 8, 30, $command, '', true); +$table->data['command'][0] .= ui_print_help_icon('alert_macros', true); +$table->data['command'][1] = html_print_textarea('command', 8, 30, $command, '', true); $table->colspan['group'][1] = 3; $table->data['group'][0] = __('Group'); -$table->data['group'][1] = html_print_select_groups(false, "LM", - true, 'id_group', $id_group, false, - '', 0, true); +$table->data['group'][1] = html_print_select_groups( + false, + 'LM', + true, + 'id_group', + $id_group, + false, + '', + 0, + true +); $table->colspan['description'][1] = 3; $table->data['description'][0] = __('Description'); -$table->data['description'][1] = html_print_textarea ('description', 10, 30, $description, '', true); +$table->data['description'][1] = html_print_textarea('description', 10, 30, $description, '', true); for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - - $table->data['field'.$i][0] = sprintf(__('Field %s description'), $i); - - // Only show help on first row - if ($i == 1) { - $table->data['field'.$i][0] .= ui_print_help_icon ('alert_fields_description', true); - } - - if (!empty($fields_descriptions)) { - $field_description = $fields_descriptions[$i-1]; - } - else { - $field_description = ''; - } - $table->data['field'.$i][1] = html_print_input_text ('field'.$i.'_description', $field_description, '', 35, 255, true); - - $table->data['field'.$i][2] = sprintf(__('Field %s values'), $i); - - // Only show help on first row - if ($i == 1) { - $table->data['field'.$i][2] .= ui_print_help_icon ('alert_fields_values', true); - } - - if (!empty($fields_values)) { - $field_values = $fields_values[$i-1]; - } - else { - $field_values = ''; - } - $table->data['field'.$i][3] = html_print_input_text ('field'.$i.'_values', $field_values, '', 65, 255, true); + $table->data['field'.$i][0] = sprintf(__('Field %s description'), $i); + + // Only show help on first row + if ($i == 1) { + $table->data['field'.$i][0] .= ui_print_help_icon('alert_fields_description', true); + } + + if (!empty($fields_descriptions)) { + $field_description = $fields_descriptions[($i - 1)]; + } else { + $field_description = ''; + } + + $table->data['field'.$i][1] = html_print_input_text('field'.$i.'_description', $field_description, '', 35, 255, true); + + $table->data['field'.$i][2] = sprintf(__('Field %s values'), $i); + + // Only show help on first row + if ($i == 1) { + $table->data['field'.$i][2] .= ui_print_help_icon('alert_fields_values', true); + } + + if (!empty($fields_values)) { + $field_values = $fields_values[($i - 1)]; + } else { + $field_values = ''; + } + + $table->data['field'.$i][3] = html_print_input_text('field'.$i.'_values', $field_values, '', 65, 255, true); } echo ''; -html_print_table ($table); +html_print_table($table); echo '
    '; if ($id) { - html_print_input_hidden ('id', $id); - html_print_input_hidden ('update_command', 1); - html_print_submit_button (__('Update'), 'create', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create_command', 1); - html_print_submit_button (__('Create'), 'create', false, 'class="sub wand"'); + html_print_input_hidden('id', $id); + html_print_input_hidden('update_command', 1); + html_print_submit_button(__('Update'), 'create', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create_command', 1); + html_print_submit_button(__('Create'), 'create', false, 'class="sub wand"'); } + echo '
    '; echo ''; enterprise_hook('close_meta_frame'); - -?> diff --git a/pandora_console/godmode/alerts/configure_alert_special_days.php b/pandora_console/godmode/alerts/configure_alert_special_days.php index f20cdfbf59..ed2ea29875 100644 --- a/pandora_console/godmode/alerts/configure_alert_special_days.php +++ b/pandora_console/godmode/alerts/configure_alert_special_days.php @@ -1,11 +1,10 @@ -width = '100%'; $table->class = 'databox filters'; -$table->style = array (); +$table->style = []; $table->style[0] = 'font-weight: bold'; -$table->size = array (); +$table->size = []; $table->size[0] = '20%'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Date'); -$table->data[0][1] = html_print_input_text ('date', $date, '', 10, 10, true); -$table->data[0][1] .= html_print_image ("images/calendar_view_day.png", true, array ("alt" => "calendar", "onclick" => "scwShow(scwID('text-date'),this);")); +$table->data[0][1] = html_print_input_text('date', $date, '', 10, 10, true); +$table->data[0][1] .= html_print_image('images/calendar_view_day.png', true, ['alt' => 'calendar', 'onclick' => "scwShow(scwID('text-date'),this);"]); $table->data[1][0] = __('Group'); -$groups = users_get_groups (); -$own_info = get_user_info ($config['id_user']); +$groups = users_get_groups(); +$own_info = get_user_info($config['id_user']); // Only display group "All" if user is administrator or has "LM" privileges -if (users_can_manage_group_all("LM")) - $display_all_group = true; -else - $display_all_group = false; -$table->data[1][1] = html_print_select_groups(false, "LW", $display_all_group, 'id_group', $id_group, '', '', 0, true); +if (users_can_manage_group_all('LM')) { + $display_all_group = true; +} else { + $display_all_group = false; +} + +$table->data[1][1] = html_print_select_groups(false, 'LW', $display_all_group, 'id_group', $id_group, '', '', 0, true); $table->data[2][0] = __('Same day of the week'); -$days = array (); -$days["monday"] = __('Monday'); -$days["tuesday"] = __('Tuesday'); -$days["wednesday"] = __('Wednesday'); -$days["thursday"] = __('Thursday'); -$days["friday"] = __('Friday'); -$days["saturday"] = __('Saturday'); -$days["sunday"] = __('Sunday'); -$table->data[2][1] = html_print_select ($days, "same_day", $same_day, '', '', 0, true, false, false); +$days = []; +$days['monday'] = __('Monday'); +$days['tuesday'] = __('Tuesday'); +$days['wednesday'] = __('Wednesday'); +$days['thursday'] = __('Thursday'); +$days['friday'] = __('Friday'); +$days['saturday'] = __('Saturday'); +$days['sunday'] = __('Sunday'); +$table->data[2][1] = html_print_select($days, 'same_day', $same_day, '', '', 0, true, false, false); $table->data[3][0] = __('Description'); -$table->data[3][1] = html_print_textarea ('description', 10, 30, $description, '', true); +$table->data[3][1] = html_print_textarea('description', 10, 30, $description, '', true); echo ''; -html_print_table ($table); +html_print_table($table); echo '
    '; if ($id) { - html_print_input_hidden ('id', $id); - html_print_input_hidden ('update_special_day', 1); - html_print_input_hidden ('id_group_orig', $id_group_orig); - html_print_input_hidden ('date_orig', $date_orig); - html_print_submit_button (__('Update'), 'create', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create_special_day', 1); - html_print_submit_button (__('Create'), 'create', false, 'class="sub wand"'); + html_print_input_hidden('id', $id); + html_print_input_hidden('update_special_day', 1); + html_print_input_hidden('id_group_orig', $id_group_orig); + html_print_input_hidden('date_orig', $date_orig); + html_print_submit_button(__('Update'), 'create', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create_special_day', 1); + html_print_submit_button(__('Create'), 'create', false, 'class="sub wand"'); } + echo '
    '; echo ''; -?> diff --git a/pandora_console/godmode/alerts/configure_alert_template.php b/pandora_console/godmode/alerts/configure_alert_template.php index b75b26561f..d6828dd599 100644 --- a/pandora_console/godmode/alerts/configure_alert_template.php +++ b/pandora_console/godmode/alerts/configure_alert_template.php @@ -1,10 +1,9 @@ -'; - - if (defined('METACONSOLE')) { - - $sec = 'advanced'; - } - else { - - $sec = 'galertas'; - } - - $pure = get_parameter('pure', 0); - - /* Step 1 */ - if ($step == 1) - echo '
  • '; - elseif ($step > 1) - echo '
  • '; - else - echo '
  • '; - - if ($id) { - echo ''; - echo __('Step') . ' 1 » '; - echo '' . __('General') . ''; - echo ''; - } - else { - echo __('Step') . ' 1 » '; - echo '' . __('General') . ''; - } - echo '
  • '; - - /* Step 2 */ - if ($step == 2) - echo '
  • '; - elseif ($step > 2) - echo '
  • '; - else - echo '
  • '; - - if ($id) { - echo ''; - echo __('Step').' 2 » '; - echo ''.__('Conditions').''; - echo ''; - } - else { - echo __('Step').' 2 » '; - echo ''.__('Conditions').''; - } - echo '
  • '; - - /* Step 3 */ - if ($step == 3) - echo '
  • '; - elseif ($step > 3) - echo '
  • '; - else - echo '
  • '; - - if ($id) { - echo ''; - echo __('Step').' 3 » '; - echo ''.__('Advanced fields').''; - echo ''; - } - else { - echo __('Step').' 3 » '; - echo ''.__('Advanced fields').''; - } - - echo ''; - echo '
    '; +function print_alert_template_steps($step, $id) +{ + echo '
      '; + + if (defined('METACONSOLE')) { + $sec = 'advanced'; + } else { + $sec = 'galertas'; + } + + $pure = get_parameter('pure', 0); + + // Step 1 + if ($step == 1) { + echo '
    1. '; + } else if ($step > 1) { + echo '
    2. '; + } else { + echo '
    3. '; + } + + if ($id) { + echo ''; + echo __('Step').' 1 » '; + echo ''.__('General').''; + echo ''; + } else { + echo __('Step').' 1 » '; + echo ''.__('General').''; + } + + echo '
    4. '; + + // Step 2 + if ($step == 2) { + echo '
    5. '; + } else if ($step > 2) { + echo '
    6. '; + } else { + echo '
    7. '; + } + + if ($id) { + echo ''; + echo __('Step').' 2 » '; + echo ''.__('Conditions').''; + echo ''; + } else { + echo __('Step').' 2 » '; + echo ''.__('Conditions').''; + } + + echo '
    8. '; + + // Step 3 + if ($step == 3) { + echo '
    9. '; + } else if ($step > 3) { + echo '
    10. '; + } else { + echo '
    11. '; + } + + if ($id) { + echo ''; + echo __('Step').' 3 » '; + echo ''.__('Advanced fields').''; + echo ''; + } else { + echo __('Step').' 3 » '; + echo ''.__('Advanced fields').''; + } + + echo '
    '; + echo '
    '; } -function update_template ($step) { - global $config; - - $id = (int) get_parameter ('id'); - - if (empty ($id)) - return false; - - if (defined('METACONSOLE')) { - - $sec = 'advanced'; - } - else { - - $sec = 'galertas'; - } - - if ($step == 1) { - $name = (string) get_parameter ('name'); - $description = (string) get_parameter ('description'); - $wizard_level = (string) get_parameter ('wizard_level'); - $priority = (int) get_parameter ('priority'); - $id_group = get_parameter ("id_group"); - - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $name_check = db_get_value ('name', 'talert_templates', 'name', $name); - break; - case "oracle": - $name_check = db_get_value ('name', 'talert_templates', 'to_char(name)', $name); - break; - } - - $values = array ('name' => $name, - 'description' => $description, - 'id_group' => $id_group, - 'priority' => $priority, - 'wizard_level' => $wizard_level); - - $result = alerts_update_alert_template ($id,$values); - } - elseif ($step == 2) { - $monday = (bool) get_parameter ('monday'); - $tuesday = (bool) get_parameter ('tuesday'); - $wednesday = (bool) get_parameter ('wednesday'); - $thursday = (bool) get_parameter ('thursday'); - $friday = (bool) get_parameter ('friday'); - $saturday = (bool) get_parameter ('saturday'); - $sunday = (bool) get_parameter ('sunday'); - $special_day = (bool) get_parameter ('special_day'); - $time_from = (string) get_parameter ('time_from'); - $time_from = date ("H:i:00", strtotime ($time_from)); - $time_to = (string) get_parameter ('time_to'); - $time_to = date ("H:i:00", strtotime ($time_to)); - $threshold = (int) get_parameter ('threshold'); - $max_alerts = (int) get_parameter ('max_alerts'); - $min_alerts = (int) get_parameter ('min_alerts'); - $min_alerts_reset_counter = (int) get_parameter ('min_alerts_reset_counter'); - $type = (string) get_parameter ('type'); - $value = (string) html_entity_decode (get_parameter ('value')); - $max = (float) get_parameter ('max'); - $min = (float) get_parameter ('min'); - $matches = (bool) get_parameter ('matches_value'); - - $default_action = (int) get_parameter ('default_action'); - if (empty ($default_action)) { - $default_action = NULL; - } - - $values = array ( - 'monday' => $monday, - 'tuesday' => $tuesday, - 'wednesday' => $wednesday, - 'thursday' => $thursday, - 'friday' => $friday, - 'saturday' => $saturday, - 'sunday' => $sunday, - 'special_day' => $special_day, - 'time_threshold' => $threshold, - 'id_alert_action' => $default_action, - 'max_alerts' => $max_alerts, - 'min_alerts' => $min_alerts, - 'min_alerts_reset_counter' => $min_alerts_reset_counter, - 'type' => $type, - 'value' => $value, - 'max_value' => $max, - 'min_value' => $min, - 'matches_value' => $matches); - - // Different datetimes format for oracle - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $values['time_from'] = $time_from; - $values['time_to'] = $time_to; - break; - case "oracle": - $values['time_from'] = "#to_date('" . $time_from . "','hh24:mi:ss')"; - $values['time_to'] = "#to_date('" . $time_to . "','hh24:mi:ss')"; - break; - } - - $result = alerts_update_alert_template ($id, $values); - } - elseif ($step == 3) { - $recovery_notify = (bool) get_parameter ('recovery_notify'); - for($i=1;$i<=$config['max_macro_fields'];$i++) { - $values['field'.$i] = (string) get_parameter ('field'.$i); - $values['field'.$i.'_recovery'] = $recovery_notify ? (string) get_parameter ('field'.$i.'_recovery') : ''; - } - - $values['recovery_notify'] = $recovery_notify; - - $result = alerts_update_alert_template ($id, $values); - } - else { - return false; - } - - if ($result) { - db_pandora_audit("Template alert management", "Update alert template #" . $id, false, false, json_encode($values)); - } - else { - db_pandora_audit("Template alert management", "Fail try to update alert template #" . $id, false, false, json_encode($values)); - } - - return $result; + +function update_template($step) +{ + global $config; + + $id = (int) get_parameter('id'); + + if (empty($id)) { + return false; + } + + if (defined('METACONSOLE')) { + $sec = 'advanced'; + } else { + $sec = 'galertas'; + } + + if ($step == 1) { + $name = (string) get_parameter('name'); + $description = (string) get_parameter('description'); + $wizard_level = (string) get_parameter('wizard_level'); + $priority = (int) get_parameter('priority'); + $id_group = get_parameter('id_group'); + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $name_check = db_get_value('name', 'talert_templates', 'name', $name); + break; + + case 'oracle': + $name_check = db_get_value('name', 'talert_templates', 'to_char(name)', $name); + break; + } + + $values = [ + 'name' => $name, + 'description' => $description, + 'id_group' => $id_group, + 'priority' => $priority, + 'wizard_level' => $wizard_level, + ]; + + $result = alerts_update_alert_template($id, $values); + } else if ($step == 2) { + $monday = (bool) get_parameter('monday'); + $tuesday = (bool) get_parameter('tuesday'); + $wednesday = (bool) get_parameter('wednesday'); + $thursday = (bool) get_parameter('thursday'); + $friday = (bool) get_parameter('friday'); + $saturday = (bool) get_parameter('saturday'); + $sunday = (bool) get_parameter('sunday'); + $special_day = (bool) get_parameter('special_day'); + $time_from = (string) get_parameter('time_from'); + $time_from = date('H:i:00', strtotime($time_from)); + $time_to = (string) get_parameter('time_to'); + $time_to = date('H:i:00', strtotime($time_to)); + $threshold = (int) get_parameter('threshold'); + $max_alerts = (int) get_parameter('max_alerts'); + $min_alerts = (int) get_parameter('min_alerts'); + $min_alerts_reset_counter = (int) get_parameter('min_alerts_reset_counter'); + $type = (string) get_parameter('type'); + $value = (string) html_entity_decode(get_parameter('value')); + $max = (float) get_parameter('max'); + $min = (float) get_parameter('min'); + $matches = (bool) get_parameter('matches_value'); + + $default_action = (int) get_parameter('default_action'); + if (empty($default_action)) { + $default_action = null; + } + + $values = [ + 'monday' => $monday, + 'tuesday' => $tuesday, + 'wednesday' => $wednesday, + 'thursday' => $thursday, + 'friday' => $friday, + 'saturday' => $saturday, + 'sunday' => $sunday, + 'special_day' => $special_day, + 'time_threshold' => $threshold, + 'id_alert_action' => $default_action, + 'max_alerts' => $max_alerts, + 'min_alerts' => $min_alerts, + 'min_alerts_reset_counter' => $min_alerts_reset_counter, + 'type' => $type, + 'value' => $value, + 'max_value' => $max, + 'min_value' => $min, + 'matches_value' => $matches, + ]; + + // Different datetimes format for oracle + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $values['time_from'] = $time_from; + $values['time_to'] = $time_to; + break; + + case 'oracle': + $values['time_from'] = "#to_date('".$time_from."','hh24:mi:ss')"; + $values['time_to'] = "#to_date('".$time_to."','hh24:mi:ss')"; + break; + } + + $result = alerts_update_alert_template($id, $values); + } else if ($step == 3) { + $recovery_notify = (bool) get_parameter('recovery_notify'); + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + $values['field'.$i] = (string) get_parameter('field'.$i); + $values['field'.$i.'_recovery'] = $recovery_notify ? (string) get_parameter('field'.$i.'_recovery') : ''; + } + + $values['recovery_notify'] = $recovery_notify; + + $result = alerts_update_alert_template($id, $values); + } else { + return false; + } + + if ($result) { + db_pandora_audit('Template alert management', 'Update alert template #'.$id, false, false, json_encode($values)); + } else { + db_pandora_audit('Template alert management', 'Fail try to update alert template #'.$id, false, false, json_encode($values)); + } + + return $result; } -/* We set here the number of steps */ -define ('LAST_STEP', 3); -$step = (int) get_parameter ('step', 1); +// We set here the number of steps +define('LAST_STEP', 3); -$create_alert = (bool) get_parameter ('create_alert'); -$create_template = (bool) get_parameter ('create_template'); -$update_template = (bool) get_parameter ('update_template'); +$step = (int) get_parameter('step', 1); + +$create_alert = (bool) get_parameter('create_alert'); +$create_template = (bool) get_parameter('create_template'); +$update_template = (bool) get_parameter('update_template'); $name = ''; $description = ''; @@ -356,13 +360,15 @@ $saturday = true; $sunday = true; $special_day = false; $default_action = 0; -$fields = array(); +$fields = []; for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - $fields[$i] = ''; + $fields[$i] = ''; } + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - $fields_recovery[$i] = ''; + $fields_recovery[$i] = ''; } + $priority = 1; $min_alerts = 0; $min_alerts_reset_counter = 0; @@ -376,473 +382,613 @@ $id_group = 0; $wizard_level = 'nowizard'; if ($create_template) { - $name = (string) get_parameter ('name'); - $description = (string) get_parameter ('description'); - $type = (string) get_parameter ('type', 'critical'); - $value = (string) get_parameter ('value'); - $max = (float) get_parameter ('max'); - $min = (float) get_parameter ('min'); - $matches = (bool) get_parameter ('matches_value'); - $priority = (int) get_parameter ('priority'); - $wizard_level = (string) get_parameter ('wizard_level'); - $id_group = get_parameter ("id_group"); - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $name_check = db_get_value ('name', 'talert_templates', 'name', $name); - break; - case "oracle": - $name_check = db_get_value ('name', 'talert_templates', 'to_char(name)', $name); - break; - } - - - $values = array ('description' => $description, - 'value' => $value, - 'max_value' => $max, - 'min_value' => $min, - 'id_group' => $id_group, - 'matches_value' => $matches, - 'priority' => $priority, - 'wizard_level' => $wizard_level); - - if ($config['dbtype'] == "oracle") { - $values['field3'] = ' '; - $values['field3_recovery'] = ' '; - } - - if (!$name_check) { - $result = alerts_create_alert_template ($name, $type, $values); - } - else { - $result = ''; - } - if ($result) { - db_pandora_audit("Template alert management", - "Create alert template #" . $result, false, false, - json_encode($values)); - } - else { - db_pandora_audit("Template alert management", - "Fail try to create alert template", false, false, - json_encode($values)); - } - + $name = (string) get_parameter('name'); + $description = (string) get_parameter('description'); + $type = (string) get_parameter('type', 'critical'); + $value = (string) get_parameter('value'); + $max = (float) get_parameter('max'); + $min = (float) get_parameter('min'); + $matches = (bool) get_parameter('matches_value'); + $priority = (int) get_parameter('priority'); + $wizard_level = (string) get_parameter('wizard_level'); + $id_group = get_parameter('id_group'); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $name_check = db_get_value('name', 'talert_templates', 'name', $name); + break; - /* Show errors */ - if (!isset($messageAction)) { - $messageAction = __('Could not be created'); - } - - if ($name == "") { - $messageAction = __('No template name specified'); - } + case 'oracle': + $name_check = db_get_value('name', 'talert_templates', 'to_char(name)', $name); + break; + } - $messageAction = ui_print_result_message ($result, - __('Successfully created'), - $messageAction); - - /* Go to previous step in case of error */ - if ($result === false) - $step = $step - 1; - else - $id = $result; + $values = [ + 'description' => $description, + 'value' => $value, + 'max_value' => $max, + 'min_value' => $min, + 'id_group' => $id_group, + 'matches_value' => $matches, + 'priority' => $priority, + 'wizard_level' => $wizard_level, + ]; + + if ($config['dbtype'] == 'oracle') { + $values['field3'] = ' '; + $values['field3_recovery'] = ' '; + } + + if (!$name_check) { + $result = alerts_create_alert_template($name, $type, $values); + } else { + $result = ''; + } + + if ($result) { + db_pandora_audit( + 'Template alert management', + 'Create alert template #'.$result, + false, + false, + json_encode($values) + ); + } else { + db_pandora_audit( + 'Template alert management', + 'Fail try to create alert template', + false, + false, + json_encode($values) + ); + } + + + // Show errors + if (!isset($messageAction)) { + $messageAction = __('Could not be created'); + } + + if ($name == '') { + $messageAction = __('No template name specified'); + } + + $messageAction = ui_print_result_message( + $result, + __('Successfully created'), + $messageAction + ); + + + // Go to previous step in case of error + if ($result === false) { + $step = ($step - 1); + } else { + $id = $result; + } } if ($update_template) { - $result = update_template ($step - 1); - - ui_print_result_message ($result, - __('Successfully updated'), - __('Could not be updated')); - /* Go to previous step in case of error */ - if ($result === false) { - $step = $step - 1; - } + $result = update_template($step - 1); + + ui_print_result_message( + $result, + __('Successfully updated'), + __('Could not be updated') + ); + // Go to previous step in case of error + if ($result === false) { + $step = ($step - 1); + } } if ($id && ! $create_template) { - $template = alerts_get_alert_template ($id); - $name = $template['name']; - $description = $template['description']; - $type = $template['type']; - $value = $template['value']; - $max = $template['max_value']; - $min = $template['min_value']; - $matches = $template['matches_value']; - $time_from = $template['time_from']; - $time_to = $template['time_to']; - $monday = (bool) $template['monday']; - $tuesday = (bool) $template['tuesday']; - $wednesday = (bool) $template['wednesday']; - $thursday = (bool) $template['thursday']; - $friday = (bool) $template['friday']; - $saturday = (bool) $template['saturday']; - $sunday = (bool) $template['sunday']; - $special_day = (bool) $template['special_day']; - $max_alerts = $template['max_alerts']; - $min_alerts = $template['min_alerts']; - $min_alerts_reset_counter = $template['min_alerts_reset_counter']; - $threshold = $template['time_threshold']; - $fields = array(); - for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - $fields[$i] = $template['field'.$i]; - } - $recovery_notify = $template['recovery_notify']; - - $fields_recovery = array(); - for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - $fields_recovery[$i] = $template['field'.$i.'_recovery']; - } - - $default_action = $template['id_alert_action']; - $priority = $template['priority']; - $id_group = $template['id_group']; - $wizard_level = $template['wizard_level']; + $template = alerts_get_alert_template($id); + $name = $template['name']; + $description = $template['description']; + $type = $template['type']; + $value = $template['value']; + $max = $template['max_value']; + $min = $template['min_value']; + $matches = $template['matches_value']; + $time_from = $template['time_from']; + $time_to = $template['time_to']; + $monday = (bool) $template['monday']; + $tuesday = (bool) $template['tuesday']; + $wednesday = (bool) $template['wednesday']; + $thursday = (bool) $template['thursday']; + $friday = (bool) $template['friday']; + $saturday = (bool) $template['saturday']; + $sunday = (bool) $template['sunday']; + $special_day = (bool) $template['special_day']; + $max_alerts = $template['max_alerts']; + $min_alerts = $template['min_alerts']; + $min_alerts_reset_counter = $template['min_alerts_reset_counter']; + $threshold = $template['time_threshold']; + $fields = []; + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + $fields[$i] = $template['field'.$i]; + } + + $recovery_notify = $template['recovery_notify']; + + $fields_recovery = []; + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + $fields_recovery[$i] = $template['field'.$i.'_recovery']; + } + + $default_action = $template['id_alert_action']; + $priority = $template['priority']; + $id_group = $template['id_group']; + $wizard_level = $template['wizard_level']; } -print_alert_template_steps ($step, $id); +print_alert_template_steps($step, $id); $table = new stdClass(); $table->id = 'template'; $table->width = '100%'; $table->class = 'databox filters'; -if(defined("METACONSOLE")) { - $table->head[0] = __('Create Template'); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; +if (defined('METACONSOLE')) { + $table->head[0] = __('Create Template'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; } -$table->style = array (); + +$table->style = []; $table->style[0] = 'font-weight: bold;'; $table->style[2] = 'font-weight: bold;'; -$table->size = array (); +$table->size = []; $table->size[0] = '20%'; $table->size[2] = '20%'; if ($step == 2) { - - if (!isset($show_matches)) - $show_matches = false; - - /* Firing conditions and events */ - $table->colspan = array (); - $table->colspan[4][1] = 3; - - $table->data[0][0] = __('Days of week'); - $table->data[0][1] = __('Mon'); - $table->data[0][1] .= html_print_checkbox ('monday', 1, $monday, true); - $table->data[0][1] .= __('Tue'); - $table->data[0][1] .= html_print_checkbox ('tuesday', 1, $tuesday, true); - $table->data[0][1] .= __('Wed'); - $table->data[0][1] .= html_print_checkbox ('wednesday', 1, $wednesday, true); - $table->data[0][1] .= __('Thu'); - $table->data[0][1] .= html_print_checkbox ('thursday', 1, $thursday, true); - $table->data[0][1] .= __('Fri'); - $table->data[0][1] .= html_print_checkbox ('friday', 1, $friday, true); - $table->data[0][1] .= __('Sat'); - $table->data[0][1] .= html_print_checkbox ('saturday', 1, $saturday, true); - $table->data[0][1] .= __('Sun'); - $table->data[0][1] .= html_print_checkbox ('sunday', 1, $sunday, true); - - $table->data[0][2] = __('Use special days list'); - $table->data[0][3] = html_print_checkbox ('special_day', 1, $special_day, true); - - $table->data[1][0] = __('Time from') . ' ' . - ui_print_help_tip(__('Watch format is hours (24h):minutes:seconds'), true); - $table->data[1][1] = html_print_input_text ('time_from', $time_from, '', 7, 8, - true); - $table->data[1][2] = __('Time to') . ' ' . - ui_print_help_tip(__('Watch format is hours (24h):minutes:seconds'), true); - $table->data[1][3] = html_print_input_text ('time_to', $time_to, '', 7, 8, - true); - - $table->colspan['threshold'][1] = 3; - $table->data['threshold'][0] = __('Time threshold'); - $table->data['threshold'][1] = html_print_extended_select_for_time ('threshold', $threshold, '', '', - '', false, true); - - $table->data[3][0] = __('Min. number of alerts'); - $table->data[3][1] = html_print_input_text ('min_alerts', - $min_alerts, '', 5, 7, true); + if (!isset($show_matches)) { + $show_matches = false; + } - $table->data[3][2] = __('Reset counter for non-sustained alerts') . ui_print_help_tip(__('Enable this option if you want the counter to be reset when the alert is not being fired consecutively, even if it\'s within the time threshold'), true); - $table->data[3][3] = html_print_checkbox ('min_alerts_reset_counter', 1, $min_alerts_reset_counter, true); + // Firing conditions and events + $table->colspan = []; + $table->colspan[4][1] = 3; - $table->data[4][0] = __('Max. number of alerts'); - $table->data[4][1] = html_print_input_text ('max_alerts', - $max_alerts, '', 5, 7, true); - - $table->data[5][0] = __('Default action'); - $usr_groups = implode(',', array_keys(users_get_groups($config['id_user'], 'LM', true))); - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $sql_query = sprintf(' + $table->data[0][0] = __('Days of week'); + $table->data[0][1] = __('Mon'); + $table->data[0][1] .= html_print_checkbox('monday', 1, $monday, true); + $table->data[0][1] .= __('Tue'); + $table->data[0][1] .= html_print_checkbox('tuesday', 1, $tuesday, true); + $table->data[0][1] .= __('Wed'); + $table->data[0][1] .= html_print_checkbox('wednesday', 1, $wednesday, true); + $table->data[0][1] .= __('Thu'); + $table->data[0][1] .= html_print_checkbox('thursday', 1, $thursday, true); + $table->data[0][1] .= __('Fri'); + $table->data[0][1] .= html_print_checkbox('friday', 1, $friday, true); + $table->data[0][1] .= __('Sat'); + $table->data[0][1] .= html_print_checkbox('saturday', 1, $saturday, true); + $table->data[0][1] .= __('Sun'); + $table->data[0][1] .= html_print_checkbox('sunday', 1, $sunday, true); + + $table->data[0][2] = __('Use special days list'); + $table->data[0][3] = html_print_checkbox('special_day', 1, $special_day, true); + + $table->data[1][0] = __('Time from').' '.ui_print_help_tip(__('Watch format is hours (24h):minutes:seconds'), true); + $table->data[1][1] = html_print_input_text( + 'time_from', + $time_from, + '', + 7, + 8, + true + ); + $table->data[1][2] = __('Time to').' '.ui_print_help_tip(__('Watch format is hours (24h):minutes:seconds'), true); + $table->data[1][3] = html_print_input_text( + 'time_to', + $time_to, + '', + 7, + 8, + true + ); + + $table->colspan['threshold'][1] = 3; + $table->data['threshold'][0] = __('Time threshold'); + $table->data['threshold'][1] = html_print_extended_select_for_time( + 'threshold', + $threshold, + '', + '', + '', + false, + true + ); + + $table->data[3][0] = __('Min. number of alerts'); + $table->data[3][1] = html_print_input_text( + 'min_alerts', + $min_alerts, + '', + 5, + 7, + true + ); + + $table->data[3][2] = __('Reset counter for non-sustained alerts').ui_print_help_tip(__('Enable this option if you want the counter to be reset when the alert is not being fired consecutively, even if it\'s within the time threshold'), true); + $table->data[3][3] = html_print_checkbox('min_alerts_reset_counter', 1, $min_alerts_reset_counter, true); + + $table->data[4][0] = __('Max. number of alerts'); + $table->data[4][1] = html_print_input_text( + 'max_alerts', + $max_alerts, + '', + 5, + 7, + true + ); + + $table->data[5][0] = __('Default action'); + $usr_groups = implode(',', array_keys(users_get_groups($config['id_user'], 'LM', true))); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $sql_query = sprintf( + ' SELECT id, name FROM talert_actions WHERE id_group IN (%s) - ORDER BY name', $usr_groups); - break; - case "oracle": - $sql_query = sprintf(' + ORDER BY name', + $usr_groups + ); + break; + + case 'oracle': + $sql_query = sprintf( + ' SELECT id, dbms_lob.substr(name,4000,1) AS nombre FROM talert_actions WHERE id_group IN (%s) - ORDER BY dbms_lob.substr(name,4000,1)', $usr_groups); - break; - } - $table->data[5][1] = html_print_select_from_sql ($sql_query, - 'default_action', $default_action, '', __('None'), 0, - true, false, false, false, false, false, 0) . - ui_print_help_tip ( - __('Unless they\'re left blank, the fields from the action will override those set on the template.'), true); - - $table->data[6][0] = __('Condition type'); - $table->data[6][1] = html_print_select (alerts_get_alert_templates_types (), 'type', - $type, '', __('Select'), 0, true, false, false); - $table->data[6][1] .= ''; - $table->data[6][1] .= ' '.html_print_checkbox ('matches_value', 1, $matches, true); - $table->data[6][1] .= html_print_label( - __('Trigger when matches the value'), - 'checkbox-matches_value', true); - $table->data[6][1] .= ''; - $table->colspan[6][1] = 3; - - $table->data['value'][0] = __('Value'); - $table->data['value'][1] = html_print_input_text ('value', $value, '', - 35, 255, true); - $table->data['value'][1] .= ' '; - $table->data['value'][1] .= html_print_image ('images/suc.png', true, - array ('style' => 'display:none', - 'id' => 'regex_good', - 'title' => __('The regular expression is valid'), - 'width' => '20px')); - $table->data['value'][1] .= html_print_image ('images/err.png', true, - array ('style' => 'display:none', - 'id' => 'regex_bad', - 'title' => __('The regular expression is not valid'), - 'width' => '20px')); - $table->data['value'][1] .= ''; - $table->colspan['value'][1] = 3; - - //Min first, then max, that's more logical - $table->data['min'][0] = __('Min.'); - $table->data['min'][1] = html_print_input_text ('min', $min, '', 5, - 255, true); - $table->colspan['min'][1] = 3; - - $table->data['max'][0] = __('Max.'); - $table->data['max'][1] = html_print_input_text ('max', $max, '', 5, - 255, true); - $table->colspan['max'][1] = 3; - - $table->data['example'][1] = ui_print_alert_template_example($id, - true, false); - $table->colspan['example'][1] = 4; -} -else if ($step == 3) { - $table->style[0] = 'font-weight: bold; vertical-align: middle'; - $table->style[1] = 'font-weight: bold; vertical-align: top'; - $table->style[2] = 'font-weight: bold; vertical-align: top'; - $table->size = array (); - $table->size[0] = '10%'; - $table->size[1] = '45%'; - $table->size[2] = '45%'; - - /* Alert recover */ - if (! $recovery_notify) { - $table->cellstyle['label_fields'][2] = 'display:none;'; - for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - $table->cellstyle['field' . $i][2] = 'display:none;'; - } - /* - $table->cellstyle['field1'][2] = 'display:none;'; - $table->cellstyle['field2'][2] = 'display:none;'; - $table->cellstyle['field3'][2] = 'display:none;'; - $table->cellstyle['field4'][2] = 'display:none;'; - $table->cellstyle['field5'][2] = 'display:none;'; - $table->cellstyle['field6'][2] = 'display:none;'; - $table->cellstyle['field7'][2] = 'display:none;'; - $table->cellstyle['field8'][2] = 'display:none;'; - $table->cellstyle['field9'][2] = 'display:none;'; - $table->cellstyle['field10'][2] = 'display:none;'; - */ - } - $table->data[0][0] = __('Alert recovery'); - $values = array (false => __('Disabled'), true => __('Enabled')); - $table->data[0][1] = html_print_select ($values, - 'recovery_notify', $recovery_notify, '', '', '', true, false, - false); - $table->colspan[0][1] = 2; - - $table->data['label_fields'][0] = ''; - $table->data['label_fields'][1] = __('Firing fields'); - $table->data['label_fields'][2] = __('Recovery fields'); - - for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - if (isset($template[$name])) { - $value = $template[$name]; - } - else { - $value = ''; - } - - //$table->rowclass['field'.$i] = 'row_field'; - - - $table->data['field'.$i][0] = sprintf(__('Field %s'), $i) . ui_print_help_icon ('alert_macros', true); - //TinyMCE - //triggering fields - //basic - $table->data['field'.$i][1] = "
    "; - $table->data['field'.$i][1] .= __('Basic') . "  "; - $table->data['field'.$i][1] .= html_print_radio_button_extended ('editor_type_value_'.$i, 0, '', false, false, "removeTinyMCE('textarea_field".$i."')", '', true); - //Advanced - $table->data['field'.$i][1] .= "    "; - $table->data['field'.$i][1] .= __('Advanced') . "  "; - $table->data['field'.$i][1] .= html_print_radio_button_extended ('editor_type_value_'.$i, 0, '', true, false, "addTinyMCE('textarea_field".$i."')", '', true); - $table->data['field'.$i][1] .= "
    "; - - //Texarea - $table->data['field'.$i][1] .= html_print_textarea('field'.$i, 1, 1, isset($fields[$i]) ? $fields[$i] : '', 'style="min-height:40px;" class="fields"', true); - - // Recovery - //basic - $table->data['field'.$i][2] = "
    "; - $table->data['field'.$i][2] .= __('Basic') . "  "; - $table->data['field'.$i][2] .= html_print_radio_button_extended ('editor_type_recovery_value_'.$i, 0, '', false, false, "removeTinyMCE('textarea_field".$i."_recovery')", '', true); - //advanced - $table->data['field'.$i][2] .= "    "; - $table->data['field'.$i][2] .= __('Advanced') . "  "; - $table->data['field'.$i][2] .= html_print_radio_button_extended ('editor_type_recovery_value_'.$i, 0, '', true, false, "addTinyMCE('textarea_field".$i."_recovery')", '', true); - $table->data['field'.$i][2] .= "
    "; + ORDER BY dbms_lob.substr(name,4000,1)', + $usr_groups + ); + break; + } - //Texarea - $table->data['field'.$i][2] .= html_print_textarea ('field'.$i.'_recovery', 1, 1, isset($fields_recovery[$i]) ? $fields_recovery[$i] : '', 'style="min-height:40px" class="fields"', true); - } -} -else { - /* Step 1 by default */ - $table->size = array (); - $table->size[0] = '20%'; - $table->data = array (); - $table->rowstyle = array (); - $table->rowstyle['value'] = 'display: none'; - $table->rowstyle['max'] = 'display: none'; - $table->rowstyle['min'] = 'display: none'; - - $show_matches = false; - switch ($type) { - case "equal": - case "not_equal": - case "regex": - $show_matches = true; - $table->rowstyle['value'] = ''; - break; - case "max_min": - $show_matches = true; - case "max": - $table->rowstyle['max'] = ''; - if ($type == 'max') - break; - case "min": - $table->rowstyle['min'] = ''; - break; - case "onchange": - $show_matches = true; - break; - } - - $table->data[0][0] = __('Name'); - $table->data[0][1] = html_print_input_text ('name', $name, '', 35, 255, true); - - - $table->data[0][1] .= "  ". __("Group"); - $groups = users_get_groups (); - $own_info = get_user_info($config['id_user']); - // Only display group "All" if user is administrator or has "PM" privileges - if ($own_info['is_admin'] || check_acl ($config['id_user'], 0, "PM")) - $display_all_group = true; - else - $display_all_group = false; - $table->data[0][1] .= " " . - html_print_select_groups(false, "AR", $display_all_group, 'id_group', $id_group, '', '', 0, true); - - - $table->data[1][0] = __('Description'); - $table->data[1][1] = html_print_textarea ('description', 10, 30, - $description, '', true); - - $table->data[2][0] = __('Priority'); - $table->data[2][1] = html_print_select (get_priorities (), 'priority', - $priority, '', 0, 0, true, false, false); - - if(defined('METACONSOLE')) { - $table->data[3][0] = __('Wizard level'); - $wizard_levels = array( - 'nowizard' => __('No wizard'), - 'basic' => __('Basic'), - 'advanced' => __('Advanced')); - $table->data[3][1] = html_print_select($wizard_levels,'wizard_level',$wizard_level,'','',-1,true, false, false); - } - else { - $table->data[2][1] .= html_print_input_hidden('wizard_level',$wizard_level,true); - } + $table->data[5][1] = html_print_select_from_sql( + $sql_query, + 'default_action', + $default_action, + '', + __('None'), + 0, + true, + false, + false, + false, + false, + false, + 0 + ).ui_print_help_tip( + __('Unless they\'re left blank, the fields from the action will override those set on the template.'), + true + ); + + $table->data[6][0] = __('Condition type'); + $table->data[6][1] = html_print_select( + alerts_get_alert_templates_types(), + 'type', + $type, + '', + __('Select'), + 0, + true, + false, + false + ); + $table->data[6][1] .= ''; + $table->data[6][1] .= ' '.html_print_checkbox('matches_value', 1, $matches, true); + $table->data[6][1] .= html_print_label( + __('Trigger when matches the value'), + 'checkbox-matches_value', + true + ); + $table->data[6][1] .= ''; + $table->colspan[6][1] = 3; + + $table->data['value'][0] = __('Value'); + $table->data['value'][1] = html_print_input_text( + 'value', + $value, + '', + 35, + 255, + true + ); + $table->data['value'][1] .= ' '; + $table->data['value'][1] .= html_print_image( + 'images/suc.png', + true, + [ + 'style' => 'display:none', + 'id' => 'regex_good', + 'title' => __('The regular expression is valid'), + 'width' => '20px', + ] + ); + $table->data['value'][1] .= html_print_image( + 'images/err.png', + true, + [ + 'style' => 'display:none', + 'id' => 'regex_bad', + 'title' => __('The regular expression is not valid'), + 'width' => '20px', + ] + ); + $table->data['value'][1] .= ''; + $table->colspan['value'][1] = 3; + + // Min first, then max, that's more logical + $table->data['min'][0] = __('Min.'); + $table->data['min'][1] = html_print_input_text( + 'min', + $min, + '', + 5, + 255, + true + ); + $table->colspan['min'][1] = 3; + + $table->data['max'][0] = __('Max.'); + $table->data['max'][1] = html_print_input_text( + 'max', + $max, + '', + 5, + 255, + true + ); + $table->colspan['max'][1] = 3; + + $table->data['example'][1] = ui_print_alert_template_example( + $id, + true, + false + ); + $table->colspan['example'][1] = 4; +} else if ($step == 3) { + $table->style[0] = 'font-weight: bold; vertical-align: middle'; + $table->style[1] = 'font-weight: bold; vertical-align: top'; + $table->style[2] = 'font-weight: bold; vertical-align: top'; + $table->size = []; + $table->size[0] = '10%'; + $table->size[1] = '45%'; + $table->size[2] = '45%'; + + // Alert recover + if (! $recovery_notify) { + $table->cellstyle['label_fields'][2] = 'display:none;'; + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + $table->cellstyle['field'.$i][2] = 'display:none;'; + } + + /* + $table->cellstyle['field1'][2] = 'display:none;'; + $table->cellstyle['field2'][2] = 'display:none;'; + $table->cellstyle['field3'][2] = 'display:none;'; + $table->cellstyle['field4'][2] = 'display:none;'; + $table->cellstyle['field5'][2] = 'display:none;'; + $table->cellstyle['field6'][2] = 'display:none;'; + $table->cellstyle['field7'][2] = 'display:none;'; + $table->cellstyle['field8'][2] = 'display:none;'; + $table->cellstyle['field9'][2] = 'display:none;'; + $table->cellstyle['field10'][2] = 'display:none;'; + */ + } + + $table->data[0][0] = __('Alert recovery'); + $values = [ + false => __('Disabled'), + true => __('Enabled'), + ]; + $table->data[0][1] = html_print_select( + $values, + 'recovery_notify', + $recovery_notify, + '', + '', + '', + true, + false, + false + ); + $table->colspan[0][1] = 2; + + $table->data['label_fields'][0] = ''; + $table->data['label_fields'][1] = __('Firing fields'); + $table->data['label_fields'][2] = __('Recovery fields'); + + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + if (isset($template[$name])) { + $value = $template[$name]; + } else { + $value = ''; + } + + // $table->rowclass['field'.$i] = 'row_field'; + $table->data['field'.$i][0] = sprintf(__('Field %s'), $i).ui_print_help_icon('alert_macros', true); + // TinyMCE + // triggering fields + // basic + $table->data['field'.$i][1] = '
    '; + $table->data['field'.$i][1] .= __('Basic').'  '; + $table->data['field'.$i][1] .= html_print_radio_button_extended('editor_type_value_'.$i, 0, '', false, false, "removeTinyMCE('textarea_field".$i."')", '', true); + // Advanced + $table->data['field'.$i][1] .= '    '; + $table->data['field'.$i][1] .= __('Advanced').'  '; + $table->data['field'.$i][1] .= html_print_radio_button_extended('editor_type_value_'.$i, 0, '', true, false, "addTinyMCE('textarea_field".$i."')", '', true); + $table->data['field'.$i][1] .= '
    '; + + // Texarea + $table->data['field'.$i][1] .= html_print_textarea('field'.$i, 1, 1, isset($fields[$i]) ? $fields[$i] : '', 'style="min-height:40px;" class="fields"', true); + + // Recovery + // basic + $table->data['field'.$i][2] = '
    '; + $table->data['field'.$i][2] .= __('Basic').'  '; + $table->data['field'.$i][2] .= html_print_radio_button_extended('editor_type_recovery_value_'.$i, 0, '', false, false, "removeTinyMCE('textarea_field".$i."_recovery')", '', true); + // advanced + $table->data['field'.$i][2] .= '    '; + $table->data['field'.$i][2] .= __('Advanced').'  '; + $table->data['field'.$i][2] .= html_print_radio_button_extended('editor_type_recovery_value_'.$i, 0, '', true, false, "addTinyMCE('textarea_field".$i."_recovery')", '', true); + $table->data['field'.$i][2] .= '
    '; + + // Texarea + $table->data['field'.$i][2] .= html_print_textarea('field'.$i.'_recovery', 1, 1, isset($fields_recovery[$i]) ? $fields_recovery[$i] : '', 'style="min-height:40px" class="fields"', true); + } +} else { + // Step 1 by default + $table->size = []; + $table->size[0] = '20%'; + $table->data = []; + $table->rowstyle = []; + $table->rowstyle['value'] = 'display: none'; + $table->rowstyle['max'] = 'display: none'; + $table->rowstyle['min'] = 'display: none'; + + $show_matches = false; + switch ($type) { + case 'equal': + case 'not_equal': + case 'regex': + $show_matches = true; + $table->rowstyle['value'] = ''; + break; + + case 'max_min': + $show_matches = true; + case 'max': + $table->rowstyle['max'] = ''; + if ($type == 'max') { + break; + } + + case 'min': + $table->rowstyle['min'] = ''; + break; + + case 'onchange': + $show_matches = true; + break; + } + + $table->data[0][0] = __('Name'); + $table->data[0][1] = html_print_input_text('name', $name, '', 35, 255, true); + + + $table->data[0][1] .= '  '.__('Group'); + $groups = users_get_groups(); + $own_info = get_user_info($config['id_user']); + // Only display group "All" if user is administrator or has "PM" privileges + if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { + $display_all_group = true; + } else { + $display_all_group = false; + } + + $table->data[0][1] .= ' '.html_print_select_groups(false, 'AR', $display_all_group, 'id_group', $id_group, '', '', 0, true); + + + $table->data[1][0] = __('Description'); + $table->data[1][1] = html_print_textarea( + 'description', + 10, + 30, + $description, + '', + true + ); + + $table->data[2][0] = __('Priority'); + $table->data[2][1] = html_print_select( + get_priorities(), + 'priority', + $priority, + '', + 0, + 0, + true, + false, + false + ); + + if (defined('METACONSOLE')) { + $table->data[3][0] = __('Wizard level'); + $wizard_levels = [ + 'nowizard' => __('No wizard'), + 'basic' => __('Basic'), + 'advanced' => __('Advanced'), + ]; + $table->data[3][1] = html_print_select($wizard_levels, 'wizard_level', $wizard_level, '', '', -1, true, false, false); + } else { + $table->data[2][1] .= html_print_input_hidden('wizard_level', $wizard_level, true); + } } if ($step == 2) { - echo ui_get_using_system_timezone_warning(); + echo ui_get_using_system_timezone_warning(); } -/* If it's the last step it will redirect to template lists */ +// If it's the last step it will redirect to template lists if ($step >= LAST_STEP) { - echo '
    '; + echo ''; +} else { + echo ''; } -else { - echo ''; -} -html_print_table ($table); -echo '
    '; +html_print_table($table); + +echo '
    '; if ($id) { - html_print_input_hidden ('id', $id); - html_print_input_hidden ('update_template', 1); -} -else { - html_print_input_hidden ('create_template', 1); + html_print_input_hidden('id', $id); + html_print_input_hidden('update_template', 1); +} else { + html_print_input_hidden('create_template', 1); } $disabled = false; if (!$create_alert && !$create_template) { - if ($a_template['id_group'] == 0) { - // then must have "PM" access privileges - if (! check_acl ($config['id_user'], 0, "PM")) { - $disabled = true; - } - } + if ($a_template['id_group'] == 0) { + // then must have "PM" access privileges + if (! check_acl($config['id_user'], 0, 'PM')) { + $disabled = true; + } + } } if (!$disabled) { - if ($step >= LAST_STEP) { - html_print_submit_button (__('Finish'), 'finish', false, 'class="sub upd"'); - } - else { - html_print_input_hidden ('step', $step + 1); - if ($step == 2) { - //Javascript onsubmit to avoid min = 0 and max = 0 - - html_print_submit_button(__('Next'), 'next', false, - 'class="sub next" onclick="return check_fields_step2();"'); - } - else { - html_print_submit_button(__('Next'), 'next', false, - 'class="sub next"'); - } - } + if ($step >= LAST_STEP) { + html_print_submit_button(__('Finish'), 'finish', false, 'class="sub upd"'); + } else { + html_print_input_hidden('step', ($step + 1)); + if ($step == 2) { + // Javascript onsubmit to avoid min = 0 and max = 0 + html_print_submit_button( + __('Next'), + 'next', + false, + 'class="sub next" onclick="return check_fields_step2();"' + ); + } else { + html_print_submit_button( + __('Next'), + 'next', + false, + 'class="sub next"' + ); + } + } } echo '
    '; @@ -850,90 +996,90 @@ echo ''; enterprise_hook('close_meta_frame'); -ui_require_javascript_file ('pandora_alerts'); +ui_require_javascript_file('pandora_alerts'); ui_include_time_picker(); -ui_require_jquery_file("ui.datepicker-" . get_user_language(), "include/javascript/i18n/"); +ui_require_jquery_file('ui.datepicker-'.get_user_language(), 'include/javascript/i18n/'); ui_require_javascript_file('tiny_mce', 'include/javascript/tiny_mce/'); ?> diff --git a/pandora_console/godmode/events/event_edit_filter.php b/pandora_console/godmode/events/event_edit_filter.php index 8c305fd90f..b2b9763d56 100644 --- a/pandora_console/godmode/events/event_edit_filter.php +++ b/pandora_console/godmode/events/event_edit_filter.php @@ -4,275 +4,331 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); +check_login(); -$event_w = check_acl ($config['id_user'], 0, "EW"); -$event_m = check_acl ($config['id_user'], 0, "EM"); +$event_w = check_acl($config['id_user'], 0, 'EW'); +$event_m = check_acl($config['id_user'], 0, 'EM'); $access = ($event_w == true) ? 'EW' : (($event_m == true) ? 'EM' : 'EW'); if (!$event_w && !$event_m) { - db_pandora_audit("ACL Violation", - "Trying to access events filter editor"); - require ("general/noaccess.php"); - return; + db_pandora_audit( + 'ACL Violation', + 'Trying to access events filter editor' + ); + include 'general/noaccess.php'; + return; } -$id = (int) get_parameter ('id'); -$update = (string)get_parameter('update', 0); -$create = (string)get_parameter('create', 0); +$id = (int) get_parameter('id'); +$update = (string) get_parameter('update', 0); +$create = (string) get_parameter('create', 0); -$strict_user = db_get_value('strict_acl', 'tusuario', 'id_user', - $config['id_user']); +$strict_user = db_get_value( + 'strict_acl', + 'tusuario', + 'id_user', + $config['id_user'] +); if ($id) { - $permission = events_check_event_filter_group ($id); - if (!$permission) { - // User doesn't have permissions to see this filter - require ("general/noaccess.php"); - - return; - } + $permission = events_check_event_filter_group($id); + if (!$permission) { + // User doesn't have permissions to see this filter + include 'general/noaccess.php'; + + return; + } } if ($id) { - $filter = events_get_event_filter ($id); - $id_group_filter = $filter['id_group_filter']; - $id_group = $filter['id_group']; - $id_name = $filter['id_name']; - $event_type = $filter['event_type']; - $severity = $filter['severity']; - $status = $filter['status']; - $search = $filter['search']; - $text_agent = $filter['text_agent']; - $id_agent = $filter['id_agent']; - $text_module = $filter['text_module']; - $id_agent_module = $filter['id_agent_module']; - $pagination = $filter['pagination']; - $event_view_hr = $filter['event_view_hr']; - $id_user_ack = $filter['id_user_ack']; - $group_rep = $filter['group_rep']; - $date_from = str_replace("-","/",$filter['date_from']); - $date_to = str_replace("-","/",$filter['date_to']); - $source = $filter['source']; - $id_extra = $filter['id_extra']; - $user_comment = $filter['user_comment']; + $filter = events_get_event_filter($id); + $id_group_filter = $filter['id_group_filter']; + $id_group = $filter['id_group']; + $id_name = $filter['id_name']; + $event_type = $filter['event_type']; + $severity = $filter['severity']; + $status = $filter['status']; + $search = $filter['search']; + $text_agent = $filter['text_agent']; + $id_agent = $filter['id_agent']; + $text_module = $filter['text_module']; + $id_agent_module = $filter['id_agent_module']; + $pagination = $filter['pagination']; + $event_view_hr = $filter['event_view_hr']; + $id_user_ack = $filter['id_user_ack']; + $group_rep = $filter['group_rep']; + $date_from = str_replace('-', '/', $filter['date_from']); + $date_to = str_replace('-', '/', $filter['date_to']); + $source = $filter['source']; + $id_extra = $filter['id_extra']; + $user_comment = $filter['user_comment']; - $tag_with_json = $filter['tag_with']; - $tag_with_json_clean = io_safe_output($tag_with_json); - $tag_with_base64 = base64_encode($tag_with_json_clean) ; - - $tag_without_json = $filter['tag_without']; - $tag_without_json_clean = io_safe_output($tag_without_json); - $tag_without_base64 = base64_encode($tag_without_json_clean) ; - - $filter_only_alert = $filter['filter_only_alert']; - - if ($id_agent_module != 0) { - $text_module = modules_get_agentmodule_name($id_agent_module); - if ($text_module == false) { - $text_module = ''; - } - } - if ($id_agent != 0) { - $text_agent = agents_get_alias($id_agent); - if ($text_agent == false) { - $text_agent = ''; - } - } -} -else { - $id_group = ''; - $id_group_filter = ''; - $id_name = ''; - $event_type = ''; - $severity = ''; - $status = ''; - $search = ''; - $text_agent = ''; - $pagination = ''; - $event_view_hr = ''; - $id_user_ack = ''; - $group_rep = ''; - $date_from = ''; - $date_to = ''; + $tag_with_json = $filter['tag_with']; + $tag_with_json_clean = io_safe_output($tag_with_json); + $tag_with_base64 = base64_encode($tag_with_json_clean); - $tag_with_json = $tag_with_json_clean = json_encode(array()); - $tag_with_base64 = base64_encode($tag_with_json); - $tag_without_json = $tag_without_json_clean = json_encode(array()); - $tag_without_base64 = base64_encode($tag_without_json); - $filter_only_alert = ''; + $tag_without_json = $filter['tag_without']; + $tag_without_json_clean = io_safe_output($tag_without_json); + $tag_without_base64 = base64_encode($tag_without_json_clean); + + $filter_only_alert = $filter['filter_only_alert']; + + if ($id_agent_module != 0) { + $text_module = modules_get_agentmodule_name($id_agent_module); + if ($text_module == false) { + $text_module = ''; + } + } + + if ($id_agent != 0) { + $text_agent = agents_get_alias($id_agent); + if ($text_agent == false) { + $text_agent = ''; + } + } +} else { + $id_group = ''; + $id_group_filter = ''; + $id_name = ''; + $event_type = ''; + $severity = ''; + $status = ''; + $search = ''; + $text_agent = ''; + $pagination = ''; + $event_view_hr = ''; + $id_user_ack = ''; + $group_rep = ''; + $date_from = ''; + $date_to = ''; + + $tag_with_json = $tag_with_json_clean = json_encode([]); + $tag_with_base64 = base64_encode($tag_with_json); + $tag_without_json = $tag_without_json_clean = json_encode([]); + $tag_without_base64 = base64_encode($tag_without_json); + $filter_only_alert = ''; } if ($update || $create) { - $id_group = (string) get_parameter ('id_group'); - $id_group_filter = get_parameter('id_group_filter'); - $id_name = (string) get_parameter ('id_name'); - $event_type = get_parameter('event_type', ''); - $severity = get_parameter('severity', ''); - $status = get_parameter('status', ''); - $search = get_parameter('search', ''); - $text_agent = get_parameter('text_agent', ''); - $id_agent = (int) get_parameter('id_agent'); - $text_module = get_parameter('text_module', ''); - $id_agent_module = (int) get_parameter('module_search_hidden'); - $pagination = get_parameter('pagination', ''); - $event_view_hr = get_parameter('event_view_hr', ''); - $id_user_ack = get_parameter('id_user_ack', ''); - $group_rep = get_parameter('group_rep', ''); - $date_from = get_parameter('date_from', ''); - $date_to = get_parameter('date_to', ''); - $source = get_parameter('source'); - $id_extra = get_parameter('id_extra'); - $user_comment = get_parameter('user_comment'); + $id_group = (string) get_parameter('id_group'); + $id_group_filter = get_parameter('id_group_filter'); + $id_name = (string) get_parameter('id_name'); + $event_type = get_parameter('event_type', ''); + $severity = get_parameter('severity', ''); + $status = get_parameter('status', ''); + $search = get_parameter('search', ''); + $text_agent = get_parameter('text_agent', ''); + $id_agent = (int) get_parameter('id_agent'); + $text_module = get_parameter('text_module', ''); + $id_agent_module = (int) get_parameter('module_search_hidden'); + $pagination = get_parameter('pagination', ''); + $event_view_hr = get_parameter('event_view_hr', ''); + $id_user_ack = get_parameter('id_user_ack', ''); + $group_rep = get_parameter('group_rep', ''); + $date_from = get_parameter('date_from', ''); + $date_to = get_parameter('date_to', ''); + $source = get_parameter('source'); + $id_extra = get_parameter('id_extra'); + $user_comment = get_parameter('user_comment'); - $tag_with_base64 = get_parameter('tag_with', json_encode(array())); - $tag_with_json = io_safe_input(base64_decode($tag_with_base64)); - - $tag_without_base64 = get_parameter('tag_without', json_encode(array())); - $tag_without_json = io_safe_input(base64_decode($tag_without_base64)); - - $filter_only_alert = get_parameter('filter_only_alert',''); - - $values = array ( - 'id_name' => $id_name, - 'id_group_filter' => $id_group_filter, - 'id_group' => $id_group, - 'event_type' => $event_type, - 'severity' => $severity, - 'status' => $status, - 'search' => $search, - 'text_agent' => $text_agent, - 'id_agent_module' => $id_agent_module, - 'id_agent' => $id_agent, - 'pagination' => $pagination, - 'event_view_hr' => $event_view_hr, - 'id_user_ack' => $id_user_ack, - 'group_rep' => $group_rep, - 'tag_with' => $tag_with_json, - 'tag_without' => $tag_without_json, - 'date_from' => $date_from, - 'date_to' => $date_to, - 'source' => $source, - 'id_extra' => $id_extra, - 'user_comment' => $user_comment, - 'filter_only_alert' => $filter_only_alert); + $tag_with_base64 = get_parameter('tag_with', json_encode([])); + $tag_with_json = io_safe_input(base64_decode($tag_with_base64)); + + $tag_without_base64 = get_parameter('tag_without', json_encode([])); + $tag_without_json = io_safe_input(base64_decode($tag_without_base64)); + + $filter_only_alert = get_parameter('filter_only_alert', ''); + + $values = [ + 'id_name' => $id_name, + 'id_group_filter' => $id_group_filter, + 'id_group' => $id_group, + 'event_type' => $event_type, + 'severity' => $severity, + 'status' => $status, + 'search' => $search, + 'text_agent' => $text_agent, + 'id_agent_module' => $id_agent_module, + 'id_agent' => $id_agent, + 'pagination' => $pagination, + 'event_view_hr' => $event_view_hr, + 'id_user_ack' => $id_user_ack, + 'group_rep' => $group_rep, + 'tag_with' => $tag_with_json, + 'tag_without' => $tag_without_json, + 'date_from' => $date_from, + 'date_to' => $date_to, + 'source' => $source, + 'id_extra' => $id_extra, + 'user_comment' => $user_comment, + 'filter_only_alert' => $filter_only_alert, + ]; } if ($update) { - if ($id_name == '') { - ui_print_error_message (__('Not updated. Blank name')); - } - else { - $result = db_process_sql_update ('tevent_filter', $values, - array ('id_filter' => $id)); - - ui_print_result_message ($result, - __('Successfully updated'), - __('Not updated. Error updating data')); - } + if ($id_name == '') { + ui_print_error_message(__('Not updated. Blank name')); + } else { + $result = db_process_sql_update( + 'tevent_filter', + $values, + ['id_filter' => $id] + ); + + ui_print_result_message( + $result, + __('Successfully updated'), + __('Not updated. Error updating data') + ); + } } if ($create) { - $id = db_process_sql_insert('tevent_filter', $values); - - if ($id === false) { - ui_print_error_message ('Error creating filter'); - } - else { - ui_print_success_message ('Filter created successfully'); - } + $id = db_process_sql_insert('tevent_filter', $values); + + if ($id === false) { + ui_print_error_message('Error creating filter'); + } else { + ui_print_success_message('Filter created successfully'); + } } -$own_info = get_user_info ($config['id_user']); +$own_info = get_user_info($config['id_user']); $table = new stdClass(); $table->width = '100%'; $table->border = 0; $table->cellspacing = 0; $table->cellpadding = 0; -$table->class = "databox filters"; +$table->class = 'databox filters'; $table->style[0] = 'vertical-align: top;'; $table->valign[1] = 'top'; if (is_metaconsole()) { - if ($id) { - $table->head[0] = __('Update Filter'); - } - else { - $table->head[0] = __('Create Filter'); - } - - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; - $table->style[0] = ''; - $table->valign[1] = ''; + if ($id) { + $table->head[0] = __('Update Filter'); + } else { + $table->head[0] = __('Create Filter'); + } + + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; + $table->style[0] = ''; + $table->valign[1] = ''; } -$table->data = array (); + +$table->data = []; $table->data[0][0] = ''.__('Filter name').''; -$table->data[0][1] = - html_print_input_text('id_name', $id_name, false, 20, 80, true); +$table->data[0][1] = html_print_input_text('id_name', $id_name, false, 20, 80, true); -$table->data[1][0] = '' . __('Save in group') . '' . - ui_print_help_tip(__('This group will be use to restrict the visibility of this filter with ACLs'), true); +$table->data[1][0] = ''.__('Save in group').''.ui_print_help_tip(__('This group will be use to restrict the visibility of this filter with ACLs'), true); $table->data[1][1] = html_print_select_groups( - $config['id_user'], $access, users_can_manage_group_all(), - "id_group_filter", $id_group_filter, '', '', -1, true, false, false, - '', false, '', false, false, 'id_grupo', $strict_user); + $config['id_user'], + $access, + users_can_manage_group_all(), + 'id_group_filter', + $id_group_filter, + '', + '', + -1, + true, + false, + false, + '', + false, + '', + false, + false, + 'id_grupo', + $strict_user +); -$table->data[2][0] = '' . __('Group').''; -$display_all_group = (users_is_admin() || users_can_manage_group_all("AR")); -$table->data[2][1] = html_print_select_groups($config['id_user'], "AR", -$display_all_group, 'id_group', $idGroup, '', '', '', true); +$table->data[2][0] = ''.__('Group').''; +$display_all_group = (users_is_admin() || users_can_manage_group_all('AR')); +$table->data[2][1] = html_print_select_groups( + $config['id_user'], + 'AR', + $display_all_group, + 'id_group', + $idGroup, + '', + '', + '', + true +); -$types = get_event_types (); +$types = get_event_types(); // Expand standard array to add not_normal (not exist in the array, used only for searches) -$types["not_normal"] = __("Not normal"); +$types['not_normal'] = __('Not normal'); -$table->data[3][0] = '' . __('Event type') . ''; +$table->data[3][0] = ''.__('Event type').''; $table->data[3][1] = html_print_select( - $types, 'event_type', $event_type, '', __('All'), '', true); + $types, + 'event_type', + $event_type, + '', + __('All'), + '', + true +); -$table->data[4][0] = '' . __('Severity') . ''; +$table->data[4][0] = ''.__('Severity').''; $table->data[4][1] = html_print_select( - get_priorities(), "severity", $severity, '', __('All'), '-1', true); + get_priorities(), + 'severity', + $severity, + '', + __('All'), + '-1', + true +); $fields = events_get_all_status(); -$table->data[5][0] = '' . __('Event status') . ''; +$table->data[5][0] = ''.__('Event status').''; $table->data[5][1] = html_print_select( - $fields, 'status', $status, '', '', '', true); + $fields, + 'status', + $status, + '', + '', + '', + true +); -$table->data[6][0] = '' . __('Free search') . ''; +$table->data[6][0] = ''.__('Free search').''; $table->data[6][1] = html_print_input_text( - 'search', io_safe_output($search), '', 15, 255, true); + 'search', + io_safe_output($search), + '', + 15, + 255, + true +); -$table->data[7][0] = '' . __('Agent search') . ''; -$params = array(); +$table->data[7][0] = ''.__('Agent search').''; +$params = []; $params['show_helptip'] = true; $params['input_name'] = 'text_agent'; $params['value'] = $text_agent; $params['return'] = true; if (is_metaconsole()) { - $params['javascript_page'] = 'enterprise/meta/include/ajax/events.ajax'; -} -else { - $params['print_hidden_input_idagent'] = true; - $params['hidden_input_idagent_name'] = 'id_agent'; - $params['hidden_input_idagent_value'] = $id_agent; + $params['javascript_page'] = 'enterprise/meta/include/ajax/events.ajax'; +} else { + $params['print_hidden_input_idagent'] = true; + $params['hidden_input_idagent_name'] = 'id_agent'; + $params['hidden_input_idagent_value'] = $id_agent; } $table->data[7][1] = ui_print_agent_autocomplete_input($params); @@ -282,72 +338,98 @@ $lpagination[50] = 50; $lpagination[100] = 100; $lpagination[200] = 200; $lpagination[500] = 500; -$table->data[8][0] = '' . __('Block size for pagination') . ''; +$table->data[8][0] = ''.__('Block size for pagination').''; $table->data[8][1] = html_print_select( - $lpagination, "pagination", $pagination, '', __('Default'), - $config["block_size"], true); + $lpagination, + 'pagination', + $pagination, + '', + __('Default'), + $config['block_size'], + true +); -$table->data[9][0] = '' . __('Max. hours old') . ''; +$table->data[9][0] = ''.__('Max. hours old').''; $table->data[9][1] = html_print_input_text( - 'event_view_hr', $event_view_hr, '', 5, 255, true); + 'event_view_hr', + $event_view_hr, + '', + 5, + 255, + true +); -$table->data[10][0] = '' . __('User ack.') . ''. ' ' . - ui_print_help_tip (__('Choose between the users who have validated an event. '), true); +$table->data[10][0] = ''.__('User ack.').''.' '.ui_print_help_tip(__('Choose between the users who have validated an event. '), true); if ($strict_user) { - $users = array($config['id_user'] => $config['id_user']); -} -else { - $users = users_get_user_users($config['id_user'], $access, - users_can_manage_group_all()); + $users = [$config['id_user'] => $config['id_user']]; +} else { + $users = users_get_user_users( + $config['id_user'], + $access, + users_can_manage_group_all() + ); } -$table->data[10][1] = html_print_select($users, "id_user_ack", - $id_user_ack, '', __('Any'), 0, true); +$table->data[10][1] = html_print_select( + $users, + 'id_user_ack', + $id_user_ack, + '', + __('Any'), + 0, + true +); -$repeated_sel[0] = __("All events"); -$repeated_sel[1] = __("Group events"); -$table->data[11][0] = '' . __('Repeated') . ''; -$table->data[11][1] = html_print_select ($repeated_sel, "group_rep", - $group_rep, '', '', '', true); +$repeated_sel[0] = __('All events'); +$repeated_sel[1] = __('Group events'); +$table->data[11][0] = ''.__('Repeated').''; +$table->data[11][1] = html_print_select( + $repeated_sel, + 'group_rep', + $group_rep, + '', + '', + '', + true +); -$table ->data[12][0] = '' . __('Date from') . ''; -$table ->data[12][1] = html_print_input_text ('date_from', $date_from, '', 15, 10, true); +$table->data[12][0] = ''.__('Date from').''; +$table->data[12][1] = html_print_input_text('date_from', $date_from, '', 15, 10, true); -$table ->data[13][0] = '' . __('Date to') . ''; -$table ->data[13][1] = html_print_input_text ('date_to', $date_to, '', 15, 10, true); +$table->data[13][0] = ''.__('Date to').''; +$table->data[13][1] = html_print_input_text('date_to', $date_to, '', 15, 10, true); $tag_with = json_decode($tag_with_json_clean, true); if (empty($tag_with)) { - $tag_with = array(); + $tag_with = []; } + $tag_without = json_decode($tag_without_json_clean, true); if (empty($tag_without)) { - $tag_without = array(); + $tag_without = []; } -# Fix : only admin users can see all tags +// Fix : only admin users can see all tags $tags = tags_get_user_tags($config['id_user'], $access); -$tags_select_with = array(); -$tags_select_without = array(); -$tag_with_temp = array(); -$tag_without_temp = array(); +$tags_select_with = []; +$tags_select_without = []; +$tag_with_temp = []; +$tag_without_temp = []; foreach ($tags as $id_tag => $tag) { - if (array_search($id_tag, $tag_with) === false) { - $tags_select_with[$id_tag] = $tag; - } - else { - $tag_with_temp[$id_tag] = $tag; - } - - if (array_search($id_tag, $tag_without) === false) { - $tags_select_without[$id_tag] = $tag; - } - else { - $tag_without_temp[$id_tag] = $tag; - } + if (array_search($id_tag, $tag_with) === false) { + $tags_select_with[$id_tag] = $tag; + } else { + $tag_with_temp[$id_tag] = $tag; + } + + if (array_search($id_tag, $tag_without) === false) { + $tags_select_without[$id_tag] = $tag; + } else { + $tag_without_temp[$id_tag] = $tag; + } } $add_with_tag_disabled = empty($tags_select_with); @@ -356,244 +438,335 @@ $add_without_tag_disabled = empty($tags_select_without); $remove_without_tag_disabled = empty($tag_without_temp); $table->colspan[14][0] = '2'; -$table->data[14][0] = '' . __('Events with following tags') . ''; -$table->data[15][0] = html_print_select ($tags_select_with, 'select_with', - '', '', '', 0, true, false, true, '', false, 'width: 220px;'); -$table->data[15][1] = html_print_button(__('Add'), 'add_whith', - $add_with_tag_disabled, '', 'class="add sub"', true); +$table->data[14][0] = ''.__('Events with following tags').''; +$table->data[15][0] = html_print_select( + $tags_select_with, + 'select_with', + '', + '', + '', + 0, + true, + false, + true, + '', + false, + 'width: 220px;' +); +$table->data[15][1] = html_print_button( + __('Add'), + 'add_whith', + $add_with_tag_disabled, + '', + 'class="add sub"', + true +); -$table->data[16][0] = html_print_select ($tag_with_temp, - 'tag_with_temp', array(), '', '', 0, true, true, - true, '', false, "width: 220px; height: 50px;"); -$table->data[16][0] .= html_print_input_hidden('tag_with', - $tag_with_base64, true); -$table->data[16][1] = html_print_button(__('Remove'), - 'remove_whith', $remove_with_tag_disabled, '', 'class="delete sub"', true); +$table->data[16][0] = html_print_select( + $tag_with_temp, + 'tag_with_temp', + [], + '', + '', + 0, + true, + true, + true, + '', + false, + 'width: 220px; height: 50px;' +); +$table->data[16][0] .= html_print_input_hidden( + 'tag_with', + $tag_with_base64, + true +); +$table->data[16][1] = html_print_button( + __('Remove'), + 'remove_whith', + $remove_with_tag_disabled, + '', + 'class="delete sub"', + true +); $table->colspan[17][0] = '2'; -$table->data[17][0] = '' . __('Events without following tags') . ''; -$table->data[18][0] = html_print_select ($tags_select_without, 'select_without', - '', '', '', 0, true, false, true, '', false, 'width: 220px;'); -$table->data[18][1] = html_print_button(__('Add'), 'add_whithout', - $add_without_tag_disabled, '', 'class="add sub"', true); +$table->data[17][0] = ''.__('Events without following tags').''; +$table->data[18][0] = html_print_select( + $tags_select_without, + 'select_without', + '', + '', + '', + 0, + true, + false, + true, + '', + false, + 'width: 220px;' +); +$table->data[18][1] = html_print_button( + __('Add'), + 'add_whithout', + $add_without_tag_disabled, + '', + 'class="add sub"', + true +); -$table->data[19][0] = html_print_select ($tag_without_temp, - 'tag_without_temp', array(), '', '', 0, true, true, - true, '', false, "width: 220px; height: 50px;"); -$table->data[19][0] .= html_print_input_hidden('tag_without', - $tag_without_base64, true); -$table->data[19][1] = html_print_button(__('Remove'), 'remove_whithout', - $remove_without_tag_disabled, '', 'class="delete sub"', true); +$table->data[19][0] = html_print_select( + $tag_without_temp, + 'tag_without_temp', + [], + '', + '', + 0, + true, + true, + true, + '', + false, + 'width: 220px; height: 50px;' +); +$table->data[19][0] .= html_print_input_hidden( + 'tag_without', + $tag_without_base64, + true +); +$table->data[19][1] = html_print_button( + __('Remove'), + 'remove_whithout', + $remove_without_tag_disabled, + '', + 'class="delete sub"', + true +); -$table->data[20][0] = '' . __('Alert events') . ''; +$table->data[20][0] = ''.__('Alert events').''; $table->data[20][1] = html_print_select( - array( - '-1' => __('All'), - '0' => __('Filter alert events'), - '1' => __('Only alert events')), - "filter_only_alert", $filter_only_alert, '', '', '', true); + [ + '-1' => __('All'), + '0' => __('Filter alert events'), + '1' => __('Only alert events'), + ], + 'filter_only_alert', + $filter_only_alert, + '', + '', + '', + true +); if (!is_metaconsole()) { - $table->data[21][0] = '' . __('Module search') . ''; - $table->data[21][1] .= html_print_autocomplete_modules('module_search', - $text_module, false, true, '', array(), true, $id_agent_module); + $table->data[21][0] = ''.__('Module search').''; + $table->data[21][1] .= html_print_autocomplete_modules( + 'module_search', + $text_module, + false, + true, + '', + [], + true, + $id_agent_module + ); } -$table ->data[22][0] = '' . __('Source') . ''; -$table ->data[22][1] = html_print_input_text ('source', $source, '', 35, 255, true); +$table->data[22][0] = ''.__('Source').''; +$table->data[22][1] = html_print_input_text('source', $source, '', 35, 255, true); -$table ->data[23][0] = '' . __('Extra ID') . ''; -$table ->data[23][1] = html_print_input_text ('id_extra', $id_extra, '', 11, 255, true); +$table->data[23][0] = ''.__('Extra ID').''; +$table->data[23][1] = html_print_input_text('id_extra', $id_extra, '', 11, 255, true); -$table ->data[24][0] = '' . __('Comment') . ''; -$table ->data[24][1] = html_print_input_text ('user_comment', $user_comment, '', 35, 255, true); +$table->data[24][0] = ''.__('Comment').''; +$table->data[24][1] = html_print_input_text('user_comment', $user_comment, '', 35, 255, true); echo '
    '; -html_print_table ($table); +html_print_table($table); echo '
    '; if ($id) { - html_print_input_hidden ('update', 1); - html_print_input_hidden ('id', $id); - html_print_submit_button (__('Update'), 'crt', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create', 1); - html_print_submit_button (__('Create'), 'crt', false, 'class="sub wand"'); + html_print_input_hidden('update', 1); + html_print_input_hidden('id', $id); + html_print_submit_button(__('Update'), 'crt', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create', 1); + html_print_submit_button(__('Create'), 'crt', false, 'class="sub wand"'); } + echo '
    '; echo ''; -ui_require_jquery_file ('bgiframe'); +ui_require_jquery_file('bgiframe'); ui_require_jquery_file('json'); ?> diff --git a/pandora_console/godmode/events/event_filter.php b/pandora_console/godmode/events/event_filter.php index a8f26eb087..40d60650f6 100644 --- a/pandora_console/godmode/events/event_filter.php +++ b/pandora_console/godmode/events/event_filter.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,198 +11,209 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -$event_w = check_acl ($config['id_user'], 0, "EW"); -$event_m = check_acl ($config['id_user'], 0, "EM"); +$event_w = check_acl($config['id_user'], 0, 'EW'); +$event_m = check_acl($config['id_user'], 0, 'EM'); $access = ($event_w == true) ? 'EW' : (($event_m == true) ? 'EM' : 'EW'); if (!$event_w && !$event_m) { - db_pandora_audit("ACL Violation", - "Trying to access events filter editor"); - require ("general/noaccess.php"); - return; + db_pandora_audit( + 'ACL Violation', + 'Trying to access events filter editor' + ); + include 'general/noaccess.php'; + return; } -$delete = (bool) get_parameter ('delete', 0); -$multiple_delete = (bool)get_parameter('multiple_delete', 0); +$delete = (bool) get_parameter('delete', 0); +$multiple_delete = (bool) get_parameter('multiple_delete', 0); if ($delete) { - - $id = (int) get_parameter('id'); - - $id_filter = db_get_value('id_filter', 'tevent_filter', 'id_filter', $id); - - if ($id_filter === false) { - $result = false; - } - else { - $result = db_process_sql_delete ('tevent_filter', array ('id_filter' => $id)); - } - - if ($result !== false) { - $result = true; - } - else { - $result = false; - } - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); - + $id = (int) get_parameter('id'); + + $id_filter = db_get_value('id_filter', 'tevent_filter', 'id_filter', $id); + + if ($id_filter === false) { + $result = false; + } else { + $result = db_process_sql_delete('tevent_filter', ['id_filter' => $id]); + } + + if ($result !== false) { + $result = true; + } else { + $result = false; + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); } if ($multiple_delete) { - $ids = (array)get_parameter('delete_multiple', array()); - - foreach ($ids as $id) { - $result = db_process_sql_delete ('tevent_filter', - array ('id_filter' => $id)); - - if ($result === false) { - break; - } - } - - if ($result !== false) $result = true; - else $result = false; - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); + $ids = (array) get_parameter('delete_multiple', []); + + foreach ($ids as $id) { + $result = db_process_sql_delete( + 'tevent_filter', + ['id_filter' => $id] + ); + + if ($result === false) { + break; + } + } + + if ($result !== false) { + $result = true; + } else { + $result = false; + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); } $strict_acl = db_get_value('strict_acl', 'tusuario', 'id_user', $config['id_user']); -$own_info = get_user_info ($config['id_user']); +$own_info = get_user_info($config['id_user']); // Get group list that user has access if ($strict_acl) { - $groups_user = users_get_strict_mode_groups($config['id_user'], - users_can_manage_group_all()); -} -else { - $groups_user = users_get_groups ($config['id_user'], $access, - users_can_manage_group_all(), true); + $groups_user = users_get_strict_mode_groups( + $config['id_user'], + users_can_manage_group_all() + ); +} else { + $groups_user = users_get_groups( + $config['id_user'], + $access, + users_can_manage_group_all(), + true + ); } -$sql = " +$sql = ' SELECT * FROM tevent_filter - WHERE id_group_filter IN (".implode(',', array_keys ($groups_user)).")"; + WHERE id_group_filter IN ('.implode(',', array_keys($groups_user)).')'; $filters = db_get_all_rows_sql($sql); -if ($filters === false) - $filters = array (); +if ($filters === false) { + $filters = []; +} $table = new stdClass(); $table->width = '100%'; $table->class = 'databox data'; -$table->head = array (); +$table->head = []; $table->head[0] = __('Name'); $table->head[1] = __('Group'); $table->head[2] = __('Event type'); $table->head[3] = __('Event status'); $table->head[4] = __('Severity'); -$table->head[5] = __('Action') . - html_print_checkbox('all_delete', 0, false, true, false); -$table->style = array (); +$table->head[5] = __('Action').html_print_checkbox('all_delete', 0, false, true, false); +$table->style = []; $table->style[0] = 'font-weight: bold'; -$table->align = array (); +$table->align = []; $table->align[1] = 'left'; $table->align[2] = 'left'; $table->align[3] = 'left'; $table->align[4] = 'left'; $table->align[5] = 'left'; -$table->size = array (); +$table->size = []; $table->size[0] = '50%'; $table->size[1] = '5px'; $table->size[2] = '80px'; $table->size[3] = '80px'; $table->size[4] = '80px'; $table->size[5] = '40px'; -$table->data = array (); +$table->data = []; -$total_filters = db_get_all_rows_filter ('tevent_filter', false, 'COUNT(*) AS total'); +$total_filters = db_get_all_rows_filter('tevent_filter', false, 'COUNT(*) AS total'); $total_filters = $total_filters[0]['total']; -//ui_pagination ($total_filters, $url); - +// ui_pagination ($total_filters, $url); foreach ($filters as $filter) { - $data = array (); - - $data[0] = ''.$filter['id_name'].''; - $data[1] = ui_print_group_icon ($filter['id_group_filter'], true); - $data[2] = events_get_event_types($filter['event_type']); - $data[3] = events_get_status($filter['status']); - $data[4] = events_get_severity_types($filter['severity']); - $data[5] = "" . - html_print_image('images/cross.png', true, array('title' => __('Delete'))) . "" . - html_print_checkbox_extended ('delete_multiple[]', $filter['id_filter'], false, false, '', 'class="check_delete"', true); + $data = []; - array_push ($table->data, $data); + $data[0] = ''.$filter['id_name'].''; + $data[1] = ui_print_group_icon($filter['id_group_filter'], true); + $data[2] = events_get_event_types($filter['event_type']); + $data[3] = events_get_status($filter['status']); + $data[4] = events_get_severity_types($filter['severity']); + $data[5] = "".html_print_image('images/cross.png', true, ['title' => __('Delete')]).''.html_print_checkbox_extended('delete_multiple[]', $filter['id_filter'], false, false, '', 'class="check_delete"', true); + + array_push($table->data, $data); } if (isset($data)) { - echo "
    "; - html_print_input_hidden('multiple_delete', 1); - html_print_table ($table); - if(!is_metaconsole()) - echo "
    "; - else - echo "
    "; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - echo "
    "; - echo ""; -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined filters') ) ); + echo "
    "; + html_print_input_hidden('multiple_delete', 1); + html_print_table($table); + if (!is_metaconsole()) { + echo "
    "; + } else { + echo "
    "; + } + + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + echo '
    '; + echo ''; +} else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined filters') ]); } -if(!defined("METACONSOLE")) - echo "
    "; -else - echo "
    "; - echo '
    '; - html_print_submit_button (__('Create filter'), 'crt', false, 'class="sub wand"'); - echo ''; -echo "
    "; +if (!defined('METACONSOLE')) { + echo "
    "; +} else { + echo "
    "; +} + + echo '
    '; + html_print_submit_button(__('Create filter'), 'crt', false, 'class="sub wand"'); + echo ''; +echo '
    '; ?> diff --git a/pandora_console/godmode/events/event_responses.editor.php b/pandora_console/godmode/events/event_responses.editor.php index 504377baf4..18943e94ef 100644 --- a/pandora_console/godmode/events/event_responses.editor.php +++ b/pandora_console/godmode/events/event_responses.editor.php @@ -4,208 +4,240 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); +check_login(); -if (! check_acl($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Group Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Group Management' + ); + include 'general/noaccess.php'; + return; } $meta = false; -if(enterprise_installed() && defined("METACONSOLE")) { - $meta = true; +if (enterprise_installed() && defined('METACONSOLE')) { + $meta = true; } $class_description = 'response_description'; if ($meta) { - $class_description = 'response_description_metaconsole'; + $class_description = 'response_description_metaconsole'; } -$event_response_id = get_parameter('id_response',0); +$event_response_id = get_parameter('id_response', 0); if ($event_response_id > 0) { - $event_response = db_get_row('tevent_response','id',$event_response_id); -} -else { - $event_response = array(); - $event_response['name'] = ''; - $event_response['description'] = ''; - $event_response['id_group'] = 0; - $event_response['type'] = ''; - $event_response['target'] = ''; - $event_response['id'] = 0; - $event_response['new_window'] = 1; - $event_response['modal_width'] = 0; - $event_response['modal_height'] = 0; - $event_response['params'] = ''; - $event_response['server_to_exec'] = ''; + $event_response = db_get_row('tevent_response', 'id', $event_response_id); +} else { + $event_response = []; + $event_response['name'] = ''; + $event_response['description'] = ''; + $event_response['id_group'] = 0; + $event_response['type'] = ''; + $event_response['target'] = ''; + $event_response['id'] = 0; + $event_response['new_window'] = 1; + $event_response['modal_width'] = 0; + $event_response['modal_height'] = 0; + $event_response['params'] = ''; + $event_response['server_to_exec'] = ''; } $table = new stdClass(); $table->width = '100%'; $table->class = 'databox filters'; -if(is_metaconsole()) { - $table->head[0] = __('Edit event responses'); - $table->head_colspan[0] = 5; - $table->headstyle[0] = 'text-align: center'; +if (is_metaconsole()) { + $table->head[0] = __('Edit event responses'); + $table->head_colspan[0] = 5; + $table->headstyle[0] = 'text-align: center'; } -$table->size = array(); +$table->size = []; $table->style[0] = 'font-weight: bold;'; $table->style[2] = 'font-weight: bold;'; -$table->data = array(); +$table->data = []; -$data = array(); +$data = []; $data[0] = __('Name'); -$data[1] = html_print_input_text('name', $event_response['name'], '', - 50, 255, true); -$data[1] .= html_print_input_hidden('id_response',$event_response['id'],true); +$data[1] = html_print_input_text( + 'name', + $event_response['name'], + '', + 50, + 255, + true +); +$data[1] .= html_print_input_hidden('id_response', $event_response['id'], true); $data[2] = __('Group'); -$data[3] = html_print_select_groups(false, 'PM', true, 'id_group',$event_response['id_group'],'','','',true); +$data[3] = html_print_select_groups(false, 'PM', true, 'id_group', $event_response['id_group'], '', '', '', true); $table->data[0] = $data; -$data = array(); +$data = []; $table->colspan[1][1] = 3; $data[0] = __('Description'); -$data[1] = html_print_textarea('description', 5, 40, - $event_response['description'], 'class="' . $class_description . '"', true); +$data[1] = html_print_textarea( + 'description', + 5, + 40, + $event_response['description'], + 'class="'.$class_description.'"', + true +); $table->data[1] = $data; -$data = array(); -$data[0] = __('Location') . ui_print_help_tip(__('For Command type Modal Window mode is enforced'), true); -$locations = array(__('Modal window'), __('New window')); -$data[1] = html_print_select($locations,'new_window',$event_response['new_window'],'','','',true); +$data = []; +$data[0] = __('Location').ui_print_help_tip(__('For Command type Modal Window mode is enforced'), true); +$locations = [ + __('Modal window'), + __('New window'), +]; +$data[1] = html_print_select($locations, 'new_window', $event_response['new_window'], '', '', '', true); $data[2] = ''.__('Size').''; if ($event_response['modal_width'] == 0) { - $event_response['modal_width'] = 620; + $event_response['modal_width'] = 620; } + if ($event_response['modal_height'] == 0) { - $event_response['modal_height'] = 500; + $event_response['modal_height'] = 500; } + $data[3] = ''.__('Width').' (px) '; -$data[3] .= ''.html_print_input_text('modal_width',$event_response['modal_width'],'',4,5,true).''; +$data[3] .= ''.html_print_input_text('modal_width', $event_response['modal_width'], '', 4, 5, true).''; $data[3] .= ''.__('Height').' (px) '; -$data[3] .= ''.html_print_input_text('modal_height',$event_response['modal_height'],'',4,5,true).''; +$data[3] .= ''.html_print_input_text('modal_height', $event_response['modal_height'], '', 4, 5, true).''; $table->data[2] = $data; -$data = array(); -$data[0] = __('Parameters').ui_print_help_icon ("response_parameters", true); -$data[1] = html_print_input_text('params', $event_response['params'], - '', 50, 255, true); -$types = array('url' => __('URL'), 'command' => __('Command')); +$data = []; +$data[0] = __('Parameters').ui_print_help_icon('response_parameters', true); +$data[1] = html_print_input_text( + 'params', + $event_response['params'], + '', + 50, + 255, + true +); +$types = [ + 'url' => __('URL'), + 'command' => __('Command'), +]; $data[2] = __('Type'); -$data[3] = html_print_select($types,'type',$event_response['type'],'','','',true); +$data[3] = html_print_select($types, 'type', $event_response['type'], '', '', '', true); $table->data[3] = $data; -$data = array(); -$data[0] = ''.__('Command').''.ui_print_help_icon ("response_macros", true); -$data[1] = html_print_input_text('target', $event_response['target'], - '', 100, 255, true); +$data = []; +$data[0] = ''.__('Command').''.ui_print_help_icon('response_macros', true); +$data[1] = html_print_input_text( + 'target', + $event_response['target'], + '', + 100, + 255, + true +); -$servers_to_exec = array(); +$servers_to_exec = []; $servers_to_exec[0] = __('Local console'); if (enterprise_installed()) { - enterprise_include_once ('include/functions_satellite.php'); - - $rows = get_proxy_servers(); - foreach ($rows as $row) { - if ($row['server_type'] != 13) { - $s_type = " (Standard)"; - } - else { - $s_type = " (Satellite)"; - } + enterprise_include_once('include/functions_satellite.php'); - $servers_to_exec[$row['id_server']] = $row['name'] . $s_type; - } + $rows = get_proxy_servers(); + foreach ($rows as $row) { + if ($row['server_type'] != 13) { + $s_type = ' (Standard)'; + } else { + $s_type = ' (Satellite)'; + } + + $servers_to_exec[$row['id_server']] = $row['name'].$s_type; + } } -$data[2] = ''; -$data[3] = ''; +$data[2] = ''; +$data[3] = ''; $table->data[4] = $data; if ($event_response_id == 0) { - echo '
    '; - html_print_table($table); - if(!defined('METACONSOLE')) - echo '
    '; - else - echo '
    '; - html_print_submit_button(__('Create'), 'create_response_button', false, array('class' => 'sub next')); - echo '
    '; - echo ''; -} -else { - echo '
    '; - html_print_table($table); - if(!defined('METACONSOLE')) - echo '
    '; - else - echo '
    '; - html_print_submit_button(__('Update'), 'update_response_button', false, array('class' => 'sub next')); - echo '
    '; - echo ''; + echo '
    '; + html_print_table($table); + if (!defined('METACONSOLE')) { + echo '
    '; + } else { + echo '
    '; + } + + html_print_submit_button(__('Create'), 'create_response_button', false, ['class' => 'sub next']); + echo '
    '; + echo ''; +} else { + echo '
    '; + html_print_table($table); + if (!defined('METACONSOLE')) { + echo '
    '; + } else { + echo '
    '; + } + + html_print_submit_button(__('Update'), 'update_response_button', false, ['class' => 'sub next']); + echo '
    '; + echo ''; } ?> - + + - - + + - - + + width = '98%'; -$table->head = array(); +$table->head = []; $table->head[] = __('File'); $table->head[] = __('Version'); -$table->head[] = __("Enterprise"); -$table->head[] = __("Godmode Function"); -$table->head[] = __("Godmode Menu"); -$table->head[] = __("Operation Menu"); -$table->head[] = __("Operation Function"); -$table->head[] = __("Login Function"); -$table->head[] = __("Agent operation tab"); -$table->head[] = __("Agent godmode tab"); -$table->head[] = __("Operation"); +$table->head[] = __('Enterprise'); +$table->head[] = __('Godmode Function'); +$table->head[] = __('Godmode Menu'); +$table->head[] = __('Operation Menu'); +$table->head[] = __('Operation Function'); +$table->head[] = __('Login Function'); +$table->head[] = __('Agent operation tab'); +$table->head[] = __('Agent godmode tab'); +$table->head[] = __('Operation'); /* -$table->width = array(); -$table->width[] = '30%'; -$table->width[] = '30%'; + $table->width = array(); + $table->width[] = '30%'; + $table->width[] = '30%'; */ $table->width = '100%'; $table->class = 'databox data'; -$table->align = array(); +$table->align = []; $table->align[] = 'left'; $table->align[] = 'center'; $table->align[] = 'center'; @@ -172,119 +164,107 @@ $table->align[] = 'center'; $table->align[] = 'center'; $table->align[] = 'center'; -$table->data = array(); +$table->data = []; foreach ($extensions as $file => $extension) { - $data = array(); - - $on = html_print_image("images/dot_green.png", true); - $off = html_print_image("images/dot_red.png", true); - if (!$extension['enabled']) { - $on = html_print_image("images/dot_green.disabled.png", true); - $off = html_print_image("images/dot_red.disabled.png", true); - $data[] = '' . $file . ''; - - //Get version of this extensions - if ($config['extensions'][$file]['operation_menu']) { - $data[] = $config['extensions'][$file]['operation_menu']['version']; - } else if ($config['extensions'][$file]['godmode_menu']) { - $data[] = $config['extensions'][$file]['godmode_menu']['version']; - } else if ($config['extensions'][$file]['extension_ope_tab']) { - $data[] = $config['extensions'][$file]['extension_ope_tab']['version']; - } else if ($config['extensions'][$file]['extension_god_tab']) { - $data[] = $config['extensions'][$file]['extension_god_tab']['version']; - } else { - $data[] = __('N/A'); - } - } - else { - $data[] = $file; - - //Get version of this extension - if ($config['extensions'][$file]['operation_menu']) { - $data[] = $config['extensions'][$file]['operation_menu']['version']; - } else if ($config['extensions'][$file]['godmode_menu']) { - $data[] = $config['extensions'][$file]['godmode_menu']['version']; - } else if (isset($config['extensions'][$file]['extension_ope_tab'])) { - $data[] = $config['extensions'][$file]['extension_ope_tab']['version']; - } else if ($config['extensions'][$file]['extension_god_tab']) { - $data[] = $config['extensions'][$file]['extension_god_tab']['version']; - } else { - $data[] = __('N/A'); - } - } - - if ($extension['enterprise']) { - $data[] = $on; - } - else { - $data[] = $off; - } - - if ($extension['godmode_function']) { - $data[] = $on; - } - else { - $data[] = $off; - } - - if ($extension['godmode_menu']) { - $data[] = $on; - } - else { - $data[] = $off; - } - - if ($extension['operation_menu']) { - $data[] = $on; - } - else { - $data[] = $off; - } - - if ($extension['operation_function']) { - $data[] = $on; - } - else { - $data[] = $off; - } - - if ($extension['login_function']) { - $data[] = $on; - } - else { - $data[] = $off; - } - - if ($extension['extension_ope_tab']) { - $data[] = $on; - } - else { - $data[] = $off; - } - - if ($extension['extension_god_tab']) { - $data[] = $on; - } - else { - $data[] = $off; - } - - //Avoid to delete or disabled update_manager - if ($file != "update_manager.php") { - if (!$extension['enabled']) { - $data[] = '' . html_print_image("images/cross.disabled.png", true) . '' . - ' ' . html_print_image("images/lightbulb_off.png", true) . ''; - } - else { - $data[] = '' . html_print_image("images/cross.png", true) . '' . - ' ' . html_print_image("images/lightbulb.png", true) . ''; - } - } - else { - $data[] = ""; - } - - $table->data[] = $data; + $data = []; + + $on = html_print_image('images/dot_green.png', true); + $off = html_print_image('images/dot_red.png', true); + if (!$extension['enabled']) { + $on = html_print_image('images/dot_green.disabled.png', true); + $off = html_print_image('images/dot_red.disabled.png', true); + $data[] = ''.$file.''; + + // Get version of this extensions + if ($config['extensions'][$file]['operation_menu']) { + $data[] = $config['extensions'][$file]['operation_menu']['version']; + } else if ($config['extensions'][$file]['godmode_menu']) { + $data[] = $config['extensions'][$file]['godmode_menu']['version']; + } else if ($config['extensions'][$file]['extension_ope_tab']) { + $data[] = $config['extensions'][$file]['extension_ope_tab']['version']; + } else if ($config['extensions'][$file]['extension_god_tab']) { + $data[] = $config['extensions'][$file]['extension_god_tab']['version']; + } else { + $data[] = __('N/A'); + } + } else { + $data[] = $file; + + // Get version of this extension + if ($config['extensions'][$file]['operation_menu']) { + $data[] = $config['extensions'][$file]['operation_menu']['version']; + } else if ($config['extensions'][$file]['godmode_menu']) { + $data[] = $config['extensions'][$file]['godmode_menu']['version']; + } else if (isset($config['extensions'][$file]['extension_ope_tab'])) { + $data[] = $config['extensions'][$file]['extension_ope_tab']['version']; + } else if ($config['extensions'][$file]['extension_god_tab']) { + $data[] = $config['extensions'][$file]['extension_god_tab']['version']; + } else { + $data[] = __('N/A'); + } + } + + if ($extension['enterprise']) { + $data[] = $on; + } else { + $data[] = $off; + } + + if ($extension['godmode_function']) { + $data[] = $on; + } else { + $data[] = $off; + } + + if ($extension['godmode_menu']) { + $data[] = $on; + } else { + $data[] = $off; + } + + if ($extension['operation_menu']) { + $data[] = $on; + } else { + $data[] = $off; + } + + if ($extension['operation_function']) { + $data[] = $on; + } else { + $data[] = $off; + } + + if ($extension['login_function']) { + $data[] = $on; + } else { + $data[] = $off; + } + + if ($extension['extension_ope_tab']) { + $data[] = $on; + } else { + $data[] = $off; + } + + if ($extension['extension_god_tab']) { + $data[] = $on; + } else { + $data[] = $off; + } + + // Avoid to delete or disabled update_manager + if ($file != 'update_manager.php') { + if (!$extension['enabled']) { + $data[] = ''.html_print_image('images/cross.disabled.png', true).''.' '.html_print_image('images/lightbulb_off.png', true).''; + } else { + $data[] = ''.html_print_image('images/cross.png', true).''.' '.html_print_image('images/lightbulb.png', true).''; + } + } else { + $data[] = ''; + } + + $table->data[] = $data; } -html_print_table ($table); -?> \ No newline at end of file + +html_print_table($table); + diff --git a/pandora_console/godmode/gis_maps/configure_gis_map.php b/pandora_console/godmode/gis_maps/configure_gis_map.php index b731c7b6d9..9e52ddeae9 100644 --- a/pandora_console/godmode/gis_maps/configure_gis_map.php +++ b/pandora_console/godmode/gis_maps/configure_gis_map.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,205 +10,277 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -$gis_w = check_acl ($config['id_user'], 0, 'MW'); -$gis_m = check_acl ($config['id_user'], 0, 'MM'); +$gis_w = check_acl($config['id_user'], 0, 'MW'); +$gis_m = check_acl($config['id_user'], 0, 'MM'); $access = ($gis_w == true) ? 'MW' : (($gis_m == true) ? 'MM' : 'MW'); -if (!$gis_w && !$gis_m ) { - db_pandora_audit("ACL Violation", "Trying to access map builder"); - require ("general/noaccess.php"); - return; +if (!$gis_w && !$gis_m) { + db_pandora_audit('ACL Violation', 'Trying to access map builder'); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_gis.php'); +require_once 'include/functions_gis.php'; -$idMap = (int)get_parameter('map_id', 0); +$idMap = (int) get_parameter('map_id', 0); $action = get_parameter('action', 'new_map'); -$sec2 = get_parameter_get ('sec2'); -$sec2 = safe_url_extraclean ($sec2); +$sec2 = get_parameter_get('sec2'); +$sec2 = safe_url_extraclean($sec2); -$sec = get_parameter_get ('sec'); -$sec = safe_url_extraclean ($sec); +$sec = get_parameter_get('sec'); +$sec = safe_url_extraclean($sec); // Layers -$layer_ids = get_parameter("layer_ids", array()); -$layers = get_parameter("layers", array()); -$layer_list = array(); +$layer_ids = get_parameter('layer_ids', []); +$layers = get_parameter('layers', []); +$layer_list = []; foreach ($layer_ids as $layer_id) { - if (empty($layers[$layer_id]) || empty($layers[$layer_id]["name"])) continue; - $trimmed_name = trim($layers[$layer_id]["name"]); - if (empty($trimmed_name)) continue; + if (empty($layers[$layer_id]) || empty($layers[$layer_id]['name'])) { + continue; + } - $layer_list[] = array( - "id" => (strpos($layer_id, "new_") === false) ? (int) $layer_id : null, - "layer_name" => $trimmed_name, - "layer_visible" => ((int) $layers[$layer_id]["visible"] === 1), - "layer_group" => (int) $layers[$layer_id]["agents_from_group"], - "layer_agent_list" => $layers[$layer_id]["agents"], - "layer_group_list" => $layers[$layer_id]["groups"] - ); + $trimmed_name = trim($layers[$layer_id]['name']); + if (empty($trimmed_name)) { + continue; + } + + $layer_list[] = [ + 'id' => (strpos($layer_id, 'new_') === false) ? (int) $layer_id : null, + 'layer_name' => $trimmed_name, + 'layer_visible' => ((int) $layers[$layer_id]['visible'] === 1), + 'layer_group' => (int) $layers[$layer_id]['agents_from_group'], + 'layer_agent_list' => $layers[$layer_id]['agents'], + 'layer_group_list' => $layers[$layer_id]['groups'], + ]; } $next_action = 'new_map'; switch ($action) { - case 'save_new': - $map_name = get_parameter('map_name'); - $map_initial_longitude = get_parameter('map_initial_longitude'); - $map_initial_latitude = get_parameter('map_initial_latitude'); - $map_initial_altitude = get_parameter('map_initial_altitude'); - $map_zoom_level = get_parameter('map_zoom_level'); - $map_background = ''; //TODO - $map_default_longitude = get_parameter('map_default_longitude'); - $map_default_latitude = get_parameter('map_default_latitude'); - $map_default_altitude = get_parameter('map_default_altitude'); - $map_group_id = get_parameter('map_group_id'); - $map_levels_zoom = get_parameter('map_levels_zoom'); - - $map_connection_list_temp = explode(",",get_parameter('map_connection_list')); - - - foreach ($map_connection_list_temp as $index => $value) { - $cleanValue = trim($value); - if ($cleanValue == '') { - unset($map_connection_list_temp[$index]); - } - } + case 'save_new': + $map_name = get_parameter('map_name'); + $map_initial_longitude = get_parameter('map_initial_longitude'); + $map_initial_latitude = get_parameter('map_initial_latitude'); + $map_initial_altitude = get_parameter('map_initial_altitude'); + $map_zoom_level = get_parameter('map_zoom_level'); + $map_background = ''; + // TODO + $map_default_longitude = get_parameter('map_default_longitude'); + $map_default_latitude = get_parameter('map_default_latitude'); + $map_default_altitude = get_parameter('map_default_altitude'); + $map_group_id = get_parameter('map_group_id'); + $map_levels_zoom = get_parameter('map_levels_zoom'); - $map_connection_default = get_parameter('map_connection_default'); - - $map_connection_list = array(); - foreach ($map_connection_list_temp as $idMapConnection) { - $default = 0; - if ($map_connection_default == $idMapConnection) - $default = 1; - - $map_connection_list[] = array('id_conection' => $idMapConnection, 'default' => $default); - } - - $invalidFields = gis_validate_map_data($map_name, $map_zoom_level, - $map_initial_longitude, $map_initial_latitude, $map_initial_altitude, - $map_default_longitude, $map_default_latitude, $map_default_altitude, - $map_connection_list, $map_levels_zoom); - - if (empty($invalidFields) && get_parameter('map_connection_list') != "") { - $idMap = gis_save_map($map_name, $map_initial_longitude, $map_initial_latitude, - $map_initial_altitude, $map_zoom_level, $map_background, - $map_default_longitude, $map_default_latitude, $map_default_altitude, - $map_group_id, $map_connection_list, $layer_list); - $mapCreatedOk = true; - $next_action = 'update_saved'; - } - else { - $next_action = 'save_new'; - $mapCreatedOk = false; - } - - ui_print_result_message ($mapCreatedOk, __('Map successfully created'), - __('Map could not be created')); - break; - case 'new_map': - $next_action = 'save_new'; - - $map_name = ''; - $map_initial_longitude = ''; - $map_initial_latitude = ''; - $map_initial_altitude = ''; - $map_zoom_level = ''; - $map_background = ''; - $map_default_longitude = ''; - $map_default_latitude = ''; - $map_default_altitude = ''; - $map_group_id = ''; - $map_connection_list = array(); - $layer_list = array(); - $map_levels_zoom = 0; - break; - case 'edit_map': - $next_action = 'update_saved'; - - break; - case 'update_saved': - $map_name = get_parameter('map_name'); - $map_initial_longitude = get_parameter('map_initial_longitude'); - $map_initial_latitude = get_parameter('map_initial_latitude'); - $map_initial_altitude = get_parameter('map_initial_altitude'); - $map_zoom_level = get_parameter('map_zoom_level'); - $map_background = ''; //TODO - $map_default_longitude = get_parameter('map_default_longitude'); - $map_default_latitude = get_parameter('map_default_latitude'); - $map_default_altitude = get_parameter('map_default_altitude'); - $map_group_id = get_parameter('map_group_id'); - $map_levels_zoom = get_parameter('map_levels_zoom'); - - $map_connection_list_temp = explode(",",get_parameter('map_connection_list')); - foreach ($map_connection_list_temp as $index => $value) { - $cleanValue = trim($value); - if ($cleanValue == '') { - unset($map_connection_list_temp[$index]); - } - } - - $map_connection_default = get_parameter('map_connection_default'); - - $map_connection_list = array(); - foreach ($map_connection_list_temp as $idMapConnection) { - $default = 0; - if ($map_connection_default == $idMapConnection) - $default = 1; - - $map_connection_list[] = array('id_conection' => $idMapConnection, 'default' => $default); - } - - $invalidFields = gis_validate_map_data($map_name, $map_zoom_level, - $map_initial_longitude, $map_initial_latitude, $map_initial_altitude, - $map_default_longitude, $map_default_latitude, $map_default_altitude, - $map_connection_list, $map_levels_zoom); + $map_connection_list_temp = explode(',', get_parameter('map_connection_list')); - if (empty($invalidFields) && get_parameter('map_connection_list') != "") { - //TODO - gis_update_map($idMap, $map_name, $map_initial_longitude, $map_initial_latitude, - $map_initial_altitude, $map_zoom_level, $map_background, - $map_default_longitude, $map_default_latitude, $map_default_altitude, - $map_group_id, $map_connection_list, $layer_list); - $mapCreatedOk = true; - } - else { - $next_action = 'update_saved'; - $mapCreatedOk = false; - } - - ui_print_result_message ($mapCreatedOk, __('Map successfully update'), - __('Map could not be updated')); - - $next_action = 'update_saved'; - html_print_input_hidden('map_id', $idMap); - break; + + foreach ($map_connection_list_temp as $index => $value) { + $cleanValue = trim($value); + if ($cleanValue == '') { + unset($map_connection_list_temp[$index]); + } + } + + $map_connection_default = get_parameter('map_connection_default'); + + $map_connection_list = []; + foreach ($map_connection_list_temp as $idMapConnection) { + $default = 0; + if ($map_connection_default == $idMapConnection) { + $default = 1; + } + + $map_connection_list[] = [ + 'id_conection' => $idMapConnection, + 'default' => $default, + ]; + } + + $invalidFields = gis_validate_map_data( + $map_name, + $map_zoom_level, + $map_initial_longitude, + $map_initial_latitude, + $map_initial_altitude, + $map_default_longitude, + $map_default_latitude, + $map_default_altitude, + $map_connection_list, + $map_levels_zoom + ); + + if (empty($invalidFields) && get_parameter('map_connection_list') != '') { + $idMap = gis_save_map( + $map_name, + $map_initial_longitude, + $map_initial_latitude, + $map_initial_altitude, + $map_zoom_level, + $map_background, + $map_default_longitude, + $map_default_latitude, + $map_default_altitude, + $map_group_id, + $map_connection_list, + $layer_list + ); + $mapCreatedOk = true; + $next_action = 'update_saved'; + } else { + $next_action = 'save_new'; + $mapCreatedOk = false; + } + + ui_print_result_message( + $mapCreatedOk, + __('Map successfully created'), + __('Map could not be created') + ); + break; + + case 'new_map': + $next_action = 'save_new'; + + $map_name = ''; + $map_initial_longitude = ''; + $map_initial_latitude = ''; + $map_initial_altitude = ''; + $map_zoom_level = ''; + $map_background = ''; + $map_default_longitude = ''; + $map_default_latitude = ''; + $map_default_altitude = ''; + $map_group_id = ''; + $map_connection_list = []; + $layer_list = []; + $map_levels_zoom = 0; + break; + + case 'edit_map': + $next_action = 'update_saved'; + + break; + + case 'update_saved': + $map_name = get_parameter('map_name'); + $map_initial_longitude = get_parameter('map_initial_longitude'); + $map_initial_latitude = get_parameter('map_initial_latitude'); + $map_initial_altitude = get_parameter('map_initial_altitude'); + $map_zoom_level = get_parameter('map_zoom_level'); + $map_background = ''; + // TODO + $map_default_longitude = get_parameter('map_default_longitude'); + $map_default_latitude = get_parameter('map_default_latitude'); + $map_default_altitude = get_parameter('map_default_altitude'); + $map_group_id = get_parameter('map_group_id'); + $map_levels_zoom = get_parameter('map_levels_zoom'); + + $map_connection_list_temp = explode(',', get_parameter('map_connection_list')); + foreach ($map_connection_list_temp as $index => $value) { + $cleanValue = trim($value); + if ($cleanValue == '') { + unset($map_connection_list_temp[$index]); + } + } + + $map_connection_default = get_parameter('map_connection_default'); + + $map_connection_list = []; + foreach ($map_connection_list_temp as $idMapConnection) { + $default = 0; + if ($map_connection_default == $idMapConnection) { + $default = 1; + } + + $map_connection_list[] = [ + 'id_conection' => $idMapConnection, + 'default' => $default, + ]; + } + + $invalidFields = gis_validate_map_data( + $map_name, + $map_zoom_level, + $map_initial_longitude, + $map_initial_latitude, + $map_initial_altitude, + $map_default_longitude, + $map_default_latitude, + $map_default_altitude, + $map_connection_list, + $map_levels_zoom + ); + + if (empty($invalidFields) && get_parameter('map_connection_list') != '') { + // TODO + gis_update_map( + $idMap, + $map_name, + $map_initial_longitude, + $map_initial_latitude, + $map_initial_altitude, + $map_zoom_level, + $map_background, + $map_default_longitude, + $map_default_latitude, + $map_default_altitude, + $map_group_id, + $map_connection_list, + $layer_list + ); + $mapCreatedOk = true; + } else { + $next_action = 'update_saved'; + $mapCreatedOk = false; + } + + ui_print_result_message( + $mapCreatedOk, + __('Map successfully update'), + __('Map could not be updated') + ); + + $next_action = 'update_saved'; + html_print_input_hidden('map_id', $idMap); + break; } -$url = 'index.php?sec=' . $sec . '&sec2=' . $sec2 . '&map_id=' . $idMap . '&action=' . $next_action; +$url = 'index.php?sec='.$sec.'&sec2='.$sec2.'&map_id='.$idMap.'&action='.$next_action; -$buttons['gis_maps_list'] = array('active' => true, - 'text' => '' . - html_print_image("images/list.png", true, - array("title" => __('GIS Maps list'))) .''); +$buttons['gis_maps_list'] = [ + 'active' => true, + 'text' => ''.html_print_image( + 'images/list.png', + true, + ['title' => __('GIS Maps list')] + ).'', +]; if ($idMap) { - $buttons['view_gis'] = array('active' => true, - 'text' => '' . - html_print_image("images/op_gis.png", true, - array("title" => __('View GIS'))) .''); + $buttons['view_gis'] = [ + 'active' => true, + 'text' => ''.html_print_image( + 'images/op_gis.png', + true, + ['title' => __('View GIS')] + ).'', + ]; } -ui_print_page_header (__('GIS Maps builder'), - "images/gm_gis.png", false, "configure_gis_map", true, $buttons); +ui_print_page_header( + __('GIS Maps builder'), + 'images/gm_gis.png', + false, + 'configure_gis_map', + true, + $buttons +); ?> @@ -218,238 +289,239 @@ ui_print_page_header (__('GIS Maps builder'), var connectionMaps = []; function isInt(x) { - var y=parseInt(x); - if (isNaN(y)) return false; - return x==y && x.toString()==y.toString(); + var y=parseInt(x); + if (isNaN(y)) return false; + return x==y && x.toString()==y.toString(); } function deleteConnectionMap(idConnectionMap) { - for (var index in connectionMaps) { - - //int because in the object array there are method as string - if (isInt(index)) { - if (connectionMaps[index] == idConnectionMap) { - connectionMaps.splice(index, 1); - } - } - } - - checked = $("#radiobtn0001", $("#map_connection_" + idConnectionMap)).attr('checked'); - $("#map_connection_" + idConnectionMap).remove(); - - if (checked) { - //Checked first, but not is index = 0 maybe. - - for (var index in connectionMaps) { - - //int because in the object array there are method as string - if (isInt(index)) { - $("#radiobtn0001", $("#map_connection_" + connectionMaps[index])).attr('checked', 'checked'); - break; - } - } - } + for (var index in connectionMaps) { + + //int because in the object array there are method as string + if (isInt(index)) { + if (connectionMaps[index] == idConnectionMap) { + connectionMaps.splice(index, 1); + } + } + } + + checked = $("#radiobtn0001", $("#map_connection_" + idConnectionMap)).attr('checked'); + $("#map_connection_" + idConnectionMap).remove(); + + if (checked) { + //Checked first, but not is index = 0 maybe. + + for (var index in connectionMaps) { + + //int because in the object array there are method as string + if (isInt(index)) { + $("#radiobtn0001", $("#map_connection_" + connectionMaps[index])).attr('checked', 'checked'); + break; + } + } + } } function setFieldsRequestAjax(id_conexion) { - if (confirm('')) { - jQuery.ajax ({ - data: "page=operation/gis_maps/ajax&opt=get_data_conexion&id_conection=" + idConnectionMap, - type: "GET", - dataType: 'json', - url: "ajax.php", - success: function (data) { - if (data.correct) { - $("input[name=map_initial_longitude]").val(data.content.initial_longitude); - $("input[name=map_initial_latitude]").val(data.content.initial_latitude); - $("input[name=map_initial_altitude]").val(data.content.initial_altitude); - $("input[name=map_default_longitude]").val(data.content.default_longitude); - $("input[name=map_default_latitude]").val(data.content.default_latitude); - $("input[name=map_default_altitude]").val(data.content.default_altitude); - $("input[name=map_zoom_level]").val(data.content.default_zoom_level); - $("input[name=map_levels_zoom]").val(data.content.num_zoom_levels); - } - } - }); - } + if (confirm('')) { + jQuery.ajax ({ + data: "page=operation/gis_maps/ajax&opt=get_data_conexion&id_conection=" + idConnectionMap, + type: "GET", + dataType: 'json', + url: "ajax.php", + success: function (data) { + if (data.correct) { + $("input[name=map_initial_longitude]").val(data.content.initial_longitude); + $("input[name=map_initial_latitude]").val(data.content.initial_latitude); + $("input[name=map_initial_altitude]").val(data.content.initial_altitude); + $("input[name=map_default_longitude]").val(data.content.default_longitude); + $("input[name=map_default_latitude]").val(data.content.default_latitude); + $("input[name=map_default_altitude]").val(data.content.default_altitude); + $("input[name=map_zoom_level]").val(data.content.default_zoom_level); + $("input[name=map_levels_zoom]").val(data.content.num_zoom_levels); + } + } + }); + } } function changeDefaultConection(id) { - setFieldsRequestAjax(id); + setFieldsRequestAjax(id); } function addConnectionMap() { - idConnectionMap = $("#map_connection :selected").val(); - connectionMapName = $("#map_connection :selected").text(); - - //Test if before just added - for (var index in connectionMaps) { - if (isInt(index)) { - if (connectionMaps[index] == idConnectionMap) { - alert(' "' + connectionMapName + '" '); - - return; - } - } - } - - tableRows = $("#chunk_map_connection").clone(); - tableRows.attr('id','map_connection_' + idConnectionMap); - $("input[name=map_connection_default]",tableRows).val(idConnectionMap); - - if (connectionMaps.length == 0) { - //The first is checked - $("#radiobtn0001", tableRows).attr('checked', 'checked'); - - //Set the fields with conexion data (in ajax) - setFieldsRequestAjax(idConnectionMap); - } - - connectionMaps.push(idConnectionMap); - - $("#text-map_connection_name", tableRows).val(connectionMapName); - $("#text-map_connection_name", tableRows).attr('name', 'map_connection_name_' + idConnectionMap); - $("#delete_row", tableRows).attr('href', "javascript: deleteConnectionMap(" + idConnectionMap + ")"); - - $("#map_connection").append(tableRows); + idConnectionMap = $("#map_connection :selected").val(); + connectionMapName = $("#map_connection :selected").text(); + + //Test if before just added + for (var index in connectionMaps) { + if (isInt(index)) { + if (connectionMaps[index] == idConnectionMap) { + alert(' "' + connectionMapName + '" '); + + return; + } + } + } + + tableRows = $("#chunk_map_connection").clone(); + tableRows.attr('id','map_connection_' + idConnectionMap); + $("input[name=map_connection_default]",tableRows).val(idConnectionMap); + + if (connectionMaps.length == 0) { + //The first is checked + $("#radiobtn0001", tableRows).attr('checked', 'checked'); + + //Set the fields with conexion data (in ajax) + setFieldsRequestAjax(idConnectionMap); + } + + connectionMaps.push(idConnectionMap); + + $("#text-map_connection_name", tableRows).val(connectionMapName); + $("#text-map_connection_name", tableRows).attr('name', 'map_connection_name_' + idConnectionMap); + $("#delete_row", tableRows).attr('href', "javascript: deleteConnectionMap(" + idConnectionMap + ")"); + + $("#map_connection").append(tableRows); } '; -echo '
    '; - -//Load the data in edit or reload in update. +// Load the data in edit or reload in update. switch ($action) { - case 'edit_map': - case 'update_saved': - $mapData = gis_get_map_data($idMap); - - $map_name = $mapData['map']['map_name']; - $map_group_id = $mapData['map']['group_id']; - $map_zoom_level = $mapData['map']['zoom_level']; - $map_background = $mapData['map']['map_background']; - $map_initial_longitude = $mapData['map']['initial_longitude']; - $map_initial_latitude = $mapData['map']['initial_latitude']; - $map_initial_altitude = $mapData['map']['initial_altitude']; - $map_default_longitude = $mapData['map']['default_longitude']; - $map_default_latitude = $mapData['map']['default_latitude']; - $map_default_altitude = $mapData['map']['default_altitude']; - - $map_connection_list = $mapData['connections']; - $map_levels_zoom = gis_get_num_zoom_levels_connection_default($map_connection_list); - - $layer_list = !empty($mapData['layers']) ? $mapData['layers'] : array(); - break; + case 'edit_map': + case 'update_saved': + $mapData = gis_get_map_data($idMap); + + $map_name = $mapData['map']['map_name']; + $map_group_id = $mapData['map']['group_id']; + $map_zoom_level = $mapData['map']['zoom_level']; + $map_background = $mapData['map']['map_background']; + $map_initial_longitude = $mapData['map']['initial_longitude']; + $map_initial_latitude = $mapData['map']['initial_latitude']; + $map_initial_altitude = $mapData['map']['initial_altitude']; + $map_default_longitude = $mapData['map']['default_longitude']; + $map_default_latitude = $mapData['map']['default_latitude']; + $map_default_altitude = $mapData['map']['default_altitude']; + + $map_connection_list = $mapData['connections']; + $map_levels_zoom = gis_get_num_zoom_levels_connection_default($map_connection_list); + + $layer_list = !empty($mapData['layers']) ? $mapData['layers'] : []; + break; } $table = new stdClass(); $table->width = '100%'; $table->class = 'databox filters'; -$table->data = array (); +$table->data = []; -$table->data[0][0] = __('Map Name') . ui_print_help_tip (__('Descriptive name for the map'), true). ':'; -$table->data[0][1] = html_print_input_text ('map_name', $map_name, '', 30, 60, true); +$table->data[0][0] = __('Map Name').ui_print_help_tip(__('Descriptive name for the map'), true).':'; +$table->data[0][1] = html_print_input_text('map_name', $map_name, '', 30, 60, true); $table->rowspan[0][2] = 9; $iconError = ''; if (isset($invalidFields['map_connection_list'])) { - if ($invalidFields['map_connection_list']) { - $iconError = html_print_image("images/dot_red.png", true); - } + if ($invalidFields['map_connection_list']) { + $iconError = html_print_image('images/dot_red.png', true); + } } -$listConnectionTemp = db_get_all_rows_sql("SELECT id_tmap_connection, conection_name, group_id FROM tgis_map_connection"); -$listConnection = array(); +$listConnectionTemp = db_get_all_rows_sql('SELECT id_tmap_connection, conection_name, group_id FROM tgis_map_connection'); +$listConnection = []; foreach ($listConnectionTemp as $connectionTemp) { - if (check_acl ($config["id_user"], $connectionTemp['group_id'], "MW") || check_acl ($config["id_user"], $connectionTemp['group_id'], "MM")) { - $listConnection[$connectionTemp['id_tmap_connection']] = $connectionTemp['conection_name']; - } + if (check_acl($config['id_user'], $connectionTemp['group_id'], 'MW') || check_acl($config['id_user'], $connectionTemp['group_id'], 'MM')) { + $listConnection[$connectionTemp['id_tmap_connection']] = $connectionTemp['conection_name']; + } } -$table->data[1][0] = __("Add Map connection") . ui_print_help_tip (__('At least one map connection must be defined, it will be possible to change between the connections in the map'), true). ": " . $iconError; +$table->data[1][0] = __('Add Map connection').ui_print_help_tip(__('At least one map connection must be defined, it will be possible to change between the connections in the map'), true).': '.$iconError; $table->data[1][1] = "
  • - " . gis_add_conection_maps_in_form($map_connection_list) . " -
    - " . html_print_select($listConnection, 'map_connection', '', '', '', '0', true) ." + ".html_print_select($listConnection, 'map_connection', '', '', '', '0', true)." - " . html_print_image ("images/add.png", true) . " + ".html_print_image('images/add.png', true)."
    "; + ".gis_add_conection_maps_in_form($map_connection_list).' +'; $own_info = get_user_info($config['id_user']); -if ($own_info['is_admin'] || check_acl ($config['id_user'], 0, "MM")) - $display_all_group = true; -else - $display_all_group = false; -$table->data[2][0] = __('Group') . ui_print_help_tip (__('Group that owns the map'), true). ':'; +if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'MM')) { + $display_all_group = true; +} else { + $display_all_group = false; +} + +$table->data[2][0] = __('Group').ui_print_help_tip(__('Group that owns the map'), true).':'; $table->data[2][1] = html_print_select_groups(false, 'IW', $display_all_group, 'map_group_id', $map_group_id, '', '', '', true); -$table->data[3][0] = __('Default zoom') . ui_print_help_tip (__('Default zoom level when opening the map'), true). ':'; -$table->data[3][1] = html_print_input_text ('map_zoom_level', $map_zoom_level, '', 2, 4, true) . html_print_input_hidden('map_levels_zoom', $map_levels_zoom, true); +$table->data[3][0] = __('Default zoom').ui_print_help_tip(__('Default zoom level when opening the map'), true).':'; +$table->data[3][1] = html_print_input_text('map_zoom_level', $map_zoom_level, '', 2, 4, true).html_print_input_hidden('map_levels_zoom', $map_levels_zoom, true); -$table->data[4][0] = __('Center Latitude') . ':'; -$table->data[4][1] = html_print_input_text ('map_initial_latitude', $map_initial_latitude, '', 8, 8, true); +$table->data[4][0] = __('Center Latitude').':'; +$table->data[4][1] = html_print_input_text('map_initial_latitude', $map_initial_latitude, '', 8, 8, true); -$table->data[5][0] = __('Center Longitude') . ':'; -$table->data[5][1] = html_print_input_text ('map_initial_longitude', $map_initial_longitude, '', 8, 8, true); +$table->data[5][0] = __('Center Longitude').':'; +$table->data[5][1] = html_print_input_text('map_initial_longitude', $map_initial_longitude, '', 8, 8, true); -$table->data[6][0] = __('Center Altitude') . ':'; -$table->data[6][1] = html_print_input_text ('map_initial_altitude', $map_initial_altitude, '', 8, 8, true); +$table->data[6][0] = __('Center Altitude').':'; +$table->data[6][1] = html_print_input_text('map_initial_altitude', $map_initial_altitude, '', 8, 8, true); -$table->data[7][0] = __('Default Latitude') . ':'; -$table->data[7][1] = html_print_input_text ('map_default_latitude', $map_default_latitude, '', 8, 8, true); +$table->data[7][0] = __('Default Latitude').':'; +$table->data[7][1] = html_print_input_text('map_default_latitude', $map_default_latitude, '', 8, 8, true); -$table->data[8][0] = __('Default Longitude') . ':'; -$table->data[8][1] = html_print_input_text ('map_default_longitude', $map_default_longitude, '', 8, 8, true); +$table->data[8][0] = __('Default Longitude').':'; +$table->data[8][1] = html_print_input_text('map_default_longitude', $map_default_longitude, '', 8, 8, true); -$table->data[9][0] = __('Default Altitude') . ':'; -$table->data[9][1] = html_print_input_text ('map_default_altitude', $map_default_altitude, '', 8, 8, true); +$table->data[9][0] = __('Default Altitude').':'; +$table->data[9][1] = html_print_input_text('map_default_altitude', $map_default_altitude, '', 8, 8, true); html_print_table($table); -echo "

    " . __('Layers') . ui_print_help_tip (__('Each layer can show agents from one group or the agents added to that layer or both.'), true). "

    "; +echo '

    '.__('Layers').ui_print_help_tip(__('Each layer can show agents from one group or the agents added to that layer or both.'), true).'

    '; $table->width = '100%'; $table->class = 'databox filters'; -$table->valign = array(); +$table->valign = []; $table->valign[0] = 'top'; $table->valign[1] = 'top'; -$table->data = array (); +$table->data = []; -$table->data[0][0] = "

    " .__('List of layers') . ui_print_help_tip (__('It is possible to edit, delete and reorder the layers.'), true) . "

    "; -$table->data[0][1] = '
    ' . html_print_button(__('New layer'), 'new_layer', false, 'newLayer();', 'class="sub add"', true) . '
    '; +$table->data[0][0] = '

    '.__('List of layers').ui_print_help_tip(__('It is possible to edit, delete and reorder the layers.'), true).'

    '; +$table->data[0][1] = '
    '.html_print_button(__('New layer'), 'new_layer', false, 'newLayer();', 'class="sub add"', true).'
    '; $table->data[1][0] = '
    '; $table->data[1][1] = ''; - echo '
     
    '; - echo '
    '; - echo ''; - echo ''; - exit; - } + $group = db_get_row('tgrupo', 'id_grupo', $id_group); + if ($group) { + $name = $group['nombre']; + if (empty($group['icon'])) { + $icon = false; + } else { + $icon = $group['icon'].'.png'; + } + + $group_pass = io_safe_output($group['password']); + $alerts_disabled = $group['disabled']; + $id_parent = $group['parent']; + $custom_id = $group['custom_id']; + $propagate = $group['propagate']; + $skin = $group['id_skin']; + $description = $group['description']; + $contact = $group['contact']; + $other = $group['other']; + } else { + ui_print_error_message(__('There was a problem loading group')); + echo ''; + echo ''; + echo '
     
    '; + echo ''; + echo ''; + echo ''; + exit; + } } // Header if (defined('METACONSOLE')) { + agents_meta_print_header(); + $sec = 'advanced'; +} else { + if ($id_group) { + $title_in_header = __('Update group'); + } else { + $title_in_header = __('Create group'); + } - agents_meta_print_header(); - $sec = 'advanced'; - -} -else { - if ($id_group) - $title_in_header = __("Update group"); - else - $title_in_header = __("Create group"); - - ui_print_page_header ($title_in_header, "images/group.png", false, "", true, ""); - $sec = 'gagente'; - + ui_print_page_header($title_in_header, 'images/group.png', false, '', true, ''); + $sec = 'gagente'; } $table = new stdClass(); $table->width = '100%'; $table->class = 'databox filters'; -if (defined("METACONSOLE")) { - if ($id_group) - $table->head[0] = __('Update Group'); - else - $table->head[0] = __('Create Group'); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; +if (defined('METACONSOLE')) { + if ($id_group) { + $table->head[0] = __('Update Group'); + } else { + $table->head[0] = __('Create Group'); + } + + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; } $table->style[0] = 'font-weight: bold'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Name'); -$table->data[0][1] = html_print_input_text ('name', $name, '', 35, 100, true); +$table->data[0][1] = html_print_input_text('name', $name, '', 35, 100, true); $table->data[1][0] = __('Icon'); -$files = list_files ('images/groups_small/', "png", 1, 0); -foreach ($files as $key => $f) {//Remove from the list the non-desired .png files - if (strpos ($f, '.bad.png') !== false || strpos ($f, '.default.png') !== false || strpos ($f, '.ok.png') !== false || strpos ($f, '.warning.png') !== false) { - unset ($files[$key]); - } +$files = list_files('images/groups_small/', 'png', 1, 0); +foreach ($files as $key => $f) { + // Remove from the list the non-desired .png files + if (strpos($f, '.bad.png') !== false || strpos($f, '.default.png') !== false || strpos($f, '.ok.png') !== false || strpos($f, '.warning.png') !== false) { + unset($files[$key]); + } } -$table->data[1][1] = html_print_select ($files, 'icon', $icon, '', 'None', '', true); + +$table->data[1][1] = html_print_select($files, 'icon', $icon, '', 'None', '', true); $table->data[1][1] .= ' '; if ($icon) { - $table->data[1][1] .= html_print_image("images/groups_small/".$icon, true); + $table->data[1][1] .= html_print_image('images/groups_small/'.$icon, true); } $table->data[1][1] .= ''; @@ -135,95 +132,104 @@ $table->data[2][0] = __('Parent'); $acl_parent = true; if ($id_group) { - - //The user can access to the parent, but she want to edit the group. - if (!check_acl($config['id_user'], $id_parent, "AR")) { - $acl_parent = false; - - $table->data[2][1] = - __('You have not access to the parent.') . - html_print_input_hidden('id_parent', $id_parent, true); - } - else { - $table->data[2][1] = html_print_select_groups(false, "AR", true, - 'id_parent', $id_parent, '', '', '', true, false, true, '', - false, false, false, $id_group); - } -} -else { - $table->data[2][1] = html_print_select_groups(false, "AR", true, 'id_parent', $id_parent, '', '', '', true); + // The user can access to the parent, but she want to edit the group. + if (!check_acl($config['id_user'], $id_parent, 'AR')) { + $acl_parent = false; + + $table->data[2][1] = __('You have not access to the parent.').html_print_input_hidden('id_parent', $id_parent, true); + } else { + $table->data[2][1] = html_print_select_groups( + false, + 'AR', + true, + 'id_parent', + $id_parent, + '', + '', + '', + true, + false, + true, + '', + false, + false, + false, + $id_group + ); + } +} else { + $table->data[2][1] = html_print_select_groups(false, 'AR', true, 'id_parent', $id_parent, '', '', '', true); } if ($acl_parent) { - $table->data[2][1] .= ' '; - $table->data[2][1] .= html_print_image("images/groups_small/".groups_get_icon ($id_parent).".png", true); - $table->data[2][1] .= ''; + $table->data[2][1] .= ' '; + $table->data[2][1] .= html_print_image('images/groups_small/'.groups_get_icon($id_parent).'.png', true); + $table->data[2][1] .= ''; } $i = 3; if ($config['enterprise_installed']) { - $i = 4; - $table->data[3][0] = __('Group Password'); - $table->data[3][1] = html_print_input_password ('group_pass', $group_pass, '', 16, 255, true); + $i = 4; + $table->data[3][0] = __('Group Password'); + $table->data[3][1] = html_print_input_password('group_pass', $group_pass, '', 16, 255, true); } $table->data[$i][0] = __('Alerts'); -$table->data[$i][1] = html_print_checkbox ('alerts_enabled', 1, ! $alerts_disabled, true); +$table->data[$i][1] = html_print_checkbox('alerts_enabled', 1, ! $alerts_disabled, true); $i++; -$table->data[$i][0] = __('Propagate ACL') . ui_print_help_tip (__("Propagate the same ACL security into the child subgroups."), true); -$table->data[$i][1] = html_print_checkbox('propagate', 1, $propagate, true).ui_print_help_icon ("propagate_acl", true); +$table->data[$i][0] = __('Propagate ACL').ui_print_help_tip(__('Propagate the same ACL security into the child subgroups.'), true); +$table->data[$i][1] = html_print_checkbox('propagate', 1, $propagate, true).ui_print_help_icon('propagate_acl', true); $i++; $table->data[$i][0] = __('Custom ID'); -$table->data[$i][1] = html_print_input_text ('custom_id', $custom_id, '', 16, 255, true); +$table->data[$i][1] = html_print_input_text('custom_id', $custom_id, '', 16, 255, true); $i++; $table->data[$i][0] = __('Description'); -$table->data[$i][1] = html_print_input_text ('description', $description, '', 60, 255, true); +$table->data[$i][1] = html_print_input_text('description', $description, '', 60, 255, true); $i++; -$table->data[$i][0] = __('Contact') . ui_print_help_tip (__("Contact information accessible through the _groupcontact_ macro"), true); -$table->data[$i][1] = html_print_textarea ('contact', 4, 40, $contact, "style='min-height: 0px;'", true); +$table->data[$i][0] = __('Contact').ui_print_help_tip(__('Contact information accessible through the _groupcontact_ macro'), true); +$table->data[$i][1] = html_print_textarea('contact', 4, 40, $contact, "style='min-height: 0px;'", true); $i++; -$table->data[$i][0] = __('Other') . ui_print_help_tip (__("Information accessible through the _group_other_ macro"), true); -$table->data[$i][1] = html_print_textarea ('other', 4, 40, $other, "style='min-height: 0px;'", true); +$table->data[$i][0] = __('Other').ui_print_help_tip(__('Information accessible through the _group_other_ macro'), true); +$table->data[$i][1] = html_print_textarea('other', 4, 40, $other, "style='min-height: 0px;'", true); $i++; -$isFunctionSkins = enterprise_include_once ('include/functions_skins.php'); +$isFunctionSkins = enterprise_include_once('include/functions_skins.php'); if ($isFunctionSkins !== ENTERPRISE_NOT_HOOK && !defined('METACONSOLE')) { - $table->data[9][0] = __('Skin'); - $table->data[9][1] = skins_print_select($config["id_user"], 'skin', $skin, '', __('None'), 0, true); + $table->data[9][0] = __('Skin'); + $table->data[9][1] = skins_print_select($config['id_user'], 'skin', $skin, '', __('None'), 0, true); } -if (defined("METACONSOLE")) - $sec = "advanced"; -else - $sec = "gagente"; +if (defined('METACONSOLE')) { + $sec = 'advanced'; +} else { + $sec = 'gagente'; +} if (isset($config['metaconsole_node_id']) && $config['metaconsole_node_id'] > 0) { - if(isset($config['metaconsole_agent_cache']) && $config['metaconsole_agent_cache'] == 1){ - $confirm_bottom = " onsubmit=' return message_check_create();'"; - } -} -else -{ - $confirm_bottom = ""; + if (isset($config['metaconsole_agent_cache']) && $config['metaconsole_agent_cache'] == 1) { + $confirm_bottom = " onsubmit=' return message_check_create();'"; + } +} else { + $confirm_bottom = ''; } -echo '
    '; -html_print_table ($table); +echo ''; +html_print_table($table); echo '
    '; if ($id_group) { - html_print_input_hidden ('update_group', 1); - html_print_input_hidden ('id_group', $id_group); - html_print_submit_button (__('Update'), 'updbutton', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create_group', 1); - html_print_submit_button (__('Create'), 'crtbutton', false, 'class="sub wand"'); + html_print_input_hidden('update_group', 1); + html_print_input_hidden('id_group', $id_group); + html_print_submit_button(__('Update'), 'updbutton', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create_group', 1); + html_print_submit_button(__('Create'), 'crtbutton', false, 'class="sub wand"'); } + echo '
    '; echo '
    '; @@ -231,79 +237,79 @@ enterprise_hook('close_meta_frame'); ?> diff --git a/pandora_console/godmode/groups/configure_modu_group.php b/pandora_console/godmode/groups/configure_modu_group.php index b2e74f7527..815b056259 100644 --- a/pandora_console/godmode/groups/configure_modu_group.php +++ b/pandora_console/godmode/groups/configure_modu_group.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,83 +11,79 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - - global $config; -check_login (); +check_login(); enterprise_hook('open_meta_frame'); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", "Trying to access Group Management2"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit('ACL Violation', 'Trying to access Group Management2'); + include 'general/noaccess.php'; + return; } if (!is_metaconsole()) { - // Header - ui_print_page_header (__("Module group management"), "images/module_group.png", false, "", true, ""); + // Header + ui_print_page_header(__('Module group management'), 'images/module_group.png', false, '', true, ''); } // Init vars -$icon = ""; -$name = ""; +$icon = ''; +$name = ''; $id_parent = 0; $alerts_disabled = 0; -$custom_id = ""; +$custom_id = ''; -$create_group = (bool) get_parameter ('create_group'); -$id_group = (int) get_parameter ('id_group'); +$create_group = (bool) get_parameter('create_group'); +$id_group = (int) get_parameter('id_group'); if ($id_group) { - $group = db_get_row ('tmodule_group', 'id_mg', $id_group); - if ($group) { - $name = $group["name"]; - } - else { - ui_print_error_message(__('There was a problem loading group')); - echo ""; - echo ''; - echo '
     
    '; - echo ''; - echo ''; - echo ''; - exit; - } + $group = db_get_row('tmodule_group', 'id_mg', $id_group); + if ($group) { + $name = $group['name']; + } else { + ui_print_error_message(__('There was a problem loading group')); + echo ''; + echo ''; + echo '
     
    '; + echo ''; + echo ''; + echo ''; + exit; + } } $table->width = '100%'; $table->class = 'databox filters'; $table->style[0] = 'font-weight: bold'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Name'); -$table->data[0][1] = html_print_input_text ('name', $name, '', 35, 100, true); +$table->data[0][1] = html_print_input_text('name', $name, '', 35, 100, true); -echo'
    '; -if (is_metaconsole()) - echo '
    '; -else - echo ''; -html_print_table ($table); +echo ''; +if (is_metaconsole()) { + echo ''; +} else { + echo ''; +} + +html_print_table($table); echo '
    '; if ($id_group) { - html_print_input_hidden ('update_group', 1); - html_print_input_hidden ('id_group', $id_group); - html_print_submit_button (__('Update'), 'updbutton', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create_group', 1); - html_print_submit_button (__('Create'), 'crtbutton', false, 'class="sub wand"'); + html_print_input_hidden('update_group', 1); + html_print_input_hidden('id_group', $id_group); + html_print_submit_button(__('Update'), 'updbutton', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create_group', 1); + html_print_submit_button(__('Create'), 'crtbutton', false, 'class="sub wand"'); } + echo '
    '; echo '
    '; enterprise_hook('close_meta_frame'); - -?> diff --git a/pandora_console/godmode/groups/group_list.php b/pandora_console/godmode/groups/group_list.php index 0efe11ad31..6fc899a5d8 100644 --- a/pandora_console/godmode/groups/group_list.php +++ b/pandora_console/godmode/groups/group_list.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,7 +11,8 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - +ui_require_css_file('tree'); +ui_require_css_file('fixed-bottom-box'); // Load global vars global $config; @@ -21,427 +21,474 @@ check_login(); enterprise_hook('open_meta_frame'); -require_once($config['homedir'] . "/include/functions_groups.php"); -require_once($config['homedir'] . "/include/functions_agents.php"); -require_once($config['homedir'] . '/include/functions_users.php'); -enterprise_include_once ('meta/include/functions_agents_meta.php'); +require_once $config['homedir'].'/include/functions_groups.php'; +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_users.php'; +enterprise_include_once('meta/include/functions_agents_meta.php'); -if (is_ajax ()) { - if (! check_acl($config['id_user'], 0, "AR")) { - db_pandora_audit("ACL Violation", "Trying to access Group Management"); - require ("general/noaccess.php"); - return; - } +if (is_ajax()) { + if (! check_acl($config['id_user'], 0, 'AR')) { + db_pandora_audit('ACL Violation', 'Trying to access Group Management'); + include 'general/noaccess.php'; + return; + } - $get_group_json = (bool) get_parameter ('get_group_json'); - $get_group_agents = (bool) get_parameter ('get_group_agents'); - $get_is_disabled = (bool) get_parameter ('get_is_disabled'); + $get_group_json = (bool) get_parameter('get_group_json'); + $get_group_agents = (bool) get_parameter('get_group_agents'); + $get_is_disabled = (bool) get_parameter('get_is_disabled'); - if ($get_group_json) { - $id_group = (int) get_parameter ('id_group'); + if ($get_group_json) { + $id_group = (int) get_parameter('id_group'); - if ($id_group == 0) { - $group = array('id_grupo' => 0, - 'nombre' => 'All', - 'icon' => 'world', - 'parent' => 0, - 'disabled' => 0, - 'custom_id' => null); - echo json_encode ($group); - return; - } + if ($id_group == 0) { + $group = [ + 'id_grupo' => 0, + 'nombre' => 'All', + 'icon' => 'world', + 'parent' => 0, + 'disabled' => 0, + 'custom_id' => null, + ]; + echo json_encode($group); + return; + } - if (! check_acl ($config['id_user'], $id_group, "AR")) { - db_pandora_audit("ACL Violation", - "Trying to access Alert Management"); - echo json_encode (false); - return; - } + if (! check_acl($config['id_user'], $id_group, 'AR')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Alert Management' + ); + echo json_encode(false); + return; + } - $group = db_get_row ('tgrupo', 'id_grupo', $id_group); + $group = db_get_row('tgrupo', 'id_grupo', $id_group); - echo json_encode ($group); - return; - } + echo json_encode($group); + return; + } - if ($get_group_agents) { - ob_clean(); - $id_group = (int) get_parameter ('id_group'); - $disabled = (int) get_parameter ('disabled', 0); - $search = (string) get_parameter ('search', ''); - $recursion = (int) get_parameter ('recursion', 0); - $privilege = (string) get_parameter ('privilege', ''); - $all_agents = (int) get_parameter ('all_agents', 0); - // Is is possible add keys prefix to avoid auto sorting in js object conversion - $keys_prefix = (string) get_parameter ('keys_prefix', ''); - // This attr is for the operation "bulk alert accions add", it controls the query that take the agents - // from db - $add_alert_bulk_op = get_parameter ('add_alert_bulk_op', false); - // Ids of agents to be include in the SQL clause as id_agent IN () - $filter_agents_json = (string) get_parameter ('filter_agents_json', ''); - $status_agents = (int)get_parameter('status_agents', AGENT_STATUS_ALL); - // Juanma (22/05/2014) Fix: If setted remove void agents from result (by default and for compatibility show void agents) - $show_void_agents = (int)get_parameter('show_void_agents', 1); - $serialized = (bool)get_parameter('serialized', false); - $serialized_separator = (string)get_parameter('serialized_separator', "|"); - $force_serialized = (bool)get_parameter('force_serialized', false); + if ($get_group_agents) { + ob_clean(); + $id_group = (int) get_parameter('id_group'); + $disabled = (int) get_parameter('disabled', 0); + $search = (string) get_parameter('search', ''); + $recursion = (int) get_parameter('recursion', 0); + $privilege = (string) get_parameter('privilege', ''); + $all_agents = (int) get_parameter('all_agents', 0); + // Is is possible add keys prefix to avoid auto sorting in js object conversion + $keys_prefix = (string) get_parameter('keys_prefix', ''); + // This attr is for the operation "bulk alert accions add", it controls the query that take the agents + // from db + $add_alert_bulk_op = get_parameter('add_alert_bulk_op', false); + // Ids of agents to be include in the SQL clause as id_agent IN () + $filter_agents_json = (string) get_parameter('filter_agents_json', ''); + $status_agents = (int) get_parameter('status_agents', AGENT_STATUS_ALL); + // Juanma (22/05/2014) Fix: If setted remove void agents from result (by default and for compatibility show void agents) + $show_void_agents = (int) get_parameter('show_void_agents', 1); + $serialized = (bool) get_parameter('serialized', false); + $serialized_separator = (string) get_parameter('serialized_separator', '|'); + $force_serialized = (bool) get_parameter('force_serialized', false); - if (! check_acl ($config['id_user'], $id_group, "AR")) { - db_pandora_audit("ACL Violation", - "Trying to access Alert Management"); - echo json_encode (false); - return; - } + if (! check_acl($config['id_user'], $id_group, 'AR')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Alert Management' + ); + echo json_encode(false); + return; + } - if ( https_is_running() ) { - header('Content-type: application/json'); - } + if (https_is_running()) { + header('Content-type: application/json'); + } - if ($filter_agents_json != '') { - $filter['id_agente'] = json_decode(io_safe_output($filter_agents_json), true); - } + if ($filter_agents_json != '') { + $filter['id_agente'] = json_decode(io_safe_output($filter_agents_json), true); + } - if ($all_agents) { - $filter['all_agents'] = true; - } - else { - $filter['disabled'] = $disabled; - } + if ($all_agents) { + $filter['all_agents'] = true; + } else { + $filter['disabled'] = $disabled; + } - if ($search != '') { - $filter['string'] = $search; - } + if ($search != '') { + $filter['string'] = $search; + } - if ($status_agents != AGENT_STATUS_ALL) { - $filter['status'] = $status_agents; - } + if ($status_agents != AGENT_STATUS_ALL) { + $filter['status'] = $status_agents; + } - # Juanma (22/05/2014) Fix: If remove void agents setted - $_sql_post = ' 1=1 '; - if ($show_void_agents == 0) { - $_sql_post .= ' AND id_agente IN (SELECT a.id_agente FROM tagente a, tagente_modulo b WHERE a.id_agente=b.id_agente AND b.delete_pending=0) AND \'1\''; - $filter[$_sql_post] = '1'; - } + // Juanma (22/05/2014) Fix: If remove void agents setted + $_sql_post = ' 1=1 '; + if ($show_void_agents == 0) { + $_sql_post .= ' AND id_agente IN (SELECT a.id_agente FROM tagente a, tagente_modulo b WHERE a.id_agente=b.id_agente AND b.delete_pending=0) AND \'1\''; + $filter[$_sql_post] = '1'; + } - $id_groups_get_agents = $id_group; - if ( $id_group == 0 && $privilege != '') { - $groups = users_get_groups ($config["id_user"], $privilege, false); - // if group ID doesn't matter and $privilege is specified (like 'AW'), - // retruns all agents that current user has $privilege privilege for. - $id_groups_get_agents = array_keys($groups); - } - $agents = agents_get_group_agents( - $id_groups_get_agents, - $filter, - "none", - false, - $recursion, - $serialized, - $serialized_separator, - $add_alert_bulk_op, - $force_serialized - ); + $id_groups_get_agents = $id_group; + if ($id_group == 0 && $privilege != '') { + $groups = users_get_groups($config['id_user'], $privilege, false); + // if group ID doesn't matter and $privilege is specified (like 'AW'), + // retruns all agents that current user has $privilege privilege for. + $id_groups_get_agents = array_keys($groups); + } - $agents_disabled = array(); - // Add keys prefix - if ($keys_prefix !== "") { - foreach($agents as $k => $v) { - $agents[$keys_prefix . $k] = $v; - unset($agents[$k]); - if ($all_agents) { - // Unserialize to get the status - if ($serialized && is_metaconsole()) { - $agent_info = explode($serialized_separator, $k); - $agent_disabled = db_get_value_filter( - 'disabled', - 'tmetaconsole_agent', - array( - 'id_tagente' => $agent_info[1], - 'id_tmetaconsole_setup' => $agent_info[0] - ) - ); - } elseif ($serialized && !is_metaconsole() && $force_serialized) { - $agent_info = explode($serialized_separator, $k); - $agent_disabled = db_get_value_filter( - 'disabled', - 'tagente', - array('id_agente' => $agent_info[1]) - ); - } elseif (!$serialized && is_metaconsole()) { - // Cannot retrieve the disabled status. Mark all as not disabled - $agent_disabled = 0; - } else { - $agent_disabled = db_get_value_filter( - 'disabled', - 'tagente', - array('id_agente' => $k) - ); - } - $agents_disabled[$keys_prefix . $k] = $agent_disabled; - } - } - } + $agents = agents_get_group_agents( + $id_groups_get_agents, + $filter, + 'none', + false, + $recursion, + $serialized, + $serialized_separator, + $add_alert_bulk_op, + $force_serialized + ); - if ($all_agents) { - $all_agents_array = array(); - $all_agents_array['agents'] = $agents; - $all_agents_array['agents_disabled'] = $agents_disabled; + $agents_disabled = []; + // Add keys prefix + if ($keys_prefix !== '') { + foreach ($agents as $k => $v) { + $agents[$keys_prefix.$k] = $v; + unset($agents[$k]); + if ($all_agents) { + // Unserialize to get the status + if ($serialized && is_metaconsole()) { + $agent_info = explode($serialized_separator, $k); + $agent_disabled = db_get_value_filter( + 'disabled', + 'tmetaconsole_agent', + [ + 'id_tagente' => $agent_info[1], + 'id_tmetaconsole_setup' => $agent_info[0], + ] + ); + } else if ($serialized && !is_metaconsole() && $force_serialized) { + $agent_info = explode($serialized_separator, $k); + $agent_disabled = db_get_value_filter( + 'disabled', + 'tagente', + ['id_agente' => $agent_info[1]] + ); + } else if (!$serialized && is_metaconsole()) { + // Cannot retrieve the disabled status. Mark all as not disabled + $agent_disabled = 0; + } else { + $agent_disabled = db_get_value_filter( + 'disabled', + 'tagente', + ['id_agente' => $k] + ); + } - $agents = $all_agents_array; - } + $agents_disabled[$keys_prefix.$k] = $agent_disabled; + } + } + } - echo json_encode ($agents); - return; - } + if ($all_agents) { + $all_agents_array = []; + $all_agents_array['agents'] = $agents; + $all_agents_array['agents_disabled'] = $agents_disabled; - if ($get_is_disabled) { - $index = get_parameter('id_agent'); + $agents = $all_agents_array; + } - $agent_disabled = db_get_value_filter('disabled', 'tagente', array('id_agente' => $index)); + echo json_encode($agents); + return; + } - $return['disabled'] = $agent_disabled; - $return['id_agent'] = $index; + if ($get_is_disabled) { + $index = get_parameter('id_agent'); - echo json_encode($return); - return; - } - return; + $agent_disabled = db_get_value_filter('disabled', 'tagente', ['id_agente' => $index]); + + $return['disabled'] = $agent_disabled; + $return['id_agent'] = $index; + + echo json_encode($return); + return; + } + + return; } -if (! check_acl($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Group Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Group Management' + ); + include 'general/noaccess.php'; + return; } $sec = defined('METACONSOLE') ? 'advanced' : 'gagente'; $url_tree = "index.php?sec=$sec&sec2=godmode/groups/group_list&tab=tree"; $url_groups = "index.php?sec=$sec&sec2=godmode/groups/group_list&tab=groups"; -$buttons['tree'] = array( - 'active' => false, - 'text' => "" . - html_print_image( - "images/gm_massive_operations.png", - true, - array ( - "title" => __('Tree Group view') - ) - ) . "" -); +$buttons['tree'] = [ + 'active' => false, + 'text' => "".html_print_image( + 'images/gm_massive_operations.png', + true, + [ + 'title' => __('Tree Group view'), + ] + ).'', +]; -$buttons['groups'] = array( - 'active' => false, - 'text' => "" . - html_print_image( - "images/group.png", - true, - array( - "title" => __('Group view') - ) - ) . "" -); +$buttons['groups'] = [ + 'active' => false, + 'text' => "".html_print_image( + 'images/group.png', + true, + [ + 'title' => __('Group view'), + ] + ).'', +]; -$tab = (string)get_parameter('tab', 'groups'); +$tab = (string) get_parameter('tab', 'groups'); // Marks correct tab switch ($tab) { - case 'tree': - $buttons['tree']['active'] = true; - break; - case 'groups': - default: - $buttons['groups']['active'] = true; - break; + case 'tree': + $buttons['tree']['active'] = true; + break; + + case 'groups': + default: + $buttons['groups']['active'] = true; + break; } // Header if (defined('METACONSOLE')) { - agents_meta_print_header(); - echo '
    '; - echo __("Edit or delete groups can cause problems with synchronization"); - echo '
    '; + agents_meta_print_header(); + echo '
    '; + echo __('Edit or delete groups can cause problems with synchronization'); + echo '
    '; } else { - ui_print_page_header ( - __("Groups defined in %s", get_product_name()), - "images/group.png", false, "", true, $buttons - ); + ui_print_page_header( + __('Groups defined in %s', get_product_name()), + 'images/group.png', + false, + '', + true, + $buttons + ); } -$create_group = (bool) get_parameter ('create_group'); -$update_group = (bool) get_parameter ('update_group'); -$delete_group = (bool) get_parameter ('delete_group'); +$create_group = (bool) get_parameter('create_group'); +$update_group = (bool) get_parameter('update_group'); +$delete_group = (bool) get_parameter('delete_group'); $pure = get_parameter('pure', 0); -/* Create group */ -if (($create_group) && (check_acl($config['id_user'], 0, "PM"))) { - $name = (string) get_parameter ('name'); - $icon = (string) get_parameter ('icon'); - $id_parent = (int) get_parameter ('id_parent'); - $group_pass = (string)get_parameter('group_pass'); - $alerts_disabled = (bool) get_parameter ('alerts_disabled'); - $custom_id = (string) get_parameter ('custom_id'); - $skin = (string) get_parameter ('skin'); - $description = (string) get_parameter ('description'); - $contact = (string) get_parameter ('contact'); - $other = (string) get_parameter ('other'); - $check = db_get_value('nombre', 'tgrupo', 'nombre', $name); - $propagate = (bool) get_parameter('propagate'); +// Create group +if (($create_group) && (check_acl($config['id_user'], 0, 'PM'))) { + $name = (string) get_parameter('name'); + $icon = (string) get_parameter('icon'); + $id_parent = (int) get_parameter('id_parent'); + $group_pass = (string) get_parameter('group_pass'); + $alerts_disabled = (bool) get_parameter('alerts_disabled'); + $custom_id = (string) get_parameter('custom_id'); + $skin = (string) get_parameter('skin'); + $description = (string) get_parameter('description'); + $contact = (string) get_parameter('contact'); + $other = (string) get_parameter('other'); + $check = db_get_value('nombre', 'tgrupo', 'nombre', $name); + $propagate = (bool) get_parameter('propagate'); - /*Check if name field is empty*/ - if ($name != "") { - if (!$check) { - $values = array( - 'nombre' => $name, - 'icon' => empty($icon) ? '' : substr ($icon, 0, -4), - 'parent' => $id_parent, - 'disabled' => $alerts_disabled, - 'custom_id' => $custom_id, - 'id_skin' => $skin, - 'description' => $description, - 'contact' => $contact, - 'propagate' => $propagate, - 'other' => $other, - 'password' => io_safe_input($group_pass) - ); + // Check if name field is empty + if ($name != '') { + if (!$check) { + $values = [ + 'nombre' => $name, + 'icon' => empty($icon) ? '' : substr($icon, 0, -4), + 'parent' => $id_parent, + 'disabled' => $alerts_disabled, + 'custom_id' => $custom_id, + 'id_skin' => $skin, + 'description' => $description, + 'contact' => $contact, + 'propagate' => $propagate, + 'other' => $other, + 'password' => io_safe_input($group_pass), + ]; - $result = db_process_sql_insert('tgrupo', $values); - if ($result) { - ui_print_success_message(__('Group successfully created')); - } - else { - ui_print_error_message(__('There was a problem creating group')); - } - } - else { - ui_print_error_message(__('Each group must have a different name')); - } - } - else { - //$result = false; - ui_print_error_message(__('Group must have a name')); - } + $result = db_process_sql_insert('tgrupo', $values); + if ($result) { + ui_print_success_message(__('Group successfully created')); + } else { + ui_print_error_message(__('There was a problem creating group')); + } + } else { + ui_print_error_message(__('Each group must have a different name')); + } + } else { + // $result = false; + ui_print_error_message(__('Group must have a name')); + } } -/* Update group */ +// Update group if ($update_group) { - $id_group = (int) get_parameter ('id_group'); - $name = (string) get_parameter ('name'); - $icon = (string) get_parameter ('icon'); - $id_parent = (int) get_parameter ('id_parent'); - $description = (string) get_parameter ('description'); - $group_pass = (string)get_parameter('group_pass'); - $alerts_enabled = (bool) get_parameter ('alerts_enabled'); - $custom_id = (string) get_parameter ('custom_id'); - $propagate = (bool) get_parameter('propagate'); - $skin = (string) get_parameter ('skin'); - $description = (string) get_parameter ('description'); - $contact = (string) get_parameter ('contact'); - $other = (string) get_parameter ('other'); + $id_group = (int) get_parameter('id_group'); + $name = (string) get_parameter('name'); + $icon = (string) get_parameter('icon'); + $id_parent = (int) get_parameter('id_parent'); + $description = (string) get_parameter('description'); + $group_pass = (string) get_parameter('group_pass'); + $alerts_enabled = (bool) get_parameter('alerts_enabled'); + $custom_id = (string) get_parameter('custom_id'); + $propagate = (bool) get_parameter('propagate'); + $skin = (string) get_parameter('skin'); + $description = (string) get_parameter('description'); + $contact = (string) get_parameter('contact'); + $other = (string) get_parameter('other'); - /*Check if name field is empty*/ - if ( $name != "") { - switch ($config["dbtype"]) { - case "mysql": - $sql = sprintf ('UPDATE tgrupo SET nombre = "%s", + // Check if name field is empty + if ($name != '') { + switch ($config['dbtype']) { + case 'mysql': + $sql = sprintf( + 'UPDATE tgrupo SET nombre = "%s", icon = "%s", disabled = %d, parent = %d, custom_id = "%s", propagate = %d, id_skin = %d, description = "%s", contact = "%s", other = "%s", password = "%s" WHERE id_grupo = %d', - $name, empty($icon) ? '' : substr ($icon, 0, -4), !$alerts_enabled, $id_parent, $custom_id, $propagate, $skin, $description, $contact, $other, $group_pass, $id_group); - break; - case "postgresql": - case "oracle": - $sql = sprintf ('UPDATE tgrupo SET nombre = \'%s\', + $name, + empty($icon) ? '' : substr($icon, 0, -4), + !$alerts_enabled, + $id_parent, + $custom_id, + $propagate, + $skin, + $description, + $contact, + $other, + $group_pass, + $id_group + ); + break; + + case 'postgresql': + case 'oracle': + $sql = sprintf( + 'UPDATE tgrupo SET nombre = \'%s\', icon = \'%s\', disabled = %d, parent = %d, custom_id = \'%s\', propagate = %d, id_skin = %d, description = \'%s\', contact = \'%s\', other = \'%s\' WHERE id_grupo = %d', - $name, substr ($icon, 0, -4), !$alerts_enabled, $id_parent, $custom_id, $propagate, $skin, $description, $contact, $other, $id_group); - break; - } - $result = db_process_sql ($sql); - } - else { - $result = false; - } + $name, + substr($icon, 0, -4), + !$alerts_enabled, + $id_parent, + $custom_id, + $propagate, + $skin, + $description, + $contact, + $other, + $id_group + ); + break; + } - if ($result !== false) { - ui_print_success_message(__('Group successfully updated')); - } - else { - ui_print_error_message(__('There was a problem modifying group')); - } + $result = db_process_sql($sql); + } else { + $result = false; + } + + if ($result !== false) { + ui_print_success_message(__('Group successfully updated')); + } else { + ui_print_error_message(__('There was a problem modifying group')); + } } -/* Delete group */ -if (($delete_group) && (check_acl($config['id_user'], 0, "PM"))) { - $id_group = (int) get_parameter ('id_group'); +// Delete group +if (($delete_group) && (check_acl($config['id_user'], 0, 'PM'))) { + $id_group = (int) get_parameter('id_group'); - $usedGroup = groups_check_used($id_group); + $usedGroup = groups_check_used($id_group); - if (!$usedGroup['return']) { - $group = db_get_row_filter('tgrupo', - array('id_grupo' => $id_group)); + if (!$usedGroup['return']) { + $group = db_get_row_filter( + 'tgrupo', + ['id_grupo' => $id_group] + ); - db_process_sql_update('tgrupo', - array('parent' => $group['parent']), array('parent' => $id_group)); + db_process_sql_update( + 'tgrupo', + ['parent' => $group['parent']], + ['parent' => $id_group] + ); - $result = db_process_sql_delete('tgroup_stat', - array('id_group' => $id_group)); + $result = db_process_sql_delete( + 'tgroup_stat', + ['id_group' => $id_group] + ); - $result = db_process_sql_delete('tgrupo', - array('id_grupo' => $id_group)); - } - else { - ui_print_error_message( - sprintf(__('The group is not empty. It is use in %s.'), implode(', ', $usedGroup['tables']))); - } + $result = db_process_sql_delete( + 'tgrupo', + ['id_grupo' => $id_group] + ); + } else { + ui_print_error_message( + sprintf(__('The group is not empty. It is use in %s.'), implode(', ', $usedGroup['tables'])) + ); + } - if ($result && (!$usedGroup['return'])) { - ui_print_success_message(__('Group successfully deleted')); - } - else { - ui_print_error_message(__('There was a problem deleting group')); - } + if ($result && (!$usedGroup['return'])) { + ui_print_success_message(__('Group successfully deleted')); + } else { + ui_print_error_message(__('There was a problem deleting group')); + } } -if($tab == 'tree'){ - echo html_print_image('images/spinner.gif', true, - array('class' => "loading_tree", - 'style' => 'display: none;')); - echo "
    "; +if ($tab == 'tree') { + echo html_print_image( + 'images/spinner.gif', + true, + [ + 'class' => 'loading_tree', + 'style' => 'display: none;', + ] + ); + echo "
    "; +} else { + $acl = ''; + $search_name = ''; + $offset = (int) get_parameter('offset', 0); + $search = (string) get_parameter('search', ''); + $block_size = $config['block_size']; -} -else{ - $acl=''; - $search_name = ''; - $offset = (int)get_parameter('offset', 0); - $search = (string)get_parameter('search', ''); - $block_size = $config['block_size']; + if (!empty($search)) { + $search_name = "AND t.nombre LIKE '%$search%'"; + } - if(!empty($search)){ - $search_name = "AND t.nombre LIKE '%$search%'"; - } + if (!users_can_manage_group_all('AR')) { + $user_groups_acl = users_get_groups(false, 'AR'); + $groups_acl = implode(',', $user_groups_ACL); + if (empty($groups_acl)) { + return ui_print_info_message(['no_close' => true, 'message' => __('There are no defined groups') ]); + } - if (!users_can_manage_group_all("AR")){ - $user_groups_acl = users_get_groups(false, "AR"); - $groups_acl = implode(",", $user_groups_ACL); - if(empty($groups_acl)) return ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined groups') ) ); + $acl = "AND t.id_grupo IN ($groups_acl)"; + } - $acl = "AND t.id_grupo IN ($groups_acl)"; - } + $form = "
    "; + $form .= ""; + $form .= ''; + $form .= '
    '.__('Search').' '; + $form .= html_print_input_text('search', $search, '', 100, 100, true); + $form .= ''; + $form .= ""; + $form .= '
    '; + $form .= '
    '; - $form = "
    "; - $form .= ""; - $form .= ""; - $form .= "
    " . __('Search') . ' '; - $form .= html_print_input_text ("search", $search, '', 100, 100, true); - $form .= ""; - $form .= ""; - $form .= "
    "; - $form .= "
    "; + echo $form; - echo $form; - - $groups_sql = - "SELECT t.*, + $groups_sql = "SELECT t.*, p.nombre AS parent_name, IF(t.parent=p.id_grupo, 1, 0) AS has_child FROM tgrupo t @@ -454,211 +501,217 @@ else{ LIMIT $offset, $block_size "; - $groups = db_get_all_rows_sql($groups_sql); + $groups = db_get_all_rows_sql($groups_sql); - if (!empty($groups)) { - //Count all groups for pagination only saw user and filters - $groups_sql_count = "SELECT count(*) + if (!empty($groups)) { + // Count all groups for pagination only saw user and filters + $groups_sql_count = "SELECT count(*) FROM tgrupo t WHERE 1=1 $acl $search_name "; - $groups_count = db_get_value_sql($groups_sql_count); + $groups_count = db_get_value_sql($groups_sql_count); - $table = new StdClass(); - $table->width = '100%'; - $table->class = "databox data"; - $table->head = array (); - $table->head[0] = __('ID'); - $table->head[1] = __('Name'); - $table->head[2] = __('Icon'); - $table->head[3] = __('Alerts'); - $table->head[4] = __('Parent'); - $table->head[5] = __('Description'); - $table->head[6] = __('Actions'); - $table->align = array (); - $table->align[0] = 'left'; - $table->align[2] = 'left'; - $table->align[6] = 'left'; - $table->size[0] = '3%'; - $table->size[5] = '30%'; - $table->size[6] = '5%'; - $table->data = array (); + $table = new StdClass(); + $table->width = '100%'; + $table->class = 'databox data'; + $table->head = []; + $table->head[0] = __('ID'); + $table->head[1] = __('Name'); + $table->head[2] = __('Icon'); + $table->head[3] = __('Alerts'); + $table->head[4] = __('Parent'); + $table->head[5] = __('Description'); + $table->head[6] = __('Actions'); + $table->align = []; + $table->align[0] = 'left'; + $table->align[2] = 'left'; + $table->align[6] = 'left'; + $table->size[0] = '3%'; + $table->size[5] = '30%'; + $table->size[6] = '5%'; + $table->data = []; - foreach ($groups as $key => $group) { - $url = "index.php?sec=gagente&sec2=godmode/groups/configure_group&id_group=".$group['id_grupo']; - $url_delete = "index.php?sec=gagente&sec2=godmode/groups/group_list&delete_group=1&id_group=" . $group['id_grupo']; - $table->data[$key][0] = $group['id_grupo']; - $table->data[$key][1] = "" . $group['nombre'] . ""; - $table->data[$key][2] = html_print_image( - "images/groups_small/" . $group['icon'] . ".png", - true, - array( - "style" => '', - "class" => "bot", - "alt" => $group['nombre'], - "title" => $group['nombre'], - false, false, false, true - ) - ); + foreach ($groups as $key => $group) { + $url = 'index.php?sec=gagente&sec2=godmode/groups/configure_group&id_group='.$group['id_grupo']; + $url_delete = 'index.php?sec=gagente&sec2=godmode/groups/group_list&delete_group=1&id_group='.$group['id_grupo']; + $table->data[$key][0] = $group['id_grupo']; + $table->data[$key][1] = "".$group['nombre'].''; + if ($group['icon'] != '') { + $table->data[$key][2] = html_print_image( + 'images/groups_small/'.$group['icon'].'.png', + true, + [ + 'style' => '', + 'class' => 'bot', + 'alt' => $group['nombre'], + 'title' => $group['nombre'], + false, false, false, true + ] + ); + } else { + $table->data[$key][2] = ''; + } - //reporting_get_group_stats - $table->data[$key][3] = $group['disabled'] ? __('Disabled') : __('Enabled'); - $table->data[$key][4] = $group['parent_name']; - $table->data[$key][5] = $group['description']; - $table->data[$key][6] = "" . - html_print_image( - "images/config.png", - true, - array( - "alt" => __('Edit'), - "title" => __('Edit'), - "border" => '0' - ) - ) . - ""; - $confirm_message = __('Are you sure?'); - if ($group['has_child']) { - $confirm_message = __('The child groups will be updated to use the parent id of the deleted group') . ". " . $confirm_message; - } + // reporting_get_group_stats + $table->data[$key][3] = $group['disabled'] ? __('Disabled') : __('Enabled'); + $table->data[$key][4] = $group['parent_name']; + $table->data[$key][5] = $group['description']; + $table->data[$key][6] = "".html_print_image( + 'images/config.png', + true, + [ + 'alt' => __('Edit'), + 'title' => __('Edit'), + 'border' => '0', + ] + ).''; - $table->data[$key][6] .= '  ' . - '' . - html_print_image( - "images/cross.png", - true, - array( - "alt" => __('Delete'), - "title" => __('Delete'), - "border" => '0' - ) - ) . - ""; + $confirm_message = __('Are you sure?'); + if ($group['has_child']) { + $confirm_message = __('The child groups will be updated to use the parent id of the deleted group').'. '.$confirm_message; + } - } + $table->data[$key][6] .= '  '.''.html_print_image( + 'images/cross.png', + true, + [ + 'alt' => __('Delete'), + 'title' => __('Delete'), + 'border' => '0', + ] + ).''; + } - echo ui_pagination( - $groups_count, false, - $offset, $block_size, - true, 'offset', false - ); - html_print_table ($table); - echo ui_pagination( - $groups_count, false, - $offset, $block_size, - true, 'offset', true - ); - } - else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined groups') ) ); - } + echo ui_pagination( + $groups_count, + false, + $offset, + $block_size, + true, + 'offset', + false + ); + html_print_table($table); + echo ui_pagination( + $groups_count, + false, + $offset, + $block_size, + true, + 'offset', + true + ); + } else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined groups') ]); + } } -if (check_acl($config['id_user'], 0, "PM")) { - echo '
    '; - echo '
    '; - html_print_submit_button (__('Create group'), 'crt', false, 'class="sub next"'); - echo '
    '; - echo '
    '; +if (check_acl($config['id_user'], 0, 'PM')) { + echo '
    '; + echo '
    '; + html_print_submit_button(__('Create group'), 'crt', false, 'class="sub next"'); + echo '
    '; + echo '
    '; } -ui_require_javascript_file("TreeController", "include/javascript/tree/"); +ui_require_javascript_file('TreeController', 'include/javascript/tree/'); enterprise_hook('close_meta_frame'); -$tab = "group_edition"; +$tab = 'group_edition'; ?> - - - - + + + + diff --git a/pandora_console/godmode/groups/modu_group_list.php b/pandora_console/godmode/groups/modu_group_list.php index 508e6d32bd..f75d46cfd8 100644 --- a/pandora_console/godmode/groups/modu_group_list.php +++ b/pandora_console/godmode/groups/modu_group_list.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,171 +11,171 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - - // Load global vars global $config; check_login(); -if (! check_acl($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Group Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Group Management' + ); + include 'general/noaccess.php'; + return; } -if (is_ajax ()) { - $get_group_json = (bool) get_parameter ('get_group_json'); - $get_group_agents = (bool) get_parameter ('get_group_agents'); - - if ($get_group_json) { - $id_group = (int) get_parameter ('id_group'); - - if (! check_acl ($config['id_user'], $id_group, "AR")) { - db_pandora_audit("ACL Violation", - "Trying to access Alert Management"); - echo json_encode (false); - return; - } - - $group = db_get_row ('tmodule_group', 'id_mg', $id_group); - - echo json_encode ($group); - return; - } - - return; +if (is_ajax()) { + $get_group_json = (bool) get_parameter('get_group_json'); + $get_group_agents = (bool) get_parameter('get_group_agents'); + + if ($get_group_json) { + $id_group = (int) get_parameter('id_group'); + + if (! check_acl($config['id_user'], $id_group, 'AR')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Alert Management' + ); + echo json_encode(false); + return; + } + + $group = db_get_row('tmodule_group', 'id_mg', $id_group); + + echo json_encode($group); + return; + } + + return; } if (!is_metaconsole()) { - // Header - ui_print_page_header (__("Module groups defined in %s", get_product_name()), "images/module_group.png", false, "", true, ""); + // Header + ui_print_page_header(__('Module groups defined in %s', get_product_name()), 'images/module_group.png', false, '', true, ''); } -$create_group = (bool) get_parameter ('create_group'); -$update_group = (bool) get_parameter ('update_group'); -$delete_group = (bool) get_parameter ('delete_group'); -/* Create group */ +$create_group = (bool) get_parameter('create_group'); +$update_group = (bool) get_parameter('update_group'); +$delete_group = (bool) get_parameter('delete_group'); + +// Create group if ($create_group) { - $name = (string) get_parameter ('name'); - $icon = (string) get_parameter ('icon'); - $id_parent = (int) get_parameter ('id_parent'); - $alerts_disabled = (bool) get_parameter ('alerts_disabled'); - $custom_id = (string) get_parameter ('custom_id'); - $check = db_get_value('name', 'tmodule_group', 'name', $name); - - if ($name) { - if (!$check) { - $result = db_process_sql_insert('tmodule_group', array('name' => $name)); - - if ($result) { - ui_print_success_message(__('Group successfully created')); - } - else { - ui_print_error_message(__('There was a problem creating group')); - } - } - else { - ui_print_error_message(__('Each module group must have a different name')); - } - } - else { - ui_print_error_message(__('Module group must have a name')); - } + $name = (string) get_parameter('name'); + $icon = (string) get_parameter('icon'); + $id_parent = (int) get_parameter('id_parent'); + $alerts_disabled = (bool) get_parameter('alerts_disabled'); + $custom_id = (string) get_parameter('custom_id'); + $check = db_get_value('name', 'tmodule_group', 'name', $name); + + if ($name) { + if (!$check) { + $result = db_process_sql_insert('tmodule_group', ['name' => $name]); + + if ($result) { + ui_print_success_message(__('Group successfully created')); + } else { + ui_print_error_message(__('There was a problem creating group')); + } + } else { + ui_print_error_message(__('Each module group must have a different name')); + } + } else { + ui_print_error_message(__('Module group must have a name')); + } } -/* Update group */ +// Update group if ($update_group) { - $id_group = (int) get_parameter ('id_group'); - $name = (string) get_parameter ('name'); - $icon = (string) get_parameter ('icon'); - $id_parent = (int) get_parameter ('id_parent'); - $alerts_enabled = (bool) get_parameter ('alerts_enabled'); - $custom_id = (string) get_parameter ('custom_id'); - $check = db_get_value('name', 'tmodule_group', 'name', $name); - $subcheck = db_get_value('name', 'tmodule_group', 'id_mg', $id_group); - - if ($name) { - if (!$check || $subcheck == $name) { - $result = db_process_sql_update('tmodule_group', array('name' => $name), array('id_mg' => $id_group)); + $id_group = (int) get_parameter('id_group'); + $name = (string) get_parameter('name'); + $icon = (string) get_parameter('icon'); + $id_parent = (int) get_parameter('id_parent'); + $alerts_enabled = (bool) get_parameter('alerts_enabled'); + $custom_id = (string) get_parameter('custom_id'); + $check = db_get_value('name', 'tmodule_group', 'name', $name); + $subcheck = db_get_value('name', 'tmodule_group', 'id_mg', $id_group); - if ($result !== false) { - ui_print_success_message(__('Group successfully updated')); - } - else { - ui_print_error_message(__('There was a problem modifying group')); - } - } - else { - ui_print_error_message(__('Each module group must have a different name')); - } - } - else { - ui_print_error_message(__('Module group must have a name')); - } + if ($name) { + if (!$check || $subcheck == $name) { + $result = db_process_sql_update('tmodule_group', ['name' => $name], ['id_mg' => $id_group]); + + if ($result !== false) { + ui_print_success_message(__('Group successfully updated')); + } else { + ui_print_error_message(__('There was a problem modifying group')); + } + } else { + ui_print_error_message(__('Each module group must have a different name')); + } + } else { + ui_print_error_message(__('Module group must have a name')); + } } -/* Delete group */ +// Delete group if ($delete_group) { - $id_group = (int) get_parameter ('id_group'); - - $result = db_process_sql_delete('tmodule_group', array('id_mg' => $id_group)); - - if ($result) { - $result = db_process_sql_update('tagente_modulo', array('id_module_group' => 0), array('id_module_group' => $id_group)); - db_process_sql_update('tpolicy_modules', array('id_module_group' => 0), array('id_module_group' => $id_group)); - db_process_sql_update('tcontainer_item', array('id_module_group' => 0), array('id_module_group' => $id_group)); - db_process_sql_update('tnetwork_component', array('id_module_group' => 0), array('id_module_group' => $id_group)); - db_process_sql_update('treport_content', array('id_module_group' => 0), array('id_module_group' => $id_group)); - db_process_sql_update('tnetwork_map', array('id_module_group' => 0), array('id_module_group' => $id_group)); - db_process_sql_update('tlocal_component', array('id_module_group' => 0), array('id_module_group' => $id_group)); - db_process_sql_update('treport_content_template', array('id_module_group' => 0), array('id_module_group' => $id_group)); - - // A group with no modules can be deleted, to avoid a message error then do the follwing - if ($result !== false) - $result = true; - } - - if (! $result) - ui_print_error_message(__('There was a problem deleting group')); - else - ui_print_success_message(__('Group successfully deleted')); + $id_group = (int) get_parameter('id_group'); + + $result = db_process_sql_delete('tmodule_group', ['id_mg' => $id_group]); + + if ($result) { + $result = db_process_sql_update('tagente_modulo', ['id_module_group' => 0], ['id_module_group' => $id_group]); + db_process_sql_update('tpolicy_modules', ['id_module_group' => 0], ['id_module_group' => $id_group]); + db_process_sql_update('tcontainer_item', ['id_module_group' => 0], ['id_module_group' => $id_group]); + db_process_sql_update('tnetwork_component', ['id_module_group' => 0], ['id_module_group' => $id_group]); + db_process_sql_update('treport_content', ['id_module_group' => 0], ['id_module_group' => $id_group]); + db_process_sql_update('tnetwork_map', ['id_module_group' => 0], ['id_module_group' => $id_group]); + db_process_sql_update('tlocal_component', ['id_module_group' => 0], ['id_module_group' => $id_group]); + db_process_sql_update('treport_content_template', ['id_module_group' => 0], ['id_module_group' => $id_group]); + + // A group with no modules can be deleted, to avoid a message error then do the follwing + if ($result !== false) { + $result = true; + } + } + + if (! $result) { + ui_print_error_message(__('There was a problem deleting group')); + } else { + ui_print_success_message(__('Group successfully deleted')); + } } $total_groups = db_get_num_rows('SELECT * FROM tmodule_group'); -$url = ui_get_url_refresh (array ('offset' => false)); +$url = ui_get_url_refresh(['offset' => false]); -$offset = (int)get_parameter('offset', 0); +$offset = (int) get_parameter('offset', 0); ui_pagination($total_groups, $url, $offset); -switch ($config["dbtype"]) { - case "mysql": - $sql = "SELECT * +switch ($config['dbtype']) { + case 'mysql': + $sql = 'SELECT * FROM tmodule_group ORDER BY name ASC - LIMIT " . $offset . ", " . $config['block_size']; - break; - case "postgresql": - $sql = "SELECT * + LIMIT '.$offset.', '.$config['block_size']; + break; + + case 'postgresql': + $sql = 'SELECT * FROM tmodule_group ORDER BY name ASC - LIMIT " . $config['block_size'] . " OFFSET " . $offset; - break; - case "oracle": - $set = array (); - $set['limit'] = $config["block_size"]; - $set['offset'] = $offset; - - $sql = "SELECT * + LIMIT '.$config['block_size'].' OFFSET '.$offset; + break; + + case 'oracle': + $set = []; + $set['limit'] = $config['block_size']; + $set['offset'] = $offset; + + $sql = 'SELECT * FROM tmodule_group - ORDER BY name ASC"; - - $sql = oracle_recode_query ($sql, $set); - break; + ORDER BY name ASC'; + + $sql = oracle_recode_query($sql, $set); + break; } $groups = db_get_all_rows_sql($sql); @@ -185,40 +184,37 @@ $table->width = '100%'; $table->class = 'databox data'; if (!empty($groups)) { - $table->head = array (); - $table->head[0] = __('ID'); - $table->head[1] = __('Name'); - $table->head[2] = __('Delete'); - $table->align = array (); - $table->align[1] = 'left'; - $table->align[2] = 'left'; - $table->size[2] = '5%'; - $table->data = array (); - - foreach ($groups as $id_group ) { - $data = array (); - $data[0] = $id_group["id_mg"]; - - $data[1] = '' . - ui_print_truncate_text($id_group["name"], GENERIC_SIZE_TEXT).''; - if (is_metaconsole()) - $data[2] = '' . html_print_image("images/cross.png", true, array("border" => '0')) . ''; - else - $data[2] = '' . html_print_image("images/cross.png", true, array("border" => '0')) . ''; - - array_push ($table->data, $data); - } - - html_print_table ($table); -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined module groups') ) ); + $table->head = []; + $table->head[0] = __('ID'); + $table->head[1] = __('Name'); + $table->head[2] = __('Delete'); + $table->align = []; + $table->align[1] = 'left'; + $table->align[2] = 'left'; + $table->size[2] = '5%'; + $table->data = []; + + foreach ($groups as $id_group) { + $data = []; + $data[0] = $id_group['id_mg']; + + $data[1] = ''.ui_print_truncate_text($id_group['name'], GENERIC_SIZE_TEXT).''; + if (is_metaconsole()) { + $data[2] = ''.html_print_image('images/cross.png', true, ['border' => '0']).''; + } else { + $data[2] = ''.html_print_image('images/cross.png', true, ['border' => '0']).''; + } + + array_push($table->data, $data); + } + + html_print_table($table); +} else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined module groups') ]); } echo '
    '; echo '
    '; -html_print_submit_button (__('Create module group'), 'crt', false, 'class="sub next"'); +html_print_submit_button(__('Create module group'), 'crt', false, 'class="sub next"'); echo '
    '; echo '
    '; - -?> diff --git a/pandora_console/godmode/massive/massive_add_action_alerts.php b/pandora_console/godmode/massive/massive_add_action_alerts.php index faec370e12..919380c9a9 100755 --- a/pandora_console/godmode/massive/massive_add_action_alerts.php +++ b/pandora_console/godmode/massive/massive_add_action_alerts.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,303 +11,335 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access massive agent deletion section"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access massive agent deletion section' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_agents.php'); -require_once ('include/functions_alerts.php'); -require_once ('include/functions_users.php'); +require_once 'include/functions_agents.php'; +require_once 'include/functions_alerts.php'; +require_once 'include/functions_users.php'; -if (is_ajax ()) { - $get_alerts = (bool) get_parameter ('get_alerts'); - - if ($get_alerts) { - $id_agents = get_parameter ('id_agents'); - if (empty($id_agents)) { - echo json_encode (''); - return; - } - - if (is_array($id_agents) && count($id_agents) == 1 && $id_agents[0] == '') { - $id_agents = false; - } - - $alert_templates = agents_get_alerts_simple ($id_agents); - echo json_encode (index_array ($alert_templates, 'id_alert_template', 'template_name')); - return; - } - return; +if (is_ajax()) { + $get_alerts = (bool) get_parameter('get_alerts'); + + if ($get_alerts) { + $id_agents = get_parameter('id_agents'); + if (empty($id_agents)) { + echo json_encode(''); + return; + } + + if (is_array($id_agents) && count($id_agents) == 1 && $id_agents[0] == '') { + $id_agents = false; + } + + $alert_templates = agents_get_alerts_simple($id_agents); + echo json_encode(index_array($alert_templates, 'id_alert_template', 'template_name')); + return; + } + + return; } -$id_group = (int) get_parameter ('id_group'); -$id_agents = get_parameter ('id_agents'); -$id_alert_templates = (array) get_parameter ('id_alert_templates'); -$recursion = get_parameter ('recursion'); -$add = (bool) get_parameter_post ('add'); +$id_group = (int) get_parameter('id_group'); +$id_agents = get_parameter('id_agents'); +$id_alert_templates = (array) get_parameter('id_alert_templates'); +$recursion = get_parameter('recursion'); +$add = (bool) get_parameter_post('add'); if ($add) { - if (empty($id_agents) || $id_agents[0] == 0) - ui_print_result_message (false, '', __('Could not be added').". ".__('No agents selected')); - else { - $actions = get_parameter ('action'); - $fires_min = (int) get_parameter ('fires_min'); - $fires_max = (int) get_parameter ('fires_max'); - - if (!empty($actions)) { - $modules = get_parameter ('module'); - $modules_id = array(); - if (!empty($modules)) { - foreach ($modules as $module) { - foreach ($id_agents as $id_agent) { - $module_id = modules_get_agentmodule_id($module, $id_agent); - $modules_id[] = $module_id['id_agente_modulo']; - } - } - - $agent_alerts = agents_get_alerts($id_agents); - $cont = 0; - $agent_alerts_id = array(); - - foreach ($agent_alerts['simple'] as $agent_alert) { - - if ((in_array($agent_alert['id_alert_template'], $id_alert_templates)) && (in_array($agent_alert['id_agent_module'], $modules_id))) { - $agent_alerts_id[$cont] = $agent_alert['id']; - $cont += 1; - } - } - - $options = array(); - - if ($fires_min > 0) - $options['fires_min'] = $fires_min; - if ($fires_max > 0) - $options['fires_max'] = $fires_max; - - if (empty($agent_alerts_id)) { - ui_print_result_message (false, '', __('Could not be added').". ".__('No alerts selected')); - } - else { - $results = true; - foreach ($agent_alerts_id as $agent_alert_id) { - foreach ($actions as $action) { - $result = alerts_add_alert_agent_module_action($agent_alert_id, $action, $options); - if ($result === false) - $results = false; - } - } - $info = array('Agents' => implode(',',$id_agents), - 'Alerts' => addslashes(io_json_mb_encode($agent_alerts)), - 'Fires Min' => $fires_min, - 'Fires_max' => $fires_max, - 'Actions' => implode(',',$actions)); - db_pandora_audit("Massive management", "Add alert action " . json_encode($id_agents), false, false, json_encode($info)); - ui_print_result_message ($results, __('Successfully added'), __('Could not be added')); - } - } - else { - ui_print_result_message (false, '', __('Could not be added').". ".__('No modules selected')); - } - } - else { - ui_print_result_message (false, '', __('Could not be added').". ".__('No actions selected')); - } - } - + if (empty($id_agents) || $id_agents[0] == 0) { + ui_print_result_message(false, '', __('Could not be added').'. '.__('No agents selected')); + } else { + $actions = get_parameter('action'); + $fires_min = (int) get_parameter('fires_min'); + $fires_max = (int) get_parameter('fires_max'); + + if (!empty($actions)) { + $modules = get_parameter('module'); + $modules_id = []; + if (!empty($modules)) { + foreach ($modules as $module) { + foreach ($id_agents as $id_agent) { + $module_id = modules_get_agentmodule_id($module, $id_agent); + $modules_id[] = $module_id['id_agente_modulo']; + } + } + + $agent_alerts = agents_get_alerts($id_agents); + $cont = 0; + $agent_alerts_id = []; + + foreach ($agent_alerts['simple'] as $agent_alert) { + if ((in_array($agent_alert['id_alert_template'], $id_alert_templates)) && (in_array($agent_alert['id_agent_module'], $modules_id))) { + $agent_alerts_id[$cont] = $agent_alert['id']; + $cont += 1; + } + } + + $options = []; + + if ($fires_min > 0) { + $options['fires_min'] = $fires_min; + } + + if ($fires_max > 0) { + $options['fires_max'] = $fires_max; + } + + if (empty($agent_alerts_id)) { + ui_print_result_message(false, '', __('Could not be added').'. '.__('No alerts selected')); + } else { + $results = true; + foreach ($agent_alerts_id as $agent_alert_id) { + foreach ($actions as $action) { + $result = alerts_add_alert_agent_module_action($agent_alert_id, $action, $options); + if ($result === false) { + $results = false; + } + } + } + + $info = [ + 'Agents' => implode(',', $id_agents), + 'Alerts' => addslashes(io_json_mb_encode($agent_alerts)), + 'Fires Min' => $fires_min, + 'Fires_max' => $fires_max, + 'Actions' => implode(',', $actions), + ]; + db_pandora_audit('Massive management', 'Add alert action '.json_encode($id_agents), false, false, json_encode($info)); + ui_print_result_message($results, __('Successfully added'), __('Could not be added')); + } + } else { + ui_print_result_message(false, '', __('Could not be added').'. '.__('No modules selected')); + } + } else { + ui_print_result_message(false, '', __('Could not be added').'. '.__('No actions selected')); + } + } } -$groups = users_get_groups (); +$groups = users_get_groups(); $own_info = get_user_info($config['id_user']); -if (!$own_info['is_admin'] && !check_acl ($config['id_user'], 0, "AW")) - $return_all_group = false; -else - $return_all_group = true; +if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'AW')) { + $return_all_group = false; +} else { + $return_all_group = true; +} // Avoid php warning if (empty($alert_templates)) { - $alert_templates = ''; + $alert_templates = ''; } $table->id = 'delete_table'; $table->width = '98%'; -$table->data = array (); -$table->style = array (); +$table->data = []; +$table->style = []; $table->style[0] = 'font-weight: bold; vertical-align:top'; $table->style[2] = 'font-weight: bold'; -$table->size = array (); +$table->size = []; $table->size[0] = '15%'; $table->size[1] = '35%'; $table->size[2] = '15%'; $table->size[3] = '35%'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Group'); -$table->data[0][1] = html_print_select_groups(false, "AW", $return_all_group, - 'id_group', $id_group, false, '', '', true); +$table->data[0][1] = html_print_select_groups( + false, + 'AW', + $return_all_group, + 'id_group', + $id_group, + false, + '', + '', + true +); $table->data[0][2] = __('Group recursion'); -$table->data[0][3] = html_print_checkbox ("recursion", 1, $recursion, true, false); +$table->data[0][3] = html_print_checkbox('recursion', 1, $recursion, true, false); $table->data[1][0] = __('Agents with templates'); $table->data[1][0] .= ''; -$table->data[1][1] = html_print_select (array(),'id_agents[]', 0, false, __('Any'), '', true, true); +$table->data[1][1] = html_print_select([], 'id_agents[]', 0, false, __('Any'), '', true, true); $table->data[2][0] = __('Alert templates'); $table->data[2][0] .= ''; -$table->data[2][1] = html_print_select (array(), 'id_alert_templates[]', '', '', '', '', true, true, true, '', $alert_templates == 0); +$table->data[2][1] = html_print_select([], 'id_alert_templates[]', '', '', '', '', true, true, true, '', $alert_templates == 0); $table->data[2][2] = __('When select agents'); $table->data[2][2] .= '
    '; -$table->data[2][2] .= html_print_select ( - array('common' => __('Show common modules'), - 'all' => __('Show all modules'),'unknown' => __('Show unknown and not init modules')), - 'modules_selection_mode', - 'common', false, '', '', true); -$table->data[2][3] = html_print_select (array(), 'module[]', - $modules_select, false, '', '', true, true, false); +$table->data[2][2] .= html_print_select( + [ + 'common' => __('Show common modules'), + 'all' => __('Show all modules'), + 'unknown' => __('Show unknown and not init modules'), + ], + 'modules_selection_mode', + 'common', + false, + '', + '', + true +); +$table->data[2][3] = html_print_select( + [], + 'module[]', + $modules_select, + false, + '', + '', + true, + true, + false +); -$actions = alerts_get_alert_actions (); +$actions = alerts_get_alert_actions(); $table->data[3][0] = __('Action'); -$table->data[3][1] = html_print_select ($actions, 'action[]', '', '', '', '', true, true); +$table->data[3][1] = html_print_select($actions, 'action[]', '', '', '', '', true, true); $table->data[3][1] .= ''.__('Advanced options').' » '; $table->data[3][1] .= ''; echo '
    '; -html_print_table ($table); +html_print_table($table); $sql = 'SELECT id_agente FROM tagente_modulo WHERE id_agente_modulo IN (SELECT id_agent_module FROM talert_template_modules)'; $agents_with_templates = db_get_all_rows_sql($sql); -$agents_with_templates_json = array(); +$agents_with_templates_json = []; foreach ($agents_with_templates as $ag) { - $agents_with_templates_json[] = $ag['id_agente']; + $agents_with_templates_json[] = $ag['id_agente']; } + $agents_with_templates_json = json_encode($agents_with_templates_json); echo ""; -echo '
    '; -html_print_input_hidden ('add', 1); -html_print_submit_button (__('Add'), 'go', false, 'class="sub add"'); +echo '
    '; +html_print_input_hidden('add', 1); +html_print_submit_button(__('Add'), 'go', false, 'class="sub add"'); echo '
    '; echo ''; echo ''; -ui_require_jquery_file ('form'); -ui_require_jquery_file ('pandora.controls'); +ui_require_jquery_file('form'); +ui_require_jquery_file('pandora.controls'); ?> diff --git a/pandora_console/godmode/massive/massive_add_alerts.php b/pandora_console/godmode/massive/massive_add_alerts.php index ba8bfa5ad4..989a8cd3a8 100755 --- a/pandora_console/godmode/massive/massive_add_alerts.php +++ b/pandora_console/godmode/massive/massive_add_alerts.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,188 +11,254 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access massive alert deletion"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access massive alert deletion' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_agents.php'); -require_once ('include/functions_alerts.php'); -require_once($config['homedir'] . "/include/functions_modules.php"); -require_once($config['homedir'] . '/include/functions_users.php'); +require_once 'include/functions_agents.php'; +require_once 'include/functions_alerts.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_users.php'; -if (is_ajax ()) { - $get_agents = (bool) get_parameter ('get_agents'); - $recursion = (bool) get_parameter ('recursion',false); - - if ($get_agents) { - $id_group = (int) get_parameter ('id_group', 0); - // Is is possible add keys prefix to avoid auto sorting in js object conversion - $keys_prefix = (string) get_parameter ('keys_prefix', ''); - - if ($id_group == 0) { - $agents = agents_get_group_agents ( - array_keys( - users_get_groups( - $config["id_user"], - "AW", - true, - false) - ), - false, "", false, $recursion); - } - else { - $agents = agents_get_group_agents ( $id_group, - false, "", false, $recursion); - } - - // Add keys prefix - if ($keys_prefix !== "") { - foreach($agents as $k => $v) { - $agents[$keys_prefix . $k] = $v; - unset($agents[$k]); - } - } - - echo json_encode ($agents); - return; - } - return; +if (is_ajax()) { + $get_agents = (bool) get_parameter('get_agents'); + $recursion = (bool) get_parameter('recursion', false); + + if ($get_agents) { + $id_group = (int) get_parameter('id_group', 0); + // Is is possible add keys prefix to avoid auto sorting in js object conversion + $keys_prefix = (string) get_parameter('keys_prefix', ''); + + if ($id_group == 0) { + $agents = agents_get_group_agents( + array_keys( + users_get_groups( + $config['id_user'], + 'AW', + true, + false + ) + ), + false, + '', + false, + $recursion + ); + } else { + $agents = agents_get_group_agents( + $id_group, + false, + '', + false, + $recursion + ); + } + + // Add keys prefix + if ($keys_prefix !== '') { + foreach ($agents as $k => $v) { + $agents[$keys_prefix.$k] = $v; + unset($agents[$k]); + } + } + + echo json_encode($agents); + return; + } + + return; } -function process_manage_add ($id_alert_template, $id_agents, $module_names) { - if (empty ($id_agents) || $id_agents[0] == 0) { - ui_print_error_message(__('No agents selected')); - return false; - } - - if (empty ($id_alert_template)) { - ui_print_error_message(__('No alert selected')); - return false; - } - - foreach($module_names as $module) { - foreach($id_agents as $id_agent) { - $module_id = modules_get_agentmodule_id($module, $id_agent); - $modules_id[] = $module_id['id_agente_modulo']; - } - } - - if(count($module_names) == 1 && $module_names[0] == '0') { - $modules_id = agents_common_modules ($id_agents, false, true); - } - - - $conttotal = 0; - $contsuccess = 0; - foreach($modules_id as $module) { - $success = alerts_create_alert_agent_module ($module, $id_alert_template); - - if($success) - $contsuccess ++; - $conttotal ++; - } - - if ($contsuccess > 0) { - db_pandora_audit("Massive management", "Add alert", false, false, "Alert template: " . $id_alert_template . " Modules: " . json_encode($modules_id)); - } - else { - db_pandora_audit("Massive management", "Fail try to add alert", false, false, "Alert template: " . $id_alert_template . " Modules: " . json_encode($modules_id)); - } - - ui_print_result_message ($contsuccess > 0, - __('Successfully added')."(".$contsuccess."/".$conttotal.")", - __('Could not be added')); - + +function process_manage_add($id_alert_template, $id_agents, $module_names) +{ + if (empty($id_agents) || $id_agents[0] == 0) { + ui_print_error_message(__('No agents selected')); + return false; + } + + if (empty($id_alert_template)) { + ui_print_error_message(__('No alert selected')); + return false; + } + + foreach ($module_names as $module) { + foreach ($id_agents as $id_agent) { + $module_id = modules_get_agentmodule_id($module, $id_agent); + $modules_id[] = $module_id['id_agente_modulo']; + } + } + + if (count($module_names) == 1 && $module_names[0] == '0') { + $modules_id = agents_common_modules($id_agents, false, true); + } + + $conttotal = 0; + $contsuccess = 0; + foreach ($modules_id as $module) { + $success = alerts_create_alert_agent_module($module, $id_alert_template); + + if ($success) { + $contsuccess ++; + } + + $conttotal ++; + } + + if ($contsuccess > 0) { + db_pandora_audit('Massive management', 'Add alert', false, false, 'Alert template: '.$id_alert_template.' Modules: '.json_encode($modules_id)); + } else { + db_pandora_audit('Massive management', 'Fail try to add alert', false, false, 'Alert template: '.$id_alert_template.' Modules: '.json_encode($modules_id)); + } + + ui_print_result_message( + $contsuccess > 0, + __('Successfully added').'('.$contsuccess.'/'.$conttotal.')', + __('Could not be added') + ); + } -$id_group = (int) get_parameter ('id_group', -1); -$id_agents = get_parameter ('id_agents'); -$module_names = get_parameter ('module'); -$id_alert_template = (int) get_parameter ('id_alert_template'); -$recursion = get_parameter ('recursion'); -$add = (bool) get_parameter_post ('add'); +$id_group = (int) get_parameter('id_group', -1); +$id_agents = get_parameter('id_agents'); +$module_names = get_parameter('module'); +$id_alert_template = (int) get_parameter('id_alert_template'); +$recursion = get_parameter('recursion'); + +$add = (bool) get_parameter_post('add'); if ($add) { - process_manage_add ($id_alert_template, $id_agents, $module_names); + process_manage_add($id_alert_template, $id_agents, $module_names); } -$groups = users_get_groups (); +$groups = users_get_groups(); $own_info = get_user_info($config['id_user']); -if (!$own_info['is_admin'] && !check_acl ($config['id_user'], 0, "AW")) - $return_all_group = false; -else - $return_all_group = true; +if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'AW')) { + $return_all_group = false; +} else { + $return_all_group = true; +} $table->id = 'add_table'; $table->class = 'databox filters'; $table->width = '100%'; -$table->data = array (); -$table->style = array (); +$table->data = []; +$table->style = []; $table->style[0] = 'font-weight: bold; vertical-align:top'; $table->style[2] = 'font-weight: bold; vertical-align:top'; -$table->size = array (); +$table->size = []; $table->size[0] = '15%'; $table->size[1] = '25%'; $table->size[2] = '15%'; $table->size[3] = '30%'; -$table->data = array (); - +$table->data = []; + $table->data[0][0] = __('Group'); -$table->data[0][1] = html_print_select_groups(false, "AW", $return_all_group, 'id_group', 0, - '', 'Select', -1, true, false, true, '', false, 'width:180px;'); +$table->data[0][1] = html_print_select_groups( + false, + 'AW', + $return_all_group, + 'id_group', + 0, + '', + 'Select', + -1, + true, + false, + true, + '', + false, + 'width:180px;' +); $table->data[0][2] = __('Group recursion'); -$table->data[0][3] = html_print_checkbox ("recursion", 1, $recursion, true, false,'',true); +$table->data[0][3] = html_print_checkbox('recursion', 1, $recursion, true, false, '', true); $table->data[1][0] = __('Agents'); $table->data[1][0] .= ''; -$agents_alerts = alerts_get_agents_with_alert_template ($id_alert_template, $id_group, - false, array ('tagente.nombre', 'tagente.id_agente')); +$agents_alerts = alerts_get_agents_with_alert_template( + $id_alert_template, + $id_group, + false, + [ + 'tagente.nombre', + 'tagente.id_agente', + ] +); -$agents = agents_get_group_agents (array_keys (users_get_groups ($config["id_user"], "AW", false))); -$table->data[1][1] = html_print_select ($agents, - 'id_agents[]', '', '', '', '', true, true, true, '', false, 'width:180px;'); +$agents = agents_get_group_agents(array_keys(users_get_groups($config['id_user'], 'AW', false))); +$table->data[1][1] = html_print_select( + $agents, + 'id_agents[]', + '', + '', + '', + '', + true, + true, + true, + '', + false, + 'width:180px;' +); $table->data[1][2] = __('When select agents'); $table->data[1][2] .= '
    '; -$table->data[1][2] .= html_print_select (array('common' => __('Show common modules'), 'all' => __('Show all modules')), 'modules_selection_mode', - 'common', false, '', '', true); -$table->data[1][3] = html_print_select (array(), 'module[]', '', false, '', '', true, true, false, '', false, 'width:180px;'); +$table->data[1][2] .= html_print_select( + [ + 'common' => __('Show common modules'), + 'all' => __('Show all modules'), + ], + 'modules_selection_mode', + 'common', + false, + '', + '', + true +); +$table->data[1][3] = html_print_select([], 'module[]', '', false, '', '', true, true, false, '', false, 'width:180px;'); -$templates = alerts_get_alert_templates (false, array ('id', 'name')); +$templates = alerts_get_alert_templates(false, ['id', 'name']); $table->data[2][0] = __('Alert template'); -$table->data[2][1] = html_print_select (index_array ($templates, 'id', 'name'), - 'id_alert_template', $id_alert_template, false, __('Select'), 0, true); +$table->data[2][1] = html_print_select( + index_array($templates, 'id', 'name'), + 'id_alert_template', + $id_alert_template, + false, + __('Select'), + 0, + true +); $table->data[2][2] = ''; $table->data[2][3] = ''; echo '
    '; -html_print_table ($table); +html_print_table($table); echo '
    '; -html_print_input_hidden ('add', 1); -html_print_submit_button (__('Add'), 'go', false, 'class="sub add"'); +html_print_input_hidden('add', 1); +html_print_submit_button(__('Add'), 'go', false, 'class="sub add"'); echo '
    '; echo '
    '; // TODO: Change to iu_print_error system echo ''; -//Hack to translate text "none" in PHP to javascript -echo ''; +// Hack to translate text "none" in PHP to javascript +echo ''; -ui_require_jquery_file ('form'); -ui_require_jquery_file ('pandora.controls'); +ui_require_jquery_file('form'); +ui_require_jquery_file('pandora.controls'); ?> diff --git a/pandora_console/godmode/massive/massive_add_profiles.php b/pandora_console/godmode/massive/massive_add_profiles.php index 559ffa6291..6000dbe9a6 100644 --- a/pandora_console/godmode/massive/massive_add_profiles.php +++ b/pandora_console/godmode/massive/massive_add_profiles.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,77 +11,89 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access massive profile addition"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access massive profile addition' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_agents.php'); -require_once ('include/functions_alerts.php'); -require_once($config['homedir'] . "/include/functions_profile.php"); -require_once($config['homedir'] . "/include/functions_users.php"); +require_once 'include/functions_agents.php'; +require_once 'include/functions_alerts.php'; +require_once $config['homedir'].'/include/functions_profile.php'; +require_once $config['homedir'].'/include/functions_users.php'; -$create_profiles = (int) get_parameter ('create_profiles'); +$create_profiles = (int) get_parameter('create_profiles'); if ($create_profiles) { - $profiles_id = get_parameter ('profiles_id', -1); - $groups_id = get_parameter ('groups_id', -1); - $users_id = get_parameter ('users_id', -1); - $n_added = 0; + $profiles_id = get_parameter('profiles_id', -1); + $groups_id = get_parameter('groups_id', -1); + $users_id = get_parameter('users_id', -1); + $n_added = 0; - if ($profiles_id == -1 || $groups_id == -1 || $users_id == -1) { - $result = false; - } - else { - foreach ($profiles_id as $profile) { - foreach ($groups_id as $group) { - foreach ($users_id as $user) { - $profile_data = db_get_row_filter ("tusuario_perfil", array("id_usuario" => $user, "id_perfil" => $profile, "id_grupo" => $group)); - // If the profile doesnt exist, we create it - if ($profile_data === false) { - db_pandora_audit("User management", - "Added profile for user ".io_safe_output($user)); - $return = profile_create_user_profile ($user, $profile, $group); - if ($return !== false) { - $n_added ++; - } - } - } - } - } - } - - if ($n_added > 0) { - db_pandora_audit("Massive management", "Add profiles", false, false, - 'Profiles: ' . json_encode($profiles_id) . ' Groups: ' . json_encode($groups_id) . 'Users: ' . json_encode($users_id)); - } - else { - db_pandora_audit("Massive management", "Fail to try add profiles", false, false, - 'Profiles: ' . json_encode($profiles_id) . ' Groups: ' . json_encode($groups_id) . 'Users: ' . json_encode($users_id)); - } - - ui_print_result_message ($n_added > 0, - __('Profiles added successfully').'('.$n_added.')', - __('Profiles cannot be added')); + if ($profiles_id == -1 || $groups_id == -1 || $users_id == -1) { + $result = false; + } else { + foreach ($profiles_id as $profile) { + foreach ($groups_id as $group) { + foreach ($users_id as $user) { + $profile_data = db_get_row_filter('tusuario_perfil', ['id_usuario' => $user, 'id_perfil' => $profile, 'id_grupo' => $group]); + // If the profile doesnt exist, we create it + if ($profile_data === false) { + db_pandora_audit( + 'User management', + 'Added profile for user '.io_safe_input($user) + ); + $return = profile_create_user_profile($user, $profile, $group); + if ($return !== false) { + $n_added ++; + } + } + } + } + } + } + + if ($n_added > 0) { + db_pandora_audit( + 'Massive management', + 'Add profiles', + false, + false, + 'Profiles: '.json_encode($profiles_id).' Groups: '.json_encode($groups_id).'Users: '.json_encode($users_id) + ); + } else { + db_pandora_audit( + 'Massive management', + 'Fail to try add profiles', + false, + false, + 'Profiles: '.json_encode($profiles_id).' Groups: '.json_encode($groups_id).'Users: '.json_encode($users_id) + ); + } + + ui_print_result_message( + $n_added > 0, + __('Profiles added successfully').'('.$n_added.')', + __('Profiles cannot be added') + ); } -html_print_table ($table); +html_print_table($table); unset($table); $table->width = '100%'; $table->class = 'databox filters'; -$table->data = array (); -$table->head = array (); -$table->align = array (); -$table->style = array (); +$table->data = []; +$table->head = []; +$table->align = []; +$table->style = []; $table->style[0] = 'font-weight: bold'; $table->style[1] = 'font-weight: bold'; $table->head[0] = __('Profile name'); @@ -93,32 +104,71 @@ $table->size[0] = '34%'; $table->size[1] = '33%'; $table->size[2] = '33%'; -$data = array (); +$data = []; $data[0] = '
    '; -$data[0] .= html_print_select (profile_get_profiles (), 'profiles_id[]', '', '', '', - '', true, true, false, '', false, 'width: 100%'); -$data[1] = html_print_select_groups($config['id_user'], "UM", true, - 'groups_id[]', '', '', '', '', true, true, false, '', false, 'width: 100%'); +$data[0] .= html_print_select( + profile_get_profiles(), + 'profiles_id[]', + '', + '', + '', + '', + true, + true, + false, + '', + false, + 'width: 100%' +); +$data[1] = html_print_select_groups( + $config['id_user'], + 'UM', + true, + 'groups_id[]', + '', + '', + '', + '', + true, + true, + false, + '', + false, + 'width: 100%' +); $data[2] = ''; -$users_profiles = ""; -$users_order = array('field' => 'id_user', 'order' => 'ASC'); -$data[2] .= html_print_select (users_get_info($users_order,'id_user'), 'users_id[]', '', '', '', - '', true, true, true, '', false, 'width: 100%'); +$users_profiles = ''; +$users_order = [ + 'field' => 'id_user', + 'order' => 'ASC', +]; +$data[2] .= html_print_select( + users_get_info($users_order, 'id_user'), + 'users_id[]', + '', + '', + '', + '', + true, + true, + true, + '', + false, + 'width: 100%' +); -array_push ($table->data, $data); +array_push($table->data, $data); -html_print_table ($table); +html_print_table($table); echo '
    '; -html_print_input_hidden ('create_profiles', 1); -html_print_submit_button (__('Create'), 'go', false, 'class="sub add"'); +html_print_input_hidden('create_profiles', 1); +html_print_submit_button(__('Create'), 'go', false, 'class="sub add"'); echo '
    '; echo '
    '; -unset ($table); - -?> +unset($table); diff --git a/pandora_console/godmode/massive/massive_copy_modules.php b/pandora_console/godmode/massive/massive_copy_modules.php index aae7d4e2df..00c76792e4 100755 --- a/pandora_console/godmode/massive/massive_copy_modules.php +++ b/pandora_console/godmode/massive/massive_copy_modules.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,71 +11,91 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent Config Management Admin section"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Config Management Admin section' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_agents.php'); -require_once ('include/functions_alerts.php'); -require_once ('include/functions_modules.php'); -require_once ('include/functions_users.php'); +require_once 'include/functions_agents.php'; +require_once 'include/functions_alerts.php'; +require_once 'include/functions_modules.php'; +require_once 'include/functions_users.php'; -$source_id_group = (int) get_parameter ('source_id_group'); -$source_id_agent = (int) get_parameter ('source_id_agent'); -$destiny_id_group = (int) get_parameter ('destiny_id_group'); -$destiny_id_agents = (array) get_parameter ('destiny_id_agent', array ()); -$source_recursion = get_parameter ('source_recursion'); -$destiny_recursion = get_parameter ('destiny_recursion'); +$source_id_group = (int) get_parameter('source_id_group'); +$source_id_agent = (int) get_parameter('source_id_agent'); +$destiny_id_group = (int) get_parameter('destiny_id_group'); +$destiny_id_agents = (array) get_parameter('destiny_id_agent', []); +$source_recursion = get_parameter('source_recursion'); +$destiny_recursion = get_parameter('destiny_recursion'); -$do_operation = (bool) get_parameter ('do_operation'); +$do_operation = (bool) get_parameter('do_operation'); if ($do_operation) { - $result = agents_process_manage_config($source_id_agent, - $destiny_id_agents); - - $info = array('Source agent' => $source_id_agent, - 'Destinity agent' => implode(",",$destiny_id_agents)); - if ($result) { - - - db_pandora_audit("Massive management", "Copy modules", false, - false, json_encode($info)); - } - else { - db_pandora_audit("Massive management", - "Fail to try copy modules", false, false,json_encode($info)); - } + $result = agents_process_manage_config( + $source_id_agent, + $destiny_id_agents + ); + + $info = [ + 'Source agent' => $source_id_agent, + 'Destinity agent' => implode(',', $destiny_id_agents), + ]; + if ($result) { + db_pandora_audit( + 'Massive management', + 'Copy modules', + false, + false, + json_encode($info) + ); + } else { + db_pandora_audit( + 'Massive management', + 'Fail to try copy modules', + false, + false, + json_encode($info) + ); + } } -$groups = users_get_groups (); +$groups = users_get_groups(); $table->class = 'databox filters'; $table->width = '100%'; -$table->data = array (); -$table->style = array (); +$table->data = []; +$table->style = []; $table->style[0] = 'font-weight: bold;'; $table->style[2] = 'font-weight: bold'; $table->style[4] = 'font-weight: bold'; $table->style[6] = 'font-weight: bold'; -/* Source selection */ +// Source selection $table->id = 'source_table'; $table->data[0][0] = __('Group'); -$table->data[0][1] = html_print_select_groups(false, "AW", true, 'source_id_group', $source_id_group, - false, '', '', true); +$table->data[0][1] = html_print_select_groups( + false, + 'AW', + true, + 'source_id_group', + $source_id_group, + false, + '', + '', + true +); $table->data[0][2] = __('Group recursion'); -$table->data[0][3] = html_print_checkbox ("source_recursion", 1, $source_recursion, true, false); -$status_list = array (); +$table->data[0][3] = html_print_checkbox('source_recursion', 1, $source_recursion, true, false); +$status_list = []; $status_list[AGENT_STATUS_NORMAL] = __('Normal'); $status_list[AGENT_STATUS_WARNING] = __('Warning'); $status_list[AGENT_STATUS_CRITICAL] = __('Critical'); @@ -84,117 +103,156 @@ $status_list[AGENT_STATUS_UNKNOWN] = __('Unknown'); $status_list[AGENT_STATUS_NOT_NORMAL] = __('Not normal'); $status_list[AGENT_STATUS_NOT_INIT] = __('Not init'); $table->data[0][4] = __('Status'); -$table->data[0][5] = html_print_select($status_list, - 'status_agents_source', 'selected', '', __('All'), AGENT_STATUS_ALL, true); +$table->data[0][5] = html_print_select( + $status_list, + 'status_agents_source', + 'selected', + '', + __('All'), + AGENT_STATUS_ALL, + true +); $table->data[0][6] = __('Agent'); $table->data[0][6] .= ' '; // $table->data[0][7] = html_print_select (agents_get_group_agents ($source_id_group, false, "none"), -// 'source_id_agent', $source_id_agent, false, __('Select'), 0, true); -$agents = ( $source_id_group ? - agents_get_group_agents ($source_id_group, false, "none") : - agents_get_group_agents (array_keys (users_get_groups ($config["id_user"], "AW", false))) ); -$table->data[0][7] = html_print_select ($agents, 'source_id_agent', $source_id_agent, false, __('Select'), 0, true); +// 'source_id_agent', $source_id_agent, false, __('Select'), 0, true); +$agents = ( $source_id_group ? agents_get_group_agents($source_id_group, false, 'none') : agents_get_group_agents(array_keys(users_get_groups($config['id_user'], 'AW', false))) ); +$table->data[0][7] = html_print_select($agents, 'source_id_agent', $source_id_agent, false, __('Select'), 0, true); -echo '
    '; +echo ''; echo '
    '; echo ''; -echo '' . - __('Source') . ui_print_help_icon('manageconfig', true) . - ''; +echo ''.__('Source').ui_print_help_icon('manageconfig', true).''; echo ''; -html_print_table ($table); +html_print_table($table); echo '
    '; -/* Target selection */ +// Target selection $table->id = 'target_table'; $table->class = 'databox filters'; -$table->data = array (); +$table->data = []; -$modules = array (); -if ($source_id_agent) - $modules = agents_get_modules ($source_id_agent, 'nombre'); +$modules = []; +if ($source_id_agent) { + $modules = agents_get_modules($source_id_agent, 'nombre'); +} -$agent_alerts = array (); -if ($source_id_agent) - $agent_alerts = agents_get_alerts_simple ($source_id_agent); -$alerts = array (); +$agent_alerts = []; +if ($source_id_agent) { + $agent_alerts = agents_get_alerts_simple($source_id_agent); +} + +$alerts = []; foreach ($agent_alerts as $alert) { - $name = alerts_get_alert_template_name ($alert['id_alert_template']); - $name .= ' ('.$modules[$alert['id_agent_module']].')'; - $alerts[$alert['id']] = $name; + $name = alerts_get_alert_template_name($alert['id_alert_template']); + $name .= ' ('.$modules[$alert['id_agent_module']].')'; + $alerts[$alert['id']] = $name; } $tags = tags_get_user_tags(); $table->data['tags'][0] = __('Tags'); -$table->data['tags'][1] = html_print_select ($tags, 'tags[]', - $tags_name, false, __('Any'), -1, true, true, true); +$table->data['tags'][1] = html_print_select( + $tags, + 'tags[]', + $tags_name, + false, + __('Any'), + -1, + true, + true, + true +); $table->data['operations'][0] = __('Operations'); -$table->data['operations'][1] = ''; -$table->data['operations'][1] .= html_print_checkbox ('copy_modules', 1, true, true); -$table->data['operations'][1] .= html_print_label (__('Copy modules'), 'checkbox-copy_modules', true); +$table->data['operations'][1] = ''; +$table->data['operations'][1] .= html_print_checkbox('copy_modules', 1, true, true); +$table->data['operations'][1] .= html_print_label(__('Copy modules'), 'checkbox-copy_modules', true); $table->data['operations'][1] .= '
    '; -$table->data['operations'][1] .= ''; -$table->data['operations'][1] .= html_print_checkbox ('copy_alerts', 1, true, true); -$table->data['operations'][1] .= html_print_label (__('Copy alerts'), 'checkbox-copy_alerts', true); +$table->data['operations'][1] .= ''; +$table->data['operations'][1] .= html_print_checkbox('copy_alerts', 1, true, true); +$table->data['operations'][1] .= html_print_label(__('Copy alerts'), 'checkbox-copy_alerts', true); $table->data['operations'][1] .= ''; $table->data[1][0] = __('Modules'); -$table->data[1][1] = ''; -$table->data[1][1] .= html_print_select ($modules, - 'target_modules[]', 0, false, '', '', true, true); +$table->data[1][1] = ''; +$table->data[1][1] .= html_print_select( + $modules, + 'target_modules[]', + 0, + false, + '', + '', + true, + true +); $table->data[1][1] .= ''; -$table->data[1][1] .= ''; +$table->data[1][1] .= ''; $table->data[1][1] .= ''.__('No modules for this agent').''; $table->data[1][1] .= ''; $table->data[2][0] = __('Alerts'); -$table->data[2][1] = ''; -$table->data[2][1] .= html_print_select ($alerts, - 'target_alerts[]', 0, false, '', '', true, true); +$table->data[2][1] = ''; +$table->data[2][1] .= html_print_select( + $alerts, + 'target_alerts[]', + 0, + false, + '', + '', + true, + true +); $table->data[2][1] .= ''; -$table->data[2][1] .= ''; +$table->data[2][1] .= ''; $table->data[2][1] .= ''.__('No alerts for this agent').''; $table->data[2][1] .= ''; echo ''; echo ''; -/* Destiny selection */ +// Destiny selection $table->id = 'destiny_table'; $table->class = 'databox filters'; -$table->data = array (); +$table->data = []; $table->size[0] = '20%'; $table->size[1] = '30%'; $table->size[2] = '20%'; $table->size[3] = '30%'; $table->data[0][0] = __('Group'); -$table->data[0][1] = html_print_select_groups(false, "AW", true, 'destiny_id_group', - $destiny_id_group, false, '', '', true); +$table->data[0][1] = html_print_select_groups( + false, + 'AW', + true, + 'destiny_id_group', + $destiny_id_group, + false, + '', + '', + true +); $table->data[0][2] = __('Group recursion'); -$table->data[0][3] = html_print_checkbox ("destiny_recursion", 1, - $destiny_recursion, true, false); +$table->data[0][3] = html_print_checkbox( + 'destiny_recursion', + 1, + $destiny_recursion, + true, + false +); -$status_list = array (); +$status_list = []; $status_list[AGENT_STATUS_NORMAL] = __('Normal'); $status_list[AGENT_STATUS_WARNING] = __('Warning'); $status_list[AGENT_STATUS_CRITICAL] = __('Critical'); @@ -202,34 +260,38 @@ $status_list[AGENT_STATUS_UNKNOWN] = __('Unknown'); $status_list[AGENT_STATUS_NOT_NORMAL] = __('Not normal'); $status_list[AGENT_STATUS_NOT_INIT] = __('Not init'); $table->data[1][0] = __('Status'); -$table->data[1][1] = html_print_select($status_list, - 'status_agents_destiny', 'selected', '', __('All'), AGENT_STATUS_ALL, true); +$table->data[1][1] = html_print_select( + $status_list, + 'status_agents_destiny', + 'selected', + '', + __('All'), + AGENT_STATUS_ALL, + true +); $table->data[2][0] = __('Agent'); $table->data[2][0] .= ''; -$agents = array(); +$agents = []; if ($source_id_agent) { - $agents = ( $destiny_id_group ? - agents_get_group_agents ($destiny_id_group, false, "none") : - agents_get_group_agents (array_keys (users_get_groups ($config["id_user"], "AW", false))) ); - unset($agents[$source_id_agent]); + $agents = ( $destiny_id_group ? agents_get_group_agents($destiny_id_group, false, 'none') : agents_get_group_agents(array_keys(users_get_groups($config['id_user'], 'AW', false))) ); + unset($agents[$source_id_agent]); } -$table->data[2][1] = html_print_select ($agents, 'destiny_id_agent[]', 0, false, '', '', true, true); +$table->data[2][1] = html_print_select($agents, 'destiny_id_agent[]', 0, false, '', '', true, true); -echo '
    '; echo ''; ?> diff --git a/pandora_console/godmode/massive/massive_enable_disable_alerts.php b/pandora_console/godmode/massive/massive_enable_disable_alerts.php index aa82305865..d034e1b1d6 100644 --- a/pandora_console/godmode/massive/massive_enable_disable_alerts.php +++ b/pandora_console/godmode/massive/massive_enable_disable_alerts.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,310 +11,358 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access massive alert deletion"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access massive alert deletion' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_agents.php'); -require_once ('include/functions_alerts.php'); -require_once ('include/functions_users.php'); +require_once 'include/functions_agents.php'; +require_once 'include/functions_alerts.php'; +require_once 'include/functions_users.php'; -if (is_ajax ()) { - $get_alerts = (bool) get_parameter ('get_alerts'); - - if ($get_alerts) { - $id_agents = get_parameter ('id_agents'); - $get_templates = (bool) get_parameter ('get_templates'); +if (is_ajax()) { + $get_alerts = (bool) get_parameter('get_alerts'); - if ($get_templates) { - if (!is_array($id_agents)) { - echo json_encode (''); - return; - } - $alert_templates = agents_get_alerts_simple ($id_agents); - echo json_encode (index_array ($alert_templates, 'id_alert_template', 'template_name')); - return; - } - else { - $id_alert_templates = (array) get_parameter ('id_alert_templates'); - $disabled = (int) get_parameter ('disabled'); - - $agents_alerts = alerts_get_agents_with_alert_template ($id_alert_templates, false, - array('order' => 'tagente.alias, talert_template_modules.disabled', 'talert_template_modules.disabled' => $disabled), - array ('CONCAT(tagente.alias, " - ", tagente_modulo.nombre) as agent_agentmodule_name', - 'talert_template_modules.id as template_module_id'), $id_agents); - - echo json_encode (index_array ($agents_alerts, 'template_module_id', 'agent_agentmodule_name')); - return; - } - } - return; + if ($get_alerts) { + $id_agents = get_parameter('id_agents'); + $get_templates = (bool) get_parameter('get_templates'); + + if ($get_templates) { + if (!is_array($id_agents)) { + echo json_encode(''); + return; + } + + $alert_templates = agents_get_alerts_simple($id_agents); + echo json_encode(index_array($alert_templates, 'id_alert_template', 'template_name')); + return; + } else { + $id_alert_templates = (array) get_parameter('id_alert_templates'); + $disabled = (int) get_parameter('disabled'); + + $agents_alerts = alerts_get_agents_with_alert_template( + $id_alert_templates, + false, + [ + 'order' => 'tagente.alias, talert_template_modules.disabled', + 'talert_template_modules.disabled' => $disabled, + ], + [ + 'CONCAT(tagente.alias, " - ", tagente_modulo.nombre) as agent_agentmodule_name', + 'talert_template_modules.id as template_module_id', + ], + $id_agents + ); + + echo json_encode(index_array($agents_alerts, 'template_module_id', 'agent_agentmodule_name')); + return; + } + } + + return; } -$id_group = (int) get_parameter ('id_group'); -$id_agents = (array) get_parameter ('id_agents'); -$action = (string) get_parameter ('action', ''); -$recursion = get_parameter ('recursion'); +$id_group = (int) get_parameter('id_group'); +$id_agents = (array) get_parameter('id_agents'); +$action = (string) get_parameter('action', ''); +$recursion = get_parameter('recursion'); $result = false; switch ($action) { - case 'enable_alerts': - $id_alert_templates = (int) get_parameter ('id_alert_template_disabled', 0); - $id_disabled_alerts = get_parameter_post ('id_disabled_alerts', array()); - foreach($id_disabled_alerts as $id_alert) { - $result = alerts_agent_module_disable ($id_alert, false); - } - - ui_print_result_message ($result, __('Successfully enabled'), __('Could not be enabled')); - - $info = '{"Alert":"'.implode(",",$id_disabled_alerts).'"}'; - if ($result) { - db_pandora_audit("Massive management", "Enable alert", false, false, $info); - } - else { - db_pandora_audit("Massive management", "Fail try to enable alert", false, false, $info); - } - break; - case 'disable_alerts': - $id_alert_templates = (int) get_parameter ('id_alert_template_enabled', 0); - $id_enabled_alerts = get_parameter_post ('id_enabled_alerts', array()); - - foreach($id_enabled_alerts as $id_alert) { - $result = alerts_agent_module_disable ($id_alert, true); - } - - ui_print_result_message ($result, __('Successfully disabled'), __('Could not be disabled')); - - $info = '{"Alert":"'.implode(",",$id_enabled_alerts).'"}'; - if ($result) { - db_pandora_audit("Massive management", "Disable alert", false, false, $info); - } - else { - db_pandora_audit("Massive management", "Fail try to Disable alert", false, false, $info); - } - break; - default: - $id_alert_templates = (int) get_parameter ('id_alert_template', 0); - break; + case 'enable_alerts': + $id_alert_templates = (int) get_parameter('id_alert_template_disabled', 0); + $id_disabled_alerts = get_parameter_post('id_disabled_alerts', []); + foreach ($id_disabled_alerts as $id_alert) { + $result = alerts_agent_module_disable($id_alert, false); + } + + ui_print_result_message($result, __('Successfully enabled'), __('Could not be enabled')); + + $info = '{"Alert":"'.implode(',', $id_disabled_alerts).'"}'; + if ($result) { + db_pandora_audit('Massive management', 'Enable alert', false, false, $info); + } else { + db_pandora_audit('Massive management', 'Fail try to enable alert', false, false, $info); + } + break; + + case 'disable_alerts': + $id_alert_templates = (int) get_parameter('id_alert_template_enabled', 0); + $id_enabled_alerts = get_parameter_post('id_enabled_alerts', []); + + foreach ($id_enabled_alerts as $id_alert) { + $result = alerts_agent_module_disable($id_alert, true); + } + + ui_print_result_message($result, __('Successfully disabled'), __('Could not be disabled')); + + $info = '{"Alert":"'.implode(',', $id_enabled_alerts).'"}'; + if ($result) { + db_pandora_audit('Massive management', 'Disable alert', false, false, $info); + } else { + db_pandora_audit('Massive management', 'Fail try to Disable alert', false, false, $info); + } + break; + + default: + $id_alert_templates = (int) get_parameter('id_alert_template', 0); + break; } -$groups = users_get_groups (); +$groups = users_get_groups(); $own_info = get_user_info($config['id_user']); -if (!$own_info['is_admin'] && !check_acl ($config['id_user'], 0, "AW")) - $return_all_group = false; -else - $return_all_group = true; +if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'AW')) { + $return_all_group = false; +} else { + $return_all_group = true; +} $table->id = 'delete_table'; $table->class = 'databox filters'; $table->width = '100%'; -$table->data = array (); -$table->style = array (); +$table->data = []; +$table->style = []; $table->style[0] = 'font-weight: bold;'; $table->style[2] = 'font-weight: bold'; -$table->size = array (); +$table->size = []; $table->size[0] = '15%'; $table->size[1] = '55%'; $table->size[2] = '15%'; $table->size[3] = '15%'; -$table->data = array (); +$table->data = []; $table->data[0][0] = '
    '; $table->data[0][0] .= html_print_input_hidden('id_alert_template_enabled', $id_alert_templates, true); $table->data[0][0] .= __('Group'); -$table->data[0][1] = html_print_select_groups(false, "AW", $return_all_group, 'id_group', $id_group, '', '', '', true); +$table->data[0][1] = html_print_select_groups(false, 'AW', $return_all_group, 'id_group', $id_group, '', '', '', true); $table->data[0][2] = __('Group recursion'); -$table->data[0][3] = html_print_checkbox ("recursion", 1, $recursion, true, false); +$table->data[0][3] = html_print_checkbox('recursion', 1, $recursion, true, false); $table->data[1][0] = __('Agents'); $table->data[1][0] .= ''; -$table->data[1][1] = html_print_select (agents_get_group_agents (array_keys (users_get_groups ($config["id_user"], "AW", false))), - 'id_agents[]', 0, false, '', '', true, true); +$table->data[1][1] = html_print_select( + agents_get_group_agents(array_keys(users_get_groups($config['id_user'], 'AW', false))), + 'id_agents[]', + 0, + false, + '', + '', + true, + true +); $table->data[2][0] = __('Alert template'); $table->data[2][0] .= ''; -$table->data[2][1] = html_print_select ('', 'id_alert_templates[]', '', '', '', '', true, true, true, '', true); +$table->data[2][1] = html_print_select('', 'id_alert_templates[]', '', '', '', '', true, true, true, '', true); -$table->data[3][0] = __('Enabled alerts').ui_print_help_tip(__('Format').":
    ".__('Agent')." - ".__('Module'), true); +$table->data[3][0] = __('Enabled alerts').ui_print_help_tip(__('Format').':
    '.__('Agent').' - '.__('Module'), true); $table->data[3][0] .= ''; -$agents_alerts = alerts_get_agents_with_alert_template ($id_alert_templates, $id_group, - false, array ('tagente.alias', 'tagente.id_agente')); -$table->data[3][1] = html_print_select (index_array ($agents_alerts, 'id_agente', 'alias'), - 'id_enabled_alerts[]', '', '', '', '', true, true, true, '', $id_alert_templates == 0); +$agents_alerts = alerts_get_agents_with_alert_template( + $id_alert_templates, + $id_group, + false, + [ + 'tagente.alias', + 'tagente.id_agente', + ] +); +$table->data[3][1] = html_print_select( + index_array($agents_alerts, 'id_agente', 'alias'), + 'id_enabled_alerts[]', + '', + '', + '', + '', + true, + true, + true, + '', + $id_alert_templates == 0 +); $table->data[4][0] = __('Action'); -$table->data[4][1] = "
    ".html_print_input_image ('disable_alerts', 'images/darrowdown.png', 1, 'margin-left: 150px;', true, array ('title' => __('Disable selected alerts'))).""; +$table->data[4][1] = "
    ".html_print_input_image('disable_alerts', 'images/darrowdown.png', 1, 'margin-left: 150px;', true, ['title' => __('Disable selected alerts')]).''; $table->data[4][1] .= ''; $table->data[4][1] .= '
    '; $table->data[4][1] .= html_print_input_hidden('id_alert_template_disabled', $id_alert_templates, true); -$table->data[4][1] .= html_print_input_image ('enable_alerts', 'images/darrowup.png', 1, 'margin-left: 200px;', true, array ('title' => __('Enable selected alerts')))."
    "; +$table->data[4][1] .= html_print_input_image('enable_alerts', 'images/darrowup.png', 1, 'margin-left: 200px;', true, ['title' => __('Enable selected alerts')]).'
    '; -$table->data[5][0] = __('Disabled alerts').ui_print_help_tip(__('Format').":
    ".__('Agent')." - ".__('Module'), true); +$table->data[5][0] = __('Disabled alerts').ui_print_help_tip(__('Format').':
    '.__('Agent').' - '.__('Module'), true); $table->data[5][0] .= ''; -$table->data[5][1] = html_print_select (index_array ($agents_alerts, 'id_agente2', 'nombre'), - 'id_disabled_alerts[]', '', '', '', '', true, true, true, '', $id_alert_templates == 0); +$table->data[5][1] = html_print_select( + index_array($agents_alerts, 'id_agente2', 'nombre'), + 'id_disabled_alerts[]', + '', + '', + '', + '', + true, + true, + true, + '', + $id_alert_templates == 0 +); $table->data[5][1] .= ''; -html_print_table ($table); +html_print_table($table); echo ''; -ui_require_jquery_file ('form'); -ui_require_jquery_file ('pandora.controls'); +ui_require_jquery_file('form'); +ui_require_jquery_file('pandora.controls'); ?> diff --git a/pandora_console/godmode/massive/massive_operations.php b/pandora_console/godmode/massive/massive_operations.php index 276ab4c478..d8e9335137 100755 --- a/pandora_console/godmode/massive/massive_operations.php +++ b/pandora_console/godmode/massive/massive_operations.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,216 +11,249 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access massive operation section"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access massive operation section' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_agents.php'); -require_once ('include/functions_alerts.php'); -require_once ('include/functions_modules.php'); +require_once 'include/functions_agents.php'; +require_once 'include/functions_alerts.php'; +require_once 'include/functions_modules.php'; -enterprise_include ('godmode/massive/massive_operations.php'); +enterprise_include('godmode/massive/massive_operations.php'); -$tab = (string) get_parameter ('tab', 'massive_agents'); -$option = (string) get_parameter ('option', ''); +$tab = (string) get_parameter('tab', 'massive_agents'); +$option = (string) get_parameter('option', ''); -$options_alerts = array( - 'add_alerts' => __('Bulk alert add'), - 'delete_alerts' => __('Bulk alert delete'), - 'add_action_alerts' => __('Bulk alert actions add'), - 'delete_action_alerts' => __('Bulk alert actions delete'), - 'enable_disable_alerts' => __('Bulk alert enable/disable'), - 'standby_alerts' => __('Bulk alert setting standby')); -$options_agents = array( - 'edit_agents' => __('Bulk agent edit'), - 'delete_agents' => __('Bulk agent delete')); +$options_alerts = [ + 'add_alerts' => __('Bulk alert add'), + 'delete_alerts' => __('Bulk alert delete'), + 'add_action_alerts' => __('Bulk alert actions add'), + 'delete_action_alerts' => __('Bulk alert actions delete'), + 'enable_disable_alerts' => __('Bulk alert enable/disable'), + 'standby_alerts' => __('Bulk alert setting standby'), +]; -if (check_acl ($config['id_user'], 0, "PM")) { - $options_users = array( - 'add_profiles' => __('Bulk profile add'), - 'delete_profiles' => __('Bulk profile delete')); -} -else { - $options_users = array(); +$options_agents = [ + 'edit_agents' => __('Bulk agent edit'), + 'delete_agents' => __('Bulk agent delete'), +]; + +if (check_acl($config['id_user'], 0, 'PM')) { + $options_users = [ + 'add_profiles' => __('Bulk profile add'), + 'delete_profiles' => __('Bulk profile delete'), + ]; +} else { + $options_users = []; } -$options_modules = array( - 'delete_modules' => __('Bulk module delete'), - 'edit_modules' => __('Bulk module edit'), - 'copy_modules' => __('Bulk module copy')); +$options_modules = [ + 'edit_modules' => __('Bulk module edit'), + 'copy_modules' => __('Bulk module copy'), + 'delete_modules' => __('Bulk module delete'), +]; -$options_plugins = array( - 'edit_plugins' => __('Bulk plugin edit') - ); +$options_plugins = [ + 'edit_plugins' => __('Bulk plugin edit'), +]; -if (! check_acl ($config['id_user'], 0, "AW")) { - unset($options_modules['edit_modules']); +if (! check_acl($config['id_user'], 0, 'AW')) { + unset($options_modules['edit_modules']); } -$options_policies = array(); +$options_policies = []; $policies_options = enterprise_hook('massive_policies_options'); if ($policies_options != ENTERPRISE_NOT_HOOK) { - $options_policies = - array_merge($options_policies, $policies_options); + $options_policies = array_merge($options_policies, $policies_options); } -$options_snmp = array(); +$options_snmp = []; $snmp_options = enterprise_hook('massive_snmp_options'); - +$snmp_options = array_reverse($snmp_options); if ($snmp_options != ENTERPRISE_NOT_HOOK) { - $options_snmp = - array_merge($options_snmp, $snmp_options); + $options_snmp = array_merge($options_snmp, $snmp_options); } -$options_satellite = array(); +$options_satellite = []; $satellite_options = enterprise_hook('massive_satellite_options'); if ($satellite_options != ENTERPRISE_NOT_HOOK) { - $options_satellite = - array_merge($options_satellite, $satellite_options); + $options_satellite = array_merge($options_satellite, $satellite_options); } if (in_array($option, array_keys($options_alerts))) { - $tab = 'massive_alerts'; -} -elseif (in_array($option, array_keys($options_agents))) { - $tab = 'massive_agents'; -} -elseif (in_array($option, array_keys($options_users))) { - $tab = 'massive_users'; -} -elseif (in_array($option, array_keys($options_modules))) { - $tab = 'massive_modules'; -} -elseif (in_array($option, array_keys($options_policies))) { - $tab = 'massive_policies'; -} -elseif (in_array($option, array_keys($options_snmp))) { - $tab = 'massive_snmp'; -} -elseif (in_array($option, array_keys($options_satellite))) { - $tab = 'massive_satellite'; -} -elseif (in_array($option, array_keys($options_plugins))) { - $tab = 'massive_plugins'; -} -else { - $option = ''; + $tab = 'massive_alerts'; +} else if (in_array($option, array_keys($options_agents))) { + $tab = 'massive_agents'; +} else if (in_array($option, array_keys($options_users))) { + $tab = 'massive_users'; +} else if (in_array($option, array_keys($options_modules))) { + $tab = 'massive_modules'; +} else if (in_array($option, array_keys($options_policies))) { + $tab = 'massive_policies'; +} else if (in_array($option, array_keys($options_snmp))) { + $tab = 'massive_snmp'; +} else if (in_array($option, array_keys($options_satellite))) { + $tab = 'massive_satellite'; +} else if (in_array($option, array_keys($options_plugins))) { + $tab = 'massive_plugins'; +} else { + $option = ''; } switch ($tab) { - case 'massive_alerts': - $options = $options_alerts; - break; - case 'massive_agents': - $options = $options_agents; - break; - case 'massive_modules': - $options = $options_modules; - break; - case 'massive_users': - $options = $options_users; - break; - case 'massive_policies': - $options = $options_policies; - break; - case 'massive_snmp': - $options = $options_snmp; - break; - case 'massive_satellite': - $options = $options_satellite; - break; - case 'massive_plugins': - $options = $options_plugins; - break; + case 'massive_alerts': + $options = $options_alerts; + break; + + case 'massive_agents': + $options = $options_agents; + break; + + case 'massive_modules': + $options = $options_modules; + break; + + case 'massive_users': + $options = $options_users; + break; + + case 'massive_policies': + $options = $options_policies; + break; + + case 'massive_snmp': + $options = $options_snmp; + break; + + case 'massive_satellite': + $options = $options_satellite; + break; + + case 'massive_plugins': + $options = $options_plugins; + break; } // Set the default option of the category if ($option == '') { - $option = array_shift(array_keys($options)); + $option = array_shift(array_keys($options)); } -$alertstab = array('text' => '' - . html_print_image ('images/op_alerts.png', true, - array ('title' => __('Alerts operations'))) - . '', 'active' => $tab == 'massive_alerts'); +$alertstab = [ + 'text' => ''.html_print_image( + 'images/op_alerts.png', + true, + ['title' => __('Alerts operations')] + ).'', 'active' => $tab == 'massive_alerts', +]; -$userstab = array('text' => '' - . html_print_image ('images/op_workspace.png', true, - array ('title' => __('Users operations'))) - . '', 'active' => $tab == 'massive_users'); +$userstab = [ + 'text' => ''.html_print_image( + 'images/op_workspace.png', + true, + ['title' => __('Users operations')] + ).'', 'active' => $tab == 'massive_users', +]; -$agentstab = array('text' => '' - . html_print_image ('images/bricks.png', true, - array ('title' => __('Agents operations'))) - . '', 'active' => $tab == 'massive_agents'); +$agentstab = [ + 'text' => ''.html_print_image( + 'images/bricks.png', + true, + ['title' => __('Agents operations')] + ).'', 'active' => $tab == 'massive_agents', +]; -$modulestab = array('text' => '' - . html_print_image ('images/brick.png', true, - array ('title' => __('Modules operations'))) - . '', 'active' => $tab == 'massive_modules'); +$modulestab = [ + 'text' => ''.html_print_image( + 'images/brick.png', + true, + ['title' => __('Modules operations')] + ).'', 'active' => $tab == 'massive_modules', +]; -$pluginstab = array('text' => '' - . html_print_image ('images/plugin.png', true, - array ('title' => __('Plugins operations'))) - . '', 'active' => $tab == 'massive_plugins'); +$pluginstab = [ + 'text' => ''.html_print_image( + 'images/plugin.png', + true, + ['title' => __('Plugins operations')] + ).'', 'active' => $tab == 'massive_plugins', +]; $policiestab = enterprise_hook('massive_policies_tab'); -if ($policiestab == ENTERPRISE_NOT_HOOK) - $policiestab = ""; +if ($policiestab == ENTERPRISE_NOT_HOOK) { + $policiestab = ''; +} $snmptab = enterprise_hook('massive_snmp_tab'); -if ($snmptab == ENTERPRISE_NOT_HOOK) - $snmptab = ""; - +if ($snmptab == ENTERPRISE_NOT_HOOK) { + $snmptab = ''; +} + $satellitetab = enterprise_hook('massive_satellite_tab'); -if ($satellitetab == ENTERPRISE_NOT_HOOK) - $satellitetab = ""; +if ($satellitetab == ENTERPRISE_NOT_HOOK) { + $satellitetab = ''; +} -$onheader = array(); +$onheader = []; $onheader['massive_agents'] = $agentstab; $onheader['massive_modules'] = $modulestab; $onheader['massive_plugins'] = $pluginstab; -if (check_acl ($config['id_user'], 0, "PM")) { - $onheader['user_agents'] = $userstab; +if (check_acl($config['id_user'], 0, 'PM')) { + $onheader['user_agents'] = $userstab; } + $onheader['massive_alerts'] = $alertstab; $onheader['policies'] = $policiestab; $onheader['snmp'] = $snmptab; $onheader['satellite'] = $satellitetab; -/* Hello there! :) +/* + Hello there! :) -We added some of what seems to be "buggy" messages to the openSource version recently. This is not to force open-source users to move to the enterprise version, this is just to inform people using Pandora FMS open source that it requires skilled people to maintain and keep it running smoothly without professional support. This does not imply open-source version is limited in any way. If you check the recently added code, it contains only warnings and messages, no limitations except one: we removed the option to add custom logo in header. In the Update Manager section, it warns about the 'danger’ of applying automated updates without a proper backup, remembering in the process that the Enterprise version comes with a human-tested package. Maintaining an OpenSource version with more than 500 agents is not so easy, that's why someone using a Pandora with 8000 agents should consider asking for support. It's not a joke, we know of many setups with a huge number of agents, and we hate to hear that “its becoming unstable and slow” :( + We added some of what seems to be "buggy" messages to the openSource version recently. This is not to force open-source users to move to the enterprise version, this is just to inform people using Pandora FMS open source that it requires skilled people to maintain and keep it running smoothly without professional support. This does not imply open-source version is limited in any way. If you check the recently added code, it contains only warnings and messages, no limitations except one: we removed the option to add custom logo in header. In the Update Manager section, it warns about the 'danger’ of applying automated updates without a proper backup, remembering in the process that the Enterprise version comes with a human-tested package. Maintaining an OpenSource version with more than 500 agents is not so easy, that's why someone using a Pandora with 8000 agents should consider asking for support. It's not a joke, we know of many setups with a huge number of agents, and we hate to hear that “its becoming unstable and slow” :( -You can of course remove the warnings, that's why we include the source and do not use any kind of trick. And that's why we added here this comment, to let you know this does not reflect any change in our opensource mentality of does the last 14 years. + You can of course remove the warnings, that's why we include the source and do not use any kind of trick. And that's why we added here this comment, to let you know this does not reflect any change in our opensource mentality of does the last 14 years. */ ui_print_page_header( - __('Bulk operations') . ' » '. $options[$option], - "images/gm_massive_operations.png", false, "", true, $onheader,true, "massivemodal"); + __('Bulk operations').' » '.$options[$option], + 'images/gm_massive_operations.png', + false, + '', + true, + $onheader, + true, + 'massivemodal' +); // Checks if the PHP configuration is correctly -if ((get_cfg_var("max_execution_time") != 0) - or (get_cfg_var("max_input_time") != -1)) { - - echo '
    '; - echo __("In order to perform massive operations, PHP needs a correct configuration in timeout parameters. Please, open your PHP configuration file (php.ini) for example: sudo vi /etc/php5/apache2/php.ini;
    And set your timeout parameters to a correct value:
    max_execution_time = 0 and max_input_time = -1"); - echo '
    '; +if ((get_cfg_var('max_execution_time') != 0) + or (get_cfg_var('max_input_time') != -1) +) { + echo '
    '; + echo __('In order to perform massive operations, PHP needs a correct configuration in timeout parameters. Please, open your PHP configuration file (php.ini) for example: sudo vi /etc/php5/apache2/php.ini;
    And set your timeout parameters to a correct value:
    max_execution_time = 0 and max_input_time = -1'); + echo '
    '; +} + +if ($tab == 'massive_policies' && is_central_policies_on_node()) { + ui_print_warning_message(__('This node is configured with centralized mode. All policies information is read only. Go to metaconsole to manage it.')); + return; } // Catch all submit operations in this view to display Wait banner @@ -235,96 +267,120 @@ $submit_template_standby = get_parameter('id_alert_template_standby'); $submit_add = get_parameter('crtbutton'); echo '
    '; -echo html_print_image("images/wait.gif", true, array("border" => '0')) . '
    '; -echo '' . __('Please wait...') . ''; +echo html_print_image('images/wait.gif', true, ['border' => '0']).'
    '; +echo ''.__('Please wait...').''; echo '
    '; ?> "; +echo '
    '; echo '
    '; echo '
    '; -echo __("Action"); +echo __('Action'); echo ''; -html_print_select($options, 'option', $option, 'this.form.submit()', '', - 0, false, false, false); -if ($option == 'edit_agents' || $option == 'edit_modules') - ui_print_help_tip(__("The blank fields will not be updated")); +html_print_select( + $options, + 'option', + $option, + 'this.form.submit()', + '', + 0, + false, + false, + false +); +if ($option == 'edit_agents' || $option == 'edit_modules') { + ui_print_help_tip(__('The blank fields will not be updated')); +} + echo '
    '; echo '
    '; -echo "
    "; +echo '
    '; switch ($option) { - case 'delete_alerts': - require_once ('godmode/massive/massive_delete_alerts.php'); - break; - case 'add_alerts': - require_once ('godmode/massive/massive_add_alerts.php'); - break; - case 'delete_action_alerts': - require_once ('godmode/massive/massive_delete_action_alerts.php'); - break; - case 'add_action_alerts': - require_once ('godmode/massive/massive_add_action_alerts.php'); - break; - case 'enable_disable_alerts': - require_once ('godmode/massive/massive_enable_disable_alerts.php'); - break; - case 'standby_alerts': - require_once ('godmode/massive/massive_standby_alerts.php'); - break; - case 'add_profiles': - require_once ('godmode/massive/massive_add_profiles.php'); - break; - case 'delete_profiles': - require_once ('godmode/massive/massive_delete_profiles.php'); - break; - case 'delete_agents': - require_once ('godmode/massive/massive_delete_agents.php'); - break; - case 'edit_agents': - require_once ('godmode/massive/massive_edit_agents.php'); - break; - case 'delete_modules': - require_once ('godmode/massive/massive_delete_modules.php'); - break; - case 'edit_modules': - require_once ('godmode/massive/massive_edit_modules.php'); - break; - case 'copy_modules': - require_once ('godmode/massive/massive_copy_modules.php'); - break; - case 'edit_plugins': - require_once ('godmode/massive/massive_edit_plugins.php'); - break; - default: - if (!enterprise_hook('massive_operations', array($option))) { - require_once ('godmode/massive/massive_config.php'); - } - break; + case 'delete_alerts': + include_once 'godmode/massive/massive_delete_alerts.php'; + break; + + case 'add_alerts': + include_once 'godmode/massive/massive_add_alerts.php'; + break; + + case 'delete_action_alerts': + include_once 'godmode/massive/massive_delete_action_alerts.php'; + break; + + case 'add_action_alerts': + include_once 'godmode/massive/massive_add_action_alerts.php'; + break; + + case 'enable_disable_alerts': + include_once 'godmode/massive/massive_enable_disable_alerts.php'; + break; + + case 'standby_alerts': + include_once 'godmode/massive/massive_standby_alerts.php'; + break; + + case 'add_profiles': + include_once 'godmode/massive/massive_add_profiles.php'; + break; + + case 'delete_profiles': + include_once 'godmode/massive/massive_delete_profiles.php'; + break; + + case 'delete_agents': + include_once 'godmode/massive/massive_delete_agents.php'; + break; + + case 'edit_agents': + include_once 'godmode/massive/massive_edit_agents.php'; + break; + + case 'delete_modules': + include_once 'godmode/massive/massive_delete_modules.php'; + break; + + case 'edit_modules': + include_once 'godmode/massive/massive_edit_modules.php'; + break; + + case 'copy_modules': + include_once 'godmode/massive/massive_copy_modules.php'; + break; + + case 'edit_plugins': + include_once 'godmode/massive/massive_edit_plugins.php'; + break; + + default: + if (!enterprise_hook('massive_operations', [$option])) { + include_once 'godmode/massive/massive_config.php'; + } + break; } -?> diff --git a/pandora_console/godmode/massive/massive_standby_alerts.php b/pandora_console/godmode/massive/massive_standby_alerts.php index 496e72707c..7379f4c931 100644 --- a/pandora_console/godmode/massive/massive_standby_alerts.php +++ b/pandora_console/godmode/massive/massive_standby_alerts.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,310 +11,370 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access massive alert deletion"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access massive alert deletion' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_agents.php'); -require_once ('include/functions_alerts.php'); -require_once ('include/functions_users.php'); +require_once 'include/functions_agents.php'; +require_once 'include/functions_alerts.php'; +require_once 'include/functions_users.php'; -if (is_ajax ()) { - $get_alerts = (bool) get_parameter ('get_alerts'); - - if ($get_alerts) { - $id_agents = get_parameter ('id_agents'); - $get_templates = (bool) get_parameter ('get_templates'); +if (is_ajax()) { + $get_alerts = (bool) get_parameter('get_alerts'); - if ($get_templates) { - if (!is_array($id_agents)) { - echo json_encode (''); - return; - } - $alert_templates = agents_get_alerts_simple ($id_agents); - echo json_encode (index_array ($alert_templates, 'id_alert_template', 'template_name')); - return; - } - else { - $id_alert_templates = (array) get_parameter ('id_alert_templates'); - $standby = (int) get_parameter ('standby'); + if ($get_alerts) { + $id_agents = get_parameter('id_agents'); + $get_templates = (bool) get_parameter('get_templates'); - $agents_alerts = alerts_get_agents_with_alert_template ($id_alert_templates, false, - array('order' => 'tagente.alias, talert_template_modules.standby', 'talert_template_modules.standby' => $standby), - array ('CONCAT(tagente.alias, " - ", tagente_modulo.nombre) as agent_agentmodule_name', - 'talert_template_modules.id as template_module_id'), $id_agents); + if ($get_templates) { + if (!is_array($id_agents)) { + echo json_encode(''); + return; + } - echo json_encode (index_array ($agents_alerts, 'template_module_id', 'agent_agentmodule_name')); - return; - } - } - return; + $alert_templates = agents_get_alerts_simple($id_agents); + echo json_encode(index_array($alert_templates, 'id_alert_template', 'template_name')); + return; + } else { + $id_alert_templates = (array) get_parameter('id_alert_templates'); + $standby = (int) get_parameter('standby'); + + $agents_alerts = alerts_get_agents_with_alert_template( + $id_alert_templates, + false, + [ + 'order' => 'tagente.alias, talert_template_modules.standby', + 'talert_template_modules.standby' => $standby, + ], + [ + 'CONCAT(tagente.alias, " - ", tagente_modulo.nombre) as agent_agentmodule_name', + 'talert_template_modules.id as template_module_id', + ], + $id_agents + ); + + echo json_encode(index_array($agents_alerts, 'template_module_id', 'agent_agentmodule_name')); + return; + } + } + + return; } -$id_group = (int) get_parameter ('id_group'); -$id_agents = (array) get_parameter ('id_agents'); -$action = (string) get_parameter ('action', ''); -$recursion = get_parameter ('recursion'); +$id_group = (int) get_parameter('id_group'); +$id_agents = (array) get_parameter('id_agents'); +$action = (string) get_parameter('action', ''); +$recursion = get_parameter('recursion'); $result = false; -switch($action) { - case 'set_off_standby_alerts': - $id_alert_templates = (int) get_parameter ('id_alert_template_standby', 0); - $id_standby_alerts = get_parameter_post ('id_standby_alerts', array()); - foreach($id_standby_alerts as $id_alert) { - $result = alerts_agent_module_standby ($id_alert, false); - } - - ui_print_result_message ($result, __('Successfully set off standby'), __('Could not be set off standby')); - - $info = '{"Alert":"'.implode(",",$id_standby_alerts).'"}'; - if ($result) { - db_pandora_audit("Massive management", "Set off standby alerts", false, false, $info); - } - else { - db_pandora_audit("Massive management", "Fail try to set off standby alerts", false, false, $info); - } - break; - case 'set_standby_alerts': - $id_alert_templates = (int) get_parameter ('id_alert_template_standby', 0); - $id_not_standby_alerts = get_parameter_post ('id_not_standby_alerts', array()); - - foreach($id_not_standby_alerts as $id_alert) { - $result = alerts_agent_module_standby ($id_alert, true); - } - - ui_print_result_message ($result, __('Successfully set standby'), __('Could not be set standby')); - - $info = '{"Alert":"'.implode(",",$id_not_standby_alerts).'"}'; - if ($result) { - db_pandora_audit("Massive management", "Set on standby alerts", false, false, $info); - } - else { - db_pandora_audit("Massive management", "Fail try to set on standby alerts", false, false, $info); - } - break; - default: - $id_alert_templates = (int) get_parameter ('id_alert_template', 0); - break; +switch ($action) { + case 'set_off_standby_alerts': + $id_alert_templates = (int) get_parameter('id_alert_template_standby', 0); + $id_standby_alerts = get_parameter_post('id_standby_alerts', []); + foreach ($id_standby_alerts as $id_alert) { + $result = alerts_agent_module_standby($id_alert, false); + } + + ui_print_result_message($result, __('Successfully set off standby'), __('Could not be set off standby')); + + $info = '{"Alert":"'.implode(',', $id_standby_alerts).'"}'; + if ($result) { + db_pandora_audit('Massive management', 'Set off standby alerts', false, false, $info); + } else { + db_pandora_audit('Massive management', 'Fail try to set off standby alerts', false, false, $info); + } + break; + + case 'set_standby_alerts': + $id_alert_templates = (int) get_parameter('id_alert_template_standby', 0); + $id_not_standby_alerts = get_parameter_post('id_not_standby_alerts', []); + + foreach ($id_not_standby_alerts as $id_alert) { + $result = alerts_agent_module_standby($id_alert, true); + } + + ui_print_result_message($result, __('Successfully set standby'), __('Could not be set standby')); + + $info = '{"Alert":"'.implode(',', $id_not_standby_alerts).'"}'; + if ($result) { + db_pandora_audit('Massive management', 'Set on standby alerts', false, false, $info); + } else { + db_pandora_audit('Massive management', 'Fail try to set on standby alerts', false, false, $info); + } + break; + + default: + $id_alert_templates = (int) get_parameter('id_alert_template', 0); + break; } -$groups = users_get_groups (); +$groups = users_get_groups(); $own_info = get_user_info($config['id_user']); -if (!$own_info['is_admin'] && !check_acl ($config['id_user'], 0, "AW")) - $return_all_group = false; -else - $return_all_group = true; +if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'AW')) { + $return_all_group = false; +} else { + $return_all_group = true; +} $table->id = 'delete_table'; $table->class = 'databox filters'; $table->width = '100%'; -$table->data = array (); -$table->style = array (); +$table->data = []; +$table->style = []; $table->style[0] = 'font-weight: bold; vertical-align:top'; $table->style[2] = 'font-weight: bold'; -$table->size = array (); +$table->size = []; $table->size[0] = '15%'; $table->size[1] = '55%'; $table->size[2] = '15%'; $table->size[3] = '15%'; -$table->data = array (); +$table->data = []; -$templates = alerts_get_alert_templates (false, array ('id', 'name')); +$templates = alerts_get_alert_templates(false, ['id', 'name']); $table->data[0][0] = '
    '; $table->data[0][0] .= html_print_input_hidden('id_alert_template_not_standby', $id_alert_templates, true); $table->data[0][0] .= __('Group'); -$table->data[0][1] = html_print_select_groups(false, "AW", $return_all_group, - 'id_group', $id_group, '', '', '', true, false, true, ''); +$table->data[0][1] = html_print_select_groups( + false, + 'AW', + $return_all_group, + 'id_group', + $id_group, + '', + '', + '', + true, + false, + true, + '' +); $table->data[0][2] = __('Group recursion'); -$table->data[0][3] = html_print_checkbox ("recursion", 1, $recursion, true, false); +$table->data[0][3] = html_print_checkbox('recursion', 1, $recursion, true, false); $table->data[1][0] = __('Agents'); $table->data[1][0] .= ''; -$table->data[1][1] = html_print_select (agents_get_group_agents (array_keys (users_get_groups ($config["id_user"], "AW", false))), - 'id_agents[]', 0, false, '', '', true, true); +$table->data[1][1] = html_print_select( + agents_get_group_agents(array_keys(users_get_groups($config['id_user'], 'AW', false))), + 'id_agents[]', + 0, + false, + '', + '', + true, + true +); $table->data[2][0] = __('Alert template'); $table->data[2][0] .= ''; -$table->data[2][1] = html_print_select ('', 'id_alert_templates[]', '', '', '', '', true, true, true, '', true); +$table->data[2][1] = html_print_select('', 'id_alert_templates[]', '', '', '', '', true, true, true, '', true); -$table->data[3][0] = __('Not standby alerts').ui_print_help_tip(__('Format').":
    ".__('Agent')." - ".__('Module'), true); +$table->data[3][0] = __('Not standby alerts').ui_print_help_tip(__('Format').':
    '.__('Agent').' - '.__('Module'), true); $table->data[3][0] .= ''; -$agents_alerts = alerts_get_agents_with_alert_template ($id_alert_templates, $id_group, - false, array ('tagente.alias', 'tagente.id_agente')); -$table->data[3][1] = html_print_select (index_array ($agents_alerts, 'id_agente', 'alias'), - 'id_not_standby_alerts[]', '', '', '', '', true, true, true, '', $id_alert_templates == 0); +$agents_alerts = alerts_get_agents_with_alert_template( + $id_alert_templates, + $id_group, + false, + [ + 'tagente.alias', + 'tagente.id_agente', + ] +); +$table->data[3][1] = html_print_select( + index_array($agents_alerts, 'id_agente', 'alias'), + 'id_not_standby_alerts[]', + '', + '', + '', + '', + true, + true, + true, + '', + $id_alert_templates == 0 +); $table->data[4][0] = __('Action'); -$table->data[4][1] = "
    ".html_print_input_image ('standby_alerts', 'images/darrowdown.png', 1, 'margin-left: 150px;', true, array ('title' => __('Set standby selected alerts'))).""; +$table->data[4][1] = "
    ".html_print_input_image('standby_alerts', 'images/darrowdown.png', 1, 'margin-left: 150px;', true, ['title' => __('Set standby selected alerts')]).''; $table->data[4][1] .= ''; $table->data[4][1] .= '
    '; $table->data[4][1] .= html_print_input_hidden('id_alert_template_standby', $id_alert_templates, true); -$table->data[4][1] .= html_print_input_image ('set_off_standby_alerts', 'images/darrowup.png', 1, 'margin-left: 200px;', true, array ('title' => __('Set standby selected alerts')))."
    "; +$table->data[4][1] .= html_print_input_image('set_off_standby_alerts', 'images/darrowup.png', 1, 'margin-left: 200px;', true, ['title' => __('Set standby selected alerts')]).'
    '; -$table->data[5][0] = __('Standby alerts').ui_print_help_tip(__('Format').":
    ".__('Agent')." - ".__('Module'), true); +$table->data[5][0] = __('Standby alerts').ui_print_help_tip(__('Format').':
    '.__('Agent').' - '.__('Module'), true); $table->data[5][0] .= ''; -$table->data[5][1] = html_print_select (index_array ($agents_alerts, 'id_agente2', 'alias'), - 'id_standby_alerts[]', '', '', '', '', true, true, true, '', $id_alert_templates == 0); +$table->data[5][1] = html_print_select( + index_array($agents_alerts, 'id_agente2', 'alias'), + 'id_standby_alerts[]', + '', + '', + '', + '', + true, + true, + true, + '', + $id_alert_templates == 0 +); $table->data[5][1] .= ''; -html_print_table ($table); +html_print_table($table); echo ''; -ui_require_jquery_file ('form'); -ui_require_jquery_file ('pandora.controls'); +ui_require_jquery_file('form'); +ui_require_jquery_file('pandora.controls'); ?> diff --git a/pandora_console/godmode/menu.php b/pandora_console/godmode/menu.php index 71fac6bf03..69ec49cfce 100644 --- a/pandora_console/godmode/menu.php +++ b/pandora_console/godmode/menu.php @@ -4,474 +4,463 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +require_once 'include/config.php'; -require_once ('include/config.php'); +check_login(); -check_login (); +enterprise_include('godmode/menu.php'); +require_once 'include/functions_menu.php'; -enterprise_include ('godmode/menu.php'); -require_once ('include/functions_menu.php'); - -$menu_godmode = array (); +$menu_godmode = []; $menu_godmode['class'] = 'godmode'; -$sub = array (); -if (check_acl ($config['id_user'], 0, "AW") || check_acl ($config['id_user'], 0, "AD")) { - $sub['godmode/agentes/modificar_agente']['text'] = __('Manage agents'); - $sub['godmode/agentes/modificar_agente']['id'] = 'Manage agents'; - $sub["godmode/agentes/modificar_agente"]["subsecs"] = array( - "godmode/agentes/configurar_agente"); +$sub = []; +if (check_acl($config['id_user'], 0, 'AW') || check_acl($config['id_user'], 0, 'AD')) { + $sub['godmode/agentes/modificar_agente']['text'] = __('Manage agents'); + $sub['godmode/agentes/modificar_agente']['id'] = 'Manage agents'; + $sub['godmode/agentes/modificar_agente']['subsecs'] = ['godmode/agentes/configurar_agente']; } -if (check_acl ($config["id_user"], 0, "PM")) { - $sub["godmode/agentes/fields_manager"]["text"] = __('Custom fields'); - $sub["godmode/agentes/fields_manager"]["id"] = 'Custom fields'; - - $sub["godmode/modules/manage_nc_groups"]["text"] = __('Component groups'); - $sub["godmode/modules/manage_nc_groups"]["id"] = 'Component groups'; - // Category - $sub["godmode/category/category"]["text"] = __('Module categories'); - $sub["godmode/category/category"]["id"] = 'Module categories'; - $sub["godmode/category/category"]["subsecs"] = "godmode/category/edit_category"; - - $sub["godmode/modules/module_list"]["text"] = __('Module types'); - $sub["godmode/modules/module_list"]["id"] = 'Module types'; - - $sub["godmode/groups/modu_group_list"]["text"] = __('Module groups'); - $sub["godmode/groups/modu_group_list"]["id"] = 'Module groups'; +if (check_acl($config['id_user'], 0, 'PM')) { + $sub['godmode/agentes/fields_manager']['text'] = __('Custom fields'); + $sub['godmode/agentes/fields_manager']['id'] = 'Custom fields'; + + $sub['godmode/modules/manage_nc_groups']['text'] = __('Component groups'); + $sub['godmode/modules/manage_nc_groups']['id'] = 'Component groups'; + // Category + $sub['godmode/category/category']['text'] = __('Module categories'); + $sub['godmode/category/category']['id'] = 'Module categories'; + $sub['godmode/category/category']['subsecs'] = 'godmode/category/edit_category'; + + $sub['godmode/modules/module_list']['text'] = __('Module types'); + $sub['godmode/modules/module_list']['id'] = 'Module types'; + + $sub['godmode/groups/modu_group_list']['text'] = __('Module groups'); + $sub['godmode/groups/modu_group_list']['id'] = 'Module groups'; } -if (check_acl ($config['id_user'], 0, "AW")) { - //Netflow - if ($config['activate_netflow']) { - $sub["godmode/netflow/nf_edit"]["text"] = __('Netflow filters'); - $sub["godmode/netflow/nf_edit"]["id"] = 'Netflow filters'; - } +if (check_acl($config['id_user'], 0, 'AW')) { + // Netflow + if ($config['activate_netflow']) { + $sub['godmode/netflow/nf_edit']['text'] = __('Netflow filters'); + $sub['godmode/netflow/nf_edit']['id'] = 'Netflow filters'; + } } if (!empty($sub)) { - $menu_godmode["gagente"]["text"] = __('Resources'); - $menu_godmode["gagente"]["sec2"] = "godmode/agentes/modificar_agente"; - $menu_godmode["gagente"]["id"] = "god-resources"; - $menu_godmode["gagente"]["sub"] = $sub; + $menu_godmode['gagente']['text'] = __('Resources'); + $menu_godmode['gagente']['sec2'] = 'godmode/agentes/modificar_agente'; + $menu_godmode['gagente']['id'] = 'god-resources'; + $menu_godmode['gagente']['sub'] = $sub; } -$sub = array (); -if (check_acl ($config['id_user'], 0, "AW")) { - $sub["godmode/groups/group_list"]["text"] = __('Manage agents groups'); - $sub["godmode/groups/group_list"]["id"] = 'Manage agents groups'; +$sub = []; +if (check_acl($config['id_user'], 0, 'AW')) { + $sub['godmode/groups/group_list']['text'] = __('Manage agents groups'); + $sub['godmode/groups/group_list']['id'] = 'Manage agents groups'; } -if (check_acl ($config['id_user'], 0, "PM")) { - // Tag - $sub["godmode/tag/tag"]["text"] = __('Module tags'); - $sub["godmode/tag/tag"]["id"] = 'Module tags'; - $sub["godmode/tag/tag"]["subsecs"] = "godmode/tag/edit_tag"; +if (check_acl($config['id_user'], 0, 'PM')) { + // Tag + $sub['godmode/tag/tag']['text'] = __('Module tags'); + $sub['godmode/tag/tag']['id'] = 'Module tags'; + $sub['godmode/tag/tag']['subsecs'] = 'godmode/tag/edit_tag'; - enterprise_hook ('enterprise_acl_submenu'); + enterprise_hook('enterprise_acl_submenu'); } -if (check_acl ($config['id_user'], 0, "UM")) { - $sub['godmode/users/user_list']['text'] = __('Users management'); - $sub['godmode/users/user_list']['id'] = 'Users management'; - $sub['godmode/users/profile_list']['text'] = __('Profile management'); - $sub['godmode/users/profile_list']['id'] = 'Profile management'; + +if (check_acl($config['id_user'], 0, 'UM')) { + $sub['godmode/users/user_list']['text'] = __('Users management'); + $sub['godmode/users/user_list']['id'] = 'Users management'; + $sub['godmode/users/profile_list']['text'] = __('Profile management'); + $sub['godmode/users/profile_list']['id'] = 'Profile management'; } if (!empty($sub)) { - $menu_godmode["gusuarios"]["sub"] = $sub; - $menu_godmode["gusuarios"]["text"] = __('Profiles'); - $menu_godmode["gusuarios"]["sec2"] = "godmode/users/user_list"; - $menu_godmode["gusuarios"]["id"] = "god-users"; + $menu_godmode['gusuarios']['sub'] = $sub; + $menu_godmode['gusuarios']['text'] = __('Profiles'); + $menu_godmode['gusuarios']['sec2'] = 'godmode/users/user_list'; + $menu_godmode['gusuarios']['id'] = 'god-users'; } -$sub = array (); -if (check_acl ($config['id_user'], 0, "PM")) { - $sub["godmode/modules/manage_network_components"]["text"] = __('Network components'); - $sub["godmode/modules/manage_network_components"]["id"] = 'Network components'; - enterprise_hook ('components_submenu'); - $sub["godmode/modules/manage_network_templates"]["text"] = __('Module templates'); - $sub["godmode/modules/manage_network_templates"]["id"] = 'Module templates'; - enterprise_hook ('inventory_submenu'); - enterprise_hook ('autoconfiguration_menu'); +$sub = []; +if (check_acl($config['id_user'], 0, 'PM')) { + $sub['godmode/modules/manage_network_components']['text'] = __('Network components'); + $sub['godmode/modules/manage_network_components']['id'] = 'Network components'; + enterprise_hook('components_submenu'); + $sub['godmode/modules/manage_network_templates']['text'] = __('Module templates'); + $sub['godmode/modules/manage_network_templates']['id'] = 'Module templates'; + enterprise_hook('inventory_submenu'); + enterprise_hook('autoconfiguration_menu'); } -if (check_acl ($config['id_user'], 0, "AW")) { - enterprise_hook ('policies_menu'); - enterprise_hook('agents_submenu'); -} -if (check_acl ($config['id_user'], 0, "AW")) { - $sub["gmassive"]["text"] = __('Bulk operations'); - $sub["gmassive"]["id"] = 'Bulk operations'; - $sub["gmassive"]["type"] = "direct"; - $sub["gmassive"]["subtype"] = "nolink"; - $sub2 = array (); - $sub2["godmode/massive/massive_operations&tab=massive_agents"]["text"] = __('Agents operations'); - $sub2["godmode/massive/massive_operations&tab=massive_modules"]["text"] = __('Modules operations'); - $sub2["godmode/massive/massive_operations&tab=massive_plugins"]["text"] = __('Plugins operations'); - if (check_acl ($config['id_user'], 0, "PM")) { - $sub2["godmode/massive/massive_operations&tab=massive_users"]["text"] = __('Users operations'); - } - $sub2["godmode/massive/massive_operations&tab=massive_alerts"]["text"] = __('Alerts operations'); - if ($config["centralized_management"] != 1) { - enterprise_hook('massivepolicies_submenu'); - } - enterprise_hook('massivesnmp_submenu'); - enterprise_hook('massivesatellite_submenu'); - $sub["gmassive"]["sub2"] = $sub2; +if (check_acl($config['id_user'], 0, 'AW')) { + enterprise_hook('policies_menu'); + enterprise_hook('agents_submenu'); +} + +if (check_acl($config['id_user'], 0, 'AW')) { + $sub['gmassive']['text'] = __('Bulk operations'); + $sub['gmassive']['id'] = 'Bulk operations'; + $sub['gmassive']['type'] = 'direct'; + $sub['gmassive']['subtype'] = 'nolink'; + $sub2 = []; + $sub2['godmode/massive/massive_operations&tab=massive_agents']['text'] = __('Agents operations'); + $sub2['godmode/massive/massive_operations&tab=massive_modules']['text'] = __('Modules operations'); + $sub2['godmode/massive/massive_operations&tab=massive_plugins']['text'] = __('Plugins operations'); + if (check_acl($config['id_user'], 0, 'PM')) { + $sub2['godmode/massive/massive_operations&tab=massive_users']['text'] = __('Users operations'); + } + + $sub2['godmode/massive/massive_operations&tab=massive_alerts']['text'] = __('Alerts operations'); + enterprise_hook('massivepolicies_submenu'); + enterprise_hook('massivesnmp_submenu'); + enterprise_hook('massivesatellite_submenu'); + + $sub['gmassive']['sub2'] = $sub2; } if (!empty($sub)) { - $menu_godmode["gmodules"]["text"] = __('Configuration'); - $menu_godmode["gmodules"]["sec2"] = "godmode/modules/manage_network_templates"; - $menu_godmode["gmodules"]["id"] = "god-configuration"; - $menu_godmode["gmodules"]["sub"] = $sub; + $menu_godmode['gmodules']['text'] = __('Configuration'); + $menu_godmode['gmodules']['sec2'] = 'godmode/modules/manage_network_templates'; + $menu_godmode['gmodules']['id'] = 'god-configuration'; + $menu_godmode['gmodules']['sub'] = $sub; } -if (check_acl ($config['id_user'], 0, "LW") || - check_acl ($config['id_user'], 0, "LM") || - check_acl ($config['id_user'], 0, "AD")) { - $menu_godmode["galertas"]["text"] = __('Alerts'); - $menu_godmode["galertas"]["sec2"] = "godmode/alerts/alert_list"; - $menu_godmode["galertas"]["id"] = "god-alerts"; - - $sub = array (); - $sub["godmode/alerts/alert_list"]["text"] = __('List of Alerts'); - $sub["godmode/alerts/alert_list"]["id"] = 'List of Alerts'; - $sub["godmode/alerts/alert_list"]["pages"] = - array("godmode/alerts/alert_view"); - - if (check_acl ($config['id_user'], 0, "LM")) { - $sub["godmode/alerts/alert_templates"]["text"] = __('Templates'); - $sub["godmode/alerts/alert_templates"]["id"] = 'Templates'; - $sub["godmode/alerts/alert_templates"]["pages"] = - array("godmode/alerts/configure_alert_template"); - - $sub["godmode/alerts/alert_actions"]["text"] = __('Actions'); - $sub["godmode/alerts/alert_actions"]["id"] = 'Actions'; - $sub["godmode/alerts/alert_actions"]["pages"] = - array("godmode/alerts/configure_alert_action"); - $sub["godmode/alerts/alert_commands"]["text"] = __('Commands'); - $sub["godmode/alerts/alert_commands"]["id"] = 'Commands'; - $sub["godmode/alerts/alert_commands"]["pages"] = - array("godmode/alerts/configure_alert_command"); - $sub["godmode/alerts/alert_special_days"]["text"] = __('Special days list'); - $sub["godmode/alerts/alert_special_days"]["id"] = __('Special days list'); - $sub["godmode/alerts/alert_special_days"]["pages"] = - array("godmode/alerts/configure_alert_special_days"); - - enterprise_hook('eventalerts_submenu'); - $sub["godmode/snmpconsole/snmp_alert"]["text"] = __("SNMP alerts"); - $sub["godmode/snmpconsole/snmp_alert"]["id"] = "SNMP alerts"; - } - $menu_godmode["galertas"]["sub"] = $sub; +if (check_acl($config['id_user'], 0, 'LW') + || check_acl($config['id_user'], 0, 'LM') + || check_acl($config['id_user'], 0, 'AD') +) { + $menu_godmode['galertas']['text'] = __('Alerts'); + $menu_godmode['galertas']['sec2'] = 'godmode/alerts/alert_list'; + $menu_godmode['galertas']['id'] = 'god-alerts'; + + $sub = []; + $sub['godmode/alerts/alert_list']['text'] = __('List of Alerts'); + $sub['godmode/alerts/alert_list']['id'] = 'List of Alerts'; + $sub['godmode/alerts/alert_list']['pages'] = ['godmode/alerts/alert_view']; + + if (check_acl($config['id_user'], 0, 'LM')) { + $sub['godmode/alerts/alert_templates']['text'] = __('Templates'); + $sub['godmode/alerts/alert_templates']['id'] = 'Templates'; + $sub['godmode/alerts/alert_templates']['pages'] = ['godmode/alerts/configure_alert_template']; + + $sub['godmode/alerts/alert_actions']['text'] = __('Actions'); + $sub['godmode/alerts/alert_actions']['id'] = 'Actions'; + $sub['godmode/alerts/alert_actions']['pages'] = ['godmode/alerts/configure_alert_action']; + $sub['godmode/alerts/alert_commands']['text'] = __('Commands'); + $sub['godmode/alerts/alert_commands']['id'] = 'Commands'; + $sub['godmode/alerts/alert_commands']['pages'] = ['godmode/alerts/configure_alert_command']; + $sub['godmode/alerts/alert_special_days']['text'] = __('Special days list'); + $sub['godmode/alerts/alert_special_days']['id'] = __('Special days list'); + $sub['godmode/alerts/alert_special_days']['pages'] = ['godmode/alerts/configure_alert_special_days']; + + enterprise_hook('eventalerts_submenu'); + $sub['godmode/snmpconsole/snmp_alert']['text'] = __('SNMP alerts'); + $sub['godmode/snmpconsole/snmp_alert']['id'] = 'SNMP alerts'; + } + + $menu_godmode['galertas']['sub'] = $sub; } // Manage events -$sub = array (); -if (check_acl ($config['id_user'], 0, "EW") || check_acl ($config['id_user'], 0, "EM")) { - // Custom event fields - $sub["godmode/events/events&section=filter"]["text"] = __('Event filters'); - $sub["godmode/events/events&section=filter"]["id"] = 'Event filters'; +$sub = []; +if (check_acl($config['id_user'], 0, 'EW') || check_acl($config['id_user'], 0, 'EM')) { + // Custom event fields + $sub['godmode/events/events&section=filter']['text'] = __('Event filters'); + $sub['godmode/events/events&section=filter']['id'] = 'Event filters'; } -if (check_acl ($config['id_user'], 0, "PM")) { - $sub["godmode/events/events&section=fields"]["text"] = __('Custom events'); - $sub["godmode/events/events&section=fields"]["id"] = 'Custom events'; - $sub["godmode/events/events&section=responses"]["text"] = __('Event responses'); - $sub["godmode/events/events&section=responses"]["id"] = 'Event responses'; +if (check_acl($config['id_user'], 0, 'PM')) { + $sub['godmode/events/events&section=fields']['text'] = __('Custom events'); + $sub['godmode/events/events&section=fields']['id'] = 'Custom events'; + $sub['godmode/events/events&section=responses']['text'] = __('Event responses'); + $sub['godmode/events/events&section=responses']['id'] = 'Event responses'; } if (!empty($sub)) { - $menu_godmode["geventos"]["text"] = __('Events'); - $menu_godmode["geventos"]["sec2"] = "godmode/events/events&section=filter"; - $menu_godmode["geventos"]["id"] = "god-events"; - $menu_godmode["geventos"]["sub"] = $sub; + $menu_godmode['geventos']['text'] = __('Events'); + $menu_godmode['geventos']['sec2'] = 'godmode/events/events&section=filter'; + $menu_godmode['geventos']['id'] = 'god-events'; + $menu_godmode['geventos']['sub'] = $sub; } -if (check_acl ($config['id_user'], 0, "AW") || check_acl ($config['id_user'], 0, "PM") || check_acl ($config['id_user'], 0, "RR")) { - // Servers - $menu_godmode["gservers"]["text"] = __('Servers'); - $menu_godmode["gservers"]["sec2"] = "godmode/servers/modificar_server"; - $menu_godmode["gservers"]["id"] = "god-servers"; +if (check_acl($config['id_user'], 0, 'AW') || check_acl($config['id_user'], 0, 'PM') || check_acl($config['id_user'], 0, 'RR')) { + // Servers + $menu_godmode['gservers']['text'] = __('Servers'); + $menu_godmode['gservers']['sec2'] = 'godmode/servers/modificar_server'; + $menu_godmode['gservers']['id'] = 'god-servers'; - $sub = array (); - if (check_acl ($config['id_user'], 0, "AW")) { - $sub["godmode/servers/modificar_server"]["text"] = __('Manage servers'); - $sub["godmode/servers/modificar_server"]["id"] = 'Manage servers'; - } - //This subtabs are only for Pandora Admin - if (check_acl ($config['id_user'], 0, "PM")) { - - enterprise_hook('ha_cluster'); - - $sub["godmode/servers/manage_recontask"]["text"] = __('Recon task'); - $sub["godmode/servers/manage_recontask"]["id"] = 'Recon task'; - - $sub["godmode/servers/plugin"]["text"] = __('Plugins'); - $sub["godmode/servers/plugin"]["id"] = 'Plugins'; + $sub = []; + if (check_acl($config['id_user'], 0, 'AW')) { + $sub['godmode/servers/modificar_server']['text'] = __('Manage servers'); + $sub['godmode/servers/modificar_server']['id'] = 'Manage servers'; + } - $sub["godmode/servers/recon_script"]["text"] = __('Recon script'); - $sub["godmode/servers/recon_script"]["id"] = 'Recon script'; + // This subtabs are only for Pandora Admin + if (check_acl($config['id_user'], 0, 'PM')) { + enterprise_hook('ha_cluster'); - enterprise_hook('export_target_submenu'); + $sub['godmode/servers/manage_recontask']['text'] = __('Recon task'); + $sub['godmode/servers/manage_recontask']['id'] = 'Recon task'; - enterprise_hook('manage_satellite_submenu'); - } + $sub['godmode/servers/plugin']['text'] = __('Plugins'); + $sub['godmode/servers/plugin']['id'] = 'Plugins'; - $menu_godmode["gservers"]["sub"] = $sub; + $sub['godmode/servers/recon_script']['text'] = __('Recon script'); + $sub['godmode/servers/recon_script']['id'] = 'Recon script'; + + enterprise_hook('export_target_submenu'); + + enterprise_hook('manage_satellite_submenu'); + } + + $menu_godmode['gservers']['sub'] = $sub; } -if (check_acl ($config['id_user'], 0, "PM")) { - // Setup - $menu_godmode["gsetup"]["text"] = __('Setup'); - $menu_godmode["gsetup"]["sec2"] = "godmode/setup/setup§ion=general"; - $menu_godmode["gsetup"]["id"] = "god-setup"; - - $sub = array (); - - // Options Setup - $sub["general"]["text"] = __('Setup'); - $sub["general"]["id"] = 'Setup'; - $sub["general"]["type"] = "direct"; - $sub["general"]["subtype"] = "nolink"; - $sub2 = array (); - - $sub2["godmode/setup/setup&section=general"]["text"] = __('General Setup'); - $sub2["godmode/setup/setup&section=general"]["id"] = 'General Setup'; - $sub2["godmode/setup/setup&section=general"]["refr"] = 0; - - enterprise_hook ('password_submenu'); - enterprise_hook ('enterprise_submenu'); - enterprise_hook ('historydb_submenu'); - enterprise_hook ('log_collector_submenu'); - - $sub2["godmode/setup/setup&section=auth"]["text"] = __('Authentication'); - $sub2["godmode/setup/setup&section=auth"]["refr"] = 0; - - $sub2["godmode/setup/setup&section=perf"]["text"] = __('Performance'); - $sub2["godmode/setup/setup&section=perf"]["refr"] = 0; - - $sub2["godmode/setup/setup&section=vis"]["text"] = __('Visual styles'); - $sub2["godmode/setup/setup&section=vis"]["refr"] = 0; - - if (check_acl ($config['id_user'], 0, "AW")) { - if ($config['activate_netflow']) { - $sub2["godmode/setup/setup&section=net"]["text"] = __('Netflow'); - $sub2["godmode/setup/setup&section=net"]["refr"] = 0; - } - } - - $sub2["godmode/setup/setup&section=ehorus"]["text"] = __('eHorus'); - $sub2["godmode/setup/setup&section=ehorus"]["refr"] = 0; - - if ($config['activate_gis']) { - $sub2["godmode/setup/gis"]["text"] = __('Map conections GIS'); - } - - $sub["general"]["sub2"] = $sub2; - $sub["godmode/setup/os"]["text"] = __('Edit OS'); - $sub["godmode/setup/os"]["id"] = 'Edit OS'; - $sub["godmode/setup/license"]["text"] = __('License'); - $sub["godmode/setup/license"]["id"] = 'License'; - - enterprise_hook ('skins_submenu'); - - $menu_godmode["gsetup"]["sub"] = $sub; +if (check_acl($config['id_user'], 0, 'PM')) { + // Setup + $menu_godmode['gsetup']['text'] = __('Setup'); + $menu_godmode['gsetup']['sec2'] = 'godmode/setup/setup§ion=general'; + $menu_godmode['gsetup']['id'] = 'god-setup'; + + $sub = []; + + // Options Setup + $sub['general']['text'] = __('Setup'); + $sub['general']['id'] = 'Setup'; + $sub['general']['type'] = 'direct'; + $sub['general']['subtype'] = 'nolink'; + $sub2 = []; + + $sub2['godmode/setup/setup&section=general']['text'] = __('General Setup'); + $sub2['godmode/setup/setup&section=general']['id'] = 'General Setup'; + $sub2['godmode/setup/setup&section=general']['refr'] = 0; + + enterprise_hook('password_submenu'); + enterprise_hook('enterprise_submenu'); + enterprise_hook('historydb_submenu'); + enterprise_hook('log_collector_submenu'); + + $sub2['godmode/setup/setup&section=auth']['text'] = __('Authentication'); + $sub2['godmode/setup/setup&section=auth']['refr'] = 0; + + $sub2['godmode/setup/setup&section=perf']['text'] = __('Performance'); + $sub2['godmode/setup/setup&section=perf']['refr'] = 0; + + $sub2['godmode/setup/setup&section=vis']['text'] = __('Visual styles'); + $sub2['godmode/setup/setup&section=vis']['refr'] = 0; + + if (check_acl($config['id_user'], 0, 'AW')) { + if ($config['activate_netflow']) { + $sub2['godmode/setup/setup&section=net']['text'] = __('Netflow'); + $sub2['godmode/setup/setup&section=net']['refr'] = 0; + } + } + + $sub2['godmode/setup/setup&section=ehorus']['text'] = __('eHorus'); + $sub2['godmode/setup/setup&section=ehorus']['refr'] = 0; + + if ($config['activate_gis']) { + $sub2['godmode/setup/gis']['text'] = __('Map conections GIS'); + } + + $sub['general']['sub2'] = $sub2; + $sub['godmode/setup/os']['text'] = __('Edit OS'); + $sub['godmode/setup/os']['id'] = 'Edit OS'; + $sub['godmode/setup/license']['text'] = __('License'); + $sub['godmode/setup/license']['id'] = 'License'; + + enterprise_hook('skins_submenu'); + + $menu_godmode['gsetup']['sub'] = $sub; } -if (check_acl ($config['id_user'], 0, "PM") || check_acl ($config['id_user'], 0, "DM")) { - - $menu_godmode["gextensions"]["text"] = __('Admin tools'); - $menu_godmode["gextensions"]["sec2"] = "godmode/extensions"; - $menu_godmode["gextensions"]["id"] = "god-extensions"; - - $sub = array (); - - if (check_acl ($config['id_user'], 0, "PM")) { - // Audit //meter en extensiones - $sub["godmode/admin_access_logs"]["text"] = __('System audit log'); - $sub["godmode/admin_access_logs"]["id"] = 'System audit log'; - $sub["godmode/setup/links"]["text"] = __('Links'); - $sub["godmode/setup/links"]["id"] = 'Links'; - $sub["extras/pandora_diag"]["text"] = __('Diagnostic info'); - $sub["extras/pandora_diag"]["id"] = 'Diagnostic info'; - $sub["godmode/setup/news"]["text"] = __('Site news'); - $sub["godmode/setup/news"]["id"] = 'Site news'; - $sub["godmode/setup/file_manager"]["text"] = __('File manager'); - $sub["godmode/setup/file_manager"]["id"] = 'File manager'; - - if(is_user_admin($config['id_user'])){ - $sub["extensions/db_status"]["text"] = __('DB Schema Check'); - $sub["extensions/db_status"]["id"] = 'DB Schema Check'; - $sub["extensions/db_status"]["sec"] = "gbman"; - $sub["extensions/dbmanager"]["text"] = __('DB Interface'); - $sub["extensions/dbmanager"]["id"] = 'DB Interface'; - $sub["extensions/dbmanager"]["sec"] = "gbman"; - } - - } - - $menu_godmode["gextensions"]["sub"] = $sub; -} - -if (is_array ($config['extensions'])) { - - $sub = array (); - $sub2 = array (); - - foreach ($config['extensions'] as $extension) { - //If no godmode_menu is a operation extension - if ($extension['godmode_menu'] == '') { - continue; - } - - if ($extension['godmode_menu']['name'] == 'System Info') { - continue; - } - - - - if($extension['godmode_menu']['name'] != __('DB Schema check') && $extension['godmode_menu']['name'] != __('DB interface')){ - $extmenu = $extension['godmode_menu']; - } - - //Check the ACL for this user - if (! check_acl ($config['id_user'], 0, $extmenu['acl'])) { - continue; - } - - //Check if was displayed inside other menu - if ($extension['godmode_menu']["fatherId"] == '') { - $sub2[$extmenu["sec2"]]["text"] = __($extmenu["name"]); - $sub2[$extmenu["sec2"]]["id"] = $extmenu["name"]; - $sub2[$extmenu["sec2"]]["refr"] = 0; - } - else { - if (is_array($extmenu) && array_key_exists('fatherId',$extmenu)) { - 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; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]["icon"] = $extmenu['icon']; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]["sec"] = 'extensions'; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]["extension"] = true; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]["enterprise"] = $extension['enterprise']; - $menu_godmode[$extmenu['fatherId']]['hasExtensions'] = true; - } - else { - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["text"] = __($extmenu['name']); - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["id"] = $extmenu['name']; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["refr"] = 0; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["icon"] = $extmenu['icon']; - if ($extmenu["name"] == 'Cron jobs') - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["sec"] = 'extensions'; - else - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["sec"] = 'gextensions'; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["extension"] = true; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["enterprise"] = $extension['enterprise']; - $menu_godmode[$extmenu['fatherId']]['hasExtensions'] = true; - } - } - else { - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["text"] = __($extmenu['name']); - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["id"] = $extmenu['name']; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["refr"] = 0; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["icon"] = $extmenu['icon']; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["sec"] = 'gextensions'; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["extension"] = true; - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]["enterprise"] = $extension['enterprise']; - $menu_godmode[$extmenu['fatherId']]['hasExtensions'] = true; - } - } - } - } - } - - // Complete the submenu - $extension_view = array(); - $extension_view["godmode/extensions"]["id"] = 'Extension manager view'; - $extension_view["godmode/extensions"]["text"] = __('Extension manager view'); - $extension_submenu = array_merge($extension_view,$sub2); - - $sub["godmode/extensions"]["sub2"] = $extension_submenu; - $sub["godmode/extensions"]["text"] = __('Extension manager'); - $sub["godmode/extensions"]["id"] = 'Extension manager'; - $sub["godmode/extensions"]["type"] = 'direct'; - $sub["godmode/extensions"]["subtype"] = 'nolink'; - - $submenu = array_merge($menu_godmode["gextensions"]["sub"],$sub); - if($menu_godmode['gextensions']['sub'] != null){ - $menu_godmode["gextensions"]["sub"] = $submenu; - } +if (check_acl($config['id_user'], 0, 'PM') || check_acl($config['id_user'], 0, 'DM')) { + $menu_godmode['gextensions']['text'] = __('Admin tools'); + $menu_godmode['gextensions']['sec2'] = 'godmode/extensions'; + $menu_godmode['gextensions']['id'] = 'god-extensions'; + + $sub = []; + + if (check_acl($config['id_user'], 0, 'PM')) { + // Audit //meter en extensiones + $sub['godmode/admin_access_logs']['text'] = __('System audit log'); + $sub['godmode/admin_access_logs']['id'] = 'System audit log'; + $sub['godmode/setup/links']['text'] = __('Links'); + $sub['godmode/setup/links']['id'] = 'Links'; + $sub['extras/pandora_diag']['text'] = __('Diagnostic info'); + $sub['extras/pandora_diag']['id'] = 'Diagnostic info'; + $sub['godmode/setup/news']['text'] = __('Site news'); + $sub['godmode/setup/news']['id'] = 'Site news'; + $sub['godmode/setup/file_manager']['text'] = __('File manager'); + $sub['godmode/setup/file_manager']['id'] = 'File manager'; + + if (is_user_admin($config['id_user'])) { + $sub['extensions/db_status']['text'] = __('DB Schema Check'); + $sub['extensions/db_status']['id'] = 'DB Schema Check'; + $sub['extensions/db_status']['sec'] = 'gbman'; + $sub['extensions/dbmanager']['text'] = __('DB Interface'); + $sub['extensions/dbmanager']['id'] = 'DB Interface'; + $sub['extensions/dbmanager']['sec'] = 'gbman'; + } + } + + $menu_godmode['gextensions']['sub'] = $sub; } -$menu_godmode["links"]["text"] = __('Links'); -$menu_godmode["links"]["sec2"] = ""; -$menu_godmode["links"]["id"] = "god-links"; +if (is_array($config['extensions'])) { + $sub = []; + $sub2 = []; -$sub = array (); + foreach ($config['extensions'] as $extension) { + // If no godmode_menu is a operation extension + if ($extension['godmode_menu'] == '') { + continue; + } + + if ($extension['godmode_menu']['name'] == 'System Info') { + continue; + } + + + + if ($extension['godmode_menu']['name'] != __('DB Schema check') && $extension['godmode_menu']['name'] != __('DB interface')) { + $extmenu = $extension['godmode_menu']; + } + + // Check the ACL for this user + if (! check_acl($config['id_user'], 0, $extmenu['acl'])) { + continue; + } + + // Check if was displayed inside other menu + if ($extension['godmode_menu']['fatherId'] == '') { + $sub2[$extmenu['sec2']]['text'] = __($extmenu['name']); + $sub2[$extmenu['sec2']]['id'] = $extmenu['name']; + $sub2[$extmenu['sec2']]['refr'] = 0; + } else { + if (is_array($extmenu) && array_key_exists('fatherId', $extmenu)) { + 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; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]['icon'] = $extmenu['icon']; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]['sec'] = 'extensions'; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]['extension'] = true; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]['enterprise'] = $extension['enterprise']; + $menu_godmode[$extmenu['fatherId']]['hasExtensions'] = true; + } else { + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['text'] = __($extmenu['name']); + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['id'] = $extmenu['name']; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['refr'] = 0; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['icon'] = $extmenu['icon']; + if ($extmenu['name'] == 'Cron jobs') { + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['sec'] = 'extensions'; + } else { + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['sec'] = 'gextensions'; + } + + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['extension'] = true; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['enterprise'] = $extension['enterprise']; + $menu_godmode[$extmenu['fatherId']]['hasExtensions'] = true; + } + } else { + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['text'] = __($extmenu['name']); + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['id'] = $extmenu['name']; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['refr'] = 0; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['icon'] = $extmenu['icon']; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['sec'] = 'gextensions'; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['extension'] = true; + $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['sec2']]['enterprise'] = $extension['enterprise']; + $menu_godmode[$extmenu['fatherId']]['hasExtensions'] = true; + } + } + } + } + } + + // Complete the submenu + $extension_view = []; + $extension_view['godmode/extensions']['id'] = 'Extension manager view'; + $extension_view['godmode/extensions']['text'] = __('Extension manager view'); + $extension_submenu = array_merge($extension_view, $sub2); + + $sub['godmode/extensions']['sub2'] = $extension_submenu; + $sub['godmode/extensions']['text'] = __('Extension manager'); + $sub['godmode/extensions']['id'] = 'Extension manager'; + $sub['godmode/extensions']['type'] = 'direct'; + $sub['godmode/extensions']['subtype'] = 'nolink'; + + $submenu = array_merge($menu_godmode['gextensions']['sub'], $sub); + if ($menu_godmode['gextensions']['sub'] != null) { + $menu_godmode['gextensions']['sub'] = $submenu; + } +} + +$menu_godmode['links']['text'] = __('Links'); +$menu_godmode['links']['sec2'] = ''; +$menu_godmode['links']['id'] = 'god-links'; + +$sub = []; $rows = db_get_all_rows_in_table('tlink', 'name'); foreach ($rows as $row) { - // Audit //meter en extensiones - - $sub[$row['link']]["text"] = $row['name']; - $sub[$row['link']]["id"] = $row['name']; - $sub[$row['link']]["type"] = 'direct'; - $sub[$row['link']]["subtype"] = 'new_blank'; + // Audit //meter en extensiones + $sub[$row['link']]['text'] = $row['name']; + $sub[$row['link']]['id'] = $row['name']; + $sub[$row['link']]['type'] = 'direct'; + $sub[$row['link']]['subtype'] = 'new_blank'; } -$menu_godmode["links"]["sub"] = $sub; +$menu_godmode['links']['sub'] = $sub; // Update Manager -if (check_acl ($config['id_user'], 0, "PM") && $config['enable_update_manager']) { - $menu_godmode["messages"]["text"] = __('Update manager'); - $menu_godmode["messages"]["sec2"] = ""; - $menu_godmode["messages"]["id"] = "god-um_messages"; +if (check_acl($config['id_user'], 0, 'PM') && $config['enable_update_manager']) { + $menu_godmode['messages']['text'] = __('Update manager'); + $menu_godmode['messages']['sec2'] = ''; + $menu_godmode['messages']['id'] = 'god-um_messages'; - $sub = array (); - if ($config['enterprise_installed']) { - $sub["godmode/update_manager/update_manager&tab=offline"]["text"] = __('Update Manager offline'); - $sub["godmode/update_manager/update_manager&tab=offline"]["id"] = 'Offline'; - } - $sub["godmode/update_manager/update_manager&tab=online"]["text"] = __('Update Manager online'); - $sub["godmode/update_manager/update_manager&tab=online"]["id"] = 'Online'; - $sub["godmode/update_manager/update_manager&tab=setup"]["text"] = __('Update Manager options'); - $sub["godmode/update_manager/update_manager&tab=setup"]["id"] = 'Options'; - - if (license_free() && is_user_admin ($config['id_user'])) { - - include_once ("include/functions_update_manager.php"); - //If there are unread messages, display the notification icon - $number_total_messages; - $number_unread_messages = update_manager_get_unread_messages (); - if ($number_unread_messages > 0) { - $menu_godmode["messages"]["notification"] = $number_unread_messages; - } - - $sub["godmode/update_manager/update_manager&tab=messages"]["text"] = __('Messages'); - $sub["godmode/update_manager/update_manager&tab=messages"]["id"] = 'Messages'; - - } - $menu_godmode["messages"]["sub"] = $sub; + $sub = []; + if ($config['enterprise_installed']) { + $sub['godmode/update_manager/update_manager&tab=offline']['text'] = __('Update Manager offline'); + $sub['godmode/update_manager/update_manager&tab=offline']['id'] = 'Offline'; + } + + $sub['godmode/update_manager/update_manager&tab=online']['text'] = __('Update Manager online'); + $sub['godmode/update_manager/update_manager&tab=online']['id'] = 'Online'; + $sub['godmode/update_manager/update_manager&tab=setup']['text'] = __('Update Manager options'); + $sub['godmode/update_manager/update_manager&tab=setup']['id'] = 'Options'; + + if (license_free() && is_user_admin($config['id_user'])) { + include_once 'include/functions_update_manager.php'; + // If there are unread messages, display the notification icon + $number_total_messages; + $number_unread_messages = update_manager_get_unread_messages(); + if ($number_unread_messages > 0) { + $menu_godmode['messages']['notification'] = $number_unread_messages; + } + + $sub['godmode/update_manager/update_manager&tab=messages']['text'] = __('Messages'); + $sub['godmode/update_manager/update_manager&tab=messages']['id'] = 'Messages'; + } + + $menu_godmode['messages']['sub'] = $sub; } if (!$config['pure']) { - menu_print_menu ($menu_godmode); + menu_print_menu($menu_godmode); } -?> diff --git a/pandora_console/godmode/modules/manage_nc_groups.php b/pandora_console/godmode/modules/manage_nc_groups.php index 8c4fa71bf9..5fddce35f4 100644 --- a/pandora_console/godmode/modules/manage_nc_groups.php +++ b/pandora_console/godmode/modules/manage_nc_groups.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,237 +11,264 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); enterprise_hook('open_meta_frame'); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access SNMP Group Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access SNMP Group Management' + ); + include 'general/noaccess.php'; + return; } -enterprise_include_once ('meta/include/functions_components_meta.php'); -require_once ($config['homedir'] . '/include/functions_network_components.php'); -require_once ($config['homedir'] . '/include/functions_component_groups.php'); +enterprise_include_once('meta/include/functions_components_meta.php'); +require_once $config['homedir'].'/include/functions_network_components.php'; +require_once $config['homedir'].'/include/functions_component_groups.php'; // Header if (defined('METACONSOLE')) { - components_meta_print_header(); - $sec = 'advanced'; -} -else { - ui_print_page_header (__('Module management').' » '. __('Component group management'), "", false, "component_groups", true); - $sec = 'gmodules'; + components_meta_print_header(); + $sec = 'advanced'; +} else { + ui_print_page_header(__('Module management').' » '.__('Component group management'), '', false, 'component_groups', true); + $sec = 'gmodules'; } -$create = (bool) get_parameter ('create'); -$update = (bool) get_parameter ('update'); -$delete = (bool) get_parameter ('delete'); -$new = (bool) get_parameter ('new'); -$id = (int) get_parameter ('id'); -$multiple_delete = (bool)get_parameter('multiple_delete', 0); +$create = (bool) get_parameter('create'); +$update = (bool) get_parameter('update'); +$delete = (bool) get_parameter('delete'); +$new = (bool) get_parameter('new'); +$id = (int) get_parameter('id'); +$multiple_delete = (bool) get_parameter('multiple_delete', 0); $pure = get_parameter('pure', 0); - + if ($create) { - $name = (string) get_parameter ('name'); - $parent = (int) get_parameter ('parent'); - - if ($name == '') { - ui_print_error_message (__('Could not be created. Blank name')); - require_once ('manage_nc_groups_form.php'); - return; - } - else { - $result = db_process_sql_insert ('tnetwork_component_group', - array ('name' => $name, - 'parent' => $parent)); - if ($result) { - db_pandora_audit( "Module management", "Create component group #$result"); - } - else { - db_pandora_audit( "Module management", "Fail try to create component group"); - } - ui_print_result_message ($result, - __('Successfully created'), - __('Could not be created')); - } + $name = (string) get_parameter('name'); + $parent = (int) get_parameter('parent'); + + if ($name == '') { + ui_print_error_message(__('Could not be created. Blank name')); + include_once 'manage_nc_groups_form.php'; + return; + } else { + $result = db_process_sql_insert( + 'tnetwork_component_group', + [ + 'name' => $name, + 'parent' => $parent, + ] + ); + if ($result) { + db_pandora_audit('Module management', "Create component group #$result"); + } else { + db_pandora_audit('Module management', 'Fail try to create component group'); + } + + ui_print_result_message( + $result, + __('Successfully created'), + __('Could not be created') + ); + } } if ($update) { - $name = (string) get_parameter ('name'); - $parent = (int) get_parameter ('parent'); - - if ($name == '') { - ui_print_error_message (__('Not updated. Blank name')); - } - else { - $result = db_process_sql_update ('tnetwork_component_group', - array ('name' => $name, - 'parent' => $parent), - array ('id_sg' => $id)); - if ($result) { - db_pandora_audit( "Module management", "Update component group #$id"); - } - else { - db_pandora_audit( "Module management", "Fail try to update component group #$id"); - } - - ui_print_result_message ($result, - __('Successfully updated'), - __('Not updated. Error updating data')); - } + $name = (string) get_parameter('name'); + $parent = (int) get_parameter('parent'); + + if ($name == '') { + ui_print_error_message(__('Not updated. Blank name')); + } else { + $result = db_process_sql_update( + 'tnetwork_component_group', + [ + 'name' => $name, + 'parent' => $parent, + ], + ['id_sg' => $id] + ); + if ($result) { + db_pandora_audit('Module management', "Update component group #$id"); + } else { + db_pandora_audit('Module management', "Fail try to update component group #$id"); + } + + ui_print_result_message( + $result, + __('Successfully updated'), + __('Not updated. Error updating data') + ); + } } if ($delete) { - $parent_id = db_get_value_filter('parent', 'tnetwork_component_group', array('id_sg' => $id)); - - $result1 = db_process_sql_update('tnetwork_component_group', array('parent' => $parent_id), array('parent' => $id)); + $parent_id = db_get_value_filter('parent', 'tnetwork_component_group', ['id_sg' => $id]); - $result = db_process_sql_delete ('tnetwork_component_group', - array ('id_sg' => $id)); - - if (($result !== false) and ($result1 !== false)) $result = true; - else $result = false; - - if ($result) { - db_pandora_audit( "Module management", "Delete component group #$id"); - } - else { - db_pandora_audit( "Module management", "Fail try to delete component group #$id"); - } - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); + $result1 = db_process_sql_update('tnetwork_component_group', ['parent' => $parent_id], ['parent' => $id]); + + $result = db_process_sql_delete( + 'tnetwork_component_group', + ['id_sg' => $id] + ); + + if (($result !== false) and ($result1 !== false)) { + $result = true; + } else { + $result = false; + } + + if ($result) { + db_pandora_audit('Module management', "Delete component group #$id"); + } else { + db_pandora_audit('Module management', "Fail try to delete component group #$id"); + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); } if ($multiple_delete) { - $ids = (array)get_parameter('delete_multiple', array()); - - foreach ($ids as $id) { - $result = db_process_sql_delete ('tnetwork_component_group', - array ('id_sg' => $id)); - - $result1 = db_process_sql_update('tnetwork_component_group', array('parent' => 0), array('parent' => $id)); - - if (($result === false) or ($result1 === false)) { - break; - } - } - - - if ($result !== false) $result = true; - else $result = false; - - $str_ids = implode (',', $ids); - if ($result) { - db_pandora_audit( "Module management", - "Multiple delete component group: $str_ids"); - } - else { - db_pandora_audit( "Module management", - "Fail try to delete component group: $str_ids"); - } - ui_print_result_message ($result, - __('Successfully multiple deleted'), - __('Not deleted. Error deleting multiple data')); + $ids = (array) get_parameter('delete_multiple', []); + + foreach ($ids as $id) { + $result = db_process_sql_delete( + 'tnetwork_component_group', + ['id_sg' => $id] + ); + + $result1 = db_process_sql_update('tnetwork_component_group', ['parent' => 0], ['parent' => $id]); + + if (($result === false) or ($result1 === false)) { + break; + } + } + + + if ($result !== false) { + $result = true; + } else { + $result = false; + } + + $str_ids = implode(',', $ids); + if ($result) { + db_pandora_audit( + 'Module management', + "Multiple delete component group: $str_ids" + ); + } else { + db_pandora_audit( + 'Module management', + "Fail try to delete component group: $str_ids" + ); + } + + ui_print_result_message( + $result, + __('Successfully multiple deleted'), + __('Not deleted. Error deleting multiple data') + ); } if (($id || $new) && !$delete && !$multiple_delete) { - require_once ('manage_nc_groups_form.php'); - return; + include_once 'manage_nc_groups_form.php'; + return; } -$url = ui_get_url_refresh (array ('offset' => false, - 'create' => false, - 'update' => false, - 'delete' => false, - 'new' => false, - 'crt' => false, - 'upd' => false, - 'id' => false)); +$url = ui_get_url_refresh( + [ + 'offset' => false, + 'create' => false, + 'update' => false, + 'delete' => false, + 'new' => false, + 'crt' => false, + 'upd' => false, + 'id' => false, + ] +); -$filter = array (); +$filter = []; -//$filter['offset'] = (int) get_parameter ('offset'); -//$filter['limit'] = (int) $config['block_size']; +// $filter['offset'] = (int) get_parameter ('offset'); +// $filter['limit'] = (int) $config['block_size']; $filter['order'] = 'parent'; -$groups = db_get_all_rows_filter ('tnetwork_component_group', $filter); -if ($groups === false) - $groups = array (); +$groups = db_get_all_rows_filter('tnetwork_component_group', $filter); +if ($groups === false) { + $groups = []; +} -$groups_clean = array(); +$groups_clean = []; foreach ($groups as $group_key => $group_val) { - $groups_clean[$group_val['id_sg']] = $group_val; + $groups_clean[$group_val['id_sg']] = $group_val; } // Format component groups in tree form -$groups = component_groups_get_groups_tree_recursive($groups_clean,0,0); +$groups = component_groups_get_groups_tree_recursive($groups_clean, 0, 0); $table = new stdClass(); $table->width = '100%'; $table->class = 'databox data'; -$table->head = array (); +$table->head = []; $table->head[0] = __('Name'); -$table->head[1] = __('Action') . - html_print_checkbox('all_delete', 0, false, true, false); -$table->style = array (); +$table->head[1] = __('Action').html_print_checkbox('all_delete', 0, false, true, false); +$table->style = []; $table->style[0] = 'font-weight: bold'; -$table->align = array (); +$table->align = []; $table->align[1] = 'left'; -$table->size = array (); +$table->size = []; $table->size[0] = '80%'; $table->size[1] = '10%'; -$table->data = array (); +$table->data = []; -$total_groups = db_get_all_rows_filter ('tnetwork_component_group', false, 'COUNT(*) AS total'); +$total_groups = db_get_all_rows_filter('tnetwork_component_group', false, 'COUNT(*) AS total'); $total_groups = $total_groups[0]['total']; -//ui_pagination ($total_groups, $url); - +// ui_pagination ($total_groups, $url); foreach ($groups as $group) { - $data = array (); - - $tabulation = str_repeat('    ', $group['deep']); - if (defined("METACONSOLE")) - $data[0] = $tabulation . ''.$group['name'].''; - else - $data[0] = $tabulation . ''.$group['name'].''; - - $data[1] = "" . - html_print_image('images/cross.png', true, array('title' => __('Delete'))) . "" . - html_print_checkbox_extended ('delete_multiple[]', $group['id_sg'], false, false, '', 'class="check_delete"', true); - - array_push ($table->data, $data); + $data = []; + + $tabulation = str_repeat('    ', $group['deep']); + if (defined('METACONSOLE')) { + $data[0] = $tabulation.''.$group['name'].''; + } else { + $data[0] = $tabulation.''.$group['name'].''; + } + + $data[1] = "".html_print_image('images/cross.png', true, ['title' => __('Delete')]).''.html_print_checkbox_extended('delete_multiple[]', $group['id_sg'], false, false, '', 'class="check_delete"', true); + + array_push($table->data, $data); } if (isset($data)) { - echo "
    "; - html_print_input_hidden('multiple_delete', 1); - html_print_table ($table); - echo "
    "; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - echo "
    "; - echo "
    "; -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined component groups') ) ); + echo "
    "; + html_print_input_hidden('multiple_delete', 1); + html_print_table($table); + echo "
    "; + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + echo '
    '; + echo '
    '; +} else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined component groups') ]); } echo '
    '; echo '
    '; -html_print_input_hidden ('new', 1); -html_print_submit_button (__('Create'), 'crt', false, 'class="sub next"'); +html_print_input_hidden('new', 1); +html_print_submit_button(__('Create'), 'crt', false, 'class="sub next"'); echo '
    '; echo '
    '; @@ -250,31 +276,31 @@ enterprise_hook('close_meta_frame'); ?> diff --git a/pandora_console/godmode/modules/manage_nc_groups_form.php b/pandora_console/godmode/modules/manage_nc_groups_form.php index 9a9d694bac..5510c22715 100644 --- a/pandora_console/godmode/modules/manage_nc_groups_form.php +++ b/pandora_console/godmode/modules/manage_nc_groups_form.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,36 +11,37 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access SNMO Groups Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access SNMO Groups Management' + ); + include 'general/noaccess.php'; + exit; } -require_once ($config['homedir'] . '/include/functions_network_components.php'); +require_once $config['homedir'].'/include/functions_network_components.php'; -$id = (int) get_parameter ('id'); +$id = (int) get_parameter('id'); -if (defined('METACONSOLE')) - $sec = 'advanced'; -else - $sec = 'gmodules'; +if (defined('METACONSOLE')) { + $sec = 'advanced'; +} else { + $sec = 'gmodules'; +} if ($id) { - $group = network_components_get_group ($id); - $name = $group['name']; - $parent = $group['parent']; -} -else { - $name = ''; - $parent = ''; + $group = network_components_get_group($id); + $name = $group['name']; + $parent = $group['parent']; +} else { + $name = ''; + $parent = ''; } $table = new stdClass(); @@ -49,40 +49,49 @@ $table->width = '100%'; $table->class = 'databox filters'; if (defined('METACONSOLE')) { - $table->class = 'databox data'; - if ($id) { - $table->head[0] = __('Update Group Component'); - } - else { - $table->head[0] = __('Create Group Component'); - } - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; + $table->class = 'databox data'; + if ($id) { + $table->head[0] = __('Update Group Component'); + } else { + $table->head[0] = __('Create Group Component'); + } + + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; } -$table->style = array (); + +$table->style = []; $table->style[0] = 'font-weight: bold'; $table->style[2] = 'font-weight: bold'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Name'); -$table->data[0][1] = html_print_input_text ('name', $name, '', 15, 255, true); +$table->data[0][1] = html_print_input_text('name', $name, '', 15, 255, true); $table->data[0][2] = __('Parent'); -$table->data[0][3] = html_print_select (network_components_get_groups (), - 'parent', $parent, false, __('None'), 0, true, false, false); +$table->data[0][3] = html_print_select( + network_components_get_groups(), + 'parent', + $parent, + false, + __('None'), + 0, + true, + false, + false +); echo '
    '; -html_print_table ($table); +html_print_table($table); echo '
    '; if ($id) { - html_print_input_hidden ('update', 1); - html_print_input_hidden ('id', $id); - html_print_submit_button (__('Update'), 'crt', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create', 1); - html_print_submit_button (__('Create'), 'crt', false, 'class="sub wand"'); + html_print_input_hidden('update', 1); + html_print_input_hidden('id', $id); + html_print_submit_button(__('Update'), 'crt', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create', 1); + html_print_submit_button(__('Create'), 'crt', false, 'class="sub wand"'); } + echo '
    '; echo '
    '; -?> diff --git a/pandora_console/godmode/modules/manage_network_components.php b/pandora_console/godmode/modules/manage_network_components.php index 77b9fceda5..f1fae1785d 100644 --- a/pandora_console/godmode/modules/manage_network_components.php +++ b/pandora_console/godmode/modules/manage_network_components.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,102 +11,108 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); enterprise_hook('open_meta_frame'); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Management' + ); + include 'general/noaccess.php'; + exit; } -require_once ($config['homedir'] . '/include/functions_network_components.php'); -include_once($config['homedir'] . "/include/functions_categories.php"); -enterprise_include_once ('meta/include/functions_components_meta.php'); -require_once ($config['homedir'].'/include/functions_component_groups.php'); +require_once $config['homedir'].'/include/functions_network_components.php'; +require_once $config['homedir'].'/include/functions_categories.php'; +enterprise_include_once('meta/include/functions_components_meta.php'); +require_once $config['homedir'].'/include/functions_component_groups.php'; // Header if (defined('METACONSOLE')) { - components_meta_print_header(); - $sec = 'advanced'; -} -else { - - /* Hello there! :) + components_meta_print_header(); + $sec = 'advanced'; +} else { + /* + Hello there! :) -We added some of what seems to be "buggy" messages to the openSource version recently. This is not to force open-source users to move to the enterprise version, this is just to inform people using Pandora FMS open source that it requires skilled people to maintain and keep it running smoothly without professional support. This does not imply open-source version is limited in any way. If you check the recently added code, it contains only warnings and messages, no limitations except one: we removed the option to add custom logo in header. In the Update Manager section, it warns about the 'danger’ of applying automated updates without a proper backup, remembering in the process that the Enterprise version comes with a human-tested package. Maintaining an OpenSource version with more than 500 agents is not so easy, that's why someone using a Pandora with 8000 agents should consider asking for support. It's not a joke, we know of many setups with a huge number of agents, and we hate to hear that “its becoming unstable and slow” :( + We added some of what seems to be "buggy" messages to the openSource version recently. This is not to force open-source users to move to the enterprise version, this is just to inform people using Pandora FMS open source that it requires skilled people to maintain and keep it running smoothly without professional support. This does not imply open-source version is limited in any way. If you check the recently added code, it contains only warnings and messages, no limitations except one: we removed the option to add custom logo in header. In the Update Manager section, it warns about the 'danger’ of applying automated updates without a proper backup, remembering in the process that the Enterprise version comes with a human-tested package. Maintaining an OpenSource version with more than 500 agents is not so easy, that's why someone using a Pandora with 8000 agents should consider asking for support. It's not a joke, we know of many setups with a huge number of agents, and we hate to hear that “its becoming unstable and slow” :( -You can of course remove the warnings, that's why we include the source and do not use any kind of trick. And that's why we added here this comment, to let you know this does not reflect any change in our opensource mentality of does the last 14 years. + You can of course remove the warnings, that's why we include the source and do not use any kind of trick. And that's why we added here this comment, to let you know this does not reflect any change in our opensource mentality of does the last 14 years. -*/ - - ui_print_page_header (__('Module management') . ' » ' . - __('Network component management'), "", false, - "network_component", true,"",false,"modulemodal"); - $sec = 'gmodules'; + */ + + ui_print_page_header( + __('Module management').' » '.__('Network component management'), + '', + false, + 'network_component', + true, + '', + false, + 'modulemodal' + ); + $sec = 'gmodules'; } -$type = (int) get_parameter ('type'); -$name = (string) get_parameter ('name'); -$description = (string) get_parameter ('description'); -$max = (int) get_parameter ('max'); -$min = (int) get_parameter ('min'); -$tcp_send = (string) get_parameter ('tcp_send'); -$tcp_rcv = (string) get_parameter ('tcp_rcv'); -$tcp_port = (int) get_parameter ('tcp_port'); -$snmp_oid = (string) get_parameter ('snmp_oid'); -$snmp_community = (string) get_parameter ('snmp_community'); -$id_module_group = (int) get_parameter ('id_module_group'); -$module_interval = (int) get_parameter ('module_interval'); -$id_group = (int) get_parameter ('id_group'); -$plugin_user = (string) get_parameter ('plugin_user'); -$plugin_pass = io_input_password((string) get_parameter ('plugin_pass')); -$plugin_parameter = (string) get_parameter ('plugin_parameter'); -$macros = (string) get_parameter ('macros'); +$type = (int) get_parameter('type'); +$name = (string) get_parameter('name'); +$description = (string) get_parameter('description'); +$max = (int) get_parameter('max'); +$min = (int) get_parameter('min'); +$tcp_send = (string) get_parameter('tcp_send'); +$tcp_rcv = (string) get_parameter('tcp_rcv'); +$tcp_port = (int) get_parameter('tcp_port'); +$snmp_oid = (string) get_parameter('snmp_oid'); +$snmp_community = (string) get_parameter('snmp_community'); +$id_module_group = (int) get_parameter('id_module_group'); +$module_interval = (int) get_parameter('module_interval'); +$id_group = (int) get_parameter('id_group'); +$plugin_user = (string) get_parameter('plugin_user'); +$plugin_pass = io_input_password((string) get_parameter('plugin_pass')); +$plugin_parameter = (string) get_parameter('plugin_parameter'); +$macros = (string) get_parameter('macros'); if (!empty($macros)) { - $macros = json_decode(base64_decode($macros), true); - - foreach($macros as $k => $m) { - $macros[$k]['value'] = get_parameter($m['macro'], ''); - } - - $macros = io_json_mb_encode($macros); + $macros = json_decode(base64_decode($macros), true); + + foreach ($macros as $k => $m) { + $macros[$k]['value'] = get_parameter($m['macro'], ''); + } + + $macros = io_json_mb_encode($macros); } -$max_timeout = (int) get_parameter ('max_timeout'); -$max_retries = (int) get_parameter ('max_retries'); -$id_modulo = (int) get_parameter ('id_component_type'); -$id_plugin = (int) get_parameter ('id_plugin'); +$max_timeout = (int) get_parameter('max_timeout'); +$max_retries = (int) get_parameter('max_retries'); +$id_modulo = (int) get_parameter('id_component_type'); +$id_plugin = (int) get_parameter('id_plugin'); $dynamic_interval = (int) get_parameter('dynamic_interval'); $dynamic_max = (int) get_parameter('dynamic_max'); $dynamic_min = (int) get_parameter('dynamic_min'); $dynamic_two_tailed = (int) get_parameter('dynamic_two_tailed'); -$min_warning = (float) get_parameter ('min_warning'); -$max_warning = (float) get_parameter ('max_warning'); -$str_warning = (string) get_parameter ('str_warning'); -$min_critical = (float) get_parameter ('min_critical'); -$max_critical = (float) get_parameter ('max_critical'); -$str_critical = (string) get_parameter ('str_critical'); -$ff_event = (int) get_parameter ('ff_event'); -$history_data = (bool) get_parameter ('history_data'); +$min_warning = (float) get_parameter('min_warning'); +$max_warning = (float) get_parameter('max_warning'); +$str_warning = (string) get_parameter('str_warning'); +$min_critical = (float) get_parameter('min_critical'); +$max_critical = (float) get_parameter('max_critical'); +$str_critical = (string) get_parameter('str_critical'); +$ff_event = (int) get_parameter('ff_event'); +$history_data = (bool) get_parameter('history_data'); // Don't read as (float) because it lost it's decimals when put into MySQL // where are very big and PHP uses scientific notation, p.e: // 1.23E-10 is 0.000000000123 - -$post_process = (string) get_parameter ('post_process', 0.0); +$post_process = (string) get_parameter('post_process', 0.0); $unit = (string) get_parameter('unit'); -$id = (int) get_parameter ('id'); -$wizard_level = get_parameter ('wizard_level', 'nowizard'); +$id = (int) get_parameter('id'); +$wizard_level = get_parameter('wizard_level', 'nowizard'); $critical_instructions = (string) get_parameter('critical_instructions'); $warning_instructions = (string) get_parameter('warning_instructions'); $unknown_instructions = (string) get_parameter('unknown_instructions'); @@ -116,16 +121,15 @@ $warning_inverse = (int) get_parameter('warning_inverse'); $id_category = (int) get_parameter('id_category'); $id_tag_selected = (array) get_parameter('id_tag_selected'); $pure = get_parameter('pure', 0); -$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'); -$each_ff = (int) get_parameter ('each_ff'); +$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'); +$each_ff = (int) get_parameter('each_ff'); if (count($id_tag_selected) == 1 && empty($id_tag_selected[0])) { - $tags = ''; -} -else { - $tags = implode(',',$id_tag_selected); + $tags = ''; +} else { + $tags = implode(',', $id_tag_selected); } $snmp_version = (string) get_parameter('snmp_version'); @@ -138,510 +142,587 @@ $snmp3_security_level = (string) get_parameter('snmp3_security_level'); $throw_unknown_events = get_parameter('throw_unknown_events', false); -//Set the event type that can show. -$disabled_types_event = array(EVENTS_GOING_UNKNOWN => (int)$throw_unknown_events); +// Set the event type that can show. +$disabled_types_event = [EVENTS_GOING_UNKNOWN => (int) $throw_unknown_events]; $disabled_types_event = json_encode($disabled_types_event); -$create_component = (bool) get_parameter ('create_component'); -$update_component = (bool) get_parameter ('update_component'); -$delete_component = (bool) get_parameter ('delete_component'); -$new_component = (bool) get_parameter ('new_component'); -$duplicate_network_component = (bool) get_parameter ('duplicate_network_component'); +$create_component = (bool) get_parameter('create_component'); +$update_component = (bool) get_parameter('update_component'); +$delete_component = (bool) get_parameter('delete_component'); +$new_component = (bool) get_parameter('new_component'); +$duplicate_network_component = (bool) get_parameter('duplicate_network_component'); $delete_multiple = (bool) get_parameter('delete_multiple'); -$multiple_delete = (bool)get_parameter('multiple_delete', 0); -$create_network_from_module = (bool) get_parameter ('create_network_from_module', 0); -$create_network_from_snmp_browser = (bool)get_parameter('create_network_from_snmp_browser', 0); +$multiple_delete = (bool) get_parameter('multiple_delete', 0); +$create_network_from_module = (bool) get_parameter('create_network_from_module', 0); +$create_network_from_snmp_browser = (bool) get_parameter('create_network_from_snmp_browser', 0); if ($duplicate_network_component) { - $source_id = (int) get_parameter ('source_id'); - - $id = network_components_duplicate_network_component ($source_id); - ui_print_result_message ($id, - __('Successfully created from %s', - network_components_get_name ($source_id)), - __('Could not be created')); - - //List unset for jump the bug in the pagination (TODO) that the make another - //copy for each pass into pages. - unset($_GET['source_id']); - unset($_GET['duplicate_network_component']); - - $id = 0; + $source_id = (int) get_parameter('source_id'); + + $id = network_components_duplicate_network_component($source_id); + ui_print_result_message( + $id, + __( + 'Successfully created from %s', + network_components_get_name($source_id) + ), + __('Could not be created') + ); + + // List unset for jump the bug in the pagination (TODO) that the make another + // copy for each pass into pages. + unset($_GET['source_id']); + unset($_GET['duplicate_network_component']); + + $id = 0; } if ($create_component) { - - $custom_string_1 = ''; - $custom_string_2 = ''; - $custom_string_3 = ''; - $name_check = db_get_value ('name', 'tnetwork_component', 'name', - $name); - - //remote_snmp = 15 - //remote_snmp_proc = 18 - if ($type >= 15 && $type <= 18) { - // New support for snmp v3 - $tcp_send = $snmp_version; - $plugin_user = $snmp3_auth_user; - $plugin_pass = $snmp3_auth_pass; - $plugin_parameter = $snmp3_auth_method; - $custom_string_1 = $snmp3_privacy_method; - $custom_string_2 = $snmp3_privacy_pass; - $custom_string_3 = $snmp3_security_level; - $name_check = db_get_value ('name', 'tnetwork_component', - 'name', $name); - } - - if ($name && !$name_check) { - - $id = network_components_create_network_component ($name, - $type, - $id_group, - array ('description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $tcp_send, - 'tcp_rcv' => $tcp_rcv, - 'tcp_port' => $tcp_port, - 'snmp_oid' => $snmp_oid, - 'snmp_community' => $snmp_community, - 'id_module_group' => $id_module_group, - 'id_modulo' => $id_modulo, - 'id_plugin' => $id_plugin, - 'plugin_user' => $plugin_user, - 'plugin_pass' => $plugin_pass, - 'plugin_parameter' => $plugin_parameter, - 'macros' => $macros, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $history_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_max' => $dynamic_max, - 'dynamic_min' => $dynamic_min, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_warning, - 'max_warning' => $max_warning, - 'str_warning' => $str_warning, - 'min_critical' => $min_critical, - 'max_critical' => $max_critical, - 'str_critical' => $str_critical, - 'min_ff_event' => $ff_event, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process, - 'unit' => $unit, - 'wizard_level' => $wizard_level, - 'macros' => $macros, - 'critical_instructions' => $critical_instructions, - 'warning_instructions' => $warning_instructions, - 'unknown_instructions' => $unknown_instructions, - 'critical_inverse' => $critical_inverse, - 'warning_inverse' => $warning_inverse, - 'id_category' => $id_category, - 'tags' => $tags, - 'disabled_types_event' => $disabled_types_event, - 'min_ff_event_normal' => $ff_event_normal, - 'min_ff_event_warning' => $ff_event_warning, - 'min_ff_event_critical' => $ff_event_critical, - 'each_ff' => $each_ff)); - } - else { - $id = ''; - } - - if ($id === false || !$id) { - db_pandora_audit("Module management", "Fail try to create network component"); - ui_print_error_message (__('Could not be created')); - include_once ('godmode/modules/manage_network_components_form.php'); - return; - } - db_pandora_audit("Module management", "Create network component #$id"); - ui_print_success_message (__('Created successfully')); - $id = 0; + $custom_string_1 = ''; + $custom_string_2 = ''; + $custom_string_3 = ''; + $name_check = db_get_value( + 'name', + 'tnetwork_component', + 'name', + $name + ); + + // remote_snmp = 15 + // remote_snmp_proc = 18 + if ($type >= 15 && $type <= 18) { + // New support for snmp v3 + $tcp_send = $snmp_version; + $plugin_user = $snmp3_auth_user; + $plugin_pass = $snmp3_auth_pass; + $plugin_parameter = $snmp3_auth_method; + $custom_string_1 = $snmp3_privacy_method; + $custom_string_2 = $snmp3_privacy_pass; + $custom_string_3 = $snmp3_security_level; + $name_check = db_get_value( + 'name', + 'tnetwork_component', + 'name', + $name + ); + } + + if ($name && !$name_check) { + $id = network_components_create_network_component( + $name, + $type, + $id_group, + [ + 'description' => $description, + 'module_interval' => $module_interval, + 'max' => $max, + 'min' => $min, + 'tcp_send' => $tcp_send, + 'tcp_rcv' => $tcp_rcv, + 'tcp_port' => $tcp_port, + 'snmp_oid' => $snmp_oid, + 'snmp_community' => $snmp_community, + 'id_module_group' => $id_module_group, + 'id_modulo' => $id_modulo, + 'id_plugin' => $id_plugin, + 'plugin_user' => $plugin_user, + 'plugin_pass' => $plugin_pass, + 'plugin_parameter' => $plugin_parameter, + 'macros' => $macros, + 'max_timeout' => $max_timeout, + 'max_retries' => $max_retries, + 'history_data' => $history_data, + 'dynamic_interval' => $dynamic_interval, + 'dynamic_max' => $dynamic_max, + 'dynamic_min' => $dynamic_min, + 'dynamic_two_tailed' => $dynamic_two_tailed, + 'min_warning' => $min_warning, + 'max_warning' => $max_warning, + 'str_warning' => $str_warning, + 'min_critical' => $min_critical, + 'max_critical' => $max_critical, + 'str_critical' => $str_critical, + 'min_ff_event' => $ff_event, + 'custom_string_1' => $custom_string_1, + 'custom_string_2' => $custom_string_2, + 'custom_string_3' => $custom_string_3, + 'post_process' => $post_process, + 'unit' => $unit, + 'wizard_level' => $wizard_level, + 'macros' => $macros, + 'critical_instructions' => $critical_instructions, + 'warning_instructions' => $warning_instructions, + 'unknown_instructions' => $unknown_instructions, + 'critical_inverse' => $critical_inverse, + 'warning_inverse' => $warning_inverse, + 'id_category' => $id_category, + 'tags' => $tags, + 'disabled_types_event' => $disabled_types_event, + 'min_ff_event_normal' => $ff_event_normal, + 'min_ff_event_warning' => $ff_event_warning, + 'min_ff_event_critical' => $ff_event_critical, + 'each_ff' => $each_ff, + ] + ); + } else { + $id = ''; + } + + if ($id === false || !$id) { + db_pandora_audit('Module management', 'Fail try to create network component'); + ui_print_error_message(__('Could not be created')); + include_once 'godmode/modules/manage_network_components_form.php'; + return; + } + + db_pandora_audit('Module management', "Create network component #$id"); + ui_print_success_message(__('Created successfully')); + $id = 0; } if ($update_component) { - $id = (int) get_parameter ('id'); - - $custom_string_1 = ''; - $custom_string_2 = ''; - $custom_string_3 = ''; - - //$name_check = db_get_value ('name', 'tnetwork_component', 'name', $name); - if ($type >= 15 && $type <= 18) { - // New support for snmp v3 - $tcp_send = $snmp_version; - $plugin_user = $snmp3_auth_user; - $plugin_pass = $snmp3_auth_pass; - $plugin_parameter = $snmp3_auth_method; - $custom_string_1 = $snmp3_privacy_method; - $custom_string_2 = $snmp3_privacy_pass; - $custom_string_3 = $snmp3_security_level; - //$name_check = db_get_value ('name', 'tnetwork_component', 'name', $name); - } - - if (!empty($name)) { - $result = network_components_update_network_component ($id, - array ('type' => $type, - 'name' => $name, - 'id_group' => $id_group, - 'description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $tcp_send, - 'tcp_rcv' => $tcp_rcv, - 'tcp_port' => $tcp_port, - 'snmp_oid' => $snmp_oid, - 'snmp_community' => $snmp_community, - 'id_module_group' => $id_module_group, - 'id_modulo' => $id_modulo, - 'id_plugin' => $id_plugin, - 'plugin_user' => $plugin_user, - 'plugin_pass' => $plugin_pass, - 'plugin_parameter' => $plugin_parameter, - 'macros' => $macros, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $history_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_max' => $dynamic_max, - 'dynamic_min' => $dynamic_min, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_warning, - 'max_warning' => $max_warning, - 'str_warning' => $str_warning, - 'min_critical' => $min_critical, - 'max_critical' => $max_critical, - 'str_critical' => $str_critical, - 'min_ff_event' => $ff_event, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process, - 'unit' => $unit, - 'wizard_level' => $wizard_level, - 'macros' => $macros, - 'critical_instructions' => $critical_instructions, - 'warning_instructions' => $warning_instructions, - 'unknown_instructions' => $unknown_instructions, - 'critical_inverse' => $critical_inverse, - 'warning_inverse' => $warning_inverse, - 'id_category' => $id_category, - 'tags' => $tags, - 'disabled_types_event' => $disabled_types_event, - 'min_ff_event_normal' => $ff_event_normal, - 'min_ff_event_warning' => $ff_event_warning, - 'min_ff_event_critical' => $ff_event_critical, - 'each_ff' => $each_ff)); - } - else { - $result = ''; - } - if ($result === false || !$result) { - db_pandora_audit("Module management", - "Fail try to update network component #$id"); - ui_print_error_message (__('Could not be updated')); - include_once ('godmode/modules/manage_network_components_form.php'); - return; - } - - db_pandora_audit("Module management", "Update network component #$id"); - ui_print_success_message (__('Updated successfully')); - - $id = 0; + $id = (int) get_parameter('id'); + + $custom_string_1 = ''; + $custom_string_2 = ''; + $custom_string_3 = ''; + + // $name_check = db_get_value ('name', 'tnetwork_component', 'name', $name); + if ($type >= 15 && $type <= 18) { + // New support for snmp v3 + $tcp_send = $snmp_version; + $plugin_user = $snmp3_auth_user; + $plugin_pass = $snmp3_auth_pass; + $plugin_parameter = $snmp3_auth_method; + $custom_string_1 = $snmp3_privacy_method; + $custom_string_2 = $snmp3_privacy_pass; + $custom_string_3 = $snmp3_security_level; + // $name_check = db_get_value ('name', 'tnetwork_component', 'name', $name); + } + + if (!empty($name)) { + $result = network_components_update_network_component( + $id, + [ + 'type' => $type, + 'name' => $name, + 'id_group' => $id_group, + 'description' => $description, + 'module_interval' => $module_interval, + 'max' => $max, + 'min' => $min, + 'tcp_send' => $tcp_send, + 'tcp_rcv' => $tcp_rcv, + 'tcp_port' => $tcp_port, + 'snmp_oid' => $snmp_oid, + 'snmp_community' => $snmp_community, + 'id_module_group' => $id_module_group, + 'id_modulo' => $id_modulo, + 'id_plugin' => $id_plugin, + 'plugin_user' => $plugin_user, + 'plugin_pass' => $plugin_pass, + 'plugin_parameter' => $plugin_parameter, + 'macros' => $macros, + 'max_timeout' => $max_timeout, + 'max_retries' => $max_retries, + 'history_data' => $history_data, + 'dynamic_interval' => $dynamic_interval, + 'dynamic_max' => $dynamic_max, + 'dynamic_min' => $dynamic_min, + 'dynamic_two_tailed' => $dynamic_two_tailed, + 'min_warning' => $min_warning, + 'max_warning' => $max_warning, + 'str_warning' => $str_warning, + 'min_critical' => $min_critical, + 'max_critical' => $max_critical, + 'str_critical' => $str_critical, + 'min_ff_event' => $ff_event, + 'custom_string_1' => $custom_string_1, + 'custom_string_2' => $custom_string_2, + 'custom_string_3' => $custom_string_3, + 'post_process' => $post_process, + 'unit' => $unit, + 'wizard_level' => $wizard_level, + 'macros' => $macros, + 'critical_instructions' => $critical_instructions, + 'warning_instructions' => $warning_instructions, + 'unknown_instructions' => $unknown_instructions, + 'critical_inverse' => $critical_inverse, + 'warning_inverse' => $warning_inverse, + 'id_category' => $id_category, + 'tags' => $tags, + 'disabled_types_event' => $disabled_types_event, + 'min_ff_event_normal' => $ff_event_normal, + 'min_ff_event_warning' => $ff_event_warning, + 'min_ff_event_critical' => $ff_event_critical, + 'each_ff' => $each_ff, + ] + ); + } else { + $result = ''; + } + + if ($result === false || !$result) { + db_pandora_audit( + 'Module management', + "Fail try to update network component #$id" + ); + ui_print_error_message(__('Could not be updated')); + include_once 'godmode/modules/manage_network_components_form.php'; + return; + } + + db_pandora_audit('Module management', "Update network component #$id"); + ui_print_success_message(__('Updated successfully')); + + $id = 0; } if ($delete_component) { - $id = (int) get_parameter ('id'); - - $result = network_components_delete_network_component ($id); - - if ($result) { - db_pandora_audit( "Module management", - "Delete network component #$id"); - } - else { - db_pandora_audit( "Module management", - "Fail try to delete network component #$id"); - } - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Could not be deleted')); - $id = 0; + $id = (int) get_parameter('id'); + + $result = network_components_delete_network_component($id); + + if ($result) { + db_pandora_audit( + 'Module management', + "Delete network component #$id" + ); + } else { + db_pandora_audit( + 'Module management', + "Fail try to delete network component #$id" + ); + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Could not be deleted') + ); + $id = 0; } if ($multiple_delete) { - $ids = (array)get_parameter('delete_multiple', array()); - - foreach ($ids as $id) { - $result = network_components_delete_network_component ($id); - - if ($result === false) { - break; - } - } - - $str_ids = implode (',', $ids); - if ($result) { - db_pandora_audit( "Module management", - "Multiple delete network component: $str_ids"); - } - else { - db_pandora_audit( "Module management", - "Fail try to delete network component: $str_ids"); - } - - ui_print_result_message ($result, - __('Successfully multiple deleted'), - __('Not deleted. Error deleting multiple data')); - - $id = 0; + $ids = (array) get_parameter('delete_multiple', []); + + foreach ($ids as $id) { + $result = network_components_delete_network_component($id); + + if ($result === false) { + break; + } + } + + $str_ids = implode(',', $ids); + if ($result) { + db_pandora_audit( + 'Module management', + "Multiple delete network component: $str_ids" + ); + } else { + db_pandora_audit( + 'Module management', + "Fail try to delete network component: $str_ids" + ); + } + + ui_print_result_message( + $result, + __('Successfully multiple deleted'), + __('Not deleted. Error deleting multiple data') + ); + + $id = 0; } if ($id || $new_component || $create_network_from_module || $create_network_from_snmp_browser) { - include_once ($config['homedir'] . - '/godmode/modules/manage_network_components_form.php'); - return; + include_once $config['homedir'].'/godmode/modules/manage_network_components_form.php'; + return; } -$url = ui_get_url_refresh (array ('offset' => false, - 'id' => false, - 'create_component' => false, - 'update_component' => false, - 'delete_component' => false, - 'id_network_component' => false, - 'upd' => false, - 'crt' => false, - 'type' => false, - 'name' => false, - 'description' => false, - 'max' => false, - 'min' => false, - 'tcp_send' => false, - 'tcp_rcv' => false, - 'tcp_port' => false, - 'snmp_oid' => false, - 'snmp_community' => false, - 'id_module_group' => false, - 'module_interval' => false, - 'id_group' => false, - 'plugin_user' => false, - 'plugin_pass' => false, - 'plugin_parameter' => false, - 'macros' => false, - 'max_timeout' => false, - 'max_retries' => false, - 'id_modulo' => false, - 'id_plugin' => false, - 'history_data' => false, - 'dynamic_interval' => false, - 'dynamic_max' => false, - 'dynamic_min' => false, - 'dynamic_two_tailed' => false, - 'min_warning' => false, - 'max_warning' => false, - 'str_warning' => false, - 'min_critical' => false, - 'max_critical' => false, - 'str_critical' => false, - 'ff_event' => false, - 'id_component_type' => false, - 'critical_instructions' => false, - 'warning_instructions' => false, - 'unknown_instructions' => false, - 'critical_inverse' => false, - 'warning_inverse' => false, - 'id_category' => false, - 'tags' => false, - 'ff_event_normal' => false, - 'ff_event_warning' => false, - 'ff_event_critical' => false, - 'each_ff' => false)); +$url = ui_get_url_refresh( + [ + 'offset' => false, + 'id' => false, + 'create_component' => false, + 'update_component' => false, + 'delete_component' => false, + 'id_network_component' => false, + 'upd' => false, + 'crt' => false, + 'type' => false, + 'name' => false, + 'description' => false, + 'max' => false, + 'min' => false, + 'tcp_send' => false, + 'tcp_rcv' => false, + 'tcp_port' => false, + 'snmp_oid' => false, + 'snmp_community' => false, + 'id_module_group' => false, + 'module_interval' => false, + 'id_group' => false, + 'plugin_user' => false, + 'plugin_pass' => false, + 'plugin_parameter' => false, + 'macros' => false, + 'max_timeout' => false, + 'max_retries' => false, + 'id_modulo' => false, + 'id_plugin' => false, + 'history_data' => false, + 'dynamic_interval' => false, + 'dynamic_max' => false, + 'dynamic_min' => false, + 'dynamic_two_tailed' => false, + 'min_warning' => false, + 'max_warning' => false, + 'str_warning' => false, + 'min_critical' => false, + 'max_critical' => false, + 'str_critical' => false, + 'ff_event' => false, + 'id_component_type' => false, + 'critical_instructions' => false, + 'warning_instructions' => false, + 'unknown_instructions' => false, + 'critical_inverse' => false, + 'warning_inverse' => false, + 'id_category' => false, + 'tags' => false, + 'ff_event_normal' => false, + 'ff_event_warning' => false, + 'ff_event_critical' => false, + 'each_ff' => false, + ] +); -$search_id_group = (int) get_parameter ('search_id_group'); -$search_string = (string) get_parameter ('search_string'); +$search_id_group = (int) get_parameter('search_id_group'); +$search_string = (string) get_parameter('search_string'); $table = new stdClass(); $table->width = '100%'; $table->class = 'databox filters'; -$table->style = array (); +$table->style = []; $table->style[0] = 'font-weight: bold'; $table->style[2] = 'font-weight: bold'; -$table->data = array (); +$table->data = []; $table->data[0][0] = __('Group'); -$component_groups = network_components_get_groups (); +$component_groups = network_components_get_groups(); -if ($component_groups === false) - $component_groups = array(); +if ($component_groups === false) { + $component_groups = []; +} foreach ($component_groups as $component_group_key => $component_group_val) { - $num_components = db_get_num_rows( - 'SELECT id_nc + $num_components = db_get_num_rows( + 'SELECT id_nc FROM tnetwork_component - WHERE id_group = ' . $component_group_key); - - $childs = component_groups_get_childrens($component_group_key); - - $num_components_childs = 0; - - if ($childs !== false) { - - foreach ($childs as $child) { - - $num_components_childs += db_get_num_rows( - 'SELECT id + WHERE id_group = '.$component_group_key + ); + + $childs = component_groups_get_childrens($component_group_key); + + $num_components_childs = 0; + + if ($childs !== false) { + foreach ($childs as $child) { + $num_components_childs += db_get_num_rows( + 'SELECT id FROM tlocal_component - WHERE id_network_component_group = ' . $child['id_sg']); - - } - - } - - // Only show component groups with local components - if ($num_components == 0 && $num_components_childs == 0) - unset($component_groups[$component_group_key]); + WHERE id_network_component_group = '.$child['id_sg'] + ); + } + } + + // Only show component groups with local components + if ($num_components == 0 && $num_components_childs == 0) { + unset($component_groups[$component_group_key]); + } } -$table->data[0][1] = html_print_select ($component_groups, - 'search_id_group', $search_id_group, '', __('All'), 0, true, false, false); -$table->data[0][2] = __('Free Search') . ui_print_help_tip( - __('Search by name, description, tcp send or tcp rcv, list matches.'),true); -$table->data[0][3] = html_print_input_text ('search_string', $search_string, '', 25, - 255, true); -if(defined("METACONSOLE")) - $table->data[0][4] = '
    '; -else - $table->data[0][4] = '
    '; -$table->data[0][4] .= html_print_submit_button (__('Search'), 'search', false, - 'class="sub search"', true); +$table->data[0][1] = html_print_select( + $component_groups, + 'search_id_group', + $search_id_group, + '', + __('All'), + 0, + true, + false, + false +); +$table->data[0][2] = __('Free Search').ui_print_help_tip( + __('Search by name, description, tcp send or tcp rcv, list matches.'), + true +); +$table->data[0][3] = html_print_input_text( + 'search_string', + $search_string, + '', + 25, + 255, + true +); +if (defined('METACONSOLE')) { + $table->data[0][4] = '
    '; +} else { + $table->data[0][4] = '
    '; +} + +$table->data[0][4] .= html_print_submit_button( + __('Search'), + 'search', + false, + 'class="sub search"', + true +); $table->data[0][4] .= '
    '; -if (defined("METACONSOLE")) { - $filter = '
    '; - $filter .= html_print_table ($table,true); - $filter .= '
    '; - ui_toggle($filter, __("Show Options")); -} -else { - echo '
    '; - html_print_table ($table); - echo '
    '; +if (defined('METACONSOLE')) { + $filter = '
    '; + $filter .= html_print_table($table, true); + $filter .= '
    '; + ui_toggle($filter, __('Show Options')); +} else { + echo '
    '; + html_print_table($table); + echo '
    '; } -$filter = array (); -if ($search_id_group) - $filter['id_group'] = $search_id_group; -if ($search_string != '') - $filter[] = '(name LIKE ' . "'%" . $search_string . "%'" . - 'OR description LIKE ' . "'%". $search_string . "%'" . - 'OR tcp_send LIKE ' . "'%" . $search_string . "%'" . - 'OR tcp_rcv LIKE ' . "'%" . $search_string . "%'" . ')'; +$filter = []; +if ($search_id_group) { + $filter['id_group'] = $search_id_group; +} -$total_components = network_components_get_network_components (false, $filter, 'COUNT(*) AS total'); +if ($search_string != '') { + $filter[] = '(name LIKE '."'%".$search_string."%'".'OR description LIKE '."'%".$search_string."%'".'OR tcp_send LIKE '."'%".$search_string."%'".'OR tcp_rcv LIKE '."'%".$search_string."%'".')'; +} + +$total_components = network_components_get_network_components(false, $filter, 'COUNT(*) AS total'); $total_components = $total_components[0]['total']; -ui_pagination ($total_components, $url); -$filter['offset'] = (int) get_parameter ('offset'); +ui_pagination($total_components, $url); +$filter['offset'] = (int) get_parameter('offset'); $filter['limit'] = (int) $config['block_size']; -$components = network_components_get_network_components (false, $filter, - array ('id_nc', 'name', 'description', 'id_group', 'type', 'max', 'min', - 'module_interval', 'id_modulo')); -if ($components === false) - $components = array (); +$components = network_components_get_network_components( + false, + $filter, + [ + 'id_nc', + 'name', + 'description', + 'id_group', + 'type', + 'max', + 'min', + 'module_interval', + 'id_modulo', + ] +); +if ($components === false) { + $components = []; +} -unset ($table); +unset($table); $table->width = '100%'; -$table->head = array (); +$table->head = []; $table->class = 'databox data'; $table->head[0] = __('Module name'); $table->head[1] = __('Type'); $table->head[3] = __('Description'); $table->head[4] = __('Group'); $table->head[5] = __('Max/Min'); -$table->head[6] = __('Action') . - html_print_checkbox('all_delete', 0, false, true, false); -$table->size = array (); +$table->head[6] = __('Action').html_print_checkbox('all_delete', 0, false, true, false); +$table->size = []; $table->size[1] = '75px'; $table->size[6] = '80px'; $table->align[6] = 'left'; -$table->data = array (); +$table->data = []; foreach ($components as $component) { - $data = array (); - - if ($component['max'] == $component['min'] && $component['max'] == 0) { - $component['max'] = $component['min'] = __('N/A'); - } - - $data[0] = ''; - $data[0] .= io_safe_output($component['name']); - $data[0] .= ''; - $data[1] = ui_print_moduletype_icon ($component['type'], true); - switch ($component['id_modulo']) { - case MODULE_NETWORK: - $data[1] .= html_print_image('images/network.png', true, - array('title' => __('Network module'))); - break; - case MODULE_WMI: - $data[1] .= html_print_image('images/wmi.png', true, - array('title' => __('WMI module'))); - break; - case MODULE_PLUGIN: - $data[1] .= html_print_image('images/plugin.png', true, - array('title' => __('Plug-in module'))); - break; - } - $data[3] = "". - mb_strimwidth (io_safe_output($component['description']), 0, 60, "...") . ""; - $data[4] = network_components_get_group_name ($component['id_group']); - $data[5] = $component['max']." / ".$component['min']; - - $data[6] = '' . - html_print_image('images/copy.png', true, array('alt' => __('Duplicate'), 'title' => __('Duplicate'))) . ''; - $data[6] .= '' . - html_print_image('images/cross.png', true, array('alt' => __('Delete'), 'title' => __('Delete'))) . '' . - html_print_checkbox_extended ('delete_multiple[]', $component['id_nc'], false, false, '', 'class="check_delete"', true); - - array_push ($table->data, $data); + $data = []; + + if ($component['max'] == $component['min'] && $component['max'] == 0) { + $component['max'] = $component['min'] = __('N/A'); + } + + $data[0] = ''; + $data[0] .= io_safe_output($component['name']); + $data[0] .= ''; + $data[1] = ui_print_moduletype_icon($component['type'], true); + switch ($component['id_modulo']) { + case MODULE_NETWORK: + $data[1] .= html_print_image( + 'images/network.png', + true, + ['title' => __('Network module')] + ); + break; + + case MODULE_WMI: + $data[1] .= html_print_image( + 'images/wmi.png', + true, + ['title' => __('WMI module')] + ); + break; + + case MODULE_PLUGIN: + $data[1] .= html_print_image( + 'images/plugin.png', + true, + ['title' => __('Plug-in module')] + ); + break; + } + + $data[3] = "".mb_strimwidth(io_safe_output($component['description']), 0, 60, '...').''; + $data[4] = network_components_get_group_name($component['id_group']); + $data[5] = $component['max'].' / '.$component['min']; + + $data[6] = ''.html_print_image('images/copy.png', true, ['alt' => __('Duplicate'), 'title' => __('Duplicate')]).''; + $data[6] .= ''.html_print_image('images/cross.png', true, ['alt' => __('Delete'), 'title' => __('Delete')]).''.html_print_checkbox_extended('delete_multiple[]', $component['id_nc'], false, false, '', 'class="check_delete"', true); + + array_push($table->data, $data); } if (isset($data)) { - echo "
    "; - html_print_input_hidden('multiple_delete', 1); - html_print_table ($table); - echo "
    "; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - echo "
    "; - echo "
    "; -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined network components') ) ); + echo "
    "; + html_print_input_hidden('multiple_delete', 1); + html_print_table($table); + echo "
    "; + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + echo '
    '; + echo '
    '; +} else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined network components') ]); } -echo '
    '; +echo ''; echo '
    '; -html_print_input_hidden ('new_component', 1); -html_print_select (array( - 2 => __('Create a new network component'), - 4 => __('Create a new plugin component'), - 6 => __('Create a new WMI component')), - 'id_component_type', '', '', '', '', ''); -html_print_submit_button (__('Create'), 'crt', false, 'class="sub next" style="margin-left: 5px;"'); +html_print_input_hidden('new_component', 1); +html_print_select( + [ + 2 => __('Create a new network component'), + 4 => __('Create a new plugin component'), + 6 => __('Create a new WMI component'), + ], + 'id_component_type', + '', + '', + '', + '', + '' +); +html_print_submit_button(__('Create'), 'crt', false, 'class="sub next" style="margin-left: 5px;"'); echo '
    '; echo '
    '; @@ -650,29 +731,29 @@ enterprise_hook('close_meta_frame'); ?> diff --git a/pandora_console/godmode/modules/manage_network_components_form.php b/pandora_console/godmode/modules/manage_network_components_form.php index 5c5eb2ec8e..3f9a33cb8a 100644 --- a/pandora_console/godmode/modules/manage_network_components_form.php +++ b/pandora_console/godmode/modules/manage_network_components_form.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,17 +11,18 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Management' + ); + include 'general/noaccess.php'; + exit; } $create_network_from_module = get_parameter('create_network_from_module'); @@ -30,254 +30,258 @@ $create_network_from_snmp_browser = get_parameter('create_network_from_snmp_brow $pure = get_parameter('pure', 0); if ($create_network_from_module) { - - $id_agentmodule = get_parameter('create_module_from'); - $data_module = db_get_row_filter('tagente_modulo', array ('id_agente_modulo' => $id_agentmodule)); - - $name = $data_module["nombre"]; - $description = $data_module["descripcion"]; - $type = $data_module["id_tipo_modulo"]; - $max = $data_module["max"]; - $min = $data_module["min"]; - $module_interval = $data_module["module_interval"]; - $tcp_port = $data_module["tcp_port"]; - $tcp_rcv = $data_module["tcp_rcv"]; - $tcp_send = $data_module["tcp_send"]; - $snmp_community = $data_module["snmp_community"]; - $snmp_oid = $data_module["snmp_oid"]; - $id_module_group = $data_module["id_module_group"]; - $id_plugin = $data_module["id_plugin"]; - $plugin_user = $data_module["plugin_user"]; - $plugin_pass = $data_module["plugin_pass"]; - $plugin_parameter = $data_module["plugin_parameter"]; - $macros = $data_module["macros"]; - $max_timeout = $data_module["max_timeout"]; - $max_retries = $data_module["max_retries"]; - $dynamic_interval = $data_module['dynamic_interval']; - $dynamic_max = $data_module['dynamic_max']; - $dynamic_min = $data_module['dynamic_min']; - $dynamic_two_tailed = $data_module['dynamic_two_tailed']; - $min_warning = $data_module["min_warning"]; - $max_warning = $data_module["max_warning"]; - $str_warning = $data_module["str_warning"]; - $max_critical = $data_module["max_critical"]; - $min_critical = $data_module["min_critical"]; - $str_critical = $data_module["str_critical"]; - $ff_event = $data_module["min_ff_event"]; - $history_data = $data_module["history_data"]; - $post_process = $data_module["post_process"]; - $unit = $data_module["unit"]; - $wizard_level = $data_module["wizard_level"]; - $critical_instructions = $data_module["critical_instructions"]; - $warning_instructions = $data_module["warning_instructions"]; - $unknown_instructions = $data_module["unknown_instructions"]; - $critical_inverse = $data_module["critical_inverse"]; - $warning_inverse = $data_module["warning_inverse"]; - $id_category = $data_module["id_category"]; - $ff_event_normal = $data_module["min_ff_event_normal"]; - $ff_event_warning = $data_module["min_ff_event_warning"]; - $ff_event_critical = $data_module["min_ff_event_critical"]; - $each_ff = $data_module["each_ff"]; + $id_agentmodule = get_parameter('create_module_from'); + $data_module = db_get_row_filter('tagente_modulo', ['id_agente_modulo' => $id_agentmodule]); + + $name = $data_module['nombre']; + $description = $data_module['descripcion']; + $type = $data_module['id_tipo_modulo']; + $max = $data_module['max']; + $min = $data_module['min']; + $module_interval = $data_module['module_interval']; + $tcp_port = $data_module['tcp_port']; + $tcp_rcv = $data_module['tcp_rcv']; + $tcp_send = $data_module['tcp_send']; + $snmp_community = $data_module['snmp_community']; + $snmp_oid = $data_module['snmp_oid']; + $id_module_group = $data_module['id_module_group']; + $id_plugin = $data_module['id_plugin']; + $plugin_user = $data_module['plugin_user']; + $plugin_pass = io_output_password($data_module['plugin_pass']); + $plugin_parameter = $data_module['plugin_parameter']; + $macros = $data_module['macros']; + $max_timeout = $data_module['max_timeout']; + $max_retries = $data_module['max_retries']; + $dynamic_interval = $data_module['dynamic_interval']; + $dynamic_max = $data_module['dynamic_max']; + $dynamic_min = $data_module['dynamic_min']; + $dynamic_two_tailed = $data_module['dynamic_two_tailed']; + $min_warning = $data_module['min_warning']; + $max_warning = $data_module['max_warning']; + $str_warning = $data_module['str_warning']; + $max_critical = $data_module['max_critical']; + $min_critical = $data_module['min_critical']; + $str_critical = $data_module['str_critical']; + $ff_event = $data_module['min_ff_event']; + $history_data = $data_module['history_data']; + $post_process = $data_module['post_process']; + $unit = $data_module['unit']; + $wizard_level = $data_module['wizard_level']; + $critical_instructions = $data_module['critical_instructions']; + $warning_instructions = $data_module['warning_instructions']; + $unknown_instructions = $data_module['unknown_instructions']; + $critical_inverse = $data_module['critical_inverse']; + $warning_inverse = $data_module['warning_inverse']; + $id_category = $data_module['id_category']; + $ff_event_normal = $data_module['min_ff_event_normal']; + $ff_event_warning = $data_module['min_ff_event_warning']; + $ff_event_critical = $data_module['min_ff_event_critical']; + $each_ff = $data_module['each_ff']; } -$id_component_type = (int) get_parameter ('id_component_type'); +$id_component_type = (int) get_parameter('id_component_type'); if ($create_network_from_module) { - $id_component_type = 2; + $id_component_type = 2; } -if (isset ($id)) { - $component = network_components_get_network_component ((int) $id); - if ($component !== false) { - $id_component_type = $component['id_modulo']; - $name = $component["name"]; - $type = $component["type"]; - $description = $component["description"]; - $max = $component["max"]; - $min = $component["min"]; - $module_interval = $component["module_interval"]; - $tcp_port = $component["tcp_port"]; - $tcp_rcv = $component["tcp_rcv"]; - $tcp_send = $component["tcp_send"]; - $snmp_community = $component["snmp_community"]; - $snmp_oid = $component["snmp_oid"]; - $id_module_group = $component["id_module_group"]; - $id_group = $component["id_group"]; - $id_plugin = $component['id_plugin']; - $plugin_user = $component["plugin_user"]; - $plugin_pass = $component["plugin_pass"]; - $plugin_parameter = $component["plugin_parameter"]; - $macros = $component["macros"]; - $max_timeout = $component["max_timeout"]; - $max_retries = $component["max_retries"]; - $dynamic_interval = $component['dynamic_interval']; - $dynamic_max = $component['dynamic_max']; - $dynamic_min = $component['dynamic_min']; - $dynamic_two_tailed = $component['dynamic_two_tailed']; - $min_warning = $component["min_warning"]; - $max_warning = $component["max_warning"]; - $str_warning = $component["str_warning"]; - $max_critical = $component["max_critical"]; - $min_critical = $component["min_critical"]; - $str_critical = $component["str_critical"]; - $ff_event = $component["min_ff_event"]; - $history_data = $component["history_data"]; - $post_process = $component["post_process"]; - $unit = $component["unit"]; - $wizard_level = $component["wizard_level"]; - $critical_instructions = $component["critical_instructions"]; - $warning_instructions = $component["warning_instructions"]; - $unknown_instructions = $component["unknown_instructions"]; - $critical_inverse = $component["critical_inverse"]; - $warning_inverse = $component["warning_inverse"]; - $id_category = $component["id_category"]; - $tags = $component["tags"]; - $ff_event_normal = $component["min_ff_event_normal"]; - $ff_event_warning = $component["min_ff_event_warning"]; - $ff_event_critical = $component["min_ff_event_critical"]; - $each_ff = $component["each_ff"]; - - if ($type >= 15 && $type <= 18) { - // New support for snmp v3 - $snmp_version = $component["tcp_send"]; - $snmp3_auth_user = $component["plugin_user"]; - $snmp3_auth_pass = $component["plugin_pass"]; - $snmp3_auth_method = $component["plugin_parameter"]; - $snmp3_privacy_method = $component["custom_string_1"]; - $snmp3_privacy_pass = $component["custom_string_2"]; - $snmp3_security_level = $component["custom_string_3"]; - } - } - elseif (isset ($new_component) && $new_component && !$create_network_from_snmp_browser) { - - $name = ""; - $snmp_oid = ""; - $description = ""; - $id_group = 1; - $oid = ""; - $max = "0"; - $min = "0"; - $module_interval = "300"; - $tcp_port = ""; - $tcp_rcv = ""; - $tcp_send = ""; - $snmp_community = ""; - $id_module_group = ""; - if ($id_component_type == 6) $id_group = 14; - else $id_group = ""; - $type = 0; - $min_warning = 0; - $max_warning = 0; - $str_warning = ''; - $dynamic_interval = 0; - $dynamic_min = 0; - $dynamic_max = 0; - $dynamic_two_tailed = 0; - $max_critical = 0; - $min_critical = 0; - $str_critical = ''; - $ff_event = 0; - $history_data = true; - $post_process = 0; - $unit = ''; - $wizard_level = 'nowizard'; - $critical_instructions = ''; - $warning_instructions = ''; - $unknown_instructions = ''; - $critical_inverse = 0; - $warning_inverse = 0; - $id_category = 0; - $tags = ''; - $ff_event_normal = 0; - $ff_event_warning = 0; - $ff_event_critical = 0; - $each_ff = 0; - - $snmp_version = 1; - $snmp3_auth_user = ''; - $snmp3_auth_pass = ''; - $snmp3_privacy_method = ''; - $snmp3_privacy_pass = ''; - $snmp3_auth_method = ''; - $snmp3_security_level = ''; - - } +if (isset($id)) { + $component = network_components_get_network_component((int) $id); + if ($component !== false) { + $id_component_type = $component['id_modulo']; + $name = $component['name']; + $type = $component['type']; + $description = $component['description']; + $max = $component['max']; + $min = $component['min']; + $module_interval = $component['module_interval']; + $tcp_port = $component['tcp_port']; + $tcp_rcv = $component['tcp_rcv']; + $tcp_send = $component['tcp_send']; + $snmp_community = $component['snmp_community']; + $snmp_oid = $component['snmp_oid']; + $id_module_group = $component['id_module_group']; + $id_group = $component['id_group']; + $id_plugin = $component['id_plugin']; + $plugin_user = $component['plugin_user']; + $plugin_pass = io_output_password($component['plugin_pass']); + $plugin_parameter = $component['plugin_parameter']; + $macros = $component['macros']; + $max_timeout = $component['max_timeout']; + $max_retries = $component['max_retries']; + $dynamic_interval = $component['dynamic_interval']; + $dynamic_max = $component['dynamic_max']; + $dynamic_min = $component['dynamic_min']; + $dynamic_two_tailed = $component['dynamic_two_tailed']; + $min_warning = $component['min_warning']; + $max_warning = $component['max_warning']; + $str_warning = $component['str_warning']; + $max_critical = $component['max_critical']; + $min_critical = $component['min_critical']; + $str_critical = $component['str_critical']; + $ff_event = $component['min_ff_event']; + $history_data = $component['history_data']; + $post_process = $component['post_process']; + $unit = $component['unit']; + $wizard_level = $component['wizard_level']; + $critical_instructions = $component['critical_instructions']; + $warning_instructions = $component['warning_instructions']; + $unknown_instructions = $component['unknown_instructions']; + $critical_inverse = $component['critical_inverse']; + $warning_inverse = $component['warning_inverse']; + $id_category = $component['id_category']; + $tags = $component['tags']; + $ff_event_normal = $component['min_ff_event_normal']; + $ff_event_warning = $component['min_ff_event_warning']; + $ff_event_critical = $component['min_ff_event_critical']; + $each_ff = $component['each_ff']; + + if ($type >= 15 && $type <= 18) { + // New support for snmp v3 + $snmp_version = $component['tcp_send']; + $snmp3_auth_user = $component['plugin_user']; + $snmp3_auth_pass = io_output_password($component['plugin_pass']); + $snmp3_auth_method = $component['plugin_parameter']; + $snmp3_privacy_method = $component['custom_string_1']; + $snmp3_privacy_pass = io_output_password($component['custom_string_2']); + $snmp3_security_level = $component['custom_string_3']; + } + } else if (isset($new_component) && $new_component && !$create_network_from_snmp_browser) { + $name = ''; + $snmp_oid = ''; + $description = ''; + $id_group = 1; + $oid = ''; + $max = '0'; + $min = '0'; + $module_interval = '300'; + $tcp_port = ''; + $tcp_rcv = ''; + $tcp_send = ''; + $snmp_community = ''; + $id_module_group = ''; + if ($id_component_type == 6) { + $id_group = 14; + } else { + $id_group = ''; + } + + $type = 0; + $min_warning = 0; + $max_warning = 0; + $str_warning = ''; + $dynamic_interval = 0; + $dynamic_min = 0; + $dynamic_max = 0; + $dynamic_two_tailed = 0; + $max_critical = 0; + $min_critical = 0; + $str_critical = ''; + $ff_event = 0; + $history_data = true; + $post_process = 0; + $unit = ''; + $wizard_level = 'nowizard'; + $critical_instructions = ''; + $warning_instructions = ''; + $unknown_instructions = ''; + $critical_inverse = 0; + $warning_inverse = 0; + $id_category = 0; + $tags = ''; + $ff_event_normal = 0; + $ff_event_warning = 0; + $ff_event_critical = 0; + $each_ff = 0; + + $snmp_version = 1; + $snmp3_auth_user = ''; + $snmp3_auth_pass = ''; + $snmp3_privacy_method = ''; + $snmp3_privacy_pass = ''; + $snmp3_auth_method = ''; + $snmp3_security_level = ''; + } } if ($create_network_from_snmp_browser) { } -/** +/* * $id_component_type has these values: * 6 - Module WMI * 4 - Plugin component * 2 - network component - * + * * You can see this values in file godmode/modules/manage_network_components.php * in the last lines (in the call function "html_print_select"). */ $table = new stdClass(); if ($id_component_type == 6) { - $categories = array (0, 1, 2); - require ($config['homedir'] . - "/godmode/modules/manage_network_components_form_common.php"); - require ($config['homedir'] . - "/godmode/modules/manage_network_components_form_wmi.php"); -} -else if ($id_component_type == 4) { - $categories = array (0, 1, 2); - require ($config['homedir'] . - "/godmode/modules/manage_network_components_form_common.php"); - require ($config['homedir'] . - "/godmode/modules/manage_network_components_form_plugin.php"); -} -else if ($id_component_type == 2 || $create_network_from_module) { - $categories = array (3, 4, 5); - require ($config['homedir'] . - "/godmode/modules/manage_network_components_form_common.php"); - require ($config['homedir'] . - "/godmode/modules/manage_network_components_form_network.php"); -} -else { - return; + $categories = [ + 0, + 1, + 2, + ]; + include $config['homedir'].'/godmode/modules/manage_network_components_form_common.php'; + include $config['homedir'].'/godmode/modules/manage_network_components_form_wmi.php'; +} else if ($id_component_type == 4) { + $categories = [ + 0, + 1, + 2, + ]; + include $config['homedir'].'/godmode/modules/manage_network_components_form_common.php'; + include $config['homedir'].'/godmode/modules/manage_network_components_form_plugin.php'; +} else if ($id_component_type == 2 || $create_network_from_module) { + $categories = [ + 3, + 4, + 5, + ]; + include $config['homedir'].'/godmode/modules/manage_network_components_form_common.php'; + include $config['homedir'].'/godmode/modules/manage_network_components_form_network.php'; +} else { + return; } echo '
    '; $table->width = '100%'; $table->class = 'databox filters'; -/* $table came from manage_network_components_form_common.php */ +// $table came from manage_network_components_form_common.php if (defined('METACONSOLE')) { - if ($id) { - $table->head[0] = __('Update Network Component'); - } - else { - $table->head[0] = __('Create Network Component'); - } - $table->head_colspan[0] = 5; - $table->headstyle[0] = 'text-align: center'; -} -$table->colspan['description'][1] = 3; -$data = array (); -$data[0] = __('Description'); -$data[1] = html_print_textarea ('description', 2, 65, $description, '', true); -push_table_row ($data, 'description'); + if ($id) { + $table->head[0] = __('Update Network Component'); + } else { + $table->head[0] = __('Create Network Component'); + } -html_print_table ($table); + $table->head_colspan[0] = 5; + $table->headstyle[0] = 'text-align: center'; +} + +$table->colspan['description'][1] = 3; +$data = []; +$data[0] = __('Description'); +$data[1] = html_print_textarea('description', 2, 65, $description, '', true); +push_table_row($data, 'description'); + +html_print_table($table); echo '
    '; -html_print_input_hidden ('id_component_type', $id_component_type); +html_print_input_hidden('id_component_type', $id_component_type); if ($id) { - html_print_input_hidden ('update_component', 1); - html_print_input_hidden ('id', $id); - html_print_submit_button (__('Update'), 'upd', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create_component', 1); - html_print_input_hidden ('create_network_from_module', 0); - html_print_submit_button (__('Create'), 'crt', false, 'class="sub wand"'); + html_print_input_hidden('update_component', 1); + html_print_input_hidden('id', $id); + html_print_submit_button(__('Update'), 'upd', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create_component', 1); + html_print_input_hidden('create_network_from_module', 0); + html_print_submit_button(__('Create'), 'crt', false, 'class="sub wand"'); } + echo '
    '; echo '
    '; @@ -286,373 +290,373 @@ ui_require_javascript_file('pandora_modules'); diff --git a/pandora_console/godmode/modules/manage_network_components_form_network.php b/pandora_console/godmode/modules/manage_network_components_form_network.php index ec07cb1b50..329d8d1405 100755 --- a/pandora_console/godmode/modules/manage_network_components_form_network.php +++ b/pandora_console/godmode/modules/manage_network_components_form_network.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,21 +11,22 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Management' + ); + include 'general/noaccess.php'; + return; } if (!$id && !isset($snmp_community)) { - $snmp_community = "public"; + $snmp_community = 'public'; } $snmp_versions['1'] = 'v. 1'; @@ -34,88 +34,118 @@ $snmp_versions['2'] = 'v. 2'; $snmp_versions['2c'] = 'v. 2c'; $snmp_versions['3'] = 'v. 3'; -$data = array (); +$data = []; $data[0] = __('Port'); -$data[1] = html_print_input_text ('tcp_port', $tcp_port, '', 5, 20, true); +$data[1] = html_print_input_text('tcp_port', $tcp_port, '', 5, 20, true); $data[2] = __('SNMP version'); -$data[3] = html_print_select ($snmp_versions, 'snmp_version', $snmp_version, - '', '', '', true, false, false, ''); +$data[3] = html_print_select( + $snmp_versions, + 'snmp_version', + $snmp_version, + '', + '', + '', + true, + false, + false, + '' +); -push_table_row ($data, 'snmp_port'); +push_table_row($data, 'snmp_port'); -$data = array (); +$data = []; $data[0] = __('SNMP Enterprise String'); -$data[1] = html_print_input_text ('snmp_oid', $snmp_oid, '', 30, 400, true); -//$table->colspan['snmp_2'][1] = 3; +$data[1] = html_print_input_text('snmp_oid', $snmp_oid, '', 30, 400, true); +// $table->colspan['snmp_2'][1] = 3; $data[2] = __('SNMP community'); -$data[3] = html_print_input_text ('snmp_community', $snmp_community, '', 15, 60, true); +$data[3] = html_print_input_text('snmp_community', $snmp_community, '', 15, 60, true); -push_table_row ($data, 'snmp_2'); +push_table_row($data, 'snmp_2'); -$data = array(); +$data = []; $data[0] = __('Auth user'); -$data[1] = html_print_input_text ('snmp3_auth_user', $snmp3_auth_user, '', 15, 60, true); +$data[1] = html_print_input_text('snmp3_auth_user', $snmp3_auth_user, '', 15, 60, true); $data[2] = __('Auth password'); -$data[3] = html_print_input_password ('snmp3_auth_pass', $snmp3_auth_pass, '', 15, 60, true); +$data[3] = html_print_input_password('snmp3_auth_pass', $snmp3_auth_pass, '', 15, 60, true); $data[3] .= html_print_input_hidden_extended('active_snmp_v3', 0, 'active_snmp_v3_mncfn', true); push_table_row($data, 'field_snmpv3_row1'); -$data = array(); +$data = []; $data[0] = __('Privacy method'); -$data[1] = html_print_select(array('DES' => __('DES'), 'AES' => __('AES')), 'snmp3_privacy_method', $snmp3_privacy_method, '', '', '', true); +$data[1] = html_print_select(['DES' => __('DES'), 'AES' => __('AES')], 'snmp3_privacy_method', $snmp3_privacy_method, '', '', '', true); $data[2] = __('Privacy pass'); -$data[3] = html_print_input_password ('snmp3_privacy_pass', $snmp3_privacy_pass, '', 15, 60, true); +$data[3] = html_print_input_password('snmp3_privacy_pass', $snmp3_privacy_pass, '', 15, 60, true); push_table_row($data, 'field_snmpv3_row2'); -$data = array(); +$data = []; $data[0] = __('Auth method'); -$data[1] = html_print_select(array('MD5' => __('MD5'), 'SHA' => __('SHA')), 'snmp3_auth_method', $snmp3_auth_method, '', '', '', true); +$data[1] = html_print_select(['MD5' => __('MD5'), 'SHA' => __('SHA')], 'snmp3_auth_method', $snmp3_auth_method, '', '', '', true); $data[2] = __('Security level'); -$data[3] = html_print_select(array('noAuthNoPriv' => __('Not auth and not privacy method'), - 'authNoPriv' => __('Auth and not privacy method'), 'authPriv' => __('Auth and privacy method')), 'snmp3_security_level', $snmp3_security_level, '', '', '', true); +$data[3] = html_print_select( + [ + 'noAuthNoPriv' => __('Not auth and not privacy method'), + 'authNoPriv' => __('Auth and not privacy method'), + 'authPriv' => __('Auth and privacy method'), + ], + 'snmp3_security_level', + $snmp3_security_level, + '', + '', + '', + true +); push_table_row($data, 'field_snmpv3_row3'); -$data = array(); -$data[0] = __('Post process') . ' ' . ui_print_help_icon ('postprocess', true ); -$data[1] = html_print_extended_select_for_post_process('post_process', - $post_process, '', __('Empty'), '0', false, true, false, true); +$data = []; +$data[0] = __('Post process').' '.ui_print_help_icon('postprocess', true); +$data[1] = html_print_extended_select_for_post_process( + 'post_process', + $post_process, + '', + __('Empty'), + '0', + false, + true, + false, + true +); $data[2] = $data[3] = ''; push_table_row($data, 'field_process'); -/* Advanced stuff */ -$data = array (); -$data[0] = __('TCP send') . ' ' . ui_print_help_icon ("tcp_send", true); -$data[1] = html_print_textarea ('tcp_send', 2, 65, $tcp_send, '', true); +// Advanced stuff +$data = []; +$data[0] = __('TCP send').' '.ui_print_help_icon('tcp_send', true); +$data[1] = html_print_textarea('tcp_send', 2, 65, $tcp_send, '', true); $table->colspan['tcp_send'][1] = 3; -push_table_row ($data, 'tcp_send'); +push_table_row($data, 'tcp_send'); -$data = array(); +$data = []; $data[0] = __('TCP receive'); -$data[1] = html_print_textarea ('tcp_rcv', 2, 65, $tcp_rcv, '', true); +$data[1] = html_print_textarea('tcp_rcv', 2, 65, $tcp_rcv, '', true); $table->colspan['tcp_receive'][1] = 3; -push_table_row ($data, 'tcp_receive'); +push_table_row($data, 'tcp_receive'); ?> diff --git a/pandora_console/godmode/modules/manage_network_components_form_plugin.php b/pandora_console/godmode/modules/manage_network_components_form_plugin.php index 4b10cdaaea..edbabe69eb 100755 --- a/pandora_console/godmode/modules/manage_network_components_form_plugin.php +++ b/pandora_console/godmode/modules/manage_network_components_form_plugin.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,55 +11,71 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global variables global $config; -check_login (); +check_login(); -$data = array (); +$data = []; $data[0] = __('Plugin'); -$data[1] = html_print_select_from_sql ('SELECT id, name FROM tplugin ORDER BY name', - 'id_plugin', $id_plugin, 'javascript: load_plugin_macros_fields(\'network_component-macro\')', __('None'), 0, true, false, false); +$data[1] = html_print_select_from_sql( + 'SELECT id, name FROM tplugin ORDER BY name', + 'id_plugin', + $id_plugin, + 'javascript: load_plugin_macros_fields(\'network_component-macro\')', + __('None'), + 0, + true, + false, + false +); // Store the macros in base64 into a hidden control to move between pages -$data[1] .= html_print_input_hidden('macros',base64_encode($macros),true); -$data[2] = __('Post process') . ' ' . ui_print_help_icon ('postprocess', true, ui_get_full_url(false, false, false, false)); -$data[3] = html_print_extended_select_for_post_process('post_process', - $post_process, '', __('Empty'), '0', false, true, false, true); +$data[1] .= html_print_input_hidden('macros', base64_encode($macros), true); +$data[2] = __('Post process').' '.ui_print_help_icon('postprocess', true, ui_get_full_url(false, false, false, false)); +$data[3] = html_print_extended_select_for_post_process( + 'post_process', + $post_process, + '', + __('Empty'), + '0', + false, + true, + false, + true +); -push_table_row ($data, 'plugin_1'); +push_table_row($data, 'plugin_1'); // A hidden "model row" to clone it from javascript to add fields dynamicly -$data = array (); +$data = []; $data[0] = 'macro_desc'; -$data[0] .= ui_print_help_tip ('macro_help', true); -$data[1] = html_print_input_text ('macro_name', 'macro_value', '', 100, 1024, true); +$data[0] .= ui_print_help_tip('macro_help', true); +$data[1] = html_print_input_text('macro_name', 'macro_value', '', 100, 1024, true); $table->colspan['macro_field'][1] = 3; $table->rowstyle['macro_field'] = 'display:none'; -push_table_row ($data, 'macro_field'); +push_table_row($data, 'macro_field'); // If there are $macros, we create the form fields if (!empty($macros)) { - $macros = json_decode($macros, true); - - foreach ($macros as $k => $m) { - $data = array (); - $data[0] = $m['desc']; - if (!empty($m['help'])) { - $data[0] .= ui_print_help_tip ($m['help'], true); - } - if ($m['hide'] == 1) { - $data[1] = html_print_input_text($m['macro'], $m['value'], '', 100, 1024, true); - } else { - $data[1] = html_print_input_text($m['macro'], io_output_password($m['value']), '', 100, 1024, true); - } - $table->colspan['macro'.$m['macro']][1] = 3; - $table->rowclass['macro'.$m['macro']] = 'macro_field'; - - push_table_row ($data, 'macro'.$m['macro']); - } + $macros = json_decode($macros, true); + + foreach ($macros as $k => $m) { + $data = []; + $data[0] = $m['desc']; + if (!empty($m['help'])) { + $data[0] .= ui_print_help_tip($m['help'], true); + } + + if ($m['hide'] == 1) { + $data[1] = html_print_input_text($m['macro'], $m['value'], '', 100, 1024, true); + } else { + $data[1] = html_print_input_text($m['macro'], io_output_password($m['value']), '', 100, 1024, true); + } + + $table->colspan['macro'.$m['macro']][1] = 3; + $table->rowclass['macro'.$m['macro']] = 'macro_field'; + + push_table_row($data, 'macro'.$m['macro']); + } } - -?> - diff --git a/pandora_console/godmode/modules/manage_network_components_form_wmi.php b/pandora_console/godmode/modules/manage_network_components_form_wmi.php index f36791e69d..35b846250e 100755 --- a/pandora_console/godmode/modules/manage_network_components_form_wmi.php +++ b/pandora_console/godmode/modules/manage_network_components_form_wmi.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,50 +11,58 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global variables global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Management' + ); + include 'general/noaccess.php'; + return; } -include_once($config['homedir'] . "/include/functions_modules.php"); +require_once $config['homedir'].'/include/functions_modules.php'; -$data = array (); +$data = []; $data[0] = __('WMI query'); -$data[1] = html_print_input_text ('snmp_oid', $snmp_oid, '', 25, 255, true); -$data[2] = __('Key string') . ' ' . ui_print_help_icon ('wmikey', true, ui_get_full_url(false, false, false, false)); -$data[3] = html_print_input_text ('snmp_community', $snmp_community, '', 25, 255, true); +$data[1] = html_print_input_text('snmp_oid', $snmp_oid, '', 25, 255, true); +$data[2] = __('Key string').' '.ui_print_help_icon('wmikey', true, ui_get_full_url(false, false, false, false)); +$data[3] = html_print_input_text('snmp_community', $snmp_community, '', 25, 255, true); -push_table_row ($data, 'wmi_1'); +push_table_row($data, 'wmi_1'); -$data = array (); -$data[0] = __('Field number') . ' ' . ui_print_help_icon ('wmifield', true, ui_get_full_url(false, false, false, false)); -$data[1] = html_print_input_text ('tcp_port', $tcp_port, '', 5, 25, true); -$data[2] = __('Namespace') . ' ' . ui_print_help_icon ('wminamespace', true, ui_get_full_url(false, false, false, false)); -$data[3] = html_print_input_text ('tcp_send', $tcp_send, '', 25, 255, true); +$data = []; +$data[0] = __('Field number').' '.ui_print_help_icon('wmifield', true, ui_get_full_url(false, false, false, false)); +$data[1] = html_print_input_text('tcp_port', $tcp_port, '', 5, 25, true); +$data[2] = __('Namespace').' '.ui_print_help_icon('wminamespace', true, ui_get_full_url(false, false, false, false)); +$data[3] = html_print_input_text('tcp_send', $tcp_send, '', 25, 255, true); -push_table_row ($data, 'wmi_2'); +push_table_row($data, 'wmi_2'); -$data = array (); +$data = []; $data[0] = __('Username'); -$data[1] = html_print_input_text ('plugin_user', $plugin_user, '', 15, 255, true); +$data[1] = html_print_input_text('plugin_user', $plugin_user, '', 15, 255, true); $data[2] = __('Password'); -$data[3] = html_print_input_password ('plugin_pass', $plugin_pass, '', 25, 255, true); +$data[3] = html_print_input_password('plugin_pass', $plugin_pass, '', 25, 255, true); -push_table_row ($data, 'wmi_3'); +push_table_row($data, 'wmi_3'); -$data = array(); -$data[0] = __('Post process') . ' ' . ui_print_help_icon ('postprocess', true, ui_get_full_url(false, false, false, false)); -$data[1] = html_print_extended_select_for_post_process('post_process', - $post_process, '', __('Empty'), '0', false, true, false, true); +$data = []; +$data[0] = __('Post process').' '.ui_print_help_icon('postprocess', true, ui_get_full_url(false, false, false, false)); +$data[1] = html_print_extended_select_for_post_process( + 'post_process', + $post_process, + '', + __('Empty'), + '0', + false, + true, + false, + true +); $data[2] = $data[3] = ''; push_table_row($data, 'field_process'); -?> diff --git a/pandora_console/godmode/modules/manage_network_templates.php b/pandora_console/godmode/modules/manage_network_templates.php index c9cc2c1c1d..b179bdfd91 100644 --- a/pandora_console/godmode/modules/manage_network_templates.php +++ b/pandora_console/godmode/modules/manage_network_templates.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,93 +11,97 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Network Profile Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Network Profile Management' + ); + include 'general/noaccess.php'; + return; } // Header +/* + Hello there! :) -/* Hello there! :) + We added some of what seems to be "buggy" messages to the openSource version recently. This is not to force open-source users to move to the enterprise version, this is just to inform people using Pandora FMS open source that it requires skilled people to maintain and keep it running smoothly without professional support. This does not imply open-source version is limited in any way. If you check the recently added code, it contains only warnings and messages, no limitations except one: we removed the option to add custom logo in header. In the Update Manager section, it warns about the 'danger’ of applying automated updates without a proper backup, remembering in the process that the Enterprise version comes with a human-tested package. Maintaining an OpenSource version with more than 500 agents is not so easy, that's why someone using a Pandora with 8000 agents should consider asking for support. It's not a joke, we know of many setups with a huge number of agents, and we hate to hear that “its becoming unstable and slow” :( -We added some of what seems to be "buggy" messages to the openSource version recently. This is not to force open-source users to move to the enterprise version, this is just to inform people using Pandora FMS open source that it requires skilled people to maintain and keep it running smoothly without professional support. This does not imply open-source version is limited in any way. If you check the recently added code, it contains only warnings and messages, no limitations except one: we removed the option to add custom logo in header. In the Update Manager section, it warns about the 'danger’ of applying automated updates without a proper backup, remembering in the process that the Enterprise version comes with a human-tested package. Maintaining an OpenSource version with more than 500 agents is not so easy, that's why someone using a Pandora with 8000 agents should consider asking for support. It's not a joke, we know of many setups with a huge number of agents, and we hate to hear that “its becoming unstable and slow” :( - -You can of course remove the warnings, that's why we include the source and do not use any kind of trick. And that's why we added here this comment, to let you know this does not reflect any change in our opensource mentality of does the last 14 years. + You can of course remove the warnings, that's why we include the source and do not use any kind of trick. And that's why we added here this comment, to let you know this does not reflect any change in our opensource mentality of does the last 14 years. */ -ui_print_page_header (__('Module management')." » ".__('Module template management'), "images/gm_modules.png", false, "template_tab", true,"",true,"modulemodal"); +ui_print_page_header(__('Module management').' » '.__('Module template management'), 'images/gm_modules.png', false, 'template_tab', true, '', true, 'modulemodal'); -require_once ('include/functions_network_profiles.php'); +require_once 'include/functions_network_profiles.php'; -$delete_profile = (bool) get_parameter ('delete_profile'); -$export_profile = (bool) get_parameter ('export_profile'); -$multiple_delete = (bool)get_parameter('multiple_delete', 0); +$delete_profile = (bool) get_parameter('delete_profile'); +$export_profile = (bool) get_parameter('export_profile'); +$multiple_delete = (bool) get_parameter('multiple_delete', 0); -if ($delete_profile) { // if delete - $id = (int) get_parameter ('delete_profile'); - - $result = network_profiles_delete_network_profile ($id); - - if ($result) { - db_pandora_audit("Module management", "Delete module template #$id"); - } - else { - db_pandora_audit("Module management", "Fail try to delete module template #$id"); - } - - ui_print_result_message ($result, - __('Template successfully deleted'), - __('Error deleting template')); +if ($delete_profile) { + // if delete + $id = (int) get_parameter('delete_profile'); + + $result = network_profiles_delete_network_profile($id); + + if ($result) { + db_pandora_audit('Module management', "Delete module template #$id"); + } else { + db_pandora_audit('Module management', "Fail try to delete module template #$id"); + } + + ui_print_result_message( + $result, + __('Template successfully deleted'), + __('Error deleting template') + ); } if ($multiple_delete) { - $ids = (array)get_parameter('delete_multiple', array()); - - foreach ($ids as $id) { - $result = network_profiles_delete_network_profile ($id); - - if ($result === false) { - break; - } - } - - $str_ids = implode (',', $ids); - if ($result) { - db_pandora_audit("Module management", "Multiple delete module template: $str_ids"); - } - else { - db_pandora_audit("Module management", "Fail try to delete module template: $str_ids"); - } - - ui_print_result_message ($result, - __('Successfully multiple deleted'), - __('Not deleted. Error deleting multiple data')); + $ids = (array) get_parameter('delete_multiple', []); + + foreach ($ids as $id) { + $result = network_profiles_delete_network_profile($id); + + if ($result === false) { + break; + } + } + + $str_ids = implode(',', $ids); + if ($result) { + db_pandora_audit('Module management', "Multiple delete module template: $str_ids"); + } else { + db_pandora_audit('Module management', "Fail try to delete module template: $str_ids"); + } + + ui_print_result_message( + $result, + __('Successfully multiple deleted'), + __('Not deleted. Error deleting multiple data') + ); } if ($export_profile) { - $id = (int) get_parameter("export_profile"); - $profile_info = network_profiles_get_network_profile ($id); - - if (empty ($profile_info)) { - ui_print_error_message (__('This template does not exist')); - return; - } - - //It's important to keep the structure and order in the same way for backwards compatibility. - switch ($config["dbtype"]) { - case "mysql": - $sql = sprintf (" + $id = (int) get_parameter('export_profile'); + $profile_info = network_profiles_get_network_profile($id); + + if (empty($profile_info)) { + ui_print_error_message(__('This template does not exist')); + return; + } + + // It's important to keep the structure and order in the same way for backwards compatibility. + switch ($config['dbtype']) { + case 'mysql': + $sql = sprintf( + ' SELECT components.name, components.description, components.type, components.max, components.min, components.module_interval, components.tcp_port, components.tcp_send, components.tcp_rcv, components.snmp_community, components.snmp_oid, components.id_module_group, components.id_modulo, components.plugin_user, components.plugin_pass, components.plugin_parameter, @@ -107,22 +110,30 @@ if ($export_profile) { FROM `tnetwork_component` AS components, tnetwork_profile_component AS tpc, tnetwork_component_group AS comp_group WHERE tpc.id_nc = components.id_nc AND components.id_group = comp_group.id_sg - AND tpc.id_np = %d", $id); - break; - case "postgresql": - $sql = sprintf (" + AND tpc.id_np = %d', + $id + ); + break; + + case 'postgresql': + $sql = sprintf( + ' SELECT components.name, components.description, components.type, components.max, components.min, components.module_interval, components.tcp_port, components.tcp_send, components.tcp_rcv, components.snmp_community, components.snmp_oid, components.id_module_group, components.id_modulo, components.plugin_user, components.plugin_pass, components.plugin_parameter, components.max_timeout, components.max_retries, components.history_data, components.min_warning, components.max_warning, components.str_warning, components.min_critical, components.max_critical, components.str_critical, components.min_ff_event, comp_group.name AS group_name, components.critical_instructions, components.warning_instructions, components.unknown_instructions - FROM \"tnetwork_component\" AS components, tnetwork_profile_component AS tpc, tnetwork_component_group AS comp_group + FROM "tnetwork_component" AS components, tnetwork_profile_component AS tpc, tnetwork_component_group AS comp_group WHERE tpc.id_nc = components.id_nc AND components.id_group = comp_group.id_sg - AND tpc.id_np = %d", $id); - break; - case "oracle": - $sql = sprintf (" + AND tpc.id_np = %d', + $id + ); + break; + + case 'oracle': + $sql = sprintf( + ' SELECT components.name, components.description, components.type, components.max, components.min, components.module_interval, components.tcp_port, components.tcp_send, components.tcp_rcv, components.snmp_community, components.snmp_oid, components.id_module_group, components.id_modulo, components.plugin_user, components.plugin_pass, components.plugin_parameter, @@ -131,141 +142,148 @@ if ($export_profile) { FROM tnetwork_component AS components, tnetwork_profile_component AS tpc, tnetwork_component_group AS comp_group WHERE tpc.id_nc = components.id_nc AND components.id_group = comp_group.id_sg - AND tpc.id_np = %d", $id); - break; - } - - $components = db_get_all_rows_sql ($sql); - - $row_names = array (); - $inv_names = array (); - //Find the names of the rows that we are getting and throw away the duplicate numeric keys - foreach ($components[0] as $row_name => $detail) { - if (is_numeric ($row_name)) { - $inv_names[] = $row_name; - } - else { - $row_names[] = $row_name; - } - } - - //Send headers to tell the browser we're sending a file - header ("Content-type: application/octet-stream"); - header ("Content-Disposition: attachment; filename=".preg_replace ('/\s/', '_', $profile_info["name"]).".csv"); - header ("Pragma: no-cache"); - header ("Expires: 0"); - - //Clean up output buffering - while (@ob_end_clean ()); - - //Then print the first line (row names) - echo '"'.implode ('","', $row_names).'"'; - echo "\n"; - - //Then print the rest of the data. Encapsulate in quotes in case we have comma's in any of the descriptions - - foreach ($components as $row) { - foreach ($inv_names as $bad_key) { - unset ($row[$bad_key]); - } - echo '"'.implode ('","', $row).'"'; - echo "\n"; - } - - //We're done here. The original page will still be there - exit; + AND tpc.id_np = %d', + $id + ); + break; + } + + $components = db_get_all_rows_sql($sql); + + $row_names = []; + $inv_names = []; + // Find the names of the rows that we are getting and throw away the duplicate numeric keys + foreach ($components[0] as $row_name => $detail) { + if (is_numeric($row_name)) { + $inv_names[] = $row_name; + } else { + $row_names[] = $row_name; + } + } + + // Send headers to tell the browser we're sending a file + header('Content-type: application/octet-stream'); + header('Content-Disposition: attachment; filename='.preg_replace('/\s/', '_', $profile_info['name']).'.csv'); + header('Pragma: no-cache'); + header('Expires: 0'); + + // Clean up output buffering + while (@ob_end_clean()) { + } + + // Then print the first line (row names) + echo '"'.implode('","', $row_names).'"'; + echo "\n"; + + // Then print the rest of the data. Encapsulate in quotes in case we have comma's in any of the descriptions + foreach ($components as $row) { + foreach ($inv_names as $bad_key) { + unset($row[$bad_key]); + } + + echo '"'.implode('","', $row).'"'; + echo "\n"; + } + + // We're done here. The original page will still be there + exit; } -$result = db_get_all_rows_in_table ("tnetwork_profile", "name"); -if($result === false) { - $result = array(); +$result = db_get_all_rows_in_table('tnetwork_profile', 'name'); +if ($result === false) { + $result = []; } $table->cellpadding = 0; $table->cellspacing = 0; -$table->width = "100%"; -$table->class = "databox data"; +$table->width = '100%'; +$table->class = 'databox data'; -$table->head = array (); +$table->head = []; $table->head[0] = __('Name'); $table->head[1] = __('Description'); -$table->head[2] = ''.__('Action') .''. - html_print_checkbox('all_delete', 0, false, true, false); -$table->size = array (); +$table->head[2] = ''.__('Action').''.html_print_checkbox('all_delete', 0, false, true, false); +$table->size = []; $table->size[1] = '65%'; $table->size[2] = '15%'; -$table->align = array (); -$table->align[2] = "left"; +$table->align = []; +$table->align[2] = 'left'; -$table->data = array (); +$table->data = []; foreach ($result as $row) { - $data = array (); - $data[0] = ''. io_safe_output($row["name"]).''; - $data[1] = ui_print_truncate_text(io_safe_output($row["description"]), 'description', true, true, true, '[…]'); - $data[2] = html_print_input_image ("delete_profile", "images/cross.png", - $row["id_np"],'', true, - array ('onclick' => 'if (!confirm(\''.__('Are you sure?').'\')) return false;')); - $data[2] .= html_print_input_image ("export_profile", "images/csv.png", - $row["id_np"], '', true, array('title' => 'Export to CSV')); - $data[2] = '' . html_print_image("images/cross.png", true, array('title' => __('Delete'))) . ''; - $data[2] .= '  ' . html_print_image("images/csv.png", true, array('title' => __('Export to CSV'))) . '' . - html_print_checkbox_extended ('delete_multiple[]', $row['id_np'], false, false, '', 'class="check_delete"', true); - - array_push ($table->data, $data); + $data = []; + $data[0] = ''.io_safe_output($row['name']).''; + $data[1] = ui_print_truncate_text(io_safe_output($row['description']), 'description', true, true, true, '[…]'); + $data[2] = html_print_input_image( + 'delete_profile', + 'images/cross.png', + $row['id_np'], + '', + true, + ['onclick' => 'if (!confirm(\''.__('Are you sure?').'\')) return false;'] + ); + $data[2] .= html_print_input_image( + 'export_profile', + 'images/csv.png', + $row['id_np'], + '', + true, + ['title' => 'Export to CSV'] + ); + $data[2] = ''.html_print_image('images/cross.png', true, ['title' => __('Delete')]).''; + $data[2] .= '  '.html_print_image('images/csv.png', true, ['title' => __('Export to CSV')]).''.html_print_checkbox_extended('delete_multiple[]', $row['id_np'], false, false, '', 'class="check_delete"', true); + + array_push($table->data, $data); } -if (!empty ($table->data)) { - echo '
    '; - html_print_input_hidden('multiple_delete', 1); - html_print_table ($table); - echo "
    "; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - echo "
    "; - echo "
    "; -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined network profiles') ) ); +if (!empty($table->data)) { + echo '
    '; + html_print_input_hidden('multiple_delete', 1); + html_print_table($table); + echo "
    "; + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + echo '
    '; + echo '
    '; +} else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined network profiles') ]); } echo '
    '; echo '
    '; -html_print_submit_button (__('Create'), "crt", '', 'class="sub next"'); +html_print_submit_button(__('Create'), 'crt', '', 'class="sub next"'); echo '
    '; ?> diff --git a/pandora_console/godmode/modules/manage_network_templates_form.php b/pandora_console/godmode/modules/manage_network_templates_form.php index 7e8078b8c9..14f5911ab1 100644 --- a/pandora_console/godmode/modules/manage_network_templates_form.php +++ b/pandora_console/godmode/modules/manage_network_templates_form.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,315 +11,341 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Network Profile Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Network Profile Management' + ); + include 'general/noaccess.php'; + exit; } -require_once ('include/functions_network_components.php'); -require_once ("include/functions_modules.php"); +require_once 'include/functions_network_components.php'; +require_once 'include/functions_modules.php'; -ui_print_page_header (__('Module management')." » ".__('Module template management'), "", false, "", true); +ui_print_page_header(__('Module management').' » '.__('Module template management'), '', false, '', true); -$id_np = get_parameter ("id_np", -1); //Network Profile -$ncgroup = get_parameter ("ncgroup", -1); //Network component group -$ncfilter = get_parameter ("ncfilter", ''); //Network component group -$id_nc = get_parameter ("components", array ()); +$id_np = get_parameter('id_np', -1); +// Network Profile +$ncgroup = get_parameter('ncgroup', -1); +// Network component group +$ncfilter = get_parameter('ncfilter', ''); +// Network component group +$id_nc = get_parameter('components', []); -if (isset ($_GET["delete_module"])) { - // Delete module from profile - $errors = 0; - foreach ($id_nc as $component) { - $where = array( - 'id_np' => $id_np, - 'id_nc' => $component); - $result = db_process_sql_delete('tnetwork_profile_component', $where); - - if ($result === false) { - $errors++; - } - } +if (isset($_GET['delete_module'])) { + // Delete module from profile + $errors = 0; + foreach ($id_nc as $component) { + $where = [ + 'id_np' => $id_np, + 'id_nc' => $component, + ]; + $result = db_process_sql_delete('tnetwork_profile_component', $where); - ui_print_result_message (($errors < 1), - __('Successfully deleted module from profile'), - __('Error deleting module from profile')); + if ($result === false) { + $errors++; + } + } + + ui_print_result_message( + ($errors < 1), + __('Successfully deleted module from profile'), + __('Error deleting module from profile') + ); +} else if (isset($_GET['add_module'])) { + // Add module to profile + $errors = 0; + foreach ($id_nc as $component) { + $values = [ + 'id_np' => $id_np, + 'id_nc' => $component, + ]; + $result = db_process_sql_insert('tnetwork_profile_component', $values); + + if ($result === false) { + $errors++; + } + } + + ui_print_result_message( + ($errors < 1), + __('Successfully added module to profile'), + __('Error adding module to profile') + ); } -elseif (isset ($_GET["add_module"])) { - // Add module to profile - $errors = 0; - foreach ($id_nc as $component) { - $values = array('id_np' => $id_np, 'id_nc' => $component); - $result = db_process_sql_insert('tnetwork_profile_component', $values); - - if ($result === false) { - $errors++; - } - } - - ui_print_result_message (($errors < 1), - __('Successfully added module to profile'), - __('Error adding module to profile')); -} -if (isset ($_GET["create"]) || isset ($_GET["update"])) { - //Submitted form - $name = io_safe_output(get_parameter_post ("name")); - $description = get_parameter_post ("description"); +if (isset($_GET['create']) || isset($_GET['update'])) { + // Submitted form + $name = io_safe_output(get_parameter_post('name')); + $description = get_parameter_post('description'); - if (!empty($name) && !ctype_space($name)) { - $name = io_safe_input($name); - if ($id_np > 0) { - //Profile exists - $values = array( - 'name' => $name, - 'description' => $description); - $result = db_process_sql_update('tnetwork_profile', $values, array('id_np' => $id_np)); - - if ($result) { - db_pandora_audit("Module management", "Update module template #$id_np"); - } - else { - db_pandora_audit("Module management", "Fail try to update module template #$id_np"); - } - - ui_print_result_message ($result !== false, - __('Successfully updated network profile'), - __('Error updating network profile')); - } - else { - //Profile doesn't exist - $values = array('name' => $name, 'description' => $description); - $result = db_process_sql_insert('tnetwork_profile', $values); - - if ($result) { - db_pandora_audit("Module management", "Create module template #$result"); - } - else { - db_pandora_audit("Module management", "Fail try to create module template"); - } - - ui_print_result_message ($result, - __('Successfully added network profile'), - __('Error adding network profile')); - $id_np = (int) $result; //Will return either 0 (in case of error) or an int - } - } - else { - ui_print_result_message(false, "", _("Cannot create a template without name")); - } + if (!empty($name) && !ctype_space($name)) { + $name = io_safe_input($name); + if ($id_np > 0) { + // Profile exists + $values = [ + 'name' => $name, + 'description' => $description, + ]; + $result = db_process_sql_update('tnetwork_profile', $values, ['id_np' => $id_np]); -} -elseif ($id_np > 0) { - //Profile exists - $row = db_get_row ("tnetwork_profile", "id_np", $id_np); - - $description = $row["description"]; - $name = $row["name"]; + if ($result) { + db_pandora_audit('Module management', "Update module template #$id_np"); + } else { + db_pandora_audit('Module management', "Fail try to update module template #$id_np"); + } -} -else { - //Profile has to be created - $description = ""; - $name = ""; + ui_print_result_message( + $result !== false, + __('Successfully updated network profile'), + __('Error updating network profile') + ); + } else { + // Profile doesn't exist + $values = [ + 'name' => $name, + 'description' => $description, + ]; + $result = db_process_sql_insert('tnetwork_profile', $values); + + if ($result) { + db_pandora_audit('Module management', "Create module template #$result"); + } else { + db_pandora_audit('Module management', 'Fail try to create module template'); + } + + ui_print_result_message( + $result, + __('Successfully added network profile'), + __('Error adding network profile') + ); + $id_np = (int) $result; + // Will return either 0 (in case of error) or an int + } + } else { + ui_print_result_message(false, '', _('Cannot create a template without name')); + } +} else if ($id_np > 0) { + // Profile exists + $row = db_get_row('tnetwork_profile', 'id_np', $id_np); + + $description = $row['description']; + $name = $row['name']; +} else { + // Profile has to be created + $description = ''; + $name = ''; } if ($id_np < 1) { - echo '
    '; -} -else { - echo ''; + echo ''; +} else { + echo ''; } echo ''; -echo ''; -echo ''; +echo ''; echo '"; +html_print_textarea('description', 2, 60, $description); +echo ''; echo '
    ' . "" . __('Name') . "" . ''; -html_print_input_text ("name", $name, '', 63); +echo '
    '.''.__('Name').''.''; +html_print_input_text('name', $name, '', 63); echo '
    ' . "" . __('Description') . "" . '
    '.''.__('Description').''.''; -html_print_textarea ("description", 2, 60, $description); -echo "
    '; if ($id_np > 0) { - html_print_submit_button (__("Update"), "updbutton", false, 'class="sub upd"'); + html_print_submit_button(__('Update'), 'updbutton', false, 'class="sub upd"'); +} else { + html_print_submit_button(__('Create'), 'crtbutton', false, 'class="sub wand"'); } -else { - html_print_submit_button (__("Create"), "crtbutton", false, 'class="sub wand"'); -} -echo "
    "; + +echo ''; if ($id_np > 0) { - // Show associated modules, allow to delete, and to add - switch ($config["dbtype"]) { - case "mysql": - $sql = sprintf ("SELECT npc.id_nc AS component_id, nc.name, nc.type, nc.description, nc.id_group AS `group` + // Show associated modules, allow to delete, and to add + switch ($config['dbtype']) { + case 'mysql': + $sql = sprintf( + 'SELECT npc.id_nc AS component_id, nc.name, nc.type, nc.description, nc.id_group AS `group` FROM tnetwork_profile_component AS npc, tnetwork_component AS nc - WHERE npc.id_nc = nc.id_nc AND npc.id_np = %d", $id_np); - break; - case "postgresql": - $sql = sprintf ("SELECT npc.id_nc AS component_id, nc.name, nc.type, nc.description, nc.id_group AS \"group\" + WHERE npc.id_nc = nc.id_nc AND npc.id_np = %d', + $id_np + ); + break; + + case 'postgresql': + $sql = sprintf( + 'SELECT npc.id_nc AS component_id, nc.name, nc.type, nc.description, nc.id_group AS "group" FROM tnetwork_profile_component AS npc, tnetwork_component AS nc - WHERE npc.id_nc = nc.id_nc AND npc.id_np = %d", $id_np); - break; - case "oracle": - $sql = sprintf ("SELECT npc.id_nc AS component_id, nc.name, nc.type, nc.description, nc.id_group AS \"group\" + WHERE npc.id_nc = nc.id_nc AND npc.id_np = %d', + $id_np + ); + break; + + case 'oracle': + $sql = sprintf( + 'SELECT npc.id_nc AS component_id, nc.name, nc.type, nc.description, nc.id_group AS "group" FROM tnetwork_profile_component npc, tnetwork_component nc - WHERE npc.id_nc = nc.id_nc AND npc.id_np = %d", $id_np); - break; - } - - $result = db_get_all_rows_sql ($sql); + WHERE npc.id_nc = nc.id_nc AND npc.id_np = %d', + $id_np + ); + break; + } - if (empty ($result)) { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('No modules for this profile') ) ); - $result = array (); - } + $result = db_get_all_rows_sql($sql); - $table->head = array (); - $table->data = array (); - $table->align = array (); - $table->width = '100%'; - $table->cellpadding = 4; - $table->cellspacing = 4; - $table->class = "databox data"; - - $table->head[0] = __('Module name'); - $table->head[1] = __('Type'); - $table->align[1] = "center"; - $table->head[2] = __('Description'); - $table->head[3] = __('Group'); - $table->align[3] = "left"; - $table->head[4] = html_print_checkbox_extended ('allbox', '', false, false, 'CheckAll();', '', true); - $table->align[4] = "left"; - - foreach ($result as $row) { - $data = array (); - $data[0] = $row["name"]; - $data[1] = html_print_image("images/".modules_show_icon_type($row["type"]), true, array("border" => '0')); - $data[2] = mb_strimwidth(io_safe_output($row["description"]),0,150,"..."); - $data[3] = network_components_get_group_name ($row["group"]); - $data[4] = html_print_checkbox ("components[]", $row["component_id"], false, true); - array_push ($table->data, $data); - } + if (empty($result)) { + ui_print_info_message(['no_close' => true, 'message' => __('No modules for this profile') ]); + $result = []; + } - if (!empty ($table->data)) { - echo '
    '; - html_print_table ($table); - echo '
    '; - html_print_submit_button (__('Delete'), "delbutton", false, 'class="sub delete" onClick="if (!confirm(\'Are you sure?\')) return false;"'); - echo '
    '; - } - unset ($table); - - echo "

    ".__('Add modules')."

    "; - - unset($table); - - $table->head = array (); - $table->data = array (); - $table->align = array (); - $table->width = '100%'; - $table->cellpadding = 0; - $table->cellspacing = 0; - $table->class = "databox filters"; - - $table->style[0] = 'font-weight: bold'; - - //The form to submit when adding a list of components - - $filter = '
    '; - $filter .= html_print_input_text ('ncfilter', $ncfilter, '', 50, 255, true); - $filter .= '  '.html_print_submit_button (__('Filter'), 'ncgbutton', false, 'class="sub search"', true); - $filter .= '
    '; - - $group_filter = '
    '; - $group_filter .= '
    '; - $result = db_get_all_rows_in_table ("tnetwork_component_group","name"); - if($result === false) { - $result = array(); - } - - //2 arrays. 1 with the groups, 1 with the groups by parent - $groups = array (); - $groups_compound = array (); - foreach ($result as $row) { - $groups[$row["id_sg"]] = $row["name"]; - } - - foreach ($result as $row) { - $groups_compound[$row["id_sg"]] = ''; - if ($row["parent"] > 1) { - $groups_compound[$row["id_sg"]] = $groups[$row["parent"]]." / "; - } - $groups_compound[$row["id_sg"]] .= $row["name"]; - } - - $group_filter .= html_print_select ($groups_compound, "ncgroup", $ncgroup, 'javascript:this.form.submit();', __('Group')." - ".__('All'), -1, true, false, true, '" style="width:350px'); - - $group_filter .= '
    '; - - if ($ncgroup > 0) { - $sql = sprintf (" + $table->head = []; + $table->data = []; + $table->align = []; + $table->width = '100%'; + $table->cellpadding = 4; + $table->cellspacing = 4; + $table->class = 'databox data'; + + $table->head[0] = __('Module name'); + $table->head[1] = __('Type'); + $table->align[1] = 'center'; + $table->head[2] = __('Description'); + $table->head[3] = __('Group'); + $table->align[3] = 'left'; + $table->head[4] = html_print_checkbox_extended('allbox', '', false, false, 'CheckAll();', '', true); + $table->align[4] = 'left'; + + foreach ($result as $row) { + $data = []; + $data[0] = $row['name']; + $data[1] = html_print_image('images/'.modules_show_icon_type($row['type']), true, ['border' => '0']); + $data[2] = mb_strimwidth(io_safe_output($row['description']), 0, 150, '...'); + $data[3] = network_components_get_group_name($row['group']); + $data[4] = html_print_checkbox('components[]', $row['component_id'], false, true); + array_push($table->data, $data); + } + + if (!empty($table->data)) { + echo '
    '; + html_print_table($table); + echo '
    '; + html_print_submit_button(__('Delete'), 'delbutton', false, 'class="sub delete" onClick="if (!confirm(\'Are you sure?\')) return false;"'); + echo '
    '; + } + + unset($table); + + echo "

    ".__('Add modules').'

    '; + + unset($table); + + $table->head = []; + $table->data = []; + $table->align = []; + $table->width = '100%'; + $table->cellpadding = 0; + $table->cellspacing = 0; + $table->class = 'databox filters'; + + $table->style[0] = 'font-weight: bold'; + + // The form to submit when adding a list of components + $filter = '
    '; + $filter .= html_print_input_text('ncfilter', $ncfilter, '', 50, 255, true); + $filter .= '  '.html_print_submit_button(__('Filter'), 'ncgbutton', false, 'class="sub search"', true); + $filter .= '
    '; + + $group_filter = '
    '; + $group_filter .= '
    '; + $result = db_get_all_rows_in_table('tnetwork_component_group', 'name'); + if ($result === false) { + $result = []; + } + + // 2 arrays. 1 with the groups, 1 with the groups by parent + $groups = []; + $groups_compound = []; + foreach ($result as $row) { + $groups[$row['id_sg']] = $row['name']; + } + + foreach ($result as $row) { + $groups_compound[$row['id_sg']] = ''; + if ($row['parent'] > 1) { + $groups_compound[$row['id_sg']] = $groups[$row['parent']].' / '; + } + + $groups_compound[$row['id_sg']] .= $row['name']; + } + + $group_filter .= html_print_select($groups_compound, 'ncgroup', $ncgroup, 'javascript:this.form.submit();', __('Group').' - '.__('All'), -1, true, false, true, '" style="width:350px'); + + $group_filter .= '
    '; + + if ($ncgroup > 0) { + $sql = sprintf( + " SELECT id_nc, name, id_group FROM tnetwork_component - WHERE id_group = %d AND name LIKE '%" . $ncfilter . "%' - ORDER BY name", $ncgroup); - } - else { - $sql = " + WHERE id_group = %d AND name LIKE '%".$ncfilter."%' + ORDER BY name", + $ncgroup + ); + } else { + $sql = " SELECT id_nc, name, id_group FROM tnetwork_component - WHERE name LIKE '%" . $ncfilter . "%' + WHERE name LIKE '%".$ncfilter."%' ORDER BY name"; - } - - $result = db_get_all_rows_sql ($sql); - $components = array (); - if ($result === false) - $result = array (); - - foreach ($result as $row) { - $components[$row["id_nc"]] = $row["name"]; - } - - $components_select = '
    '; - $components_select .= html_print_select ($components, "components[]", $id_nc, '', '', -1, true, true, false, '" style="width:350px'); - - $table->data[0][0] = __('Filter'); - $table->data[0][1] = $filter; - $table->data[1][0] = __('Group'); - $table->data[1][1] = $group_filter; - $table->data[2][0] = __('Components'); - $table->data[2][1] = $components_select; - - html_print_table($table); - - echo '
    '; - html_print_submit_button (__('Add'), 'crtbutton', false, 'class="sub wand"'); - echo '
    '; + } + + $result = db_get_all_rows_sql($sql); + $components = []; + if ($result === false) { + $result = []; + } + + foreach ($result as $row) { + $components[$row['id_nc']] = $row['name']; + } + + $components_select = '
    '; + $components_select .= html_print_select($components, 'components[]', $id_nc, '', '', -1, true, true, false, '" style="width:350px'); + + $table->data[0][0] = __('Filter'); + $table->data[0][1] = $filter; + $table->data[1][0] = __('Group'); + $table->data[1][1] = $group_filter; + $table->data[2][0] = __('Components'); + $table->data[2][1] = $components_select; + + html_print_table($table); + + echo '
    '; + html_print_submit_button(__('Add'), 'crtbutton', false, 'class="sub wand"'); + echo '
    '; } ?> diff --git a/pandora_console/godmode/modules/module_list.php b/pandora_console/godmode/modules/module_list.php index de6c40fac2..cb87ae624e 100644 --- a/pandora_console/godmode/modules/module_list.php +++ b/pandora_console/godmode/modules/module_list.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,83 +11,81 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation","Trying to access module management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit('ACL Violation', 'Trying to access module management'); + include 'general/noaccess.php'; + exit; } // Header -ui_print_page_header (__('Module management')." » ". __('Defined modules'), "images/gm_modules.png", false, "", true); +ui_print_page_header(__('Module management').' » '.__('Defined modules'), 'images/gm_modules.png', false, '', true); -$update_module = (bool) get_parameter_post ('update_module'); +$update_module = (bool) get_parameter_post('update_module'); // Update if ($update_module) { - $name = get_parameter_post ("name"); - $id_type = get_parameter_post ("id_type"); - $description = get_parameter_post ("description"); - $icon = get_parameter_post ("icon"); - $category = get_parameter_post ("category"); - - $values = array( - 'descripcion' => $description, - 'categoria' => $category, - 'nombre' => $name, - 'icon' => $icon - ); - - $result = db_process_sql_update('ttipo_modulo', $values, array('id_tipo' => $id_type)); - - if (! $result) - ui_print_error_message(__('Problem modifying module')); - else - ui_print_success_message(__('Module updated successfully')); + $name = get_parameter_post('name'); + $id_type = get_parameter_post('id_type'); + $description = get_parameter_post('description'); + $icon = get_parameter_post('icon'); + $category = get_parameter_post('category'); + + $values = [ + 'descripcion' => $description, + 'categoria' => $category, + 'nombre' => $name, + 'icon' => $icon, + ]; + + $result = db_process_sql_update('ttipo_modulo', $values, ['id_tipo' => $id_type]); + + if (! $result) { + ui_print_error_message(__('Problem modifying module')); + } else { + ui_print_success_message(__('Module updated successfully')); + } } echo ""; -echo ""; -echo ""; -echo ""; -echo ""; +echo ''; +echo ''; +echo ''; +echo ''; $rows = db_get_all_rows_sql('SELECT * FROM ttipo_modulo ORDER BY nombre'); if ($rows === false) { - $rows = array(); + $rows = []; } $color = 0; foreach ($rows as $row) { - if ($color == 1) { - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - echo " + if ($color == 1) { + $tdcolor = 'datos'; + $color = 0; + } else { + $tdcolor = 'datos2'; + $color = 1; + } + + echo " - + - "; + '; } -echo "
    ".__('Icon')."".__('ID')."".__('Name')."".__('Description')."'.__('Icon').''.__('ID').''.__('Name').''.__('Description').'
    " . - html_print_image("images/".$row["icon"], true, array("border" => '0')) . - "".html_print_image('images/'.$row['icon'], true, ['border' => '0'])." - ".$row["id_tipo"]." + ".$row['id_tipo']." - ".$row["nombre"]." + ".$row['nombre']." - ".$row["descripcion"]." + ".$row['descripcion'].'
    "; -?> + +echo ''; diff --git a/pandora_console/godmode/netflow/nf_edit.php b/pandora_console/godmode/netflow/nf_edit.php index 4402826244..59f1ed96e8 100644 --- a/pandora_console/godmode/netflow/nf_edit.php +++ b/pandora_console/godmode/netflow/nf_edit.php @@ -4,169 +4,184 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - global $config; -include_once($config['homedir'] . "/include/functions_ui.php"); -include_once($config['homedir'] . "/include/functions_db.php"); -include_once($config['homedir'] . "/include/functions_netflow.php"); +require_once $config['homedir'].'/include/functions_ui.php'; +require_once $config['homedir'].'/include/functions_db.php'; +require_once $config['homedir'].'/include/functions_netflow.php'; -check_login (); +check_login(); enterprise_hook('open_meta_frame'); -if (! check_acl ($config["id_user"], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access event viewer"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access event viewer' + ); + include 'general/noaccess.php'; + return; } $pure = get_parameter('pure', 0); -//Header -if (! defined ('METACONSOLE')) { - ui_print_page_header (__('Manage Netflow Filter'), "images/gm_netflow.png", false, "", true); +// Header +if (! defined('METACONSOLE')) { + ui_print_page_header(__('Manage Netflow Filter'), 'images/gm_netflow.png', false, '', true); - $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; - if ($is_windows) { - ui_print_error_message(__('Not supported in Windows systems')); - } -} -else { - $nav_bar = array(array('link' => 'index.php?sec=main', 'text' => __('Main')), - array('link' => 'index.php?sec=netf&sec2=godmode/netflow/nf_edit', 'text' => __('Netflow filters'))); - - ui_meta_print_page_header($nav_bar); - - ui_meta_print_header(__("Netflow filters")); + $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; + if ($is_windows) { + ui_print_error_message(__('Not supported in Windows systems')); + } +} else { + $nav_bar = [ + [ + 'link' => 'index.php?sec=main', + 'text' => __('Main'), + ], + [ + 'link' => 'index.php?sec=netf&sec2=godmode/netflow/nf_edit', + 'text' => __('Netflow filters'), + ], + ]; + + ui_meta_print_page_header($nav_bar); + + ui_meta_print_header(__('Netflow filters')); } -$delete = (bool) get_parameter ('delete'); -$multiple_delete = (bool)get_parameter('multiple_delete', 0); -$id = (int) get_parameter ('id'); -$name = (string) get_parameter ('name'); +$delete = (bool) get_parameter('delete'); +$multiple_delete = (bool) get_parameter('multiple_delete', 0); +$id = (int) get_parameter('id'); +$name = (string) get_parameter('name'); if ($delete) { - $id_filter = db_get_value('id_name', 'tnetflow_filter', 'id_sg', $id); - $result = db_process_sql_delete ('tnetflow_filter', - array ('id_sg' => $id)); - - $result2 = db_process_sql_delete ('tnetflow_report_content', - array ('id_filter' => $id_filter)); - - if ($result !== false) { - $result = true; - } - else { - $result = false; - } - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); + $id_filter = db_get_value('id_name', 'tnetflow_filter', 'id_sg', $id); + $result = db_process_sql_delete( + 'tnetflow_filter', + ['id_sg' => $id] + ); + + $result2 = db_process_sql_delete( + 'tnetflow_report_content', + ['id_filter' => $id_filter] + ); + + if ($result !== false) { + $result = true; + } else { + $result = false; + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); } if ($multiple_delete) { - $ids = (array)get_parameter('delete_multiple', array()); - - foreach ($ids as $id) { - $id_filter = db_get_value('id_name', 'tnetflow_filter', 'id_sg', $id); - $result = db_process_sql_delete ('tnetflow_filter', - array ('id_sg' => $id)); - - $result2 = db_process_sql_delete ('tnetflow_report_content', - array ('id_filter' => $id_filter)); - - if ($result === false) { - break; - } - } - - if ($result !== false) $result = true; - else $result = false; - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); + $ids = (array) get_parameter('delete_multiple', []); + + foreach ($ids as $id) { + $id_filter = db_get_value('id_name', 'tnetflow_filter', 'id_sg', $id); + $result = db_process_sql_delete( + 'tnetflow_filter', + ['id_sg' => $id] + ); + + $result2 = db_process_sql_delete( + 'tnetflow_report_content', + ['id_filter' => $id_filter] + ); + + if ($result === false) { + break; + } + } + + if ($result !== false) { + $result = true; + } else { + $result = false; + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); } -$own_info = get_user_info ($config['id_user']); +$own_info = get_user_info($config['id_user']); // Get group list that user has access -$groups_user = users_get_groups ($config['id_user'], "AW", $own_info['is_admin'], true); -$sql = "SELECT * +$groups_user = users_get_groups($config['id_user'], 'AW', $own_info['is_admin'], true); +$sql = 'SELECT * FROM tnetflow_filter - WHERE id_group IN (0, ".implode(',', array_keys ($groups_user)).")"; + WHERE id_group IN (0, '.implode(',', array_keys($groups_user)).')'; $filters = db_get_all_rows_sql($sql); -if ($filters === false) - $filters = array (); +if ($filters === false) { + $filters = []; +} $table = new stdClass(); $table->width = '100%'; $table->class = 'databox data'; -$table->head = array (); +$table->head = []; $table->head[0] = __('Name'); $table->head[1] = __('Group'); -$table->head[2] = __('Action') . - html_print_checkbox('all_delete', 0, false, true, false); -$table->style = array (); +$table->head[2] = __('Action').html_print_checkbox('all_delete', 0, false, true, false); +$table->style = []; $table->style[0] = 'font-weight: bold'; -$table->align = array (); +$table->align = []; -$table->size = array (); +$table->size = []; $table->size[0] = '60%'; $table->size[1] = '30%'; $table->size[2] = '80px'; -$table->data = array (); +$table->data = []; -$total_filters = db_get_all_rows_filter ('tnetflow_filter', false, 'COUNT(*) AS total'); +$total_filters = db_get_all_rows_filter('tnetflow_filter', false, 'COUNT(*) AS total'); $total_filters = $total_filters[0]['total']; -//ui_pagination ($total_filters, $url); - +// ui_pagination ($total_filters, $url); foreach ($filters as $filter) { - $data = array (); - - $data[0] = ''.$filter['id_name'].''; - $data[1] = ui_print_group_icon($filter['id_group'], true, "groups_small", '', !defined('METACONSOLE')); - $data[2] = "" . - html_print_image('images/cross.png', true, array('title' => __('Delete'))) . "" . - html_print_checkbox_extended ('delete_multiple[]', $filter['id_sg'], false, false, '', 'class="check_delete"', true); - - array_push ($table->data, $data); + $data = []; + + $data[0] = ''.$filter['id_name'].''; + $data[1] = ui_print_group_icon($filter['id_group'], true, 'groups_small', '', !defined('METACONSOLE')); + $data[2] = "".html_print_image('images/cross.png', true, ['title' => __('Delete')]).''.html_print_checkbox_extended('delete_multiple[]', $filter['id_sg'], false, false, '', 'class="check_delete"', true); + + array_push($table->data, $data); } if (isset($data)) { - echo "
    "; - html_print_input_hidden('multiple_delete', 1); - html_print_table ($table); - echo "
    "; + echo ""; + html_print_input_hidden('multiple_delete', 1); + html_print_table($table); + echo "
    "; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - echo "
    "; - echo ""; -} -else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no defined filters') ) ); + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + echo '
    '; + echo ''; +} else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no defined filters') ]); } -echo '
    '; +echo ''; echo "
    "; -html_print_submit_button (__('Create filter'), 'crt', false, 'class="sub wand"'); -echo "
    "; -echo "
    "; +html_print_submit_button(__('Create filter'), 'crt', false, 'class="sub wand"'); +echo '
    '; +echo ''; enterprise_hook('close_meta_frame'); @@ -174,29 +189,29 @@ enterprise_hook('close_meta_frame'); diff --git a/pandora_console/godmode/netflow/nf_edit_form.php b/pandora_console/godmode/netflow/nf_edit_form.php index dc3c362b8a..80f88f709e 100644 --- a/pandora_console/godmode/netflow/nf_edit_form.php +++ b/pandora_console/godmode/netflow/nf_edit_form.php @@ -4,167 +4,173 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - global $config; -include_once($config['homedir'] . "/include/functions_ui.php"); -include_once($config['homedir'] . "/include/functions_netflow.php"); -include_once ($config['homedir'] . "/include/functions_users.php"); -include_once ($config['homedir'] . "/include/functions_groups.php"); +require_once $config['homedir'].'/include/functions_ui.php'; +require_once $config['homedir'].'/include/functions_netflow.php'; +require_once $config['homedir'].'/include/functions_users.php'; +require_once $config['homedir'].'/include/functions_groups.php'; -check_login (); +check_login(); enterprise_hook('open_meta_frame'); // Fix: Netflow have to check RW ACL -if (! check_acl ($config["id_user"], 0, "RW")) { - db_pandora_audit("ACL Violation", - "Trying to access event viewer"); - require ($config['homedir'] . "/general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'RW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access event viewer' + ); + include $config['homedir'].'/general/noaccess.php'; + return; } -$id = (int) get_parameter ('id'); +$id = (int) get_parameter('id'); $name = db_get_value('id_name', 'tnetflow_filter', 'id_sg', $id); -$update = (string)get_parameter('update', 0); -$create = (string)get_parameter('create', 0); +$update = (string) get_parameter('update', 0); +$create = (string) get_parameter('create', 0); $pure = get_parameter('pure', 0); if ($id) { - $permission = netflow_check_filter_group ($id); - if (!$permission) { //no tiene permisos para acceder a un filtro - require ($config['homedir'] . "/general/noaccess.php"); - return; - } + $permission = netflow_check_filter_group($id); + if (!$permission) { + // no tiene permisos para acceder a un filtro + include $config['homedir'].'/general/noaccess.php'; + return; + } } -//Header -if (! defined ('METACONSOLE')) { - $buttons['edit']['text'] = '' - . html_print_image ("images/list.png", true, array ("title" => __('Filter list'))) - . ''; - - $buttons['add']['text'] = '' - . html_print_image ("images/add_mc.png", true, array ("title" => __('Add filter'))) - . ''; - - ui_print_page_header (__('Netflow Filter'), "images/gm_netflow.png", false, "", true, $buttons); -} -else { - $nav_bar = array(array('link' => 'index.php?sec=main', 'text' => __('Main')), - array('link' => 'index.php?sec=netf&sec2=godmode/netflow/nf_edit', 'text' => __('Netflow filters')), - array('link' => 'index.php?sec=netf&sec2=godmode/netflow/nf_edit_form', 'text' => __('Add filter'))); - - ui_meta_print_page_header($nav_bar); - - ui_meta_print_header(__("Netflow filters")); +// Header +if (! defined('METACONSOLE')) { + $buttons['edit']['text'] = ''.html_print_image('images/list.png', true, ['title' => __('Filter list')]).''; + + $buttons['add']['text'] = ''.html_print_image('images/add_mc.png', true, ['title' => __('Add filter')]).''; + + ui_print_page_header(__('Netflow Filter'), 'images/gm_netflow.png', false, '', true, $buttons); +} else { + $nav_bar = [ + [ + 'link' => 'index.php?sec=main', + 'text' => __('Main'), + ], + [ + 'link' => 'index.php?sec=netf&sec2=godmode/netflow/nf_edit', + 'text' => __('Netflow filters'), + ], + [ + 'link' => 'index.php?sec=netf&sec2=godmode/netflow/nf_edit_form', + 'text' => __('Add filter'), + ], + ]; + + ui_meta_print_page_header($nav_bar); + + ui_meta_print_header(__('Netflow filters')); } if ($id) { - $filter = netflow_filter_get_filter ($id); - $assign_group = $filter['id_group']; - $name = $filter['id_name']; - $ip_dst = $filter['ip_dst']; - $ip_src = $filter['ip_src']; - $dst_port = $filter['dst_port']; - $src_port = $filter['src_port']; - $aggregate = $filter['aggregate']; - $output = $filter['output']; - $advanced_filter = $filter['advanced_filter']; -} -else { - $name = ''; - $assign_group = ''; - $ip_dst = ''; - $ip_src = ''; - $dst_port = ''; - $src_port = ''; - $aggregate = 'none'; - $output = 'bytes'; - $advanced_filter = ''; + $filter = netflow_filter_get_filter($id); + $assign_group = $filter['id_group']; + $name = $filter['id_name']; + $ip_dst = $filter['ip_dst']; + $ip_src = $filter['ip_src']; + $dst_port = $filter['dst_port']; + $src_port = $filter['src_port']; + $aggregate = $filter['aggregate']; + $output = $filter['output']; + $advanced_filter = $filter['advanced_filter']; +} else { + $name = ''; + $assign_group = ''; + $ip_dst = ''; + $ip_src = ''; + $dst_port = ''; + $src_port = ''; + $aggregate = 'none'; + $output = 'bytes'; + $advanced_filter = ''; } if ($update) { - $name = (string) get_parameter ('name'); - $assign_group = (int) get_parameter ('assign_group'); - $aggregate = get_parameter('aggregate',''); - $output = get_parameter('output','bytes'); - $ip_dst = get_parameter('ip_dst',''); - $ip_src = get_parameter('ip_src',''); - $dst_port = get_parameter('dst_port',''); - $src_port = get_parameter('src_port',''); - $advanced_filter = get_parameter('advanced_filter',''); - - if ($name == '') { - ui_print_error_message (__('Not updated. Blank name')); - } - else { - $values = array ('id_sg' => $id, - 'id_name' => $name, - 'id_group' => $assign_group, - 'aggregate' => $aggregate, - 'ip_dst' => $ip_dst, - 'ip_src' => $ip_src, - 'dst_port' => $dst_port, - 'src_port' => $src_port, - 'advanced_filter' => $advanced_filter, - 'output' => $output - ); - - // Save filter args - $values['filter_args'] = netflow_get_filter_arguments ($values); - - $result = db_process_sql_update ('tnetflow_filter', $values, array ('id_sg' => $id)); - - ui_print_result_message ($result, - __('Successfully updated'), - __('Not updated. Error updating data')); - } + $name = (string) get_parameter('name'); + $assign_group = (int) get_parameter('assign_group'); + $aggregate = get_parameter('aggregate', ''); + $output = get_parameter('output', 'bytes'); + $ip_dst = get_parameter('ip_dst', ''); + $ip_src = get_parameter('ip_src', ''); + $dst_port = get_parameter('dst_port', ''); + $src_port = get_parameter('src_port', ''); + $advanced_filter = get_parameter('advanced_filter', ''); + + if ($name == '') { + ui_print_error_message(__('Not updated. Blank name')); + } else { + $values = [ + 'id_sg' => $id, + 'id_name' => $name, + 'id_group' => $assign_group, + 'aggregate' => $aggregate, + 'ip_dst' => $ip_dst, + 'ip_src' => $ip_src, + 'dst_port' => $dst_port, + 'src_port' => $src_port, + 'advanced_filter' => $advanced_filter, + 'output' => $output, + ]; + + // Save filter args + $values['filter_args'] = netflow_get_filter_arguments($values); + + $result = db_process_sql_update('tnetflow_filter', $values, ['id_sg' => $id]); + + ui_print_result_message( + $result, + __('Successfully updated'), + __('Not updated. Error updating data') + ); + } } if ($create) { - $name = (string) get_parameter ('name'); - $assign_group = (int) get_parameter ('assign_group'); - $aggregate = get_parameter('aggregate','none'); - $output = get_parameter('output','bytes'); - $ip_dst = get_parameter('ip_dst',''); - $ip_src = get_parameter('ip_src',''); - $dst_port = get_parameter('dst_port',''); - $src_port = get_parameter('src_port',''); - $advanced_filter = (string) get_parameter('advanced_filter', ''); - - $values = array ( - 'id_name'=>$name, - 'id_group' => $assign_group, - 'ip_dst'=>$ip_dst, - 'ip_src'=>$ip_src, - 'dst_port'=>$dst_port, - 'src_port'=>$src_port, - 'aggregate'=>$aggregate, - 'advanced_filter'=>$advanced_filter, - 'output'=>$output); - - // Save filter args - $values['filter_args'] = netflow_get_filter_arguments ($values); - - $id = db_process_sql_insert('tnetflow_filter', $values); - if ($id === false) { - ui_print_error_message ('Error creating filter'); - } - else { - ui_print_success_message ('Filter created successfully'); - } + $name = (string) get_parameter('name'); + $assign_group = (int) get_parameter('assign_group'); + $aggregate = get_parameter('aggregate', 'none'); + $output = get_parameter('output', 'bytes'); + $ip_dst = get_parameter('ip_dst', ''); + $ip_src = get_parameter('ip_src', ''); + $dst_port = get_parameter('dst_port', ''); + $src_port = get_parameter('src_port', ''); + $advanced_filter = (string) get_parameter('advanced_filter', ''); + + $values = [ + 'id_name' => $name, + 'id_group' => $assign_group, + 'ip_dst' => $ip_dst, + 'ip_src' => $ip_src, + 'dst_port' => $dst_port, + 'src_port' => $src_port, + 'aggregate' => $aggregate, + 'advanced_filter' => $advanced_filter, + 'output' => $output, + ]; + + // Save filter args + $values['filter_args'] = netflow_get_filter_arguments($values); + + $id = db_process_sql_insert('tnetflow_filter', $values); + if ($id === false) { + ui_print_error_message('Error creating filter'); + } else { + ui_print_success_message('Filter created successfully'); + } } $table->id = 'table1'; @@ -172,77 +178,100 @@ $table->width = '100%'; $table->border = 0; $table->cellspacing = 0; $table->cellpadding = 0; -$table->class = "databox filters"; +$table->class = 'databox filters'; $table->style[0] = 'font-weight: bold'; if (defined('METACONSOLE')) { - if($id) - $table->head[0] = __("Update filter"); - else - $table->head[0] = __("Create filter"); - $table->head_colspan[0] = 5; - $table->headstyle[0] = 'text-align: center'; + if ($id) { + $table->head[0] = __('Update filter'); + } else { + $table->head[0] = __('Create filter'); + } + + $table->head_colspan[0] = 5; + $table->headstyle[0] = 'text-align: center'; } -$table->data = array (); +$table->data = []; $table->data[0][0] = ''.__('Name').''; -$table->data[0][1] = html_print_input_text ('name', $name, false, 20, 80, true); +$table->data[0][1] = html_print_input_text('name', $name, false, 20, 80, true); -$own_info = get_user_info ($config['id_user']); +$own_info = get_user_info($config['id_user']); $table->data[1][0] = ''.__('Group').''; // Fix: Netflow filters have to check RW ACL -$table->data[1][1] = html_print_select_groups($config['id_user'], "RW", - $own_info['is_admin'], 'assign_group', $assign_group, '', '', -1, true, - false, false); +$table->data[1][1] = html_print_select_groups( + $config['id_user'], + 'RW', + $own_info['is_admin'], + 'assign_group', + $assign_group, + '', + '', + -1, + true, + false, + false +); if ($advanced_filter != '') { - $filter_type = 1; -} -else { - $filter_type = 0; + $filter_type = 1; +} else { + $filter_type = 0; } $table->data[2][0] = ''.__('Filter:').''; -$table->data[2][1] = __('Normal') . ' ' . html_print_radio_button_extended ('filter_type', 0, '', $filter_type, false, 'displayNormalFilter();', 'style="margin-right: 40px;"', true); -$table->data[2][1] .= __('Advanced') . ' ' . html_print_radio_button_extended ('filter_type', 1, '', $filter_type, false, 'displayAdvancedFilter();', 'style="margin-right: 40px;"', true); +$table->data[2][1] = __('Normal').' '.html_print_radio_button_extended('filter_type', 0, '', $filter_type, false, 'displayNormalFilter();', 'style="margin-right: 40px;"', true); +$table->data[2][1] .= __('Advanced').' '.html_print_radio_button_extended('filter_type', 1, '', $filter_type, false, 'displayAdvancedFilter();', 'style="margin-right: 40px;"', true); -$table->data[3][0] = __('Dst Ip'). ui_print_help_tip (__("Destination IP. A comma separated list of destination ip. If we leave the field blank, will show all ip. Example filter by ip:
    25.46.157.214,160.253.135.249"), true); -$table->data[3][1] = html_print_input_text ('ip_dst', $ip_dst, false, 40, 80, true); - -$table->data[4][0] = __('Src Ip'). ui_print_help_tip (__("Source IP. A comma separated list of source ip. If we leave the field blank, will show all ip. Example filter by ip:
    25.46.157.214,160.253.135.249"), true); -$table->data[4][1] = html_print_input_text ('ip_src', $ip_src, false, 40, 80, true); - -$table->data[5][0] = __('Dst Port'). ui_print_help_tip (__("Destination port. A comma separated list of destination ports. If we leave the field blank, will show all ports. Example filter by ports 80 and 22:
    80,22"), true); -$table->data[5][1] = html_print_input_text ('dst_port', $dst_port, false, 40, 80, true); +$table->data[3][0] = __('Dst Ip').ui_print_help_tip(__('Destination IP. A comma separated list of destination ip. If we leave the field blank, will show all ip. Example filter by ip:
    25.46.157.214,160.253.135.249'), true); +$table->data[3][1] = html_print_input_text('ip_dst', $ip_dst, false, 40, 80, true); -$table->data[6][0] = __('Src Port'). ui_print_help_tip (__("Source port. A comma separated list of source ports. If we leave the field blank, will show all ports. Example filter by ports 80 and 22:
    80,22"), true); -$table->data[6][1] = html_print_input_text ('src_port', $src_port, false, 40, 80, true); +$table->data[4][0] = __('Src Ip').ui_print_help_tip(__('Source IP. A comma separated list of source ip. If we leave the field blank, will show all ip. Example filter by ip:
    25.46.157.214,160.253.135.249'), true); +$table->data[4][1] = html_print_input_text('ip_src', $ip_src, false, 40, 80, true); -$table->data[7][0] = ui_print_help_icon ('pcap_filter', true); -$table->data[7][1] = html_print_textarea ('advanced_filter', 4, 40, $advanced_filter, '', true); +$table->data[5][0] = __('Dst Port').ui_print_help_tip(__('Destination port. A comma separated list of destination ports. If we leave the field blank, will show all ports. Example filter by ports 80 and 22:
    80,22'), true); +$table->data[5][1] = html_print_input_text('dst_port', $dst_port, false, 40, 80, true); -$table->data[8][0] = ''.__('Aggregate by').''. ui_print_help_icon ('aggregate_by', true); -$aggregate_list = array ('none' => __('None'), 'proto' => __('Protocol'), 'srcip' =>__('Src Ip Address'), 'dstip' =>__('Dst Ip Address'), 'srcport' =>__('Src Port'), 'dstport' =>__('Dst Port') ); +$table->data[6][0] = __('Src Port').ui_print_help_tip(__('Source port. A comma separated list of source ports. If we leave the field blank, will show all ports. Example filter by ports 80 and 22:
    80,22'), true); +$table->data[6][1] = html_print_input_text('src_port', $src_port, false, 40, 80, true); -$table->data[8][1] = html_print_select ($aggregate_list, "aggregate", $aggregate, '', '', 0, true, false, true, '', false); +$table->data[7][0] = ui_print_help_icon('pcap_filter', true); +$table->data[7][1] = html_print_textarea('advanced_filter', 4, 40, $advanced_filter, '', true); + +$table->data[8][0] = ''.__('Aggregate by').''.ui_print_help_icon('aggregate_by', true); +$aggregate_list = [ + 'none' => __('None'), + 'proto' => __('Protocol'), + 'srcip' => __('Src Ip Address'), + 'dstip' => __('Dst Ip Address'), + 'srcport' => __('Src Port'), + 'dstport' => __('Dst Port'), +]; + +$table->data[8][1] = html_print_select($aggregate_list, 'aggregate', $aggregate, '', '', 0, true, false, true, '', false); $table->data[9][0] = ''.__('Output format').''; -$show_output = array ('kilobytes' => __('Kilobytes'), 'megabytes' => __('Megabytes'), 'kilobytespersecond' => __('Kilobytes per second'), 'megabytespersecond' => __('Megabytes per second')); -$table->data[9][1] = html_print_select ($show_output, 'output', $output, '', '', 0, true, false, true, '', false); +$show_output = [ + 'kilobytes' => __('Kilobytes'), + 'megabytes' => __('Megabytes'), + 'kilobytespersecond' => __('Kilobytes per second'), + 'megabytespersecond' => __('Megabytes per second'), +]; +$table->data[9][1] = html_print_select($show_output, 'output', $output, '', '', 0, true, false, true, '', false); -echo '
    '; -html_print_table ($table); +echo ''; +html_print_table($table); echo '
    '; if ($id) { - html_print_input_hidden ('update', 1); - html_print_input_hidden ('id', $id); - html_print_submit_button (__('Update'), 'crt', false, 'class="sub upd"'); -} -else { - html_print_input_hidden ('create', 1); - html_print_submit_button (__('Create'), 'crt', false, 'class="sub wand"'); + html_print_input_hidden('update', 1); + html_print_input_hidden('id', $id); + html_print_submit_button(__('Update'), 'crt', false, 'class="sub upd"'); +} else { + html_print_input_hidden('create', 1); + html_print_submit_button(__('Create'), 'crt', false, 'class="sub wand"'); } + echo '
    '; echo '
    '; @@ -251,42 +280,42 @@ enterprise_hook('close_meta_frame'); ?> diff --git a/pandora_console/godmode/netflow/nf_item_list.php b/pandora_console/godmode/netflow/nf_item_list.php index 904607a197..e26bc4971d 100644 --- a/pandora_console/godmode/netflow/nf_item_list.php +++ b/pandora_console/godmode/netflow/nf_item_list.php @@ -4,174 +4,201 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - global $config; -include_once($config['homedir'] . "/include/functions_ui.php"); -include_once($config['homedir'] . "/include/functions_db.php"); -include_once($config['homedir'] . "/include/functions_netflow.php"); -include_once($config['homedir'] . "/include/functions_html.php"); +require_once $config['homedir'].'/include/functions_ui.php'; +require_once $config['homedir'].'/include/functions_db.php'; +require_once $config['homedir'].'/include/functions_netflow.php'; +require_once $config['homedir'].'/include/functions_html.php'; -check_login (); +check_login(); -if (! check_acl ($config["id_user"], 0, "IW")) { - db_pandora_audit("ACL Violation", - "Trying to access event viewer"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'IW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access event viewer' + ); + include 'general/noaccess.php'; + return; } -//id report -$id = (int)get_parameter('id'); +// id report +$id = (int) get_parameter('id'); $buttons['report_list']['active'] = false; -$buttons['report_list'] = '' - . html_print_image ("images/edit.png", true, array ("title" => __('Report list'))) - . ''; +$buttons['report_list'] = ''.html_print_image('images/edit.png', true, ['title' => __('Report list')]).''; $buttons['report_items']['active'] = true; -$buttons['report_items']['text'] = '' - . html_print_image ("images/god6.png", true, array ("title" => __('Report items'))) - . ''; +$buttons['report_items']['text'] = ''.html_print_image('images/god6.png', true, ['title' => __('Report items')]).''; $buttons['edit_report']['active'] = false; -$buttons['edit_report']['text'] = '' - . html_print_image ("images/config.png", true, array ("title" => __('Edit report'))) - . ''; +$buttons['edit_report']['text'] = ''.html_print_image('images/config.png', true, ['title' => __('Edit report')]).''; -//Header -if (! defined ('METACONSOLE')) { - ui_print_page_header (__('Report items'), "images/gm_netflow.png", false, "", true, $buttons); -} -else { - $nav_bar = array(array('link' => 'index.php?sec=main', 'text' => __('Main')), - array('link' => 'index.php?sec=netf&sec2=operation/netflow/nf_reporting', 'text' => __('Netflow reports')), - array('link' => 'index.php?sec=netf&sec2=godmode/netflow/nf_item_list&id=' . $id, 'text' => __('Item list'))); - ui_meta_print_page_header($nav_bar); +// Header +if (! defined('METACONSOLE')) { + ui_print_page_header(__('Report items'), 'images/gm_netflow.png', false, '', true, $buttons); +} else { + $nav_bar = [ + [ + 'link' => 'index.php?sec=main', + 'text' => __('Main'), + ], + [ + 'link' => 'index.php?sec=netf&sec2=operation/netflow/nf_reporting', + 'text' => __('Netflow reports'), + ], + [ + 'link' => 'index.php?sec=netf&sec2=godmode/netflow/nf_item_list&id='.$id, + 'text' => __('Item list'), + ], + ]; + ui_meta_print_page_header($nav_bar); } -$delete = (bool) get_parameter ('delete'); -$multiple_delete = (bool)get_parameter('multiple_delete', 0); +$delete = (bool) get_parameter('delete'); +$multiple_delete = (bool) get_parameter('multiple_delete', 0); $order = get_parameter('order'); -//id item -$id_rc = (int) get_parameter ('id_rc'); +// id item +$id_rc = (int) get_parameter('id_rc'); if ($order) { - $dir = get_parameter ('dir'); - $old_order = db_get_value_sql(' + $dir = get_parameter('dir'); + $old_order = db_get_value_sql( + ' SELECT `order` FROM tnetflow_report_content - WHERE id_rc = ' . $id_rc); - switch ($dir) { - case 'up': - $new_order = $old_order-1; - break; - case 'down': - $new_order = $old_order + 1; - break; - } - - $sql = "SELECT id_rc + WHERE id_rc = '.$id_rc + ); + switch ($dir) { + case 'up': + $new_order = ($old_order - 1); + break; + + case 'down': + $new_order = ($old_order + 1); + break; + } + + $sql = "SELECT id_rc FROM tnetflow_report_content WHERE id_report=$id AND `order`=$new_order"; - - $item_cont = db_get_row_sql($sql); - $id_item_mod = $item_cont['id_rc']; - $result = db_process_sql_update('tnetflow_report_content', - array('`order`' => $new_order), array('id_rc' => $id_rc)); - $result2 = db_process_sql_update('tnetflow_report_content', - array('`order`' => $old_order), array('id_rc' => $id_item_mod)); + + $item_cont = db_get_row_sql($sql); + $id_item_mod = $item_cont['id_rc']; + $result = db_process_sql_update( + 'tnetflow_report_content', + ['`order`' => $new_order], + ['id_rc' => $id_rc] + ); + $result2 = db_process_sql_update( + 'tnetflow_report_content', + ['`order`' => $old_order], + ['id_rc' => $id_item_mod] + ); } if ($delete) { - $result = db_process_sql_delete ('tnetflow_report_content', - array ('id_rc' => $id_rc)); - - if ($result !== false) $result = true; - else $result = false; - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); + $result = db_process_sql_delete( + 'tnetflow_report_content', + ['id_rc' => $id_rc] + ); + + if ($result !== false) { + $result = true; + } else { + $result = false; + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); } if ($multiple_delete) { - $ids = (array)get_parameter('delete_multiple', array()); - - foreach ($ids as $id_delete) { - $result = db_process_sql_delete ('tnetflow_report_content', - array ('id_rc' => $id_delete)); - - if ($result === false) { - break; - } - } - - if ($result !== false) $result = true; - else $result = false; - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); + $ids = (array) get_parameter('delete_multiple', []); + + foreach ($ids as $id_delete) { + $result = db_process_sql_delete( + 'tnetflow_report_content', + ['id_rc' => $id_delete] + ); + + if ($result === false) { + break; + } + } + + if ($result !== false) { + $result = true; + } else { + $result = false; + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); } -$filter = array (); +$filter = []; -$filter['offset'] = (int) get_parameter ('offset'); +$filter['offset'] = (int) get_parameter('offset'); $filter['limit'] = (int) $config['block_size']; -$reports_item = db_get_all_rows_filter ('tnetflow_report_content', $filter); +$reports_item = db_get_all_rows_filter('tnetflow_report_content', $filter); -$reports_item = db_get_all_rows_sql(" +$reports_item = db_get_all_rows_sql( + " SELECT * FROM tnetflow_report_content - WHERE id_report=$id ORDER BY `order`"); + WHERE id_report=$id ORDER BY `order`" +); + +if ($reports_item === false) { + $reports_item = []; +} -if ($reports_item === false) - $reports_item = array (); - $table->width = '98%'; -$table->head = array (); +$table->head = []; $table->head[0] = __('Order'); $table->head[1] = __('Filter'); $table->head[2] = __('Description'); $table->head[3] = __('Max. values'); $table->head[4] = __('Chart type'); -$table->head[5] = __('Action') . html_print_checkbox('all_delete', 0, false, true, false, 'check_all_checkboxes();'); +$table->head[5] = __('Action').html_print_checkbox('all_delete', 0, false, true, false, 'check_all_checkboxes();'); -$table->style = array (); +$table->style = []; $table->style[1] = 'font-weight: bold'; -$table->align = array (); +$table->align = []; $table->align[1] = 'left'; $table->align[2] = 'left'; $table->align[3] = 'center'; $table->align[4] = 'center'; $table->align[5] = 'right'; -$table->size = array (); +$table->size = []; $table->size[0] = '20px'; $table->size[3] = '5%'; $table->size[4] = '15%'; $table->size[5] = '60px'; -$table->data = array (); +$table->data = []; -$total_reports_item = db_get_all_rows_filter ('tnetflow_report_content', false, 'COUNT(*) AS total'); +$total_reports_item = db_get_all_rows_filter('tnetflow_report_content', false, 'COUNT(*) AS total'); $total_reports_item = $total_reports_item[0]['total']; -//ui_pagination ($total_reports_item, $url); - +// ui_pagination ($total_reports_item, $url); $sql = "SELECT id_rc FROM tnetflow_report_content WHERE `order`= ( @@ -193,87 +220,84 @@ $item_max = db_get_row_sql($sql); $last_item = $item_max['id_rc']; foreach ($reports_item as $item) { - - $data = array (); - if (($item['id_rc'] == $first_item) && ($item['id_rc'] == $last_item)) { - $data[0] = ' '; - } - else if (($item['id_rc'] == $first_item) && ($item['id_rc'] != $last_item)) { - $data[0] = ' '; - $data[0] .= '' . html_print_image("images/down.png", true, array("title" => __('Move to down'))) . ''; - } - else if (($item['id_rc'] == $last_item) && ($item['id_rc'] != $first_item)) { - $data[0] = '' . html_print_image("images/up.png", true, array("title" => __('Move to up'))) . ''; - } - else { - $data[0] = '' . html_print_image("images/up.png", true, array("title" => __('Move to up'))) . ''; - $data[0] .= '' . html_print_image("images/down.png", true, array("title" => __('Move to down'))) . ''; - } - - $name_filter = db_get_value('id_name', 'tnetflow_filter', 'id_sg', $item['id_filter']); - $data[1] = ''.$name_filter.''; - - $data[2] = $item['description']; - $data[3] = $item['max']; - - switch ($item['show_graph']) { - case 0: - $data[4] = 'Area graph'; - break; - case 1: - $data[4] = 'Pie graph'; - break; - case 2: - $data[4] = 'Data table'; - break; - case 3: - $data[4] = 'Statistics table'; - break; - case 4: - $data[4] = 'Summary table'; - break; - } - - $data[5] = "" . - html_print_image('images/cross.png', true, array('title' => __('Delete'))) . "" . - html_print_checkbox_extended ('delete_multiple[]', $item['id_rc'], false, false, '', 'class="check_delete"', true); - - array_push ($table->data, $data); + $data = []; + if (($item['id_rc'] == $first_item) && ($item['id_rc'] == $last_item)) { + $data[0] = ' '; + } else if (($item['id_rc'] == $first_item) && ($item['id_rc'] != $last_item)) { + $data[0] = ' '; + $data[0] .= ''.html_print_image('images/down.png', true, ['title' => __('Move to down')]).''; + } else if (($item['id_rc'] == $last_item) && ($item['id_rc'] != $first_item)) { + $data[0] = ''.html_print_image('images/up.png', true, ['title' => __('Move to up')]).''; + } else { + $data[0] = ''.html_print_image('images/up.png', true, ['title' => __('Move to up')]).''; + $data[0] .= ''.html_print_image('images/down.png', true, ['title' => __('Move to down')]).''; + } + + $name_filter = db_get_value('id_name', 'tnetflow_filter', 'id_sg', $item['id_filter']); + $data[1] = ''.$name_filter.''; + + $data[2] = $item['description']; + $data[3] = $item['max']; + + switch ($item['show_graph']) { + case 0: + $data[4] = 'Area graph'; + break; + + case 1: + $data[4] = 'Pie graph'; + break; + + case 2: + $data[4] = 'Data table'; + break; + + case 3: + $data[4] = 'Statistics table'; + break; + + case 4: + $data[4] = 'Summary table'; + break; + } + + $data[5] = "".html_print_image('images/cross.png', true, ['title' => __('Delete')]).''.html_print_checkbox_extended('delete_multiple[]', $item['id_rc'], false, false, '', 'class="check_delete"', true); + + array_push($table->data, $data); } if (isset($data)) { - echo '
    '; - html_print_input_hidden('multiple_delete', 1); - html_print_table ($table); - echo "
    "; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - echo "
    "; - echo "
    "; -} -else { - echo "
    ".__('There are no defined items')."
    "; + echo '
    '; + html_print_input_hidden('multiple_delete', 1); + html_print_table($table); + echo "
    "; + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + echo '
    '; + echo '
    '; +} else { + echo "
    ".__('There are no defined items').'
    '; } -echo '
    '; -echo "
    "; -html_print_submit_button (__('Create item'), 'crt', false, 'class="sub wand"'); -echo "
    "; -echo "
    "; +echo '
    '; +echo "
    "; +html_print_submit_button(__('Create item'), 'crt', false, 'class="sub wand"'); +echo '
    '; +echo '
    '; ?> diff --git a/pandora_console/godmode/reporting/create_container.php b/pandora_console/godmode/reporting/create_container.php index 98fbfe6b67..b0566d7867 100644 --- a/pandora_console/godmode/reporting/create_container.php +++ b/pandora_console/godmode/reporting/create_container.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,374 +10,415 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global variables global $config; // Check user credentials -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "RW")) { - db_pandora_audit("ACL Violation", - "Trying to access Inventory Module Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'RW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Inventory Module Management' + ); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_container.php'); -require_once ($config['homedir'] . '/include/functions_custom_graphs.php'); +require_once 'include/functions_container.php'; +require_once $config['homedir'].'/include/functions_custom_graphs.php'; -$id_container = get_parameter('id',0); -$offset = (int) get_parameter ('offset',0); +$id_container = get_parameter('id', 0); +$offset = (int) get_parameter('offset', 0); -if (is_ajax()){ - $add_single = (bool) get_parameter('add_single',0); - $add_custom = (bool) get_parameter('add_custom',0); - $add_dynamic = (bool) get_parameter('add_dynamic',0); - $id_container2 = get_parameter('id_container',0); +if (is_ajax()) { + $add_single = (bool) get_parameter('add_single', 0); + $add_custom = (bool) get_parameter('add_custom', 0); + $add_dynamic = (bool) get_parameter('add_dynamic', 0); + $id_container2 = get_parameter('id_container', 0); - if($add_single) { - $id_agent = get_parameter('id_agent'); - $id_agent_module = get_parameter('id_agent_module'); - $time_lapse = get_parameter('time_lapse'); - $simple_type_graph = get_parameter('simple_type_graph'); - $fullscale = get_parameter('fullscale'); + if ($add_single) { + $id_agent = get_parameter('id_agent'); + $id_agent_module = get_parameter('id_agent_module'); + $time_lapse = get_parameter('time_lapse'); + $simple_type_graph = get_parameter('simple_type_graph'); + $fullscale = get_parameter('fullscale'); - if($fullscale != 'false'){ - $fullscale = 1; - } - else{ - $fullscale = 0; - } + if ($fullscale != 'false') { + $fullscale = 1; + } else { + $fullscale = 0; + } - $values = array( - 'id_container' => $id_container2, - 'type' => "simple_graph", - 'id_agent' => $id_agent, - 'id_agent_module' => $id_agent_module, - 'time_lapse' => $time_lapse, - 'type_graph' => $simple_type_graph, - 'fullscale' => $fullscale); + $values = [ + 'id_container' => $id_container2, + 'type' => 'simple_graph', + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'time_lapse' => $time_lapse, + 'type_graph' => $simple_type_graph, + 'fullscale' => $fullscale, + ]; - $id_item = db_process_sql_insert('tcontainer_item', $values); - return; - } + $id_item = db_process_sql_insert('tcontainer_item', $values); + return; + } -if($add_custom) { - $time_lapse = get_parameter('time_lapse'); - $id_custom = get_parameter('id_custom'); - $fullscale = get_parameter('fullscale'); - if($fullscale != 'false'){ - $fullscale = 1; - } - else{ - $fullscale = 0; - } - - $values = array( - 'id_container' => $id_container2, - 'type' => "custom_graph", - 'time_lapse' => $time_lapse, - 'id_graph' => $id_custom, - 'fullscale' => $fullscale, - ); + if ($add_custom) { + $time_lapse = get_parameter('time_lapse'); + $id_custom = get_parameter('id_custom'); + $fullscale = get_parameter('fullscale'); + if ($fullscale != 'false') { + $fullscale = 1; + } else { + $fullscale = 0; + } - $id_item = db_process_sql_insert('tcontainer_item', $values); - return; -} - - if($add_dynamic) { - $time_lapse = get_parameter('time_lapse'); - $group = get_parameter('group',0); - $module_group= get_parameter('module_group',0); - $agent_alias = get_parameter('agent_alias',''); - $module_name = get_parameter('module_name',''); - $tag = get_parameter('tag',0); - - $simple_type_graph2 = get_parameter('simple_type_graph2'); - $fullscale = get_parameter('fullscale'); - - if($fullscale != 'false'){ - $fullscale = 1; - } - else{ - $fullscale = 0; - } - - $values = array( + $values = [ 'id_container' => $id_container2, - 'type' => "dynamic_graph", - 'time_lapse' => $time_lapse, - 'id_group' => $group, - 'id_module_group' => $module_group, - 'agent' => $agent_alias, - 'module' => $module_name, - 'id_tag' => $tag, - 'type_graph' => $simple_type_graph2, - 'fullscale' => $fullscale - ); + 'type' => 'custom_graph', + 'time_lapse' => $time_lapse, + 'id_graph' => $id_custom, + 'fullscale' => $fullscale, + ]; - $id_item = db_process_sql_insert('tcontainer_item', $values); - return; - } + $id_item = db_process_sql_insert('tcontainer_item', $values); + return; + } + + if ($add_dynamic) { + $time_lapse = get_parameter('time_lapse'); + $group = get_parameter('group', 0); + $module_group = get_parameter('module_group', 0); + $agent_alias = get_parameter('agent_alias', ''); + $module_name = get_parameter('module_name', ''); + $tag = get_parameter('tag', 0); + + $simple_type_graph2 = get_parameter('simple_type_graph2'); + $fullscale = get_parameter('fullscale'); + + if ($fullscale != 'false') { + $fullscale = 1; + } else { + $fullscale = 0; + } + + $values = [ + 'id_container' => $id_container2, + 'type' => 'dynamic_graph', + 'time_lapse' => $time_lapse, + 'id_group' => $group, + 'id_module_group' => $module_group, + 'agent' => $agent_alias, + 'module' => $module_name, + 'id_tag' => $tag, + 'type_graph' => $simple_type_graph2, + 'fullscale' => $fullscale, + ]; + + $id_item = db_process_sql_insert('tcontainer_item', $values); + return; + } } -$add_container = (bool) get_parameter ('add_container',0); -$edit_container = (bool) get_parameter ('edit_container',0); -$update_container = (bool) get_parameter ('update_container',0); -$delete_item = (bool) get_parameter ('delete_item',0); +$add_container = (bool) get_parameter('add_container', 0); +$edit_container = (bool) get_parameter('edit_container', 0); +$update_container = (bool) get_parameter('update_container', 0); +$delete_item = (bool) get_parameter('delete_item', 0); if ($edit_container) { - $name = io_safe_input(get_parameter ('name','')); - if (!empty($name)){ - $id_parent = get_parameter ('id_parent',0); - $description = io_safe_input(get_parameter ('description','')); - $id_group = get_parameter ('container_id_group',0); - }else{ - $tcontainer = db_get_row_sql("SELECT * FROM tcontainer WHERE id_container = " . $id_container); + $name = io_safe_input(get_parameter('name', '')); + if (!empty($name)) { + $id_parent = get_parameter('id_parent', 0); + $description = io_safe_input(get_parameter('description', '')); + $id_group = get_parameter('container_id_group', 0); + } else { + $tcontainer = db_get_row_sql('SELECT * FROM tcontainer WHERE id_container = '.$id_container); $name = $tcontainer['name']; $id_parent = $tcontainer['parent']; $description = $tcontainer['description']; $id_group = $tcontainer['id_group']; } - } -if($add_container){ - $values = array( - 'name' => $name, +if ($add_container) { + $values = [ + 'name' => $name, 'description' => $description, - 'parent' => $id_parent, - 'id_group' => $id_group); + 'parent' => $id_parent, + 'id_group' => $id_group, + ]; $id_container = db_process_sql_insert('tcontainer', $values); } -if($update_container){ - if($id_container === $id_parent){ +if ($update_container) { + if ($id_container === $id_parent) { $success = false; } else { - $values = array( - 'name' => $name, + $values = [ + 'name' => $name, 'description' => $description, - 'parent' => $id_parent, - 'id_group' => $id_group); - $success = db_process_sql_update('tcontainer', $values,array('id_container' => $id_container)); + 'parent' => $id_parent, + 'id_group' => $id_group, + ]; + $success = db_process_sql_update('tcontainer', $values, ['id_container' => $id_container]); } } -if($delete_item){ - $id_item = get_parameter('id_item',0); - $success = db_process_sql_delete('tcontainer_item', array('id_ci' => $id_item)); +if ($delete_item) { + $id_item = get_parameter('id_item', 0); + $success = db_process_sql_delete('tcontainer_item', ['id_ci' => $id_item]); } -$buttons['graph_container'] = array('active' => false, - 'text' => '' . - html_print_image("images/graph-container.png", true, array ("title" => __('Graph container'))) . ''); +$buttons['graph_container'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/graph-container.png', true, ['title' => __('Graph container')]).'', +]; // Header -ui_print_page_header (__('Create container'), "", false, "", false, $buttons); +ui_print_page_header(__('Create container'), '', false, '', false, $buttons); -if($add_container){ +if ($add_container) { ui_print_result_message($id_container, __('Container stored successfully'), __('There was a problem storing container')); } -if($update_container){ - ui_print_result_message($success, __("Update the container"), __("Bad update the container")); +if ($update_container) { + ui_print_result_message($success, __('Update the container'), __('Bad update the container')); } echo ""; -if($edit_container){ - echo ""; +if ($edit_container) { + echo ""; } else { echo ""; } -echo ""; -echo ""; -if($id_container === '1'){ +echo ''; +echo "'; +if ($id_container === '1') { echo ""; -$own_info = get_user_info ($config['id_user']); -if ($own_info['is_admin'] || check_acl ($config['id_user'], 0, "PM")) - $return_all_groups = true; -else - $return_all_groups = false; - -echo ""; -echo ""; -echo ""; -if($id_container === '1'){ +echo '>'; +$own_info = get_user_info($config['id_user']); +if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'PM')) { + $return_all_groups = true; +} else { + $return_all_groups = false; +} + +echo "'; + +echo ''; +echo "'; +if ($id_container === '1') { echo ""; +echo ''; +echo ''; $container = folder_get_folders(); $tree = folder_get_folders_tree_recursive($container); -$containers_tree = folder_flatten_tree_folders($tree,0); +$containers_tree = folder_flatten_tree_folders($tree, 0); $containers_tree = folder_get_select($containers_tree); unset($containers_tree[$id_container]); -echo ""; -echo ""; -if($id_container === '1'){ - echo "'; +echo "'; +if ($id_container === '1') { + echo ""; +echo ''; -echo "
    ".__('Name')."
    ".__('Name').'".__('Group').""; -if($id_container === '1'){ - echo html_print_select_groups($config['id_user'], '', $return_all_groups, 'container_id_group', $id_group, '', '', '', true,false,true,'',true); -} else { - echo html_print_select_groups($config['id_user'], '', $return_all_groups, 'container_id_group', $id_group, '', '', '', true,false,true,'',false); -} - -echo "
    ".__('Description')."".__('Group').''; +if ($id_container === '1') { + echo html_print_select_groups($config['id_user'], '', $return_all_groups, 'container_id_group', $id_group, '', '', '', true, false, true, '', true); +} else { + echo html_print_select_groups($config['id_user'], '', $return_all_groups, 'container_id_group', $id_group, '', '', '', true, false, true, '', false); +} + +echo '
    ".__('Description').'"; -echo "
    ".__("Parent container")."" . html_print_select ($containers_tree, "id_parent", $id_parent, - '', __('none'), 0, true,'',false,'w130',true,'width: 195px',''); +echo '
    ".__('Parent container').'".html_print_select( + $containers_tree, + 'id_parent', + $id_parent, + '', + __('none'), + 0, + true, + '', + false, + 'w130', + true, + 'width: 195px', + '' + ); } else { - echo "" . html_print_select ($containers_tree, "id_parent", $id_parent, - '', __('none'), 0, true,'',false,'w130','','width: 195px',''); + echo "".html_print_select( + $containers_tree, + 'id_parent', + $id_parent, + '', + __('none'), + 0, + true, + '', + false, + 'w130', + '', + 'width: 195px', + '' + ); } -echo "
    "; +echo ''; if ($edit_container) { - if($id_container !== '1'){ + if ($id_container !== '1') { echo "
    "; } -} -else { - echo "
    "; +} else { + echo "
    "; } -echo ""; +echo ''; -echo "
    "; -echo "
    "; -echo "
    "; +echo '
    '; +echo '
    '; +echo '
    '; + +if ($edit_container) { + $period = SECONDS_15DAYS; + $periods = []; + $periods[-1] = __('custom'); + $periods[SECONDS_1HOUR] = __('1 hour'); + $periods[SECONDS_2HOUR] = sprintf(__('%s hours'), '2 '); + $periods[SECONDS_6HOURS] = sprintf(__('%s hours'), '6 '); + $periods[SECONDS_12HOURS] = sprintf(__('%s hours'), '12 '); + $periods[SECONDS_1DAY] = __('1 day'); + $periods[SECONDS_2DAY] = sprintf(__('%s days'), '2 '); + $periods[SECONDS_5DAY] = sprintf(__('%s days'), '5 '); + $periods[SECONDS_1WEEK] = __('1 week'); + $periods[SECONDS_15DAYS] = __('15 days'); + $periods[SECONDS_1MONTH] = __('1 month'); + + $type_graphs = []; + $type_graphs[0] = __('Area'); + $type_graphs[1] = __('Line'); -if($edit_container){ - $period = SECONDS_15DAYS; - $periods = array (); - $periods[-1] = __('custom'); - $periods[SECONDS_1HOUR] = __('1 hour'); - $periods[SECONDS_2HOUR] = sprintf(__('%s hours'), '2 '); - $periods[SECONDS_6HOURS] = sprintf(__('%s hours'), '6 '); - $periods[SECONDS_12HOURS] = sprintf(__('%s hours'), '12 '); - $periods[SECONDS_1DAY] = __('1 day'); - $periods[SECONDS_2DAY] = sprintf(__('%s days'), '2 '); - $periods[SECONDS_5DAY] = sprintf(__('%s days'), '5 '); - $periods[SECONDS_1WEEK] = __('1 week'); - $periods[SECONDS_15DAYS] = __('15 days'); - $periods[SECONDS_1MONTH] = __('1 month'); - - $type_graphs = array(); - $type_graphs[0] = __('Area'); - $type_graphs[1] = __('Line'); - $single_table = ""; $single_table .= ""; $single_table .= ""; - $single_table .= ""; - $single_table .= ""; - + $single_table .= ui_print_help_tip(__('This is the interval or period of time with which the graph data will be obtained. For example, a week means data from a week ago from now. '), true); + $single_table .= ''; + $single_table .= ''; + $single_table .= ''; + $single_table .= ""; $single_table .= ""; - $single_table .= "'; + $single_table .= '"; - $single_table .= ""; - + $single_table .= ''; + $single_table .= ''; + $single_table .= ""; $single_table .= ""; - $single_table .= ""; - $single_table .= ""; + $single_table .= ''; + $single_table .= ''; + $single_table .= ''; $single_table .= ""; $single_table .= ""; - $single_table .= ""; - $single_table .= ""; + $single_table .= ''; + $single_table .= ''; + $single_table .= ''; $single_table .= ""; $single_table .= ""; - $single_table .= ""; - $single_table .= ""; + $single_table .= __('Show full scale graph (TIP)').ui_print_help_tip('This option may cause performance issues', true); + $single_table .= ''; + $single_table .= ''; + $single_table .= ''; - $single_table .= ""; - $single_table .= ""; + $single_table .= ''; + $single_table .= ''; $single_table .= ""; - $single_table .= ""; - $single_table .= "
    "; $single_table .= __('Time lapse'); - $single_table .= ui_print_help_tip(__('This is the interval or period of time with which the graph data will be obtained. For example, a week means data from a week ago from now. '),true); - $single_table .= ""; - $single_table .= html_print_extended_select_for_time('period_single', $period, - '', '', '0', 10, true,false,true,'',false,$periods); - $single_table .= "
    '; + $single_table .= html_print_extended_select_for_time( + 'period_single', + $period, + '', + '', + '0', + 10, + true, + false, + true, + '', + false, + $periods + ); + $single_table .= '
    "; $single_table .= __('Agent'); - $single_table .= ""; - $params = array(); - + $single_table .= ''; + $params = []; + $params['show_helptip'] = false; $params['input_name'] = 'agent'; $params['value'] = ''; $params['return'] = true; - + $params['javascript_is_function_select'] = true; $params['selectbox_id'] = 'id_agent_module'; $params['add_none_module'] = true; $params['use_hidden_input_idagent'] = true; $params['hidden_input_idagent_id'] = 'hidden-id_agent'; - - + + $single_table .= ui_print_agent_autocomplete_input($params); - $single_table .= "
    "; $single_table .= __('Module'); - $single_table .= ""; - if ($idAgent) { - $single_table .= html_print_select_from_sql($sql_modules, 'id_agent_module', $idAgentModule, '', '', '0',true); - } else { - $single_table .= ""; - } - $single_table .= "
    '; + if ($idAgent) { + $single_table .= html_print_select_from_sql($sql_modules, 'id_agent_module', $idAgentModule, '', '', '0', true); + } else { + $single_table .= "'; + } + + $single_table .= '
    "; $single_table .= __('Type of graph'); - $single_table .= ""; - $single_table .= html_print_select ($type_graphs, 'simple_type_graph', "","","",0,true); - $single_table .= "
    '; + $single_table .= html_print_select($type_graphs, 'simple_type_graph', '', '', '', 0, true); + $single_table .= '
    "; - $single_table .= __('Show full scale graph (TIP)') . ui_print_help_tip('This option may cause performance issues', true); - $single_table .= ""; - $single_table .= html_print_checkbox('fullscale', 1, false,true); - $single_table .= "
    '; + $single_table .= html_print_checkbox('fullscale', 1, false, true); + $single_table .= '
    "; - $single_table .= "
    '; + $single_table .= '"; $single_table .= ""; - $single_table .= "
    "; + $single_table .= ''; + $single_table .= ''; + $single_table .= ''; echo ""; - echo ""; - echo ""; - echo ""; - echo "
    "; - echo ui_toggle($single_table,'Simple module graph', '', true, true); - echo "
    "; - + echo ''; + echo ''; + echo ui_toggle($single_table, 'Simple module graph', '', true, true); + echo ''; + echo ''; + echo ''; + $table = new stdClass(); $table->id = 'custom_graph_table'; $table->width = '100%'; @@ -388,49 +428,48 @@ if($edit_container){ $table->styleTable = 'font-weight: bold;'; $table->style[0] = 'width: 13%'; - $table->data = array(); + $table->data = []; - $data = array(); + $data = []; $data[0] = __('Time lapse'); - $data[0] .= ui_print_help_tip(__('This is the interval or period of time with which the graph data will be obtained. For example, a week means data from a week ago from now. '),true); - $data[1] = html_print_extended_select_for_time('period_custom', $period,'', '', '0', 10, true,false,true,'',false,$periods); + $data[0] .= ui_print_help_tip(__('This is the interval or period of time with which the graph data will be obtained. For example, a week means data from a week ago from now. '), true); + $data[1] = html_print_extended_select_for_time('period_custom', $period, '', '', '0', 10, true, false, true, '', false, $periods); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); + $data = []; $data[0] = __('Custom graph'); - $list_custom_graphs = custom_graphs_get_user ($config['id_user'], false, true, "RR"); + $list_custom_graphs = custom_graphs_get_user($config['id_user'], false, true, 'RR'); - $graphs = array(); + $graphs = []; foreach ($list_custom_graphs as $custom_graph) { $graphs[$custom_graph['id_graph']] = $custom_graph['name']; } - $data[1] = html_print_select($graphs, 'id_custom_graph',$idCustomGraph, '', __('None'), 0,true); + $data[1] = html_print_select($graphs, 'id_custom_graph', $idCustomGraph, '', __('None'), 0, true); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); - $data[0] = __('Show full scale graph (TIP)') . - ui_print_help_tip('This option may cause performance issues', true); - $data[1] = html_print_checkbox('fullscale_2', 1, false,true); + $data = []; + $data[0] = __('Show full scale graph (TIP)').ui_print_help_tip('This option may cause performance issues', true); + $data[1] = html_print_checkbox('fullscale_2', 1, false, true); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); - $data[0] = ""; + $data = []; + $data[0] = ''; $data[1] = ""; $table->data[] = $data; $table->rowclass[] = ''; echo ""; - echo ""; - echo ""; - echo ""; - echo "
    "; - echo ui_toggle(html_print_table($table, true),'Custom graph', '', true, true); - echo "
    "; + echo ''; + echo ''; + echo ui_toggle(html_print_table($table, true), 'Custom graph', '', true, true); + echo ''; + echo ''; + echo ''; unset($table); @@ -443,159 +482,170 @@ if($edit_container){ $table->styleTable = 'font-weight: bold;'; $table->style[0] = 'width: 13%'; - $table->data = array(); + $table->data = []; - $data = array(); + $data = []; $data[0] = __('Time lapse'); - $data[0] .= ui_print_help_tip(__('This is the interval or period of time with which the graph data will be obtained. For example, a week means data from a week ago from now. '),true); - $data[1] = html_print_extended_select_for_time('period_dynamic', $period,'', '', '0', 10, true,false,true,'',false,$periods); + $data[0] .= ui_print_help_tip(__('This is the interval or period of time with which the graph data will be obtained. For example, a week means data from a week ago from now. '), true); + $data[1] = html_print_extended_select_for_time('period_dynamic', $period, '', '', '0', 10, true, false, true, '', false, $periods); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); + $data = []; $data[0] = __('Group'); $data[1] = html_print_select_groups($config['id_user'], 'RW', $return_all_groups, 'container_id_group', $id_group, '', '', '', true); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); + $data = []; $data[0] = __('Module group'); $data[1] = html_print_select_from_sql( - "SELECT * FROM tmodule_group ORDER BY name", - 'combo_modulegroup', $modulegroup, '',__('All'),false,true); + 'SELECT * FROM tmodule_group ORDER BY name', + 'combo_modulegroup', + $modulegroup, + '', + __('All'), + false, + true + ); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); - $data[0] = __('Agent'); - $data[1] = html_print_input_text ('text_agent', $textAgent, '', 30, 100, true); + $data = []; + $data[0] = __('Agent'); + $data[1] = html_print_input_text('text_agent', $textAgent, '', 30, 100, true); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); - $data[0] = __('Module'); - $data[1] = html_print_input_text ('text_agent_module', $textModule, '', 30, 100, true); + $data = []; + $data[0] = __('Module'); + $data[1] = html_print_input_text('text_agent_module', $textModule, '', 30, 100, true); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); - $data[0] = __('Tag'); - $select_tags = tags_search_tag (false, false, true); - $data[1] = html_print_select ($select_tags, 'tag', - $tag, '', __('Any'), 0, true, false, false); - $table->data[] = $data; - $table->rowclass[] = ''; - - $data = array(); - $data[0] = __('Type of graph'); - $data[1] = html_print_select ($type_graphs, 'simple_type_graph2', "","","",0,true); - $table->data[] = $data; - $table->rowclass[] = ''; - - $data = array(); - $data[0] = __('Show full scale graph (TIP)') . - ui_print_help_tip('This option may cause performance issues', true); - $data[1] = html_print_checkbox('fullscale_3', 1, false,true); + $data = []; + $data[0] = __('Tag'); + $select_tags = tags_search_tag(false, false, true); + $data[1] = html_print_select( + $select_tags, + 'tag', + $tag, + '', + __('Any'), + 0, + true, + false, + false + ); $table->data[] = $data; $table->rowclass[] = ''; - $data = array(); - $data[0] = ""; + $data = []; + $data[0] = __('Type of graph'); + $data[1] = html_print_select($type_graphs, 'simple_type_graph2', '', '', '', 0, true); + $table->data[] = $data; + $table->rowclass[] = ''; + + $data = []; + $data[0] = __('Show full scale graph (TIP)').ui_print_help_tip('This option may cause performance issues', true); + $data[1] = html_print_checkbox('fullscale_3', 1, false, true); + $table->data[] = $data; + $table->rowclass[] = ''; + + $data = []; + $data[0] = ''; $data[1] = ""; $table->data[] = $data; $table->rowclass[] = ''; echo ""; - echo ""; - echo ""; - echo ""; - echo "
    "; - echo ui_toggle(html_print_table($table, true),'Dynamic rules for simple module graph', '', true, true); - echo "
    "; - - $total_item = db_get_all_rows_sql("SELECT count(*) FROM tcontainer_item WHERE id_container = " . $id_container); - $result_item = db_get_all_rows_sql("SELECT * FROM tcontainer_item WHERE id_container = " . $id_container . " LIMIT 10 OFFSET ". $offset); - - if(!$result_item){ - echo "
    ".__('There are no defined item container')."
    "; + echo ''; + echo ''; + echo ui_toggle(html_print_table($table, true), 'Dynamic rules for simple module graph', '', true, true); + echo ''; + echo ''; + echo ''; + + $total_item = db_get_all_rows_sql('SELECT count(*) FROM tcontainer_item WHERE id_container = '.$id_container); + $result_item = db_get_all_rows_sql('SELECT * FROM tcontainer_item WHERE id_container = '.$id_container.' LIMIT 10 OFFSET '.$offset); + + if (!$result_item) { + echo "
    ".__('There are no defined item container').'
    '; } else { - ui_pagination ($total_item[0]['count(*)'],false,$offset,10); + ui_pagination($total_item[0]['count(*)'], false, $offset, 10); $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox data'; + $table->width = '100%'; + $table->class = 'databox data'; $table->id = 'item_table'; - $table->align = array (); - $table->head = array (); - $table->head[0] = __('Agent/Module'); - $table->head[1] = __('Custom graph'); - $table->head[2] = __('Group'); - $table->head[3] = __('M.Group'); + $table->align = []; + $table->head = []; + $table->head[0] = __('Agent/Module'); + $table->head[1] = __('Custom graph'); + $table->head[2] = __('Group'); + $table->head[3] = __('M.Group'); $table->head[4] = __('Agent'); $table->head[5] = __('Module'); $table->head[6] = __('Tag'); - $table->head[7] = __('Delete'); - - $table->data = array (); - - - foreach ($result_item as $item) { - $data = array (); - switch ($item['type']) { - case 'simple_graph': - $agent_alias = ui_print_truncate_text(agents_get_alias($item['id_agent'],20,false)); - $module_name = ui_print_truncate_text(modules_get_agentmodule_name($item['id_agent_module']),20,false); - $module_name = - $data[0] = $agent_alias . " / " .$module_name; - $data[1] = ''; - $data[2] = ''; - $data[3] = ''; - $data[4] = ''; - $data[5] = ''; - $data[6] = ''; - break; - - case 'custom_graph': - $data[0] = ''; - $name = db_get_value_filter('name','tgraph',array('id_graph' => $item['id_graph'])); - $data[1] = ui_print_truncate_text(io_safe_output($name),35,false); - $data[2] = ''; - $data[3] = ''; - $data[4] = ''; - $data[5] = ''; - $data[6] = ''; - break; - - case 'dynamic_graph': - $data[0] = ''; - $data[1] = ''; - - $data[2] = ui_print_group_icon($item['id_group'],true); - if ($item['id_module_group'] === '0') { - $data[3] = 'All'; - } else { - $data[3] = io_safe_output(db_get_value_filter('name','tmodule_group',array('id_mg' => $item['id_module_group']))); - - } - $data[4] = io_safe_output($item['agent']); - $data[5] = io_safe_output($item['module']); - if ($item['id_tag'] === '0') { - $data[6] = 'Any'; - } else { - $data[6] = io_safe_output(db_get_value_filter('name','ttag',array('id_tag' => $item['id_tag']))); - } - break; - - } - $data[7] = '' . html_print_image("images/cross.png", true, array('alt' => __('Delete'), 'title' => __('Delete'))) . ''; - - array_push ($table->data, $data); - } - html_print_table ($table); - } + $table->head[7] = __('Delete'); - + $table->data = []; + + + foreach ($result_item as $item) { + $data = []; + switch ($item['type']) { + case 'simple_graph': + $agent_alias = ui_print_truncate_text(agents_get_alias($item['id_agent'], 20, false)); + $module_name = ui_print_truncate_text(modules_get_agentmodule_name($item['id_agent_module']), 20, false); + $module_name = $data[0] = $agent_alias.' / '.$module_name; + $data[1] = ''; + $data[2] = ''; + $data[3] = ''; + $data[4] = ''; + $data[5] = ''; + $data[6] = ''; + break; + + case 'custom_graph': + $data[0] = ''; + $name = db_get_value_filter('name', 'tgraph', ['id_graph' => $item['id_graph']]); + $data[1] = ui_print_truncate_text(io_safe_output($name), 35, false); + $data[2] = ''; + $data[3] = ''; + $data[4] = ''; + $data[5] = ''; + $data[6] = ''; + break; + + case 'dynamic_graph': + $data[0] = ''; + $data[1] = ''; + + $data[2] = ui_print_group_icon($item['id_group'], true); + if ($item['id_module_group'] === '0') { + $data[3] = 'All'; + } else { + $data[3] = io_safe_output(db_get_value_filter('name', 'tmodule_group', ['id_mg' => $item['id_module_group']])); + } + + $data[4] = io_safe_output($item['agent']); + $data[5] = io_safe_output($item['module']); + if ($item['id_tag'] === '0') { + $data[6] = 'Any'; + } else { + $data[6] = io_safe_output(db_get_value_filter('name', 'ttag', ['id_tag' => $item['id_tag']])); + } + break; + } + + $data[7] = ''.html_print_image('images/cross.png', true, ['alt' => __('Delete'), 'title' => __('Delete')]).''; + + array_push($table->data, $data); + } + + html_print_table($table); + } } echo html_print_input_hidden('id_agent', 0); @@ -633,55 +683,55 @@ echo html_print_input_hidden('id_agent', 0); $("input[name=add_custom]").click (function () { var id_custom = $("#id_custom_graph").val(); var fullscale = $("#checkbox-fullscale_2").prop("checked"); - if (id_custom !== '0'){ - var time_lapse = $("#hidden-period_custom").attr('value'); - var id_container = ; - jQuery.post ("ajax.php", - {"page" : "godmode/reporting/create_container", - "add_custom" : 1, - "time_lapse" : time_lapse, - "id_custom" : id_custom, - "id_container" : id_container, + if (id_custom !== '0'){ + var time_lapse = $("#hidden-period_custom").attr('value'); + var id_container = ; + jQuery.post ("ajax.php", + {"page" : "godmode/reporting/create_container", + "add_custom" : 1, + "time_lapse" : time_lapse, + "id_custom" : id_custom, + "id_container" : id_container, "fullscale" : fullscale, - }, - function (data, status) { - var url = location.href.replace('&update_container=1', ""); - url = url.replace('&delete_item=1', ""); - location.href = url.replace('&add_container=1', "&id="+id_container); - } - ); - } + }, + function (data, status) { + var url = location.href.replace('&update_container=1', ""); + url = url.replace('&delete_item=1', ""); + location.href = url.replace('&add_container=1', "&id="+id_container); + } + ); + } }); - - $("input[name=add_dynamic]").click (function () { - var agent_alias = $("#text-text_agent").val(); - var module_name = $("#text-text_agent_module").val(); - var time_lapse = $("#hidden-period_dynamic").attr('value'); - var group = $("#container_id_group1").val(); - var module_group = $("#combo_modulegroup").val(); - var simple_type_graph2 = $("#simple_type_graph2 option:selected").attr('value'); - var tag = $("#tag").val(); + + $("input[name=add_dynamic]").click (function () { + var agent_alias = $("#text-text_agent").val(); + var module_name = $("#text-text_agent_module").val(); + var time_lapse = $("#hidden-period_dynamic").attr('value'); + var group = $("#container_id_group1").val(); + var module_group = $("#combo_modulegroup").val(); + var simple_type_graph2 = $("#simple_type_graph2 option:selected").attr('value'); + var tag = $("#tag").val(); - var id_container = ; - var fullscale = $("#checkbox-fullscale_3").prop("checked"); + var id_container = ; + var fullscale = $("#checkbox-fullscale_3").prop("checked"); jQuery.post ("ajax.php", - {"page" : "godmode/reporting/create_container", - "add_dynamic" : 1, - "time_lapse" : time_lapse, - "group" : group, - "module_group" : module_group, - "agent_alias" : agent_alias, - "module_name" : module_name, - "simple_type_graph2": simple_type_graph2, - "tag" : tag, - "id_container" : id_container, + {"page" : "godmode/reporting/create_container", + "add_dynamic" : 1, + "time_lapse" : time_lapse, + "group" : group, + "module_group" : module_group, + "agent_alias" : agent_alias, + "module_name" : module_name, + "simple_type_graph2": simple_type_graph2, + "tag" : tag, + "id_container" : id_container, "fullscale" : fullscale - }, - function (data, status) { - var url = location.href.replace('&update_container=1', ""); - url = url.replace('&delete_item=1', ""); - location.href = url.replace('&add_container=1', "&id="+id_container); - } + }, + function (data, status) { + var url = location.href.replace('&update_container=1', ""); + url = url.replace('&delete_item=1', ""); + location.href = url.replace('&add_container=1', "&id="+id_container); + } ); }); diff --git a/pandora_console/godmode/reporting/graph_builder.graph_editor.php b/pandora_console/godmode/reporting/graph_builder.graph_editor.php index da612b6e33..5626c51dab 100644 --- a/pandora_console/godmode/reporting/graph_builder.graph_editor.php +++ b/pandora_console/godmode/reporting/graph_builder.graph_editor.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,152 +11,167 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); +check_login(); -$report_w = check_acl ($config['id_user'], 0, "RW"); -$report_m = check_acl ($config['id_user'], 0, "RM"); +$report_w = check_acl($config['id_user'], 0, 'RW'); +$report_m = check_acl($config['id_user'], 0, 'RM'); -if (!$report_w && !$report_m ) { - db_pandora_audit("ACL Violation", - "Trying to access graph builder"); - include ("general/noaccess.php"); - exit; +if (!$report_w && !$report_m) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access graph builder' + ); + include 'general/noaccess.php'; + exit; } -require_once($config['homedir'] . "/include/functions_agents.php"); -require_once($config['homedir'] . "/include/functions_modules.php"); -require_once($config['homedir'] . "/include/functions_groups.php"); +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_groups.php'; $editGraph = (bool) get_parameter('edit_graph', 0); $action = get_parameter('action', ''); -if (isset ($_GET["get_agent"])) { - $id_agent = $_POST["id_agent"]; - if (isset($_POST["chunk"])) - $chunkdata = $_POST["chunk"]; +if (isset($_GET['get_agent'])) { + $id_agent = $_POST['id_agent']; + if (isset($_POST['chunk'])) { + $chunkdata = $_POST['chunk']; + } } switch ($action) { - case 'sort_items': - $resultOperationDB = null; - $position_to_sort = (int)get_parameter('position_to_sort', 1); - $ids_serialize = (string)get_parameter('ids_items_to_sort', ''); - $move_to = (string)get_parameter('move_to', 'after'); - - $countItems = db_get_sql(' + case 'sort_items': + $resultOperationDB = null; + $position_to_sort = (int) get_parameter('position_to_sort', 1); + $ids_serialize = (string) get_parameter('ids_items_to_sort', ''); + $move_to = (string) get_parameter('move_to', 'after'); + + $countItems = db_get_sql( + ' SELECT COUNT(id_gs) FROM tgraph_source - WHERE id_graph = ' . $id_graph); - - if (($countItems < $position_to_sort) || ($position_to_sort < 1)) { - $resultOperationDB = false; - } - else if (!empty($ids_serialize)) { - $ids = explode('|', $ids_serialize); - - switch ($config["dbtype"]) { - case "mysql": - $items = db_get_all_rows_sql(' + WHERE id_graph = '.$id_graph + ); + + if (($countItems < $position_to_sort) || ($position_to_sort < 1)) { + $resultOperationDB = false; + } else if (!empty($ids_serialize)) { + $ids = explode('|', $ids_serialize); + + switch ($config['dbtype']) { + case 'mysql': + $items = db_get_all_rows_sql( + ' SELECT id_gs, `field_order` FROM tgraph_source - WHERE id_graph = ' . $id_graph . ' - ORDER BY `field_order`'); - break; - } - - if ($items === false) $items = array(); - - - // Clean the repeated order values - $order_temp = 1; - foreach ($items as $item) { - switch ($config["dbtype"]) { - case "mysql": - db_process_sql_update('tgraph_source', - array('`field_order`' => $order_temp), - array('id_gs' => $item['id_rc'])); - break; - } - - $order_temp++; - } - - - switch ($config["dbtype"]) { - case "mysql": - $items = db_get_all_rows_sql(' + WHERE id_graph = '.$id_graph.' + ORDER BY `field_order`' + ); + break; + } + + if ($items === false) { + $items = []; + } + + + // Clean the repeated order values + $order_temp = 1; + foreach ($items as $item) { + switch ($config['dbtype']) { + case 'mysql': + db_process_sql_update( + 'tgraph_source', + ['`field_order`' => $order_temp], + ['id_gs' => $item['id_rc']] + ); + break; + } + + $order_temp++; + } + + + switch ($config['dbtype']) { + case 'mysql': + $items = db_get_all_rows_sql( + ' SELECT id_gs, `field_order` FROM tgraph_source - WHERE id_graph = ' . $id_graph . ' - ORDER BY `field_order`'); - break; - } - - if ($items === false) $items = array(); - - - - $temp = array(); - - $temp = array(); - foreach ($items as $item) { - //Remove the contents from the block to sort - if (array_search($item['id_gs'], $ids) === false) { - $temp[$item['field_order']] = $item['id_gs']; - } - } - $items = $temp; - - - - $sorted_items = array(); - foreach ($items as $pos => $id_unsort) { - if ($pos == $position_to_sort) { - if ($move_to == 'after') { - $sorted_items[] = $id_unsort; - } - - foreach ($ids as $id) { - $sorted_items[] = $id; - } - - if ($move_to != 'after') { - $sorted_items[] = $id_unsort; - } - } - else { - $sorted_items[] = $id_unsort; - } - } - - $items = $sorted_items; - - - - foreach ($items as $order => $id) { - switch ($config["dbtype"]) { - case "mysql": - - db_process_sql_update('tgraph_source', - array('`field_order`' => ($order + 1)), - array('id_gs' => $id)); - break; - } - } - - $resultOperationDB = true; - } - else { - $resultOperationDB = false; - } - break; - } + WHERE id_graph = '.$id_graph.' + ORDER BY `field_order`' + ); + break; + } + + if ($items === false) { + $items = []; + } + + + + $temp = []; + + $temp = []; + foreach ($items as $item) { + // Remove the contents from the block to sort + if (array_search($item['id_gs'], $ids) === false) { + $temp[$item['field_order']] = $item['id_gs']; + } + } + + $items = $temp; + + + + $sorted_items = []; + foreach ($items as $pos => $id_unsort) { + if ($pos == $position_to_sort) { + if ($move_to == 'after') { + $sorted_items[] = $id_unsort; + } + + foreach ($ids as $id) { + $sorted_items[] = $id; + } + + if ($move_to != 'after') { + $sorted_items[] = $id_unsort; + } + } else { + $sorted_items[] = $id_unsort; + } + } + + $items = $sorted_items; + + + + foreach ($items as $order => $id) { + switch ($config['dbtype']) { + case 'mysql': + + db_process_sql_update( + 'tgraph_source', + ['`field_order`' => ($order + 1)], + ['id_gs' => $id] + ); + break; + } + } + + $resultOperationDB = true; + } else { + $resultOperationDB = false; + } + break; +} if ($editGraph) { - $graphRows = db_get_all_rows_sql("SELECT t1.*, + $graphRows = db_get_all_rows_sql( + 'SELECT t1.*, (SELECT t3.alias FROM tagente t3 WHERE t3.id_agente = @@ -166,245 +180,274 @@ if ($editGraph) { WHERE t2.id_agente_modulo = t1.id_agent_module)) AS agent_name FROM tgraph_source t1 - WHERE t1.id_graph = " . $id_graph . " order by `field_order`"); - $position_array = array(); - $module_array = array(); - $weight_array = array(); - $agent_array = array(); - $label_array = array(); - - if($graphRows === false) { - $graphRows = array(); - } - - foreach ($graphRows as $graphRow) { - $idgs_array[] = $graphRow['id_gs']; - $module_array[] = $graphRow['id_agent_module']; - $weight_array[] = $graphRow['weight']; - $label_array[] = $graphRow['label']; - $agent_array[] = $graphRow['agent_name']; - $position_array[] = $graphRow['field_order']; - } - - $graphInTgraph = db_get_row_sql("SELECT * FROM tgraph WHERE id_graph = " . $id_graph); - $stacked = $graphInTgraph['stacked']; - $period = $graphInTgraph['period']; - $width = $graphInTgraph['width']; - $height = $graphInTgraph['height']; - - $modules = implode(',', $module_array); - $weights = implode(',', $weight_array); + WHERE t1.id_graph = '.$id_graph.' order by `field_order`' + ); + $position_array = []; + $module_array = []; + $weight_array = []; + $agent_array = []; + $label_array = []; + + if ($graphRows === false) { + $graphRows = []; + } + + foreach ($graphRows as $graphRow) { + $idgs_array[] = $graphRow['id_gs']; + $module_array[] = $graphRow['id_agent_module']; + $weight_array[] = $graphRow['weight']; + $label_array[] = $graphRow['label']; + $agent_array[] = $graphRow['agent_name']; + $position_array[] = $graphRow['field_order']; + } + + $graphInTgraph = db_get_row_sql('SELECT * FROM tgraph WHERE id_graph = '.$id_graph); + $stacked = $graphInTgraph['stacked']; + $period = $graphInTgraph['period']; + $width = $graphInTgraph['width']; + $height = $graphInTgraph['height']; + + $modules = implode(',', $module_array); + $weights = implode(',', $weight_array); } // Modules table if (count($module_array) > 0) { - echo ""; - echo " - - - - - - - "; - $color = 0; - for ($a = 0; $a < count($module_array); $a++) { - // Calculate table line color - if ($color == 1) { - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - - echo ""; - echo ""; - echo ""; - - echo ""; - - echo ""; - echo "
    ".__('P.')."".__('Agent')."".__('Module')."".__('Label')."".__('Weight')."".__('Delete')."".__('Sort')."
    $position_array[$a]" . $agent_array[$a] . ""; - echo modules_get_agentmodule_name ($module_array[$a]).""; - echo ""; + echo "
    "; + echo ' + + + + + + + '; + $color = 0; + for ($a = 0; $a < count($module_array); $a++) { + // Calculate table line color + if ($color == 1) { + $tdcolor = 'datos'; + $color = 0; + } else { + $tdcolor = 'datos2'; + $color = 1; + } - echo ""; - html_print_input_text ('label', $label_array[$a], '', 20, 30, false, false); - html_print_submit_button ('Ok', 'btn', false, '', false); - echo ""; - - echo "
    '.__('P.').''.__('Agent').''.__('Module').''.__('Label').''.__('Weight').''.__('Delete').''.__('Sort').'
    "; - echo "
    "; - echo ""; + echo ""; + echo "'; + echo "'; - echo ""; - html_print_input_text ('weight', $weight_array[$a], '', 20, 10, false, false); - html_print_submit_button ('Ok', 'btn', false, '', false); - echo ""; - - echo "
    $position_array[$a]".$agent_array[$a].'"; + echo modules_get_agentmodule_name($module_array[$a]).'
    "; - echo "
    "; - echo "".html_print_image('images/cross.png', true, array ('title' => __('Delete'))).""; + echo ""; + echo ''; - echo ""; - - echo ""; - - - echo ""; - } - echo "
    "; - - echo html_print_checkbox_extended('sorted_items[]', $idgs_array[$a], false, false, '', 'class="selected_check"', true); - - echo "
    "; + echo "
    "; + html_print_input_text('label', $label_array[$a], '', 20, 30, false, false); + html_print_submit_button('Ok', 'btn', false, '', false); + echo '
    '; + + echo '
    '; + echo ''; + + echo ""; + echo ''; + + echo ""; + html_print_input_text('weight', $weight_array[$a], '', 20, 10, false, false); + html_print_submit_button('Ok', 'btn', false, '', false); + echo ''; + + echo '
    '; + echo ''; + echo ""; + echo "".html_print_image('images/cross.png', true, ['title' => __('Delete')]).''; + + echo ''; + + echo ''; + + echo html_print_checkbox_extended('sorted_items[]', $idgs_array[$a], false, false, '', 'class="selected_check"', true); + + echo ''; + + + echo ''; + } + + echo ''; } $table = new stdClass(); $table->width = '100%'; $table->colspan[0][0] = 3; -$table->size = array(); +$table->size = []; $table->size[0] = '25%'; $table->size[1] = '25%'; $table->size[2] = '25%'; $table->size[3] = '25%'; -if (defined("METACONSOLE")) { - $table->class = "databox data"; - $table->head[0] = __("Sort items"); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; -} -else { - $table->data[0][0] = "". __("Sort items") . ""; +if (defined('METACONSOLE')) { + $table->class = 'databox data'; + $table->head[0] = __('Sort items'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; +} else { + $table->data[0][0] = ''.__('Sort items').''; } + $table->data[1][0] = __('Sort selected items'); $table->data[1][1] = html_print_select_style( - array('before' => __('before to'), 'after' => __('after to')), 'move_to', - '', '', '', '', 0, true); -$table->data[1][2] = html_print_input_text_extended('position_to_sort', 1, - 'text-position_to_sort', '', 3, 10, false, "only_numbers('position_to_sort');", '', true); + [ + 'before' => __('before to'), + 'after' => __('after to'), + ], + 'move_to', + '', + '', + '', + '', + 0, + true +); +$table->data[1][2] = html_print_input_text_extended( + 'position_to_sort', + 1, + 'text-position_to_sort', + '', + 3, + 10, + false, + "only_numbers('position_to_sort');", + '', + true +); $table->data[1][2] .= html_print_input_hidden('ids_items_to_sort', '', true); $table->data[1][3] = html_print_submit_button(__('Sort'), 'sort_submit', false, 'class="sub upd"', true); $table->data[1][4] = html_print_input_hidden('action', 'sort_items', true); echo "
    "; html_print_table($table); -echo "
    "; +echo ''; -echo "
    "; +echo '
    '; -//Configuration form -echo ''; -echo "
    "; +// Configuration form +echo ''; +echo ""; echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; +echo ''; +echo "'; +echo ''; +echo "'; +echo ''; +echo "'; +echo ''; +echo "'; +echo ''; +echo ''; +echo "'; +echo ''; +echo ''; echo ""; -echo ""; +echo '
    ".__('Filter group')."
    ".html_print_select_groups($config['id_user'], ($report_w == true) ? 'RW' : (($report_m == true) ? 'RM' : 'RW'), - true, 'group', '', 'filterByGroup($(\'#group\').val());', - '', 0, true)."
    ".__('Agents')."".__('Modules')."
    ".html_print_select (agents_get_group_agents(), 'id_agents[]', 0, false, '', '', true, true, true, '', false, '')."" . html_print_image("images/darrowright.png", true) . "".html_print_select (array (), 'module[]', 0, false, '', 0, true, true, true, '', false, '')."
    ".__('Filter group').'
    ".html_print_select_groups( + $config['id_user'], + ($report_w == true) ? 'RW' : (($report_m == true) ? 'RM' : 'RW'), + true, + 'group', + '', + 'filterByGroup($(\'#group\').val());', + '', + 0, + true +).'
    ".__('Agents').'".__('Modules').'
    '.html_print_select(agents_get_group_agents(), 'id_agents[]', 0, false, '', '', true, true, true, '', false, '').'".html_print_image('images/darrowright.png', true).''.html_print_select([], 'module[]', 0, false, '', 0, true, true, true, '', false, '').'
    "; echo ""; -echo ""; +echo ''; echo ""; -echo "
    ".__('Weight')."'.__('Weight').'
    "; -echo "
    '; +echo ''; +echo ''; echo ""; -echo ""; +echo ''; echo "
    "; -ui_require_jquery_file ('pandora.controls'); -ui_require_jquery_file ('ajaxqueue'); -ui_require_jquery_file ('bgiframe'); -ui_require_jquery_file ('autocomplete'); +ui_require_jquery_file('pandora.controls'); +ui_require_jquery_file('ajaxqueue'); +ui_require_jquery_file('bgiframe'); +ui_require_jquery_file('autocomplete'); ?> diff --git a/pandora_console/godmode/reporting/graph_builder.main.php b/pandora_console/godmode/reporting/graph_builder.main.php index b441aeda14..9e8f955e79 100644 --- a/pandora_console/godmode/reporting/graph_builder.main.php +++ b/pandora_console/godmode/reporting/graph_builder.main.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,199 +11,193 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -require_once('include/functions_custom_graphs.php'); +require_once 'include/functions_custom_graphs.php'; -if (is_ajax ()) { - $search_agents = (bool) get_parameter ('search_agents'); - - if ($search_agents) { - - require_once ('include/functions_agents.php'); - - $id_agent = (int) get_parameter ('id_agent'); - $string = (string) get_parameter ('q'); /* q is what autocomplete plugin gives */ - $id_group = (int) get_parameter('id_group'); - - $filter = array (); - $filter[] = '(nombre COLLATE utf8_general_ci LIKE "%'.$string.'%" OR direccion LIKE "%'.$string.'%" OR comentarios LIKE "%'.$string.'%")'; - $filter['id_grupo'] = $id_group; - - $agents = agents_get_agents ($filter, array ('nombre', 'direccion')); - if ($agents === false) - return; - - foreach ($agents as $agent) { - echo $agent['nombre']."|".$agent['direccion']."\n"; - } - - return; - } - - return; +if (is_ajax()) { + $search_agents = (bool) get_parameter('search_agents'); + + if ($search_agents) { + include_once 'include/functions_agents.php'; + + $id_agent = (int) get_parameter('id_agent'); + $string = (string) get_parameter('q'); + // q is what autocomplete plugin gives + $id_group = (int) get_parameter('id_group'); + + $filter = []; + $filter[] = '(nombre COLLATE utf8_general_ci LIKE "%'.$string.'%" OR direccion LIKE "%'.$string.'%" OR comentarios LIKE "%'.$string.'%")'; + $filter['id_grupo'] = $id_group; + + $agents = agents_get_agents($filter, ['nombre', 'direccion']); + if ($agents === false) { + return; + } + + foreach ($agents as $agent) { + echo $agent['nombre'].'|'.$agent['direccion']."\n"; + } + + return; + } + + return; } -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "RW") && ! check_acl ($config['id_user'], 0, "RM")) { - db_pandora_audit("ACL Violation", - "Trying to access graph builder"); - include ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'RW') && ! check_acl($config['id_user'], 0, 'RM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access graph builder' + ); + include 'general/noaccess.php'; + exit; } if ($edit_graph) { - $graphInTgraph = db_get_row_sql("SELECT * FROM tgraph WHERE id_graph = " . $id_graph); - $stacked = $graphInTgraph['stacked']; - $period = $graphInTgraph['period']; - $id_group = $graphInTgraph['id_group']; - $width = $graphInTgraph['width']; - $height = $graphInTgraph['height']; - $check = false; - $percentil = $graphInTgraph['percentil']; - $summatory_series = $graphInTgraph['summatory_series']; - $average_series = $graphInTgraph['average_series']; - $modules_series = $graphInTgraph['modules_series']; - $fullscale = $graphInTgraph['fullscale']; + $graphInTgraph = db_get_row_sql('SELECT * FROM tgraph WHERE id_graph = '.$id_graph); + $stacked = $graphInTgraph['stacked']; + $period = $graphInTgraph['period']; + $id_group = $graphInTgraph['id_group']; + $check = false; + $percentil = $graphInTgraph['percentil']; + $summatory_series = $graphInTgraph['summatory_series']; + $average_series = $graphInTgraph['average_series']; + $modules_series = $graphInTgraph['modules_series']; + $fullscale = $graphInTgraph['fullscale']; - if ($stacked == CUSTOM_GRAPH_BULLET_CHART_THRESHOLD){ - $stacked = CUSTOM_GRAPH_BULLET_CHART; - $check = true; - } -} -else { - $id_agent = 0; - $id_module = 0; - $id_group = 0; - $width = 550; - $height = 210; - $period = SECONDS_1DAY; - $factor = 1; - $stacked = 4; - $check = false; - $percentil = 0; - $summatory_series = 0; - $average_series = 0; - $modules_series = 0; - if($config['full_scale_option'] == 1){ - $fullscale = 1; - } - else{ - $fullscale = 0; - } + if ($stacked == CUSTOM_GRAPH_BULLET_CHART_THRESHOLD) { + $stacked = CUSTOM_GRAPH_BULLET_CHART; + $check = true; + } +} else { + $id_agent = 0; + $id_module = 0; + $id_group = 0; + $period = SECONDS_1DAY; + $factor = 1; + $stacked = 4; + $check = false; + $percentil = 0; + $summatory_series = 0; + $average_series = 0; + $modules_series = 0; + if ($config['full_scale_option'] == 1) { + $fullscale = 1; + } else { + $fullscale = 0; + } } // ----------------------- // CREATE/EDIT GRAPH FORM // ----------------------- - echo ""; -if ($edit_graph) - echo ""; -else - echo ""; +if ($edit_graph) { + echo ""; +} else { + echo ""; +} -echo ""; -echo ""; +echo ''; +echo "'; echo ""; -echo ""; -echo ""; +$own_info = get_user_info($config['id_user']); + +echo ''; +echo ''; +echo "'; echo ""; -if ($stacked == CUSTOM_GRAPH_GAUGE) - $hidden = ' style="display:none;" '; -else - $hidden = ''; -echo ""; -echo ""; -echo ""; -echo ""; -echo ""; +echo ''; +echo ''; +if ($stacked == CUSTOM_GRAPH_GAUGE) { + $hidden = ' style="display:none;" '; +} else { + $hidden = ''; +} -echo ""; +echo ''; echo ""; +echo ''.__('Period').''; echo ""; +echo ''.__('Type of graph').''; echo ""; +echo ''; -echo ""; -echo ""; -echo ""; -echo "'; +echo "'; +echo "'; +echo ""; -echo " -"; -echo ""; -echo ""; + This feature could be used instead of synthetic modules if you only want to see a graph.' + ), + true +).''; +echo " +'; +echo "'; +echo "'; -echo ""; -echo ""; -echo ""; -echo ""; -echo "
    ".__('Name')."
    ".__('Name').'"; -$own_info = get_user_info ($config['id_user']); +echo '>'; -echo "".__('Group').""; - if (check_acl ($config['id_user'], 0, "RW")) - echo html_print_select_groups($config['id_user'], 'RW', true, 'graph_id_group', $id_group, '', '', '', true); - elseif (check_acl ($config['id_user'], 0, "RM")) - echo html_print_select_groups($config['id_user'], 'RM', true, 'graph_id_group', $id_group, '', '', '', true); -echo "
    ".__('Description')."'.__('Group').''; +if (check_acl($config['id_user'], 0, 'RW')) { + echo html_print_select_groups($config['id_user'], 'RW', true, 'graph_id_group', $id_group, '', '', '', true); +} else if (check_acl($config['id_user'], 0, 'RM')) { + echo html_print_select_groups($config['id_user'], 'RM', true, 'graph_id_group', $id_group, '', '', '', true); +} + +echo '
    ".__('Description').'"; -echo "
    "; -echo "".__('Width').""; -echo ""; -echo "".__('Height').""; -echo "
    "; -echo "".__('Period').""; -html_print_extended_select_for_time ('period', $period, '', '', '0', 10); +html_print_extended_select_for_time('period', $period, '', '', '0', 10); echo ""; -echo "".__('Type of graph')."
    "; -include_once($config["homedir"] . "/include/functions_graph.php"); +require_once $config['homedir'].'/include/functions_graph.php'; -$stackeds = array( - CUSTOM_GRAPH_AREA => __('Area'), - CUSTOM_GRAPH_STACKED_AREA => __('Stacked area'), - CUSTOM_GRAPH_LINE => __('Line'), - CUSTOM_GRAPH_STACKED_LINE => __('Stacked line'), - CUSTOM_GRAPH_BULLET_CHART => __('Bullet chart'), - CUSTOM_GRAPH_GAUGE => __('Gauge'), - CUSTOM_GRAPH_HBARS => __('Horizontal bars'), - CUSTOM_GRAPH_VBARS => __('Vertical bars'), - CUSTOM_GRAPH_PIE => __('Pie') - ); -html_print_select ($stackeds, 'stacked', $stacked); +$stackeds = [ + CUSTOM_GRAPH_AREA => __('Area'), + CUSTOM_GRAPH_STACKED_AREA => __('Stacked area'), + CUSTOM_GRAPH_LINE => __('Line'), + CUSTOM_GRAPH_STACKED_LINE => __('Stacked line'), + CUSTOM_GRAPH_BULLET_CHART => __('Bullet chart'), + CUSTOM_GRAPH_GAUGE => __('Gauge'), + CUSTOM_GRAPH_HBARS => __('Horizontal bars'), + CUSTOM_GRAPH_VBARS => __('Vertical bars'), + CUSTOM_GRAPH_PIE => __('Pie'), +]; +html_print_select($stackeds, 'stacked', $stacked); -echo "
    ".__('Percentil')."" . html_print_checkbox ("percentil", 1, $percentil, true) . "
    ".__('Equalize maximum thresholds')."" . - ui_print_help_tip (__("If an option is selected, all graphs will have the highest value from all modules included in the graph as a maximum threshold"), true); - html_print_checkbox('threshold', CUSTOM_GRAPH_BULLET_CHART_THRESHOLD, $check, false, false, '', false); -echo "
    ".__('Add summatory series') . - ui_print_help_tip (__("Adds synthetic series to the graph, using all module +echo "
    ".__('Percentil').'".html_print_checkbox('percentil', 1, $percentil, true).'
    ".__('Equalize maximum thresholds').''.ui_print_help_tip(__('If an option is selected, all graphs will have the highest value from all modules included in the graph as a maximum threshold'), true); + html_print_checkbox('threshold', CUSTOM_GRAPH_BULLET_CHART_THRESHOLD, $check, false, false, '', false); +echo '
    ".__('Add summatory series').ui_print_help_tip( + __( + 'Adds synthetic series to the graph, using all module values to calculate the summation and/or average in each time interval. - This feature could be used instead of synthetic modules if you only want to see a graph."), true) . "" . html_print_checkbox ("summatory_series", 1, $summatory_series, true) . "".__('Add average series')."" . html_print_checkbox ("average_series", 1, $average_series, true) . "
    ".__('Modules and series')."".html_print_checkbox('summatory_series', 1, $summatory_series, true)."".__('Add average series').'".html_print_checkbox('average_series', 1, $average_series, true).'
    ".__('Modules and series').'" . html_print_checkbox ("modules_series", 1, $modules_series, true) . "".__('Show full scale graph (TIP)') . ui_print_help_tip(__('This option may cause performance issues'), true) . "" . html_print_checkbox ("fullscale", 1, $fullscale, true) . "
    "; +echo "".html_print_checkbox('modules_series', 1, $modules_series, true).''; +echo "".__('Show full scale graph (TIP)').ui_print_help_tip(__('This option may cause performance issues'), true).''; +echo "".html_print_checkbox('fullscale', 1, $fullscale, true).''; +echo ''; +echo ''; if ($edit_graph) { - echo "
    "; + echo "
    "; +} else { + echo "
    "; } -else { - echo "
    "; -} -echo ""; + +echo ''; echo ''; -?> diff --git a/pandora_console/godmode/reporting/graph_builder.php b/pandora_console/godmode/reporting/graph_builder.php index 957720f59c..28bae38d3d 100644 --- a/pandora_console/godmode/reporting/graph_builder.php +++ b/pandora_console/godmode/reporting/graph_builder.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,51 +11,53 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -if (is_ajax ()) { - $search_agents = (bool) get_parameter ('search_agents'); - - if ($search_agents) { - - require_once ('include/functions_agents.php'); - - $id_agent = (int) get_parameter ('id_agent'); - $string = (string) get_parameter ('q'); /* q is what autocomplete plugin gives */ - $id_group = (int) get_parameter('id_group'); - - $filter = array (); - $filter[] = '(nombre COLLATE utf8_general_ci LIKE "%'.$string.'%" OR direccion LIKE "%'.$string.'%" OR comentarios LIKE "%'.$string.'%")'; - $filter['id_grupo'] = $id_group; - - $agents = agents_get_agents ($filter, array ('nombre', 'direccion')); - if ($agents === false) - return; - - foreach ($agents as $agent) { - echo $agent['nombre']."|".$agent['direccion']."\n"; - } - - return; - } - - return; +if (is_ajax()) { + $search_agents = (bool) get_parameter('search_agents'); + + if ($search_agents) { + include_once 'include/functions_agents.php'; + + $id_agent = (int) get_parameter('id_agent'); + $string = (string) get_parameter('q'); + // q is what autocomplete plugin gives + $id_group = (int) get_parameter('id_group'); + + $filter = []; + $filter[] = '(nombre COLLATE utf8_general_ci LIKE "%'.$string.'%" OR direccion LIKE "%'.$string.'%" OR comentarios LIKE "%'.$string.'%")'; + $filter['id_grupo'] = $id_group; + + $agents = agents_get_agents($filter, ['nombre', 'direccion']); + if ($agents === false) { + return; + } + + foreach ($agents as $agent) { + echo $agent['nombre'].'|'.$agent['direccion']."\n"; + } + + return; + } + + return; } -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "RW") && ! check_acl ($config['id_user'], 0, "RM")) { - db_pandora_audit("ACL Violation", - "Trying to access graph builder"); - include ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'RW') && ! check_acl($config['id_user'], 0, 'RM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access graph builder' + ); + include 'general/noaccess.php'; + exit; } unset($name); -$add_module = (bool) get_parameter ('add_module', false); -$delete_module = (bool) get_parameter ('delete_module', false); +$add_module = (bool) get_parameter('add_module', false); +$delete_module = (bool) get_parameter('delete_module', false); $edit_graph = (bool) get_parameter('edit_graph', false); $active_tab = get_parameter('tab', 'main'); $add_graph = (bool) get_parameter('add_graph', false); @@ -65,268 +66,293 @@ $change_weight = (bool) get_parameter('change_weight', false); $change_label = (bool) get_parameter('change_label', false); $id_graph = (int) get_parameter('id', 0); -if($id_graph !== 0){ - $sql = "SELECT * FROM tgraph - WHERE (private = 0 OR (private = 1 AND id_user = '".$config["id_user"]."')) +if ($id_graph !== 0) { + $sql = "SELECT * FROM tgraph + WHERE (private = 0 OR (private = 1 AND id_user = '".$config['id_user']."')) AND id_graph = ".$id_graph; - $control = db_process_sql($sql); - if(!$control){ - header('Location: index.php?sec=reporting&sec2=godmode/reporting/graphs'); - } + $control = db_process_sql($sql); + if (!$control) { + header('Location: index.php?sec=reporting&sec2=godmode/reporting/graphs'); + } } if ($add_graph) { - $name = get_parameter_post ("name"); - $description = get_parameter_post ("description"); - $module_number = get_parameter_post ("module_number"); - $idGroup = get_parameter_post ('graph_id_group'); - $width = get_parameter_post ("width"); - $height = get_parameter_post ("height"); - $stacked = get_parameter ("stacked", 0); - $period = get_parameter_post ("period"); - $threshold = get_parameter('threshold'); - $percentil = get_parameter ("percentil", 0); - $summatory_series = get_parameter ("summatory_series", 0); - $average_series = get_parameter ("average_series", 0); - $modules_series = get_parameter ("modules_series", 0); - $fullscale = get_parameter ("fullscale", 0); + $name = get_parameter_post('name'); + $description = get_parameter_post('description'); + $module_number = get_parameter_post('module_number'); + $idGroup = get_parameter_post('graph_id_group'); + $stacked = get_parameter('stacked', 0); + $period = get_parameter_post('period'); + $threshold = get_parameter('threshold'); + $percentil = get_parameter('percentil', 0); + $summatory_series = get_parameter('summatory_series', 0); + $average_series = get_parameter('average_series', 0); + $modules_series = get_parameter('modules_series', 0); + $fullscale = get_parameter('fullscale', 0); - if ($threshold == CUSTOM_GRAPH_BULLET_CHART_THRESHOLD){ - $stacked = $threshold; - } + if ($threshold == CUSTOM_GRAPH_BULLET_CHART_THRESHOLD) { + $stacked = $threshold; + } - // Create graph - $values = array( - 'id_user' => $config['id_user'], - 'name' => $name, - 'description' => $description, - 'period' => $period, - 'width' => $width, - 'height' => $height, - 'private' => 0, - 'id_group' => $idGroup, - 'stacked' => $stacked, - 'percentil' => $percentil, - 'summatory_series' => $summatory_series, - 'average_series' => $average_series, - 'modules_series' => $modules_series, - 'fullscale' => $fullscale - ); - - if (trim($name) != "") { - $id_graph = db_process_sql_insert('tgraph', $values); - if ($id_graph !== false) - db_pandora_audit("Report management", "Create graph #$id_graph"); - else - db_pandora_audit("Report management", "Fail try to create graph"); - } - else { - $id_graph = false; - } - - if(!$id_graph) - $edit_graph = false; + // Create graph + $values = [ + 'id_user' => $config['id_user'], + 'name' => $name, + 'description' => $description, + 'period' => $period, + 'private' => 0, + 'id_group' => $idGroup, + 'stacked' => $stacked, + 'percentil' => $percentil, + 'summatory_series' => $summatory_series, + 'average_series' => $average_series, + 'modules_series' => $modules_series, + 'fullscale' => $fullscale, + ]; + + if (trim($name) != '') { + $id_graph = db_process_sql_insert('tgraph', $values); + if ($id_graph !== false) { + db_pandora_audit('Report management', "Create graph #$id_graph"); + } else { + db_pandora_audit('Report management', 'Fail try to create graph'); + } + } else { + $id_graph = false; + } + + if (!$id_graph) { + $edit_graph = false; + } } if ($update_graph) { - $id_graph = get_parameter('id'); - $name = get_parameter('name'); - $id_group = get_parameter('graph_id_group'); - $description = get_parameter('description'); - $width = get_parameter('width'); - $height = get_parameter('height'); - $period = get_parameter('period'); - $stacked = get_parameter('stacked'); - $percentil = get_parameter('percentil'); - $summatory_series = get_parameter ("summatory_series"); - $average_series = get_parameter ("average_series"); - $modules_series = get_parameter ("modules_series"); - $alerts = get_parameter('alerts'); - $threshold = get_parameter('threshold'); - $fullscale = get_parameter('fullscale'); + $id_graph = get_parameter('id'); + $name = get_parameter('name'); + $id_group = get_parameter('graph_id_group'); + $description = get_parameter('description'); + $period = get_parameter('period'); + $stacked = get_parameter('stacked'); + $percentil = get_parameter('percentil'); + $summatory_series = get_parameter('summatory_series'); + $average_series = get_parameter('average_series'); + $modules_series = get_parameter('modules_series'); + $alerts = get_parameter('alerts'); + $threshold = get_parameter('threshold'); + $fullscale = get_parameter('fullscale'); - if ($threshold == CUSTOM_GRAPH_BULLET_CHART_THRESHOLD){ - $stacked = $threshold; - } + if ($threshold == CUSTOM_GRAPH_BULLET_CHART_THRESHOLD) { + $stacked = $threshold; + } - if (trim($name) != "") { - - $success = db_process_sql_update('tgraph', - array('name' => $name, 'id_group' => $id_group, 'description' => $description, - 'width' => $width, 'height' => $height, 'period' => $period, 'stacked' => $stacked, - 'percentil' => $percentil, 'summatory_series' => $summatory_series, - 'average_series' => $average_series, 'modules_series' => $modules_series, 'fullscale' => $fullscale), - array('id_graph' => $id_graph)); - if ($success !== false) - db_pandora_audit("Report management", "Update graph #$id_graph"); - else - db_pandora_audit("Report management", "Fail try to update graph #$id_graph"); - - } - else { - $success = false; - } + if (trim($name) != '') { + $success = db_process_sql_update( + 'tgraph', + [ + 'name' => $name, + 'id_group' => $id_group, + 'description' => $description, + 'width' => $width, + 'height' => $height, + 'period' => $period, + 'stacked' => $stacked, + 'percentil' => $percentil, + 'summatory_series' => $summatory_series, + 'average_series' => $average_series, + 'modules_series' => $modules_series, + 'fullscale' => $fullscale, + ], + ['id_graph' => $id_graph] + ); + if ($success !== false) { + db_pandora_audit('Report management', "Update graph #$id_graph"); + } else { + db_pandora_audit('Report management', "Fail try to update graph #$id_graph"); + } + } else { + $success = false; + } } + function add_quotes($item) { - return "'$item'"; + return "'$item'"; } -if ($add_module) { - $id_graph = get_parameter('id'); - $id_modules = get_parameter('module'); - $id_agents = get_parameter('id_agents'); - $weight = get_parameter('weight'); - - //Id modules has double entities conversion - //Safe output remove all entities - io_safe_output_array($id_modules, ""); - - //We need to put the entities again - //to browse in db - io_safe_input_array($id_modules); - - $id_agent_modules = db_get_all_rows_sql("SELECT id_agente_modulo FROM tagente_modulo WHERE id_agente IN (". - implode(',', $id_agents). - ") AND nombre IN ('". - implode("','", $id_modules). - "')"); - - if (count($id_agent_modules) > 0 && $id_agent_modules != '') { - $order = db_get_row_sql("SELECT `field_order` from tgraph_source WHERE id_graph=$id_graph ORDER BY `field_order` DESC"); - $order = $order['field_order']; - foreach($id_agent_modules as $id_agent_module){ - $order++; - $result = db_process_sql_insert('tgraph_source', array('id_graph' => $id_graph, 'id_agent_module' => $id_agent_module['id_agente_modulo'], 'weight' => $weight, 'field_order' => $order)); - } - } - else - $result = false; +if ($add_module) { + $id_graph = get_parameter('id'); + $id_modules = get_parameter('module'); + $id_agents = get_parameter('id_agents'); + $weight = get_parameter('weight'); + + // Id modules has double entities conversion + // Safe output remove all entities + io_safe_output_array($id_modules, ''); + + // We need to put the entities again + // to browse in db + io_safe_input_array($id_modules); + + $id_agent_modules = db_get_all_rows_sql( + 'SELECT id_agente_modulo FROM tagente_modulo WHERE id_agente IN ('.implode(',', $id_agents).") AND nombre IN ('".implode("','", $id_modules)."')" + ); + + if (count($id_agent_modules) > 0 && $id_agent_modules != '') { + $order = db_get_row_sql("SELECT `field_order` from tgraph_source WHERE id_graph=$id_graph ORDER BY `field_order` DESC"); + + $order = $order['field_order']; + foreach ($id_agent_modules as $id_agent_module) { + $order++; + $result = db_process_sql_insert('tgraph_source', ['id_graph' => $id_graph, 'id_agent_module' => $id_agent_module['id_agente_modulo'], 'weight' => $weight, 'field_order' => $order]); + } + } else { + $result = false; + } } if ($delete_module) { - $id_graph = get_parameter('id'); - - $deleteGraph = get_parameter('delete'); - $order_val = db_get_value('field_order', 'tgraph_source', 'id_gs', $deleteGraph); - $result = db_process_sql_delete('tgraph_source', array('id_gs' => $deleteGraph)); - db_process_sql ('UPDATE tgraph_source SET field_order=field_order-1 WHERE id_graph='.$id_graph.' AND field_order>'.$order_val); + $id_graph = get_parameter('id'); + $deleteGraph = get_parameter('delete'); + $order_val = db_get_value('field_order', 'tgraph_source', 'id_gs', $deleteGraph); + $result = db_process_sql_delete('tgraph_source', ['id_gs' => $deleteGraph]); + db_process_sql('UPDATE tgraph_source SET field_order=field_order-1 WHERE id_graph='.$id_graph.' AND field_order>'.$order_val); } if ($change_weight) { - $weight = get_parameter ('weight'); - $id_gs = get_parameter ('graph'); - db_process_sql_update('tgraph_source', - array('weight' => $weight), - array('id_gs' => $id_gs)); + $weight = get_parameter('weight'); + $id_gs = get_parameter('graph'); + db_process_sql_update( + 'tgraph_source', + ['weight' => $weight], + ['id_gs' => $id_gs] + ); } + if ($change_label) { - $label = get_parameter ('label'); - $id_gs = get_parameter ('graph'); - db_process_sql_update('tgraph_source', - array('label' => $label), - array('id_gs' => $id_gs)); + $label = get_parameter('label'); + $id_gs = get_parameter('graph'); + db_process_sql_update( + 'tgraph_source', + ['label' => $label], + ['id_gs' => $id_gs] + ); } if ($edit_graph) { - $buttons = array( - 'graph_list' => array('active' => false, - 'text' => '' . - html_print_image("images/list.png", true, array ("title" => __('Graph list'))) .''), - 'main' => array('active' => false, - 'text' => '' . - html_print_image("images/chart.png", true, array ("title" => __('Main data'))) .''), - 'graph_editor' => array('active' => false, - 'text' => '' . - html_print_image("images/builder.png", true, array ("title" => __('Graph editor'))) .''), - 'view' => array('active' => false, - 'text' => '' . - html_print_image("images/operation.png", true, array ("title" => __('View graph'))) .'') - ); - - $buttons[$active_tab]['active'] = true; - - $graphInTgraph = db_get_row_sql("SELECT name FROM tgraph WHERE id_graph = " . $id_graph); - $name = $graphInTgraph['name']; -} -else { - $buttons = ''; + $buttons = [ + 'graph_list' => [ + 'active' => false, + 'text' => ''.html_print_image('images/list.png', true, ['title' => __('Graph list')]).'', + ], + 'main' => [ + 'active' => false, + 'text' => ''.html_print_image('images/chart.png', true, ['title' => __('Main data')]).'', + ], + 'graph_editor' => [ + 'active' => false, + 'text' => ''.html_print_image('images/builder.png', true, ['title' => __('Graph editor')]).'', + ], + 'view' => [ + 'active' => false, + 'text' => ''.html_print_image('images/operation.png', true, ['title' => __('View graph')]).'', + ], + ]; + + $buttons[$active_tab]['active'] = true; + + $graphInTgraph = db_get_row_sql('SELECT name FROM tgraph WHERE id_graph = '.$id_graph); + $name = $graphInTgraph['name']; +} else { + $buttons = ''; } $head = __('Graph builder'); -if (isset($name)) - $head .= " - ".$name; - -// Header -$tab = get_parameter("tab", ""); -switch ($tab) { - case "main": - ui_print_page_header ($head, "images/chart.png", false, "graph_builder", false, $buttons); - break; - case "graph_editor": - ui_print_page_header ($head, "images/chart.png", false, "graph_editor", false, $buttons); - break; - default: - ui_print_page_header ($head, "images/chart.png", false, "graph_builder", false, $buttons); - break; +if (isset($name)) { + $head .= ' - '.$name; } -if ($add_graph) - ui_print_result_message($id_graph, __('Graph stored successfully'), __('There was a problem storing Graph')); +// Header +$tab = get_parameter('tab', ''); +switch ($tab) { + case 'main': + ui_print_page_header($head, 'images/chart.png', false, 'graph_builder', false, $buttons); + break; -if ($add_module) - ui_print_result_message($result, __('Module added successfully'), __('There was a problem adding Module')); + case 'graph_editor': + ui_print_page_header($head, 'images/chart.png', false, 'graph_editor', false, $buttons); + break; -if ($update_graph) - ui_print_result_message($success, __("Update the graph"), __("Bad update the graph")); + default: + ui_print_page_header($head, 'images/chart.png', false, 'graph_builder', false, $buttons); + break; +} + +if ($add_graph) { + ui_print_result_message($id_graph, __('Graph stored successfully'), __('There was a problem storing Graph')); +} + +if ($add_module) { + ui_print_result_message($result, __('Module added successfully'), __('There was a problem adding Module')); +} + +if ($update_graph) { + ui_print_result_message($success, __('Update the graph'), __('Bad update the graph')); +} if ($delete_module) { - ui_print_result_message($result, __('Graph deleted successfully'), __('There was a problem deleting Graph')); + ui_print_result_message($result, __('Graph deleted successfully'), __('There was a problem deleting Graph')); } // Parse CHUNK information into showable information // Split id to get all parameters if (!$delete_module) { - if (isset($_POST["period"])) - $period = $_POST["period"]; - if ((isset($chunkdata) )&& ($chunkdata != "")) { - $module_array = array(); - $weight_array = array(); - $agent_array = array(); - $chunk1 = array(); - $chunk1 = explode ("|", $chunkdata); - $modules="";$weights=""; - for ($a = 0; $a < count($chunk1); $a++) { - $chunk2[$a] = array(); - $chunk2[$a] = explode ( ",", $chunk1[$a]); - if (strpos($modules, $chunk2[$a][1]) == 0) { // Skip dupes - $module_array[] = $chunk2[$a][1]; - $agent_array[] = $chunk2[$a][0]; - $weight_array[] = $chunk2[$a][2]; - if ($modules !="") - $modules = $modules.",".$chunk2[$a][1]; - else - $modules = $chunk2[$a][1]; - if ($weights !="") - $weights = $weights.",".$chunk2[$a][2]; - else - $weights = $chunk2[$a][2]; - } - } - } + if (isset($_POST['period'])) { + $period = $_POST['period']; + } + + if ((isset($chunkdata) ) && ($chunkdata != '')) { + $module_array = []; + $weight_array = []; + $agent_array = []; + $chunk1 = []; + $chunk1 = explode('|', $chunkdata); + $modules = ''; + $weights = ''; + for ($a = 0; $a < count($chunk1); $a++) { + $chunk2[$a] = []; + $chunk2[$a] = explode(',', $chunk1[$a]); + if (strpos($modules, $chunk2[$a][1]) == 0) { + // Skip dupes + $module_array[] = $chunk2[$a][1]; + $agent_array[] = $chunk2[$a][0]; + $weight_array[] = $chunk2[$a][2]; + if ($modules != '') { + $modules = $modules.','.$chunk2[$a][1]; + } else { + $modules = $chunk2[$a][1]; + } + + if ($weights != '') { + $weights = $weights.','.$chunk2[$a][2]; + } else { + $weights = $chunk2[$a][2]; + } + } + } + } } switch ($active_tab) { - case 'main': - require_once('godmode/reporting/graph_builder.main.php'); - break; - case 'graph_editor': - require_once('godmode/reporting/graph_builder.graph_editor.php'); - break; + case 'main': + include_once 'godmode/reporting/graph_builder.main.php'; + break; + + case 'graph_editor': + include_once 'godmode/reporting/graph_builder.graph_editor.php'; + break; } -?> diff --git a/pandora_console/godmode/reporting/graph_container.php b/pandora_console/godmode/reporting/graph_container.php index 2785db4dba..ccc3b6dde6 100644 --- a/pandora_console/godmode/reporting/graph_container.php +++ b/pandora_console/godmode/reporting/graph_container.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,135 +10,137 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global variables global $config; // Check user credentials -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "RR")) { - db_pandora_audit("ACL Violation", - "Trying to access Inventory Module Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'RR')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Inventory Module Management' + ); + include 'general/noaccess.php'; + return; } -$report_r = check_acl ($config['id_user'], 0, "RR"); -$report_w = check_acl ($config['id_user'], 0, "RW"); -$report_m = check_acl ($config['id_user'], 0, "RM"); +$report_r = check_acl($config['id_user'], 0, 'RR'); +$report_w = check_acl($config['id_user'], 0, 'RW'); +$report_m = check_acl($config['id_user'], 0, 'RM'); $access = ($report_r == true) ? 'RR' : (($report_w == true) ? 'RW' : (($report_m == true) ? 'RM' : 'RR')); -require_once ('include/functions_container.php'); +require_once 'include/functions_container.php'; -$delete_container = get_parameter('delete_container',0); +$delete_container = get_parameter('delete_container', 0); -if ($delete_container){ - $id_container = get_parameter('id',0); - $child = folder_get_all_child_container($id_container); - - if($child){ - foreach ($child as $key => $value) { - $parent = array( - 'parent' => 1); - db_process_sql_update('tcontainer', $parent, array('id_container' => $value['id_container'])); - } - } - db_process_sql_delete('tcontainer', array('id_container' => $id_container)); - +if ($delete_container) { + $id_container = get_parameter('id', 0); + $child = folder_get_all_child_container($id_container); + + if ($child) { + foreach ($child as $key => $value) { + $parent = ['parent' => 1]; + db_process_sql_update('tcontainer', $parent, ['id_container' => $value['id_container']]); + } + } + + db_process_sql_delete('tcontainer', ['id_container' => $id_container]); } $max_graph = $config['max_graph_container']; -$buttons['graph_list'] = array('active' => false, - 'text' => '' . - html_print_image("images/list.png", true, array ("title" => __('Graph list'))) .''); +$buttons['graph_list'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/list.png', true, ['title' => __('Graph list')]).'', +]; $enterpriseEnable = false; if (enterprise_include_once('include/functions_reporting.php') !== ENTERPRISE_NOT_HOOK) { - $enterpriseEnable = true; + $enterpriseEnable = true; } -html_print_input_hidden ('custom_graph', 1); +html_print_input_hidden('custom_graph', 1); if ($enterpriseEnable) { - $buttons = reporting_enterprise_add_template_graph_tabs($buttons); + $buttons = reporting_enterprise_add_template_graph_tabs($buttons); } $subsection = reporting_enterprise_add_graph_template_subsection('', $buttons); -$buttons['graph_container'] = array('active' => true, - 'text' => '' . - html_print_image("images/graph-container.png", true, array ("title" => __('Graph container'))) . ''); +$buttons['graph_container'] = [ + 'active' => true, + 'text' => ''.html_print_image('images/graph-container.png', true, ['title' => __('Graph container')]).'', +]; // Header -ui_print_page_header (__('Graph container'), "", false, "",false,$buttons); +ui_print_page_header(__('Graph container'), '', false, '', false, $buttons); $container = folder_get_folders(); $tree = folder_get_folders_tree_recursive($container); echo folder_togge_tree_folders($tree); -if($report_r && $report_w){ - echo "
    "; - echo '
    '; - html_print_submit_button (__('Create container'), 'create', false, 'class="sub next" style="margin-right:5px;margin-top: 15px;"'); - echo "
    "; - echo "
    "; +if ($report_r && $report_w) { + echo "
    "; + echo '
    '; + html_print_submit_button(__('Create container'), 'create', false, 'class="sub next" style="margin-right:5px;margin-top: 15px;"'); + echo '
    '; + echo '
    '; } ?> \ No newline at end of file diff --git a/pandora_console/godmode/reporting/graphs.php b/pandora_console/godmode/reporting/graphs.php index d007371704..633ed82f4d 100644 --- a/pandora_console/godmode/reporting/graphs.php +++ b/pandora_console/godmode/reporting/graphs.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,24 +10,25 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global variables global $config; -require_once ('include/functions_custom_graphs.php'); +require_once 'include/functions_custom_graphs.php'; // Check user credentials -check_login (); +check_login(); -$report_r = check_acl ($config['id_user'], 0, "RR"); -$report_w = check_acl ($config['id_user'], 0, "RW"); -$report_m = check_acl ($config['id_user'], 0, "RM"); +$report_r = check_acl($config['id_user'], 0, 'RR'); +$report_w = check_acl($config['id_user'], 0, 'RW'); +$report_m = check_acl($config['id_user'], 0, 'RM'); if (!$report_r && !$report_w && !$report_m) { - db_pandora_audit("ACL Violation", - "Trying to access Inventory Module Management"); - require ("general/noaccess.php"); - return; + db_pandora_audit( + 'ACL Violation', + 'Trying to access Inventory Module Management' + ); + include 'general/noaccess.php'; + return; } $access = ($report_r == true) ? 'RR' : (($report_w == true) ? 'RW' : (($report_m == true) ? 'RM' : 'RR')); @@ -37,196 +37,200 @@ $activeTab = get_parameter('tab', 'main'); $enterpriseEnable = false; if (enterprise_include_once('include/functions_reporting.php') !== ENTERPRISE_NOT_HOOK) { - $enterpriseEnable = true; + $enterpriseEnable = true; } -$buttons['graph_list'] = array('active' => true, - 'text' => '' . - html_print_image("images/list.png", true, array ("title" => __('Graph list'))) .''); +$buttons['graph_list'] = [ + 'active' => true, + 'text' => ''.html_print_image('images/list.png', true, ['title' => __('Graph list')]).'', +]; if ($enterpriseEnable) { - $buttons = reporting_enterprise_add_template_graph_tabs($buttons); + $buttons = reporting_enterprise_add_template_graph_tabs($buttons); } $subsection = ''; switch ($activeTab) { - case 'main': - $buttons['graph_list']['active'] = true; - $subsection = ' » '.__('Graph list'); - break; - default: - $subsection = reporting_enterprise_add_graph_template_subsection($activeTab, $buttons); - break; + case 'main': + $buttons['graph_list']['active'] = true; + $subsection = ' » '.__('Graph list'); + break; + + default: + $subsection = reporting_enterprise_add_graph_template_subsection($activeTab, $buttons); + break; } switch ($activeTab) { - case 'main': - require_once('godmode/reporting/graphs.php'); - break; - default: - reporting_enterprise_select_graph_template_tab($activeTab); - break; + case 'main': + include_once 'godmode/reporting/graphs.php'; + break; + + default: + reporting_enterprise_select_graph_template_tab($activeTab); + break; } -$buttons['graph_container'] = array('active' => false, - 'text' => '' . - html_print_image("images/graph-container.png", true, array ("title" => __('Graphs containers'))) .''); - -$delete_graph = (bool) get_parameter ('delete_graph'); -$view_graph = (bool) get_parameter ('view_graph'); -$id = (int) get_parameter ('id'); -$multiple_delete = (bool)get_parameter('multiple_delete', 0); + +$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'); +$id = (int) get_parameter('id'); +$multiple_delete = (bool) get_parameter('multiple_delete', 0); // Header -ui_print_page_header (__('Reporting')." » ".__('Custom graphs'), "images/chart.png", false, "", false, $buttons); +ui_print_page_header(__('Reporting').' » '.__('Custom graphs'), 'images/chart.png', false, '', false, $buttons); // Delete module SQL code if ($delete_graph) { - if ( $report_w || $report_m ) { - - $exist = db_get_value("id_graph", "tgraph_source", "id_graph", $id); - if ($exist) { - $result = db_process_sql_delete("tgraph_source", array('id_graph' =>$id)); - - if ($result) - $result = ui_print_success_message(__('Successfully deleted')); - else - $result = ui_print_error_message(__('Not deleted. Error deleting data')); - } - $result = db_process_sql_delete("tgraph", array('id_graph' =>$id)); - - if ($result) { - db_pandora_audit("Report management", "Delete graph #$id"); - $result = ui_print_success_message(__('Successfully deleted')); - } - else { - db_pandora_audit("Report management", "Fail try to delete graph #$id"); - $result = ui_print_error_message(__('Not deleted. Error deleting data')); - } - - echo $result; - } - else { - db_pandora_audit("ACL Violation","Trying to delete a graph from access graph builder"); - include ("general/noaccess.php"); - exit; - } + if ($report_w || $report_m) { + $exist = db_get_value('id_graph', 'tgraph_source', 'id_graph', $id); + if ($exist) { + $result = db_process_sql_delete('tgraph_source', ['id_graph' => $id]); + + if ($result) { + $result = ui_print_success_message(__('Successfully deleted')); + } else { + $result = ui_print_error_message(__('Not deleted. Error deleting data')); + } + } + + $result = db_process_sql_delete('tgraph', ['id_graph' => $id]); + + if ($result) { + db_pandora_audit('Report management', "Delete graph #$id"); + $result = ui_print_success_message(__('Successfully deleted')); + } else { + db_pandora_audit('Report management', "Fail try to delete graph #$id"); + $result = ui_print_error_message(__('Not deleted. Error deleting data')); + } + + echo $result; + } else { + db_pandora_audit('ACL Violation', 'Trying to delete a graph from access graph builder'); + include 'general/noaccess.php'; + exit; + } } if ($multiple_delete) { - $ids = (array)get_parameter('delete_multiple', array()); - - foreach ($ids as $id) { - $result = db_process_sql_delete ('tgraph', - array('id_graph' => $id)); - - if ($result === false) { - break; - } - } - - if ($result !== false) - $result = true; - else - $result = false; - - $str_ids = implode (',', $ids); - if ($result) { - db_pandora_audit("Report management", "Multiple delete graph: $str_ids"); - } - else { - db_pandora_audit("Report management", "Fail try to delete graphs: $str_ids"); - } - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Not deleted. Error deleting data')); + $ids = (array) get_parameter('delete_multiple', []); + + foreach ($ids as $id) { + $result = db_process_sql_delete( + 'tgraph', + ['id_graph' => $id] + ); + + if ($result === false) { + break; + } + } + + if ($result !== false) { + $result = true; + } else { + $result = false; + } + + $str_ids = implode(',', $ids); + if ($result) { + db_pandora_audit('Report management', "Multiple delete graph: $str_ids"); + } else { + db_pandora_audit('Report management', "Fail try to delete graphs: $str_ids"); + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Not deleted. Error deleting data') + ); } -$graphs = custom_graphs_get_user ($config['id_user'], false, true, $access); -$offset = (int) get_parameter ("offset"); +$graphs = custom_graphs_get_user($config['id_user'], false, true, $access); +$offset = (int) get_parameter('offset'); -ui_pagination (count($graphs)); +ui_pagination(count($graphs)); -if (!empty ($graphs)) { - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox data'; - $table->align = array (); - $table->head = array (); - $table->head[0] = __('Graph name'); - $table->head[1] = __('Description'); - $table->head[2] = __('Number of Graphs'); - $table->head[3] = __('Group'); - $table->size[0] = '30%'; - $table->size[2] = '200px'; - $table->size[3] = '200px'; - $table->align[2] = 'left'; - $table->align[3] = 'left'; - $op_column = false; - if ($report_w || $report_m) { - $op_column = true; - $table->align[4] = 'left'; - $table->head[4] = __('Op.') . - html_print_checkbox('all_delete', 0, false, true, false); - $table->size[4] = '90px'; - } - $table->data = array (); +if (!empty($graphs)) { + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox data'; + $table->align = []; + $table->head = []; + $table->head[0] = __('Graph name'); + $table->head[1] = __('Description'); + $table->head[2] = __('Number of Graphs'); + $table->head[3] = __('Group'); + $table->size[0] = '30%'; + $table->size[2] = '200px'; + $table->size[3] = '200px'; + $table->align[2] = 'left'; + $table->align[3] = 'left'; + $op_column = false; + if ($report_w || $report_m) { + $op_column = true; + $table->align[4] = 'left'; + $table->head[4] = __('Op.').html_print_checkbox('all_delete', 0, false, true, false); + $table->size[4] = '90px'; + } - $result_graphs = array_slice($graphs, $offset, $config['block_size']); + $table->data = []; - foreach ($result_graphs as $graph) { - $data = array (); - - $data[0] = '' . ui_print_truncate_text($graph['name'], 70) . ''; - - $data[1] = ui_print_truncate_text($graph["description"], 70); - - $data[2] = $graph["graphs_count"]; - $data[3] = ui_print_group_icon($graph['id_group'],true); - - $data[4] = ''; - if (($report_w || $report_m)) { - $data[4] = ''.html_print_image("images/config.png", true).''; - } + $result_graphs = array_slice($graphs, $offset, $config['block_size']); - $data[4] .= ' '; + foreach ($result_graphs as $graph) { + $data = []; - if ($report_m) { - $data[4] .= '' . html_print_image("images/cross.png", true, array('alt' => __('Delete'), 'title' => __('Delete'))) . '' . - 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).''; - array_push ($table->data, $data); - } + $data[1] = ui_print_truncate_text($graph['description'], 70); + + $data[2] = $graph['graphs_count']; + $data[3] = ui_print_group_icon($graph['id_group'], true); + + $data[4] = ''; + if (($report_w || $report_m)) { + $data[4] = ''.html_print_image('images/config.png', true).''; + } + + $data[4] .= ' '; + + if ($report_m) { + $data[4] .= ''.html_print_image('images/cross.png', true, ['alt' => __('Delete'), 'title' => __('Delete')]).''.html_print_checkbox_extended('delete_multiple[]', $graph['id_graph'], false, false, '', 'class="check_delete" style="margin-left:2px;"', true); + } + + array_push($table->data, $data); + } - if (!empty($result_graphs)){ - echo "
    "; - html_print_input_hidden('multiple_delete', 1); - html_print_table ($table); - echo "
    "; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - echo "
    "; - echo "
    "; - } + if (!empty($result_graphs)) { + echo "
    "; + html_print_input_hidden('multiple_delete', 1); + html_print_table($table); + echo "
    "; + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + echo '
    '; + echo '
    '; + } - echo "
    "; - if ($report_w || $report_m) { - echo '
    '; - html_print_submit_button (__('Create graph'), 'create', false, 'class="sub next" style="margin-right:5px;"'); - echo "
    "; - } - echo "
    "; - ui_pagination (count($graphs)); -} -else { - require_once ($config['homedir'] . "/general/firts_task/custom_graphs.php"); + echo "
    "; + if ($report_w || $report_m) { + echo '
    '; + html_print_submit_button(__('Create graph'), 'create', false, 'class="sub next" style="margin-right:5px;"'); + echo '
    '; + } + + echo '
    '; + ui_pagination(count($graphs)); +} else { + include_once $config['homedir'].'/general/firts_task/custom_graphs.php'; } ?> @@ -235,29 +239,29 @@ else { $("input[name=all_delete]").css("margin-left", "32px"); - $( document ).ready(function() { + $( document ).ready(function() { - $('[id^=checkbox-delete_multiple]').change(function(){ - if($(this).parent().parent().hasClass('checkselected')){ - $(this).parent().parent().removeClass('checkselected'); - } - else{ - $(this).parent().parent().addClass('checkselected'); - } - }); + $('[id^=checkbox-delete_multiple]').change(function(){ + if($(this).parent().parent().hasClass('checkselected')){ + $(this).parent().parent().removeClass('checkselected'); + } + else{ + $(this).parent().parent().addClass('checkselected'); + } + }); - $('[id^=checkbox-all_delete]').change(function(){ - if ($("#checkbox-all_delete").prop("checked")) { - $('[id^=checkbox-delete_multiple]').parent().parent().addClass('checkselected'); - $(".check_delete").prop("checked", true); - } - else{ - $('[id^=checkbox-delete_multiple]').parent().parent().removeClass('checkselected'); - $(".check_delete").prop("checked", false); - } - }); + $('[id^=checkbox-all_delete]').change(function(){ + if ($("#checkbox-all_delete").prop("checked")) { + $('[id^=checkbox-delete_multiple]').parent().parent().addClass('checkselected'); + $(".check_delete").prop("checked", true); + } + else{ + $('[id^=checkbox-delete_multiple]').parent().parent().removeClass('checkselected'); + $(".check_delete").prop("checked", false); + } + }); - }); - + }); + diff --git a/pandora_console/godmode/reporting/map_builder.php b/pandora_console/godmode/reporting/map_builder.php index a9df342750..6a20eeb30d 100644 --- a/pandora_console/godmode/reporting/map_builder.php +++ b/pandora_console/godmode/reporting/map_builder.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,307 +11,335 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -require_once ($config['homedir'] . '/include/functions_visual_map.php'); +require_once $config['homedir'].'/include/functions_visual_map.php'; // ACL for the general permission -$vconsoles_read = check_acl ($config['id_user'], 0, "VR"); -$vconsoles_write = check_acl ($config['id_user'], 0, "VW"); -$vconsoles_manage = check_acl ($config['id_user'], 0, "VM"); +$vconsoles_read = check_acl($config['id_user'], 0, 'VR'); +$vconsoles_write = check_acl($config['id_user'], 0, 'VW'); +$vconsoles_manage = check_acl($config['id_user'], 0, 'VM'); $is_enterprise = enterprise_include_once('include/functions_policies.php'); $is_metaconsole = is_metaconsole(); if (!$vconsoles_read && !$vconsoles_write && !$vconsoles_manage) { - db_pandora_audit("ACL Violation", - "Trying to access map builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access map builder' + ); + include 'general/noaccess.php'; + exit; } -if(!$is_metaconsole){ +if (!$is_metaconsole) { $url_visual_console = 'index.php?sec=network&sec2=godmode/reporting/map_builder'; $url_visual_console_favorite = 'index.php?sec=network&sec2=godmode/reporting/visual_console_favorite'; $url_visual_console_template = 'index.php?sec=network&sec2=enterprise/godmode/reporting/visual_console_template'; $url_visual_console_template_wizard = 'index.php?sec=network&sec2=enterprise/godmode/reporting/visual_console_template_wizard'; -} -else{ +} else { $url_visual_console = 'index.php?sec=screen&sec2=screens/screens&action=visualmap'; $url_visual_console_favorite = 'index.php?sec=screen&sec2=screens/screens&action=visualmap_favorite'; $url_visual_console_template = 'index.php?sec=screen&sec2=screens/screens&action=visualmap_template'; $url_visual_console_template_wizard = 'index.php?sec=screen&sec2=screens/screens&action=visualmap_wizard'; + $url_visual_console_manager = 'index.php?sec=screen&sec2=enterprise/extensions/visual_console_manager'; } -$pure = (int)get_parameter('pure', 0); +$pure = (int) get_parameter('pure', 0); $hack_metaconsole = ''; -if (defined('METACONSOLE')) - $hack_metaconsole = '../../'; +if (defined('METACONSOLE')) { + $hack_metaconsole = '../../'; +} -$buttons['visual_console'] = array( - 'active' => true, - 'text' => '' . - html_print_image ("images/visual_console.png", true, array ("title" => __('Visual Console List'))) .'' -); +$buttons['visual_console'] = [ + 'active' => true, + 'text' => ''.html_print_image('images/visual_console.png', true, ['title' => __('Visual Console List')]).'', +]; -$buttons['visual_console_favorite'] = array( - 'active' => false, - 'text' => '' . - html_print_image ("images/list.png", true, array ("title" => __('Visual Favourite Console'))) .'' -); +$buttons['visual_console_favorite'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/list.png', true, ['title' => __('Visual Favourite Console')]).'', +]; -if($is_enterprise && $vconsoles_manage){ - $buttons['visual_console_template'] = array( - 'active' => false, - 'text' => '' . - html_print_image ("images/templates.png", true, array ("title" => __('Visual Console Template'))) .'' - ); +if ($is_enterprise && $vconsoles_manage) { + $buttons['visual_console_template'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/templates.png', true, ['title' => __('Visual Console Template')]).'', + ]; - $buttons['visual_console_template_wizard'] = array( - 'active' => false, - 'text' => '' . - html_print_image ("images/wand.png", true, array ("title" => __('Visual Console Template Wizard'))) .'' - ); + $buttons['visual_console_template_wizard'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/wand.png', true, ['title' => __('Visual Console Template Wizard')]).'', + ]; + if ($is_metaconsole) { + $buttons['visual_console_manager'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/builder.png', true, ['title' => __('Visual Console Manager')]).'', + ]; + } } if (!$is_metaconsole) { - ui_print_page_header( - __('Reporting') .' » ' . __('Visual Console'), - "images/op_reporting.png", - false, - "map_builder", - false, - $buttons - ); -} -else{ - ui_meta_print_header( - __('Visual console') . " » " . $visualConsoleName, "", - $buttons); + ui_print_page_header( + __('Reporting').' » '.__('Visual Console'), + 'images/op_reporting.png', + false, + 'map_builder', + false, + $buttons + ); +} else { + ui_meta_print_header( + __('Visual console').' » '.$visualConsoleName, + '', + $buttons + ); } -$id_layout = (int) get_parameter ('id_layout'); -$copy_layout = (bool) get_parameter ('copy_layout'); -$delete_layout = (bool) get_parameter ('delete_layout'); +$id_layout = (int) get_parameter('id_layout'); +$copy_layout = (bool) get_parameter('copy_layout'); +$delete_layout = (bool) get_parameter('delete_layout'); $refr = (int) get_parameter('refr', $config['vc_refr']); $offset = (int) get_parameter('offset', 0); -$pagination = (int) get_parameter ("pagination", $config["block_size"]); -$search = (string) get_parameter("search",""); -$ag_group = (int)get_parameter("ag_group",0); -$recursion = get_parameter("recursion",0); +$pagination = (int) get_parameter('pagination', $config['block_size']); +$search = (string) get_parameter('search', ''); +$ag_group = (int) get_parameter('ag_group', 0); +$recursion = get_parameter('recursion', 0); if ($delete_layout || $copy_layout) { - // Visual console required - if (empty($id_layout)) { - db_pandora_audit("ACL Violation", - "Trying to access map builder"); - require ("general/noaccess.php"); - exit; - } + // Visual console required + if (empty($id_layout)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access map builder' + ); + include 'general/noaccess.php'; + exit; + } - $group_id = db_get_value("id_group", "tlayout", "id", $id_layout); - if ($group_id === false) { - db_pandora_audit("ACL Violation", - "Trying to access map builder"); - require ("general/noaccess.php"); - exit; - } - - // ACL for the visual console - // $vconsole_read = check_acl ($config['id_user'], $group_id, "VR"); - $vconsole_write = check_acl ($config['id_user'], $group_id, "VW"); - $vconsole_manage = check_acl ($config['id_user'], $group_id, "VM"); - - if (!$vconsole_write && !$vconsole_manage) { - db_pandora_audit("ACL Violation", - "Trying to access map builder"); - require ("general/noaccess.php"); - exit; - } - - if ($delete_layout) { - db_process_sql_delete('tlayout_data', - array ('id_layout' => $id_layout)); - $result = db_process_sql_delete('tlayout', - array ('id' => $id_layout)); - if ($result) { - db_pandora_audit( - "Visual console builder", "Delete visual console #$id_layout"); - ui_print_success_message(__('Successfully deleted')); - db_clean_cache(); - } - else { - db_pandora_audit( - "Visual console builder", "Fail try to delete visual console #$id_layout"); - ui_print_error_message( - __('Not deleted. Error deleting data')); - } - $id_layout = 0; - } - - if ($copy_layout) { - // Number of inserts - $ninsert = (int) 0; - - // Return from DB the source layout - $layout_src = db_get_all_rows_filter("tlayout", - array("id" => $id_layout)); - - // Name of dst - $name_dst = get_parameter ("name_dst", - $layout_src[0]['name'] . " copy"); - - // Create the new Console - $idGroup = $layout_src[0]['id_group']; - $background = $layout_src[0]['background']; - $height = $layout_src[0]['height']; - $width = $layout_src[0]['width']; - $visualConsoleName = $name_dst; - - $values = array( - 'name' => $visualConsoleName, - 'id_group' => $idGroup, - 'background' => $background, - 'height' => $height, - 'width' => $width); - $result = db_process_sql_insert('tlayout', $values); - - $idNewVisualConsole = $result; - - if ($result) { - $ninsert = 1; - - // Return from DB the items of the source layout - $data_layout_src = db_get_all_rows_filter( - "tlayout_data", - array("id_layout" => $id_layout)); - - if (!empty($data_layout_src)) { - - //By default the id parent 0 is always 0. - $id_relations = array(0 => 0); - - for ($a = 0; $a < count($data_layout_src); $a++) { - - // Changing the source id by the new visual console id - $data_layout_src[$a]['id_layout'] = $idNewVisualConsole; - - $old_id = $data_layout_src[$a]['id']; - - // Unsetting the source's id - unset($data_layout_src[$a]['id']); - - // Configure the cloned Console - $result = db_process_sql_insert('tlayout_data', - $data_layout_src[$a]); - - $id_relations[$old_id] = 0; - - if ($result !== false) { - $id_relations[$old_id] = $result; - } - - if ($result) - $ninsert++; - }// for each item of console - - $inserts = count($data_layout_src) + 1; - - // If the number of inserts is correct, the copy is completed - if ($ninsert == $inserts) { - - //Update the ids of parents - $items = db_get_all_rows_filter("tlayout_data", - array("id_layout" => $idNewVisualConsole)); - - foreach ($items as $item) { - $new_parent = $id_relations[$item['parent_item']]; - - db_process_sql_update('tlayout_data', - array('parent_item' => $new_parent), - array('id' => $item['id'])); - } - - - ui_print_success_message(__('Successfully copied')); - db_clean_cache(); - } - else { - ui_print_error_message(__('Not copied. Error copying data')); - } - } - else { - // If the array is empty the copy is completed - ui_print_success_message(__('Successfully copied')); - db_clean_cache(); - } - } - else { - ui_print_error_message(__('Not copied. Error copying data')); - } - } + $group_id = db_get_value('id_group', 'tlayout', 'id', $id_layout); + if ($group_id === false) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access map builder' + ); + include 'general/noaccess.php'; + exit; + } + + // ACL for the visual console + // $vconsole_read = check_acl ($config['id_user'], $group_id, "VR"); + $vconsole_write = check_acl($config['id_user'], $group_id, 'VW'); + $vconsole_manage = check_acl($config['id_user'], $group_id, 'VM'); + + if (!$vconsole_write && !$vconsole_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access map builder' + ); + include 'general/noaccess.php'; + exit; + } + + if ($delete_layout) { + db_process_sql_delete( + 'tlayout_data', + ['id_layout' => $id_layout] + ); + $result = db_process_sql_delete( + 'tlayout', + ['id' => $id_layout] + ); + if ($result) { + db_pandora_audit( + 'Visual console builder', + "Delete visual console #$id_layout" + ); + ui_print_success_message(__('Successfully deleted')); + db_clean_cache(); + } else { + db_pandora_audit( + 'Visual console builder', + "Fail try to delete visual console #$id_layout" + ); + ui_print_error_message( + __('Not deleted. Error deleting data') + ); + } + + $id_layout = 0; + } + + if ($copy_layout) { + // Number of inserts + $ninsert = (int) 0; + + // Return from DB the source layout + $layout_src = db_get_all_rows_filter( + 'tlayout', + ['id' => $id_layout] + ); + + // Name of dst + $name_dst = get_parameter( + 'name_dst', + $layout_src[0]['name'].' copy' + ); + + // Create the new Console + $idGroup = $layout_src[0]['id_group']; + $background = $layout_src[0]['background']; + $height = $layout_src[0]['height']; + $width = $layout_src[0]['width']; + $visualConsoleName = $name_dst; + + $values = [ + 'name' => $visualConsoleName, + 'id_group' => $idGroup, + 'background' => $background, + 'height' => $height, + 'width' => $width, + ]; + $result = db_process_sql_insert('tlayout', $values); + + $idNewVisualConsole = $result; + + if ($result) { + $ninsert = 1; + + // Return from DB the items of the source layout + $data_layout_src = db_get_all_rows_filter( + 'tlayout_data', + ['id_layout' => $id_layout] + ); + + if (!empty($data_layout_src)) { + // By default the id parent 0 is always 0. + $id_relations = [0 => 0]; + + for ($a = 0; $a < count($data_layout_src); $a++) { + // Changing the source id by the new visual console id + $data_layout_src[$a]['id_layout'] = $idNewVisualConsole; + + $old_id = $data_layout_src[$a]['id']; + + // Unsetting the source's id + unset($data_layout_src[$a]['id']); + + // Configure the cloned Console + $result = db_process_sql_insert( + 'tlayout_data', + $data_layout_src[$a] + ); + + $id_relations[$old_id] = 0; + + if ($result !== false) { + $id_relations[$old_id] = $result; + } + + if ($result) { + $ninsert++; + } + }//end for + + $inserts = (count($data_layout_src) + 1); + + // If the number of inserts is correct, the copy is completed + if ($ninsert == $inserts) { + // Update the ids of parents + $items = db_get_all_rows_filter( + 'tlayout_data', + ['id_layout' => $idNewVisualConsole] + ); + + foreach ($items as $item) { + $new_parent = $id_relations[$item['parent_item']]; + + db_process_sql_update( + 'tlayout_data', + ['parent_item' => $new_parent], + ['id' => $item['id']] + ); + } + + + ui_print_success_message(__('Successfully copied')); + db_clean_cache(); + } else { + ui_print_error_message(__('Not copied. Error copying data')); + } + } else { + // If the array is empty the copy is completed + ui_print_success_message(__('Successfully copied')); + db_clean_cache(); + } + } else { + ui_print_error_message(__('Not copied. Error copying data')); + } + } } if ($ag_group > 0) { - - $ag_groups = array(); - $ag_groups = (array)$ag_group; - if ($recursion) { - $ag_groups = groups_get_id_recursive($ag_group, true); - } + $ag_groups = []; + $ag_groups = (array) $ag_group; + if ($recursion) { + $ag_groups = groups_get_id_recursive($ag_group, true); + } } echo ""; -if(!is_metaconsole()){ - echo ""; } else { - echo ""; } echo ""; +echo ''; echo ""; -echo "
    "; -echo __('Search') . ' '; -html_print_input_text ("search", $search, '', 50); +echo __('Search').' '; +html_print_input_text('search', $search, '', 50); -echo ""; -echo __('Group') . ' '; +echo __('Group').' '; $own_info = get_user_info($config['id_user']); -if (!$own_info['is_admin'] && !check_acl ($config['id_user'], 0, "VR")) - $return_all_group = false; -else - $return_all_group = true; -html_print_select_groups(false, "AR", $return_all_group, "ag_group", $ag_group, 'this.form.submit();', '', 0, false, false, true, '', false); +if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'VR')) { + $return_all_group = false; +} else { + $return_all_group = true; +} + +html_print_select_groups(false, 'AR', $return_all_group, 'ag_group', $ag_group, 'this.form.submit();', '', 0, false, false, true, '', false); echo ""; -echo __('Group Recursion') . ' '; -html_print_checkbox ("recursion", 1, $recursion, false, false, 'this.form.submit()'); +echo __('Group Recursion').' '; +html_print_checkbox('recursion', 1, $recursion, false, false, 'this.form.submit()'); echo ""; echo ""; -echo ""; -echo "
    "; +echo ''; +echo ''; +echo ''; $table = new stdClass(); $table->width = '100%'; $table->class = 'databox data'; -$table->data = array (); -$table->head = array (); +$table->data = []; +$table->head = []; $table->head[0] = __('Map name'); $table->head[1] = __('Group'); $table->head[2] = __('Items'); $table->head[3] = __('Copy'); $table->head[4] = __('Delete'); -$table->size[3] = "6%"; -$table->size[4] = "6%"; +$table->size[3] = '6%'; +$table->size[4] = '6%'; -$table->align = array (); +$table->align = []; $table->align[0] = 'left'; $table->align[1] = 'left'; $table->align[2] = 'left'; @@ -323,140 +350,145 @@ $table->align[4] = 'left'; // or has "VR" privileges, otherwise show only maps of user group $filters['offset'] = $offset; $filters['limit'] = $pagination; -if(!empty($search)){ - $filters['name'] = io_safe_input($search); +if (!empty($search)) { + $filters['name'] = io_safe_input($search); } -if($ag_group){ - $filters['group'] = array_flip($ag_groups); +if ($ag_group) { + $filters['group'] = array_flip($ag_groups); } -$own_info = get_user_info ($config['id_user']); +$own_info = get_user_info($config['id_user']); if (!defined('METACONSOLE')) { - $url = 'index.php?sec=network&sec2=godmode/reporting/map_builder&recursion='.$recursion.'&ag_group='.$ag_group.'&search='.$search.'&pagination='.$pagination; -} -else { - $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&recursion='.$recursion.'&ag_group='.$ag_group.'&search='.$search.'&pagination='.$pagination; + $url = 'index.php?sec=network&sec2=godmode/reporting/map_builder&recursion='.$recursion.'&ag_group='.$ag_group.'&search='.$search.'&pagination='.$pagination; +} else { + $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&recursion='.$recursion.'&ag_group='.$ag_group.'&search='.$search.'&pagination='.$pagination; } if ($own_info['is_admin'] || $vconsoles_read) { - if($ag_group){ - $maps = visual_map_get_user_layouts ($config['id_user'],false,$filters,false); - unset($filters['offset']); - unset($filters['limit']); - $count_maps = visual_map_get_user_layouts ($config['id_user'],false,$filters,false); - $total_maps = count($count_maps); - }else{ - $maps = visual_map_get_user_layouts ($config['id_user'],false,$filters, false); - unset($filters['offset']); - unset($filters['limit']); - $count_maps = visual_map_get_user_layouts ($config['id_user'],false,$filters,false); - $total_maps = count($count_maps); - } -} -else { - $maps = visual_map_get_user_layouts ($config['id_user'], false, $filters, false); - unset($filters['offset']); - unset($filters['limit']); - $count_maps = visual_map_get_user_layouts ($config['id_user'],false,$filters,false); - $total_maps = count($count_maps); + if ($ag_group) { + $maps = visual_map_get_user_layouts($config['id_user'], false, $filters, false); + unset($filters['offset']); + unset($filters['limit']); + $count_maps = visual_map_get_user_layouts($config['id_user'], false, $filters, false); + $total_maps = count($count_maps); + } else { + $maps = visual_map_get_user_layouts($config['id_user'], false, $filters, false); + unset($filters['offset']); + unset($filters['limit']); + $count_maps = visual_map_get_user_layouts($config['id_user'], false, $filters, false); + $total_maps = count($count_maps); + } +} else { + $maps = visual_map_get_user_layouts($config['id_user'], false, $filters, false); + unset($filters['offset']); + unset($filters['limit']); + $count_maps = visual_map_get_user_layouts($config['id_user'], false, $filters, false); + $total_maps = count($count_maps); } + if (!$maps && !is_metaconsole()) { - $total = count(visual_map_get_user_layouts ($config['id_user'], false, false, false)); - if(!$total){ - require_once ($config['homedir'] . "/general/firts_task/map_builder.php"); - } else { - ui_print_info_message( - array( - 'no_close'=>false, - 'message'=> __('No available data to show'))); - } -} -elseif (!$maps && is_metaconsole()) { - $total = count(visual_map_get_user_layouts ($config['id_user'], false, false, false)); - if(!$total){ - ui_print_info_message( - array( - 'no_close'=>true, - 'message'=> __('There are no visual console defined yet.'))); - }else{ - ui_print_info_message( - array( - 'no_close'=>false, - 'message'=> __('No available data to show'))); - } - -} -else { - ui_pagination ($total_maps, $url, $offset, $pagination); - foreach ($maps as $map) { - // ACL for the visual console permission - $vconsole_write = false; - $vconsole_manage = false; - if(isset($map['vw'])){ - $vconsole_write = true; - } - - if(isset($map['vm'])){ - $vconsole_manage = true; - } + $total = count(visual_map_get_user_layouts($config['id_user'], false, false, false)); + if (!$total) { + include_once $config['homedir'].'/general/firts_task/map_builder.php'; + } else { + ui_print_info_message( + [ + 'no_close' => false, + 'message' => __('No available data to show'), + ] + ); + } +} else if (!$maps && is_metaconsole()) { + $total = count(visual_map_get_user_layouts($config['id_user'], false, false, false)); + if (!$total) { + ui_print_info_message( + [ + 'no_close' => true, + 'message' => __('There are no visual console defined yet.'), + ] + ); + } else { + ui_print_info_message( + [ + 'no_close' => false, + 'message' => __('No available data to show'), + ] + ); + } +} else { + ui_pagination($total_maps, $url, $offset, $pagination); + foreach ($maps as $map) { + // ACL for the visual console permission + $vconsole_write = false; + $vconsole_manage = false; + if (isset($map['vw'])) { + $vconsole_write = true; + } - $data = array (); - - if (!is_metaconsole()) { - $data[0] = ''.$map['name'].''; - } - else { - $data[0] = ''.$map['name'].''; - } - - $data[1] = ui_print_group_icon ($map['id_group'], true); - $data[2] = db_get_sql ("SELECT COUNT(*) FROM tlayout_data WHERE id_layout = ".$map['id']); - - // Fix: IW was the old ACL for report editing, now is RW - if ($vconsoles_write || $vconsoles_manage) { - if (!is_metaconsole()) { - $data[3] = ''.html_print_image ("images/copy.png", true).''; - $data[4] = ''.html_print_image ("images/cross.png", true).''; - } - else { - $data[3] = ''.html_print_image ("images/copy.png", true).''; - $data[4] = ''.html_print_image ("images/cross.png", true).''; - } - } - else{ - $data[3] = ''; - $data[4] = ''; - } + if (isset($map['vm'])) { + $vconsole_manage = true; + } - array_push ($table->data, $data); - } - html_print_table ($table); + $data = []; + + if (!is_metaconsole()) { + $data[0] = ''.$map['name'].''; + } else { + $data[0] = ''.$map['name'].''; + } + + $data[1] = ui_print_group_icon($map['id_group'], true); + $data[2] = db_get_sql('SELECT COUNT(*) FROM tlayout_data WHERE id_layout = '.$map['id']); + + // Fix: IW was the old ACL for report editing, now is RW + if ($vconsoles_write || $vconsoles_manage) { + if (!is_metaconsole()) { + $data[3] = ''.html_print_image('images/copy.png', true).''; + $data[4] = ''.html_print_image('images/cross.png', true).''; + } else { + $data[3] = ''.html_print_image('images/copy.png', true).''; + $data[4] = ''.html_print_image('images/cross.png', true).''; + } + } else { + $data[3] = ''; + $data[4] = ''; + } + + array_push($table->data, $data); + } + + html_print_table($table); } + if ($maps) { - if (!is_metaconsole()) - echo '
    '; - else - echo '
    '; + if (!is_metaconsole()) { + echo '
    '; + } else { + echo '
    '; + } } -if ($maps || defined("METACONSOLE")) { - if ($vconsoles_write || $vconsoles_manage) { - if (!defined('METACONSOLE')) { - echo '
    '; - } - else { - echo ''; - } - html_print_input_hidden ('edit_layout', 1); - html_print_submit_button (__('Create'), '', false, - 'class="sub next"'); - echo '
    '; - } - echo '
    '; + +if ($maps || defined('METACONSOLE')) { + if ($vconsoles_write || $vconsoles_manage) { + if (!defined('METACONSOLE')) { + echo '
    '; + } else { + echo ''; + } + + html_print_input_hidden('edit_layout', 1); + html_print_submit_button( + __('Create'), + '', + false, + 'class="sub next"' + ); + echo '
    '; + } + + echo '
    '; } -?> diff --git a/pandora_console/godmode/reporting/reporting_builder.item_editor.php b/pandora_console/godmode/reporting/reporting_builder.item_editor.php index 75c8564ae3..38584d6b6a 100755 --- a/pandora_console/godmode/reporting/reporting_builder.item_editor.php +++ b/pandora_console/godmode/reporting/reporting_builder.item_editor.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -13,38 +12,40 @@ // GNU General Public License for more details. global $config; -require_once ($config['homedir'] . '/include/functions_custom_graphs.php'); -require_once ($config['homedir'] . '/include/db/oracle.php'); +require_once $config['homedir'].'/include/functions_custom_graphs.php'; +require_once $config['homedir'].'/include/db/oracle.php'; // Login check -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "RW") && ! check_acl ($config['id_user'], 0, "RM")) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'RW') && ! check_acl($config['id_user'], 0, 'RM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } $meta = false; if (($config['metaconsole'] == 1) && (defined('METACONSOLE'))) { - $meta = true; + $meta = true; } -$show_graph_options = Array(); +$show_graph_options = []; $show_graph_options[0] = __('Only table'); $show_graph_options[1] = __('Table & Graph'); $show_graph_options[2] = __('Only graph'); // SLA sorting options -$show_sort_options = array(); +$show_sort_options = []; $show_sort_options[1] = __('Ascending'); $show_sort_options[2] = __('Descending'); enterprise_include('/godmode/reporting/reporting_builder.item_editor.php'); -require_once ($config['homedir'] . '/include/functions_agents.php'); -if (enterprise_include_once ('include/functions_metaconsole.php')) { - $servers = enterprise_hook("metaconsole_get_connection_names"); +require_once $config['homedir'].'/include/functions_agents.php'; +if (enterprise_include_once('include/functions_metaconsole.php')) { + $servers = enterprise_hook('metaconsole_get_connection_names'); } $idAgent = null; @@ -69,7 +70,7 @@ $exception_condition = REPORT_EXCEPTION_CONDITION_EVERYTHING; $exception_condition_value = 10; $modulegroup = 0; $period = SECONDS_1DAY; -$search = ""; +$search = ''; $log_number = 1000; // Added support for projection graphs $period_pg = SECONDS_5DAY; @@ -90,14 +91,14 @@ $time_to = '00:00:00'; $show_graph = 0; $sla_sorted_by = 0; $id_agents = ''; -$inventory_modules = array(); +$inventory_modules = []; $date = null; // Only avg is selected by default for the simple graphs $fullscale = false; $percentil = false; $time_compare_overlapped = false; -//Added for events items +// Added for events items $show_summary_group = false; $filter_event_severity = false; $filter_event_type = false; @@ -115,1616 +116,1821 @@ $lapse_calc = 0; $lapse = 300; $visual_format = 0; -//Others -$filter_search = ""; +// Others +$filter_search = ''; switch ($action) { - case 'new': - $actionParameter = 'save'; - $type = get_parameter('type', 'SLA'); - $name = ''; - $description = null; - $sql = null; - $show_in_same_row = 0; - $show_in_landscape = 0; - $hide_notinit_agents = 0; - $priority_mode = REPORT_PRIORITY_MODE_OK; - $server_name = ''; - $server_id = 0; - $dyn_height = 230; - break; - case 'save': - default: - $actionParameter = 'update'; - - // If we are creating a new report item then clean interface and display creation view - $type = get_parameter('type', 'SLA'); - - switch ($type) { - case 'SLA_monthly': - case 'SLA_weekly': - case 'SLA_hourly': - case 'SLA_services': - case 'SLA': - case 'top_n': - case 'exception': - case 'general': - case 'network_interfaces_report': - case 'availability': - case 'event_report_log': - case 'increment': - case 'availability_graph': - case 'agent_module': - $get_data_editor = true; - break; - - default: - $actionParameter = 'save'; - $action = 'new'; - - $type = 'SLA'; - $name = ''; - $description = null; - $sql = null; - $show_in_same_row = 0; - $show_in_landscape = 0; - $hide_notinit_agents = 0; - $server_name = ''; - $server_id = 0; - $get_data_editor = false; - $dyn_height = 230; - break; - } - - // Get data to fill editor if type is not SLA, top_n, exception, general - if ($get_data_editor) { - - $item = db_get_row_filter('treport_content', array('id_rc' => $idItem)); - $server_name = $item ['server_name']; - - // Metaconsole db connection - if ($meta && $server_name != '') { - $connection = metaconsole_get_connection($server_name); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_name); - } - } - - $style = json_decode(io_safe_output($item['style']), true); - - $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']; + case 'new': + $actionParameter = 'save'; + $type = get_parameter('type', 'SLA'); + $name = ''; + $description = null; + $sql = null; + $show_in_same_row = 0; + $show_in_landscape = 0; + $hide_notinit_agents = 0; + $priority_mode = REPORT_PRIORITY_MODE_OK; + $server_name = ''; + $server_id = 0; + $dyn_height = 230; + break; - switch ($type) { - case 'event_report_log': - $period = $item['period']; - $description = $item['description']; - - $es = json_decode($item['external_source'], true); - $id_agents = $es['id_agents']; - $source = $es['source']; - $search = $es['search']; - $log_number = empty($es['log_number']) ? $log_number : $es['log_number']; - break; - case 'simple_graph': - $fullscale = isset($style['fullscale']) ? (bool) $style['fullscale'] : 0; - $percentil = isset($style['percentil']) ? $config['percentil'] : 0; - // The break hasn't be forgotten. - case 'simple_baseline_graph': - case 'projection_graph': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $period = $item['period']; - // 'top_n_value' field will be reused for projection report - if ($type == 'projection_graph') { - $projection_period = $item['top_n_value']; - $period_pg = $item['period']; - } - - // HACK it is saved in show_graph field. - $time_compare_overlapped = $item['show_graph']; - break; - - case 'prediction_date': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - // 'top_n' field will be reused for prediction_date report - $max_interval = $item['top_n']; - $min_interval = $item['top_n_value']; - $intervals_text = $item['text']; - // Parse intervals text field - $max_interval = substr($intervals_text, 0, strpos($intervals_text, ';')); - $min_interval = substr($intervals_text, strpos($intervals_text, ';') + 1); - // 'top_n_value' field will be reused for prediction_date report - $period_pg = $item['period']; - break; - case 'custom_graph': - case 'automatic_custom_graph': - $description = $item['description']; - $period = $item['period']; - $idCustomGraph = $item['id_gs']; - break; - - case 'SLA': - case 'SLA_weekly': - case 'SLA_monthly': - case 'SLA_hourly': - case 'availability_graph': - $description = $item['description']; - $only_display_wrong = $item['only_display_wrong']; - $monday = $item['monday']; - $tuesday = $item['tuesday']; - $wednesday = $item['wednesday']; - $thursday = $item['thursday']; - $friday = $item['friday']; - $saturday = $item['saturday']; - $sunday = $item['sunday']; - $time_from = $item['time_from']; - $time_to = $item['time_to']; - $show_graph = $item['show_graph']; - $priority_mode = isset($style['priority_mode']) - ? $style['priority_mode'] - : REPORT_PRIORITY_MODE_OK; - // 'top_n' filed will be reused for SLA sort option - $sla_sorted_by = $item['top_n']; - $period = $item['period']; - break; + case 'save': + default: + $actionParameter = 'update'; - case 'module_histogram_graph': - $description = $item['description']; - $period = $item['period']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - break; + // If we are creating a new report item then clean interface and display creation view + $type = get_parameter('type', 'SLA'); - case 'increment': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $period = $item['period']; - break; + switch ($type) { + case 'SLA_monthly': + case 'SLA_weekly': + case 'SLA_hourly': + case 'SLA_services': + case 'SLA': + case 'top_n': + case 'exception': + case 'general': + case 'network_interfaces_report': + case 'availability': + case 'event_report_log': + case 'increment': + case 'availability_graph': + case 'agent_module': + $get_data_editor = true; + break; - case 'SLA_services': - $description = $item['description']; - $period = $item['period']; - $only_display_wrong = $item['only_display_wrong']; - $monday = $item['monday']; - $tuesday = $item['tuesday']; - $wednesday = $item['wednesday']; - $thursday = $item['thursday']; - $friday = $item['friday']; - $saturday = $item['saturday']; - $sunday = $item['sunday']; - $time_from = $item['time_from']; - $time_to = $item['time_to']; - $show_graph = $item['show_graph']; - // 'top_n' filed will be reused for SLA sort option - $sla_sorted_by = $item['top_n']; - break; - case 'monitor_report': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $idAgentModule = $item['id_agent_module']; - $period = $item['period']; - break; - case 'avg_value': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $idAgentModule = $item['id_agent_module']; - $period = $item['period']; - $lapse = $item['lapse']; - $lapse_calc = $item['lapse_calc']; - $visual_format = $item['visual_format']; - break; - case 'max_value': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $idAgentModule = $item['id_agent_module']; - $period = $item['period']; - $lapse = $item['lapse']; - $lapse_calc = $item['lapse_calc']; - $visual_format = $item['visual_format']; - break; - case 'min_value': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $idAgentModule = $item['id_agent_module']; - $period = $item['period']; - $lapse = $item['lapse']; - $lapse_calc = $item['lapse_calc']; - $visual_format = $item['visual_format']; - break; - case 'sumatory': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $idAgentModule = $item['id_agent_module']; - $period = $item['period']; - break; - case 'historical_data': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $idAgentModule = $item['id_agent_module']; - $period = $item['period']; - break; - case 'text': - $description = $item['description']; - $text = $item['text']; - break; - case 'sql': - $header = $item['header_definition']; - case 'sql_graph_pie': - case 'sql_graph_vbar': - case 'sql_graph_hbar': - $description = $item['description']; - $sql_query_report = $item['external_source']; - $idCustom = $item['treport_custom_sql_id']; - $historical_db = $item['historical_db']; - $period = 0; - $top_n_value = $item['top_n_value']; - break; - case 'url': - $description = $item['description']; - $url = $item['external_source']; - break; - case 'database_serialized': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $header = $item['header_definition']; - $field = $item['column_separator']; - $line = $item['line_separator']; - $period = $item['period']; - break; - case 'TTRT': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('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', array('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', array('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', array('id_agente_modulo' => $idAgentModule)); - $period = $item['period']; - break; - case 'alert_report_module': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente_modulo' => $idAgentModule)); - $period = $item['period']; - break; - case 'alert_report_agent': - $description = $item['description']; - $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', array('id_agente' => $item['id_agent'])); - $period = $item['period']; - break; - case 'alert_report_group': - $description = $item['description']; - $period = $item['period']; - $group = $item['id_group']; - $recursion = $item['recursion']; - break; - case 'event_report_agent': - case 'event_report_group': - $recursion = $item['recursion']; - break; - case 'event_report_module': - $description = $item['description']; - $period = $item['period']; - $group = $item['id_group']; - $idAgent = $item['id_agent']; - $idAgentModule = $item['id_agent_module']; + default: + $actionParameter = 'save'; + $action = 'new'; - //Added for events items - $show_summary_group = $style['show_summary_group']; - $filter_event_severity = json_decode($style['filter_event_severity'], true); - $filter_event_status = json_decode($style['filter_event_status'], true); - $filter_event_type = json_decode($style['filter_event_type'], true); - - $event_graph_by_agent = $style['event_graph_by_agent']; - $event_graph_by_user_validator = $style['event_graph_by_user_validator']; - $event_graph_by_criticity = $style['event_graph_by_criticity']; - $event_graph_validated_vs_unvalidated = $style['event_graph_validated_vs_unvalidated']; - - $filter_search = $style['event_filter_search']; - break; - case 'general': - $description = $item['description']; - $group_by_agent = $item['group_by_agent']; - $period = $item['period']; - $order_uptodown = $item['order_uptodown']; - $show_resume = $item['show_resume']; - break; - case 'availability': - $description = $item['description']; - $period = $item['period']; - $order_uptodown = $item['order_uptodown']; - $show_resume = $item['show_resume']; - // HACK it is saved in show_graph field. - // Show interfaces instead the modules - $show_address_agent = $item['show_graph']; - $monday = $item['monday']; - $tuesday = $item['tuesday']; - $wednesday = $item['wednesday']; - $thursday = $item['thursday']; - $friday = $item['friday']; - $saturday = $item['saturday']; - $sunday = $item['sunday']; - $time_from = $item['time_from']; - $time_to = $item['time_to']; - break; - case 'group_report': - $description = $item['description']; - $group = $item['id_group']; - $recursion = $item['recursion']; - break; - case 'network_interfaces_report': - $description = $item['description']; - $group = $item['id_group']; - $period = $item['period']; - $fullscale = isset($style['fullscale']) ? (bool) $style['fullscale'] : 0; - $recursion = $item['recursion']; - break; - case 'top_n': - $description = $item['description']; - $period = $item['period']; - $top_n = $item ['top_n']; - $top_n_value = $item ['top_n_value']; - $show_resume = $item['show_resume']; - $show_graph = $item['show_graph']; - $order_uptodown = $item['order_uptodown']; - break; - case 'exception': - $description = $item['description']; - $period = $item['period']; - $exception_condition = $item['exception_condition']; - - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $exception_condition_value = - $item['exception_condition_value']; - break; - case "oracle": - $exception_condition_value = - oracle_format_float_to_php( - $item['exception_condition_value']); - break; - } - - - $show_resume = $item['show_resume']; - $show_graph = $item['show_graph']; - $order_uptodown = $item['order_uptodown']; - break; - case 'agent_module': - $description = $item['description']; - $es = json_decode($item['external_source'], true); - $id_agents = $es['id_agents']; - $selection_a_m = get_parameter('selection'); - $recursion = $item['recursion']; - - if ((count($es['module']) == 1) && ($es['module'][0] == 0)) { - $module = ""; - } - else { - $module = $es['module']; - } - $group = $item['id_group']; - $modulegroup = $item['id_module_group']; - $idAgentModule = $module; - break; - case 'inventory': - $description = $item['description']; - $es = json_decode($item['external_source'], true); - $date = $es['date']; - $inventory_modules = $es['inventory_modules']; - $id_agents = $es['id_agents']; - $recursion = $item['recursion']; - - $idAgent = $es['id_agents']; - $idAgentModule = $inventory_modules; - break; - - case 'inventory_changes': - $period = $item['period']; - $description = $item['description']; - $es = json_decode($item['external_source'], true); - $inventory_modules = $es['inventory_modules']; - $id_agents = $es['id_agents']; - $recursion = $item['recursion']; - break; - - case 'agent_configuration': - $idAgent = $item['id_agent']; - break; - - case 'group_configuration': - $group = $item['id_group']; - $recursion = $item['recursion']; - break; - - case 'netflow_area': - case 'netflow_pie': - case 'netflow_data': - case 'netflow_statistics': - case 'netflow_summary': - $netflow_filter = $item['text']; // Filter - $period = $item['period']; - $description = $item['description']; - $resolution = $item ['top_n']; // Interval resolution - $max_values = $item ['top_n_value']; // Max values - break; - } - switch ($type) { - case 'event_report_agent': - case 'simple_graph': - case 'agent_configuration': - case 'event_report_module': - case 'alert_report_agent': - case 'alert_report_module': - case 'historical_data': - case 'sumatory': - case 'database_serialized': - case 'monitor_report': - case 'min_value': - case 'max_value': - 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': - $label = (isset($style['label'])) ? $style['label'] : ''; - break; - default: - $label = ''; - break; - } - //Restore db connection - if ($meta && $server_name != '') { - metaconsole_restore_db(); - } - } - - break; + $type = 'SLA'; + $name = ''; + $description = null; + $sql = null; + $show_in_same_row = 0; + $show_in_landscape = 0; + $hide_notinit_agents = 0; + $server_name = ''; + $server_id = 0; + $get_data_editor = false; + $dyn_height = 230; + break; + } + + // Get data to fill editor if type is not SLA, top_n, exception, general + if ($get_data_editor) { + $item = db_get_row_filter('treport_content', ['id_rc' => $idItem]); + $server_name = $item['server_name']; + + // Metaconsole db connection + if ($meta && $server_name != '') { + $connection = metaconsole_get_connection($server_name); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + } + } + + $style = json_decode(io_safe_output($item['style']), true); + + $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']; + + switch ($type) { + case 'event_report_log': + $period = $item['period']; + $description = $item['description']; + + $es = json_decode($item['external_source'], true); + $id_agents = $es['id_agents']; + $source = $es['source']; + $search = $es['search']; + $log_number = empty($es['log_number']) ? $log_number : $es['log_number']; + break; + + case 'simple_graph': + $fullscale = isset($style['fullscale']) ? (bool) $style['fullscale'] : 0; + $percentil = isset($style['percentil']) ? $config['percentil'] : 0; + // The break hasn't be forgotten. + case 'simple_baseline_graph': + case 'projection_graph': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $period = $item['period']; + // 'top_n_value' field will be reused for projection report + if ($type == 'projection_graph') { + $projection_period = $item['top_n_value']; + $period_pg = $item['period']; + } + + // HACK it is saved in show_graph field. + $time_compare_overlapped = $item['show_graph']; + break; + + case 'prediction_date': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + // 'top_n' field will be reused for prediction_date report + $max_interval = $item['top_n']; + $min_interval = $item['top_n_value']; + $intervals_text = $item['text']; + // Parse intervals text field + $max_interval = substr($intervals_text, 0, strpos($intervals_text, ';')); + $min_interval = substr($intervals_text, (strpos($intervals_text, ';') + 1)); + // 'top_n_value' field will be reused for prediction_date report + $period_pg = $item['period']; + break; + + case 'custom_graph': + case 'automatic_custom_graph': + $description = $item['description']; + $period = $item['period']; + $idCustomGraph = $item['id_gs']; + break; + + case 'SLA': + case 'SLA_weekly': + case 'SLA_monthly': + case 'SLA_hourly': + case 'availability_graph': + $description = $item['description']; + $only_display_wrong = $item['only_display_wrong']; + $monday = $item['monday']; + $tuesday = $item['tuesday']; + $wednesday = $item['wednesday']; + $thursday = $item['thursday']; + $friday = $item['friday']; + $saturday = $item['saturday']; + $sunday = $item['sunday']; + $time_from = $item['time_from']; + $time_to = $item['time_to']; + $show_graph = $item['show_graph']; + $priority_mode = isset($style['priority_mode']) ? $style['priority_mode'] : REPORT_PRIORITY_MODE_OK; + // 'top_n' filed will be reused for SLA sort option + $sla_sorted_by = $item['top_n']; + $period = $item['period']; + break; + + case 'module_histogram_graph': + $description = $item['description']; + $period = $item['period']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + break; + + case 'increment': + $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 'SLA_services': + $description = $item['description']; + $period = $item['period']; + $only_display_wrong = $item['only_display_wrong']; + $monday = $item['monday']; + $tuesday = $item['tuesday']; + $wednesday = $item['wednesday']; + $thursday = $item['thursday']; + $friday = $item['friday']; + $saturday = $item['saturday']; + $sunday = $item['sunday']; + $time_from = $item['time_from']; + $time_to = $item['time_to']; + $show_graph = $item['show_graph']; + // 'top_n' filed will be reused for SLA sort option + $sla_sorted_by = $item['top_n']; + break; + + case 'monitor_report': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $idAgentModule = $item['id_agent_module']; + $period = $item['period']; + break; + + case 'avg_value': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $idAgentModule = $item['id_agent_module']; + $period = $item['period']; + $lapse = $item['lapse']; + $lapse_calc = $item['lapse_calc']; + $visual_format = $item['visual_format']; + break; + + case 'max_value': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $idAgentModule = $item['id_agent_module']; + $period = $item['period']; + $lapse = $item['lapse']; + $lapse_calc = $item['lapse_calc']; + $visual_format = $item['visual_format']; + break; + + case 'min_value': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $idAgentModule = $item['id_agent_module']; + $period = $item['period']; + $lapse = $item['lapse']; + $lapse_calc = $item['lapse_calc']; + $visual_format = $item['visual_format']; + break; + + case 'sumatory': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $idAgentModule = $item['id_agent_module']; + $period = $item['period']; + break; + + case 'historical_data': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $idAgentModule = $item['id_agent_module']; + $period = $item['period']; + break; + + case 'text': + $description = $item['description']; + $text = $item['text']; + break; + + case 'sql': + $header = $item['header_definition']; + case 'sql_graph_pie': + case 'sql_graph_vbar': + case 'sql_graph_hbar': + $description = $item['description']; + $sql_query_report = $item['external_source']; + $idCustom = $item['treport_custom_sql_id']; + $historical_db = $item['historical_db']; + $period = 0; + $top_n_value = $item['top_n_value']; + break; + + case 'url': + $description = $item['description']; + $url = $item['external_source']; + break; + + case 'database_serialized': + $description = $item['description']; + $idAgentModule = $item['id_agent_module']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $header = $item['header_definition']; + $field = $item['column_separator']; + $line = $item['line_separator']; + $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']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente_modulo' => $idAgentModule]); + $period = $item['period']; + break; + + case 'alert_report_agent': + $description = $item['description']; + $idAgent = db_get_value_filter('id_agente', 'tagente_modulo', ['id_agente' => $item['id_agent']]); + $period = $item['period']; + break; + + case 'alert_report_group': + $description = $item['description']; + $period = $item['period']; + $group = $item['id_group']; + $recursion = $item['recursion']; + break; + + case 'event_report_agent': + case 'event_report_group': + $recursion = $item['recursion']; + break; + + case 'event_report_module': + $description = $item['description']; + $period = $item['period']; + $group = $item['id_group']; + $idAgent = $item['id_agent']; + $idAgentModule = $item['id_agent_module']; + + // Added for events items + $show_summary_group = $style['show_summary_group']; + $filter_event_severity = json_decode($style['filter_event_severity'], true); + $filter_event_status = json_decode($style['filter_event_status'], true); + $filter_event_type = json_decode($style['filter_event_type'], true); + + $event_graph_by_agent = $style['event_graph_by_agent']; + $event_graph_by_user_validator = $style['event_graph_by_user_validator']; + $event_graph_by_criticity = $style['event_graph_by_criticity']; + $event_graph_validated_vs_unvalidated = $style['event_graph_validated_vs_unvalidated']; + + $filter_search = $style['event_filter_search']; + break; + + case 'general': + $description = $item['description']; + $group_by_agent = $item['group_by_agent']; + $period = $item['period']; + $order_uptodown = $item['order_uptodown']; + $show_resume = $item['show_resume']; + break; + + case 'availability': + $description = $item['description']; + $period = $item['period']; + $order_uptodown = $item['order_uptodown']; + $show_resume = $item['show_resume']; + // HACK it is saved in show_graph field. + // Show interfaces instead the modules + $show_address_agent = $item['show_graph']; + $monday = $item['monday']; + $tuesday = $item['tuesday']; + $wednesday = $item['wednesday']; + $thursday = $item['thursday']; + $friday = $item['friday']; + $saturday = $item['saturday']; + $sunday = $item['sunday']; + $time_from = $item['time_from']; + $time_to = $item['time_to']; + break; + + case 'group_report': + $description = $item['description']; + $group = $item['id_group']; + $recursion = $item['recursion']; + break; + + case 'network_interfaces_report': + $description = $item['description']; + $group = $item['id_group']; + $period = $item['period']; + $fullscale = isset($style['fullscale']) ? (bool) $style['fullscale'] : 0; + $recursion = $item['recursion']; + break; + + case 'top_n': + $description = $item['description']; + $period = $item['period']; + $top_n = $item['top_n']; + $top_n_value = $item['top_n_value']; + $show_resume = $item['show_resume']; + $show_graph = $item['show_graph']; + $order_uptodown = $item['order_uptodown']; + break; + + case 'exception': + $description = $item['description']; + $period = $item['period']; + $exception_condition = $item['exception_condition']; + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $exception_condition_value = $item['exception_condition_value']; + break; + + case 'oracle': + $exception_condition_value = oracle_format_float_to_php( + $item['exception_condition_value'] + ); + break; + } + + + $show_resume = $item['show_resume']; + $show_graph = $item['show_graph']; + $order_uptodown = $item['order_uptodown']; + break; + + case 'agent_module': + $description = $item['description']; + $es = json_decode($item['external_source'], true); + $id_agents = $es['id_agents']; + $selection_a_m = get_parameter('selection'); + $recursion = $item['recursion']; + + if ((count($es['module']) == 1) && ($es['module'][0] == 0)) { + $module = ''; + } else { + $module = $es['module']; + } + + $group = $item['id_group']; + $modulegroup = $item['id_module_group']; + $idAgentModule = $module; + break; + + case 'inventory': + $description = $item['description']; + $es = json_decode($item['external_source'], true); + $date = $es['date']; + $inventory_modules = $es['inventory_modules']; + $id_agents = $es['id_agents']; + $recursion = $item['recursion']; + + $idAgent = $es['id_agents']; + $idAgentModule = $inventory_modules; + break; + + case 'inventory_changes': + $period = $item['period']; + $description = $item['description']; + $es = json_decode($item['external_source'], true); + $inventory_modules = $es['inventory_modules']; + $id_agents = $es['id_agents']; + $recursion = $item['recursion']; + break; + + case 'agent_configuration': + $idAgent = $item['id_agent']; + break; + + case 'group_configuration': + $group = $item['id_group']; + $recursion = $item['recursion']; + break; + + case 'netflow_area': + case 'netflow_pie': + case 'netflow_data': + case 'netflow_statistics': + case 'netflow_summary': + $netflow_filter = $item['text']; + // Filter + $period = $item['period']; + $description = $item['description']; + $resolution = $item['top_n']; + // Interval resolution + $max_values = $item['top_n_value']; + // Max values + break; + } + + switch ($type) { + case 'event_report_agent': + case 'simple_graph': + case 'agent_configuration': + case 'event_report_module': + case 'alert_report_agent': + case 'alert_report_module': + case 'historical_data': + case 'sumatory': + case 'database_serialized': + case 'monitor_report': + case 'min_value': + case 'max_value': + 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': + $label = (isset($style['label'])) ? $style['label'] : ''; + break; + + default: + $label = ''; + break; + } + + // Restore db connection + if ($meta && $server_name != '') { + metaconsole_restore_db(); + } + } + break; } -$urlForm = $config['homeurl'] . - 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=item_editor&action=' . $actionParameter . '&id_report=' . $idReport; +$urlForm = $config['homeurl'].'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=item_editor&action='.$actionParameter.'&id_report='.$idReport; -echo '
    '; +echo ''; html_print_input_hidden('id_item', $idItem); $class = 'databox filters'; ?> - - +
    + - "; - } - ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - + } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + $all_agent_log = db_get_all_rows_sql($sql_log_report); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + if (isset($all_agent_log) && is_array($all_agent_log)) { + foreach ($all_agent_log as $key => $value) { + $agents2[$value['id_agente']] = $value['alias']; + } + } - - - - + if ((empty($agents2)) || $agents2 == -1) { + $agents = []; + } - - - - + $agents_select = []; + if (is_array($id_agents) || is_object($id_agents)) { + foreach ($id_agents as $id) { + foreach ($agents2 as $key => $a) { + if ($key == (int) $id) { + $agents_select[$key] = $key; + } + } + } + } - - - - + html_print_select($agents2, 'id_agents3[]', $agents_select, $script = '', '', 0, false, true, true, '', false, 'min-width: 180px'); + echo "'; + ?> + + + + + + - - - + // $agents = agents_get_group_agents($group); + if ((empty($agents2)) || $agents2 == -1) { + $agents = []; + } - - - - - - - - - - - - - - - - - - - - + $agents_select = []; + if (is_array($id_agents) || is_object($id_agents)) { + foreach ($id_agents as $id) { + foreach ($agents2 as $key => $a) { + if ($key == (int) $id) { + $agents_select[$key] = $key; + } + } + } + } - - - - + html_print_select($agents2, 'id_agents2[]', $agents_select, $script = '', '', 0, false, true, true, '', false, 'min-width: 180px'); + ?> + + - - - - + + + + + + + + - - - - - - - + if ((empty($all_modules)) || $all_modules == -1) { + $all_modules = []; + } - - - - - - - - - + $modules_select = []; + $all_modules_structured = []; + if (is_array($idAgentModule) || is_object($idAgentModule)) { + foreach ($idAgentModule as $id) { + foreach ($all_modules as $key => $a) { + if ($a['id_agente_modulo'] == (int) $id) { + $modules_select[$a['id_agente_modulo']] = $a['id_agente_modulo']; + } + } + } + } - - - - + foreach ($all_modules as $a) { + $all_modules_structured[$a['id_agente_modulo']] = $a['nombre']; + } - - - - - - - - - - - - - - + html_print_select($all_modules_structured, 'module[]', $modules_select, $script = '', __('None'), 0, false, true, true, '', false, 'min-width: 180px'); + ?> + + + + + + - + + + + + - + if (empty($inventory_modules)) { + $array_inventory_modules = [0 => 0]; + } - - - - - - - - - - - - - - - - - - - - - - - - - - + $array_inventory_modules = implode(',', $inventory_modules); + + html_print_input_hidden( + 'inventory_modules_selected', + $array_inventory_modules + ); + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    - " . __('Item Editor') . " + '.__('Item Editor').'
    - - - '; - } - ?> - ' . html_print_image ("images/tip.png", true, array('title' => $text)) . ''; - ?> -
    - - - -
    - $groups) { - $groups_id[] = $groups['id_grupo']; - } - - $sql_netflow = "SELECT * FROM tnetflow_filter WHERE id_group IN (".implode(',',$groups_id).")"; - html_print_select_from_sql($sql_netflow, 'netflow_filter', $netflow_filter); - ?> -
    - -
    - -
    - - - "; - ?> -
    - - - -
    - - - -
    - - - -
    - - - -
    - - - -
    - -
    - -
    - - - - - - - - - - - - - - - - - - - - - -
    - - - - - - - - - - - - - -
    - -
    - -
    -
    - -
    - '; + } + ?> +
    + + + '; + } + ?> + '.html_print_image('images/tip.png', true, ['title' => $text]).''; + ?> +
    + + + +
    + $groups) { + $groups_id[] = $groups['id_grupo']; + } + + $sql_netflow = 'SELECT * FROM tnetflow_filter WHERE id_group IN ('.implode(',', $groups_id).')'; + html_print_select_from_sql($sql_netflow, 'netflow_filter', $netflow_filter); + ?> +
    + +
    + + + +
    + + + "; + ?> +
    + + + +
    + + + +
    + + + +
    + + + +
    + + + +
    + +
    + +
    + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + +
    + +
    + +
    +
    + +
    + $a) { - if ($index == 0) { - $sql_log .= ' AND (id_agente = ' . $key; - } - else { - $sql_log .= ' OR id_agente = ' . $key; - } - $index++; - } - $sql_log .= ")"; - } - html_print_select_from_sql ($sql_log, 'source', $source, 'onselect=source_change_agents();', __('All'), '', false, false, false); - ?> -
    - -
    - $idAgent)); - // Append server name - if (!empty($agent_name)) - $agent_name .= ' (' . $server_name . ')'; - //Restore db connection - metaconsole_restore_db(); - } - else { - $agent_name = agents_get_alias ($idAgent); - } - - html_print_input_hidden('id_agent', $idAgent); - html_print_input_hidden('server_name', $server_name); - html_print_input_hidden('server_id', $server_name); - html_print_input_hidden('id_server', ''); - - - ////////////////// - $params = array(); - - $params['show_helptip'] = false; - $params['input_name'] = 'agent'; - $params['value'] = $agent_name; - - $params['javascript_is_function_select'] = true; - $params['selectbox_id'] = 'id_agent_module'; - $params['add_none_module'] = true; - $params['use_hidden_input_idagent'] = true; - $params['hidden_input_idagent_id'] = 'hidden-id_agent'; - if ($meta) { - //$params['input_id'] = 'agent_autocomplete'; - $params['use_input_id_server'] = true; - $params['input_id_server_id'] = 'hidden-server_id'; - $params['metaconsole_enabled'] = true; - $params['input_id'] = 'agent_autocomplete_events'; - $params['javascript_page'] = 'include/ajax/agent'; //'enterprise/meta/include/ajax/events.ajax'; - $params['input_name'] = 'agent_text'; - } - ui_print_agent_autocomplete_input($params); - ?> -
    - - - - - -
    - $a) { + if ($index == 0) { + $sql_log .= ' AND (id_agente = '.$key; + } else { + $sql_log .= ' OR id_agente = '.$key; + } + + $index++; + } + + $sql_log .= ')'; + } + + html_print_select_from_sql($sql_log, 'source', $source, 'onselect=source_change_agents();', __('All'), '', false, false, false); + ?> +
    + +
    + $idAgent]); + } + + // Append server name + if (!empty($agent_name)) { + $agent_name .= ' ('.$server_name.')'; + } + + // Restore db connection + metaconsole_restore_db(); + } else { + $agent_name = agents_get_alias($idAgent); + } + + html_print_input_hidden('id_agent', $idAgent); + html_print_input_hidden('server_name', $server_name); + html_print_input_hidden('server_id', $server_name); + html_print_input_hidden('id_server', ''); + + + $params = []; + + $params['show_helptip'] = false; + $params['input_name'] = 'agent'; + $params['value'] = $agent_name; + + $params['javascript_is_function_select'] = true; + $params['selectbox_id'] = 'id_agent_module'; + $params['add_none_module'] = true; + $params['use_hidden_input_idagent'] = true; + $params['hidden_input_idagent_id'] = 'hidden-id_agent'; + if ($meta) { + // $params['input_id'] = 'agent_autocomplete'; + $params['use_input_id_server'] = true; + $params['input_id_server_id'] = 'hidden-server_id'; + $params['metaconsole_enabled'] = true; + $params['input_id'] = 'agent_autocomplete_events'; + $params['javascript_page'] = 'include/ajax/agent'; + // 'enterprise/meta/include/ajax/events.ajax'; + $params['input_name'] = 'agent_text'; + } + + ui_print_agent_autocomplete_input($params); + ?> +
    + + + + + +
    + $value) { - $agents2[$value['id_agente']] = $value['alias']; - } - - if ((empty($agents2)) || $agents2 == -1) $agents = array(); - - $agents_select = array(); - if (is_array($id_agents) || is_object($id_agents)){ - foreach ($id_agents as $id) { - foreach ($agents2 as $key => $a) { - if ($key == (int)$id) { - $agents_select[$key] = $key; - } - } - } - } - html_print_select($agents2, 'id_agents3[]', $agents_select, $script = '', "", 0, false, true, true, '', false, "min-width: 180px"); - echo ""; - ?> -
    - $value) { - $agents2[$value['id_agente']] = $value['alias']; - } - - // $agents = agents_get_group_agents($group); - if ((empty($agents2)) || $agents2 == -1) $agents = array(); - - $agents_select = array(); - if (is_array($id_agents) || is_object($id_agents)){ - foreach ($id_agents as $id) { - foreach ($agents2 as $key => $a) { - if ($key == (int)$id) { - $agents_select[$key] = $key; - } - } - } - } - html_print_select($agents2, 'id_agents2[]', $agents_select, $script = '', "", 0, false, true, true, '', false, "min-width: 180px"); - ?> -
    - __('Show common modules'), - 1=> __('Show all modules')); - html_print_select($selection, 'selection_agent_module', $selection_a_m, $script = '', "", 0, false, false, true, '', false, "min-width: 180px"); - ?> -
    - $a) { - if ($a['id_agente_modulo'] == (int)$id) { - $modules_select[$a['id_agente_modulo']] = $a['id_agente_modulo']; - } - } - } - } - foreach ($all_modules as $a) { - $all_modules_structured[$a['id_agente_modulo']] = $a['nombre']; - } - html_print_select($all_modules_structured, 'module[]', $modules_select, $script = '', __('None'), 0, false, true, true, '', false, "min-width: 180px"); - ?> -
    - -
    - 0); - } - $array_inventory_modules = - implode(',', $inventory_modules); - - html_print_input_hidden( - 'inventory_modules_selected', - $array_inventory_modules); - ?> -
    - -
    - '; - echo '    ' . __('Target server') . '  '; - html_print_select($result_servers, 'meta_servers', '', '', __('None'), 0); - echo ''; - } - else { - // If there are not metaconsole servers don't allow to create new custom graphs - $style_button_create_custom_graph = 'style="display: none;"'; - } - } - } - echo " "; - html_print_button(__("Create"), 'create_graph', false, - 'create_custom_graph();', 'class="sub add" ' . $style_button_create_custom_graph); - - html_print_button(__("Edit"), 'edit_graph', false, - 'edit_custom_graph();', 'class="sub config" ' . $style_button_edit_custom_graph); - ?> -
    - -
    - -
    - -
    - -
    - -
    - -
    + $value) { + $agents2[$value['id_agente']] = $value['alias']; + } -
    - -
    - __('Everything'), - REPORT_EXCEPTION_CONDITION_GE => __('Greater or equal (>=)'), - REPORT_EXCEPTION_CONDITION_LE => __('Less or equal (<=)'), - REPORT_EXCEPTION_CONDITION_L => __('Less (<)'), - REPORT_EXCEPTION_CONDITION_G => __('Greater (>)'), - REPORT_EXCEPTION_CONDITION_E => __('Equal (=)'), - REPORT_EXCEPTION_CONDITION_NE => __('Not equal (!=)'), - REPORT_EXCEPTION_CONDITION_OK => __('OK'), - REPORT_EXCEPTION_CONDITION_NOT_OK => __('Not OK') - ); - html_print_select($list_exception_condition, 'exception_condition', $exception_condition); - - - /* - echo ; - html_print_radio_button ('radiobutton_exception_condition', 0, '', $exception_condition); - echo __('>='); - html_print_radio_button ('radiobutton_exception_condition', 1, '', $exception_condition); - echo __('<'); - html_print_radio_button ('radiobutton_exception_condition', 2, '', $exception_condition); - echo __('OK'); - html_print_radio_button ('radiobutton_exception_condition', 3, '', $exception_condition); - echo __('Not OK'); - html_print_radio_button ('radiobutton_exception_condition', 4, '', $exception_condition); - */ - ?> -
    - - - -
    - -
    - -
    - -
    + __('Show common modules'), + 1 => __('Show all modules'), + ]; + html_print_select($selection, 'selection_agent_module', $selection_a_m, $script = '', '', 0, false, false, true, '', false, 'min-width: 180px'); + ?> +
    + - - -
    - -
    - - - - - - - - - - - - -
    - - - -
    - - - -
    - -
    + - - '; - html_print_radio_button ( - 'priority_mode', - REPORT_PRIORITY_MODE_OK, - '', - $priority_mode == REPORT_PRIORITY_MODE_OK, - '' - ); + $agents_select = []; + foreach ($agents as $a) { + $agents_select[$a['id_agente']] = $a['alias']; + } - echo (''); + html_print_select($agents_select, 'id_agents[]', $id_agents, $script = '', __('All'), -1, false, true, true, '', false, 'min-width: 180px'); + ?> +
    + '; - html_print_radio_button ( - 'priority_mode', - REPORT_PRIORITY_MODE_UNKNOWN, - '', - $priority_mode == REPORT_PRIORITY_MODE_UNKNOWN, - '' - ); - ?> -
    - - - -
    - - - -
    - '; - html_print_radio_button ('visual_format', 1, '', $visual_format_table,'',!$lapse_calc); - echo (''); - echo __('Graph only').''; - html_print_radio_button ('visual_format', 2, '', $visual_format_graph,'',!$lapse_calc); - echo (''); - echo __('Graph and table').''; - html_print_radio_button ('visual_format', 3, '', $visual_format_both,'',!$lapse_calc); - - ?> -
    + +
    + '; + echo '    '.__('Target server').'  '; + html_print_select($result_servers, 'meta_servers', '', '', __('None'), 0); + echo ''; + } else { + // If there are not metaconsole servers don't allow to create new custom graphs + $style_button_create_custom_graph = 'style="display: none;"'; + } + } + } + + echo ' '; + html_print_button( + __('Create'), + 'create_graph', + false, + 'create_custom_graph();', + 'class="sub add" '.$style_button_create_custom_graph + ); + + html_print_button( + __('Edit'), + 'edit_graph', + false, + 'edit_custom_graph();', + 'class="sub config" '.$style_button_edit_custom_graph + ); + ?> +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + __('Everything'), + REPORT_EXCEPTION_CONDITION_GE => __('Greater or equal (>=)'), + REPORT_EXCEPTION_CONDITION_LE => __('Less or equal (<=)'), + REPORT_EXCEPTION_CONDITION_L => __('Less (<)'), + REPORT_EXCEPTION_CONDITION_G => __('Greater (>)'), + REPORT_EXCEPTION_CONDITION_E => __('Equal (=)'), + REPORT_EXCEPTION_CONDITION_NE => __('Not equal (!=)'), + REPORT_EXCEPTION_CONDITION_OK => __('OK'), + REPORT_EXCEPTION_CONDITION_NOT_OK => __('Not OK'), + ]; + html_print_select($list_exception_condition, 'exception_condition', $exception_condition); + + + /* + echo ; + html_print_radio_button ('radiobutton_exception_condition', 0, '', $exception_condition); + echo __('>='); + html_print_radio_button ('radiobutton_exception_condition', 1, '', $exception_condition); + echo __('<'); + html_print_radio_button ('radiobutton_exception_condition', 2, '', $exception_condition); + echo __('OK'); + html_print_radio_button ('radiobutton_exception_condition', 3, '', $exception_condition); + echo __('Not OK'); + html_print_radio_button ('radiobutton_exception_condition', 4, '', $exception_condition); + */ + ?> +
    + + + +
    + +
    + +
    + +
    + +
    + +
    + + + + + + + + + + + + +
    + + + +
    + + + +
    + +
    + '; + html_print_radio_button( + 'priority_mode', + REPORT_PRIORITY_MODE_OK, + '', + $priority_mode == REPORT_PRIORITY_MODE_OK, + '' + ); + + echo ''; + + echo __('Priority unknown mode').''; + html_print_radio_button( + 'priority_mode', + REPORT_PRIORITY_MODE_UNKNOWN, + '', + $priority_mode == REPORT_PRIORITY_MODE_UNKNOWN, + '' + ); + ?> +
    + + + +
    + + + +
    + '; + html_print_radio_button('visual_format', 1, '', $visual_format_table, '', !$lapse_calc); + echo ''; + echo __('Graph only').''; + html_print_radio_button('visual_format', 2, '', $visual_format_graph, '', !$lapse_calc); + echo ''; + echo __('Graph and table').''; + html_print_radio_button('visual_format', 3, '', $visual_format_both, '', !$lapse_calc); + ?> +
    '; if ($action == 'new') { - html_print_submit_button(__('Create item'), 'create_item', false, 'class="sub wand"'); -} -else { - html_print_submit_button(__('Update item'), 'edit_item', false, 'class="sub upd"'); + html_print_submit_button(__('Create item'), 'create_item', false, 'class="sub wand"'); +} else { + html_print_submit_button(__('Update item'), 'edit_item', false, 'class="sub upd"'); } + echo '
    '; echo ''; @@ -1745,1793 +1951,1814 @@ ui_require_javascript_file('pandora'); if ($enterpriseEnable) { - reporting_enterprise_text_box(); + reporting_enterprise_text_box(); } -//Restore db connection + +// Restore db connection if ($meta) { - metaconsole_restore_db(); + metaconsole_restore_db(); } -function print_SLA_list($width, $action, $idItem = null) { - global $config; - global $meta; - - $report_item_type = db_get_value( - db_escape_key_identifier('type'), - 'treport_content', 'id_rc', $idItem); - ?> - - - - - - - - - - - - - - - - - '; - $itemsSLA = db_get_all_rows_filter( - 'treport_content_sla_combined', - array('id_report_content' => $idItem)); +function print_SLA_list($width, $action, $idItem=null) +{ + global $config; + global $meta; + $report_item_type = db_get_value( + db_escape_key_identifier('type'), + 'treport_content', + 'id_rc', + $idItem + ); + ?> +
    + + + + + + + + + + + + + + + + $item['id_agent_module'])); - $nameAgent = agents_get_alias($idAgent); - - $nameModule = db_get_value_filter('nombre', - 'tagente_modulo', - array('id_agente_modulo' => $item['id_agent_module'])); - - $server_name_element = ''; - if ($meta && $server_name != '') - $server_name_element .= ' (' . $server_name . ')'; - - echo ''; - echo ''; - echo ''; - - if (enterprise_installed() && $report_item_type == 'SLA_services') { - enterprise_include_once("include/functions_services.php"); - $nameService = enterprise_hook('services_get_name', array($item['id_agent_module'])); - echo ''; - echo ''; - echo ''; - echo ''; + $itemsSLA = db_get_all_rows_filter( + 'treport_content_sla_combined', + ['id_report_content' => $idItem] + ); + + if ($itemsSLA === false) { + $itemsSLA = []; + } + + foreach ($itemsSLA as $item) { + $server_name = $item['server_name']; + // Metaconsole db connection + if ($meta && $server_name != '') { + $connection = metaconsole_get_connection($server_name); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + continue; + } + } + + $idAgent = db_get_value_filter( + 'id_agente', + 'tagente_modulo', + ['id_agente_modulo' => $item['id_agent_module']] + ); + $nameAgent = agents_get_alias($idAgent); + + $nameModule = db_get_value_filter( + 'nombre', + 'tagente_modulo', + ['id_agente_modulo' => $item['id_agent_module']] + ); + + $server_name_element = ''; + if ($meta && $server_name != '') { + $server_name_element .= ' ('.$server_name.')'; + } + + echo ''; + echo ''; + echo ''; + + if (enterprise_installed() && $report_item_type == 'SLA_services') { + enterprise_include_once('include/functions_services.php'); + $nameService = enterprise_hook('services_get_name', [$item['id_agent_module']]); + echo ''; + echo ''; + echo ''; + echo ''; - echo ''; - - if ($meta) { - //Restore db connection - metaconsole_restore_db(); - } - } - echo ''; - ?> - - - - - "; - } - ?> - - - - - - - - - - - - ".html_print_select($services, 'id_service', false, '', '', '', true, false, false).""; - } - ?> - - - - - - - - -
    ' . printSmallFont($nameAgent) . $server_name_element . '' . printSmallFont($nameModule) . '' . printSmallFont($nameService) . ''; - } - - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $item_sla_min = $item['sla_min']; - $item_sla_max = $item['sla_max']; - $item_sla_limit = $item['sla_limit']; - break; - case "oracle": - $item_sla_min = - oracle_format_float_to_php($item['sla_min']); - $item_sla_max = - oracle_format_float_to_php($item['sla_max']); - $item_sla_limit = - oracle_format_float_to_php($item['sla_limit']); - break; - } - - echo '' . - $item_sla_min . '' . - $item_sla_max . '' . - $item_sla_limit . ' - ' . html_print_image("images/cross.png", true) . ' + case 'save': + case 'update': + case 'edit': + echo '
    '.printSmallFont($nameAgent).$server_name_element.''.printSmallFont($nameModule).''.printSmallFont($nameService).''; + } + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $item_sla_min = $item['sla_min']; + $item_sla_max = $item['sla_max']; + $item_sla_limit = $item['sla_limit']; + break; + + case 'oracle': + $item_sla_min = oracle_format_float_to_php($item['sla_min']); + $item_sla_max = oracle_format_float_to_php($item['sla_max']); + $item_sla_limit = oracle_format_float_to_php($item['sla_limit']); + break; + } + + echo ''.$item_sla_min.''.$item_sla_max.''.$item_sla_limit.' + '.html_print_image('images/cross.png', true).'
    - - - - - -
    - - '; + + if ($meta) { + // Restore db connection + metaconsole_restore_db(); + } + } + + echo ''; + ?> + + + + + '; + } + ?> + + + + + + + + + + + + + + + + + + '.html_print_select($services, 'id_service', false, '', '', '', true, false, false).''; + } + ?> + + + + + + + + + + + + + __('rate'), - 'max' => __('max'), - 'min' => __('min'), - 'sum' => __('sum')); - - include_once($config['homedir'] . '/include/functions_html.php'); - ?> - - - - - - - - - - - - - - - - - - - - '; - $itemsGeneral = db_get_all_rows_filter( - 'treport_content_item', - array('id_report_content' => $idItem)); +function print_General_list($width, $action, $idItem=null, $type='general') +{ + global $config; + global $meta; + if (!isset($meta)) { + $meta = false; + } - if ($itemsGeneral === false) { - $itemsGeneral = array(); - } - - foreach ($itemsGeneral as $item) { - $server_name = $item ['server_name']; - // Metaconsole db connection - if ($meta && $server_name != '') { - $connection = metaconsole_get_connection($server_name); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_name); - continue; - } - } - - - $idAgent = db_get_value_filter( - 'id_agente', 'tagente_modulo', - array('id_agente_modulo' => $item['id_agent_module'])); - - $nameAgent = agents_get_alias($idAgent); - $nameModule = db_get_value_filter('nombre', 'tagente_modulo', array('id_agente_modulo' => $item['id_agent_module'])); - - $server_name_element = ''; - if ($meta && $server_name != '') - $server_name_element .= ' (' . $server_name . ')'; - - - if ($type == "availability") { - echo ' - - + $operation = [ + 'avg' => __('rate'), + 'max' => __('max'), + 'min' => __('min'), + 'sum' => __('sum'), + ]; + + include_once $config['homedir'].'/include/functions_html.php'; + ?> +
    - -
    ' . printSmallFont($nameAgent) . $server_name_element . '' . printSmallFont($nameModule) . '
    + + + + + + + + + + + + + + + + + + + '; + $itemsGeneral = db_get_all_rows_filter( + 'treport_content_item', + ['id_report_content' => $idItem] + ); + + if ($itemsGeneral === false) { + $itemsGeneral = []; + } + + foreach ($itemsGeneral as $item) { + $server_name = $item['server_name']; + // Metaconsole db connection + if ($meta && $server_name != '') { + $connection = metaconsole_get_connection($server_name); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + continue; + } + } + + $idAgent = db_get_value_filter( + 'id_agente', + 'tagente_modulo', + ['id_agente_modulo' => $item['id_agent_module']] + ); + + $nameAgent = agents_get_alias($idAgent); + $nameModule = db_get_value_filter('nombre', 'tagente_modulo', ['id_agente_modulo' => $item['id_agent_module']]); + + $server_name_element = ''; + if ($meta && $server_name != '') { + $server_name_element .= ' ('.$server_name.')'; + } + + if ($type == 'availability') { + echo ' + + '; - } - else { - echo ' - - - + } else { + echo ' + + + '; - } - - - if ($meta) { - //Restore db connection - metaconsole_restore_db(); - } - } - echo ''; - ?> - - - - - - - - - - - - - - - - - - - - - - - - -
    + +
    + +
    '.printSmallFont($nameAgent).$server_name_element.''.printSmallFont($nameModule).' - ' . html_print_image("images/cross.png", true) . ' + '.html_print_image('images/cross.png', true).'
    ' . printSmallFont($nameAgent) . $server_name_element . '' . printSmallFont($nameModule) . '' . - printSmallFont($operation[$item['operation']]) . - '
    '.printSmallFont($nameAgent).$server_name_element.''.printSmallFont($nameModule).''.printSmallFont($operation[$item['operation']]).' - ' . html_print_image("images/cross.png", true) . ' + '.html_print_image('images/cross.png', true).'
    - - - - - - - -
    - - '; + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pandora_console/godmode/reporting/reporting_builder.list_items.php b/pandora_console/godmode/reporting/reporting_builder.list_items.php index 81bc5b7286..07d4a083fa 100755 --- a/pandora_console/godmode/reporting/reporting_builder.list_items.php +++ b/pandora_console/godmode/reporting/reporting_builder.list_items.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -14,47 +13,51 @@ global $config; // Login check -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "RW")) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'RW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } -include_once($config['homedir'] . "/include/functions_agents.php"); -enterprise_include_once ('include/functions_metaconsole.php'); +require_once $config['homedir'].'/include/functions_agents.php'; +enterprise_include_once('include/functions_metaconsole.php'); switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $type_escaped = "type"; - break; - case "oracle": - $type_escaped = db_escape_key_identifier( - "type"); - break; + case 'mysql': + case 'postgresql': + $type_escaped = 'type'; + break; + + case 'oracle': + $type_escaped = db_escape_key_identifier( + 'type' + ); + break; } -$report_w = check_acl ($config['id_user'], 0, "RW"); -$report_m = check_acl ($config['id_user'], 0, "RM"); +$report_w = check_acl($config['id_user'], 0, 'RW'); +$report_m = check_acl($config['id_user'], 0, 'RM'); -if ($config ['metaconsole'] == 1 and defined('METACONSOLE')) { - $agents = array(); - $agents = metaconsole_get_report_agents($idReport); - $modules = array(); - $modules = metaconsole_get_report_modules($idReport); - $types = array (); - $types = metaconsole_get_report_types($idReport); -} -else { - //FORM FILTER - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $rows = db_get_all_rows_sql(' +if ($config['metaconsole'] == 1 and defined('METACONSOLE')) { + $agents = []; + $agents = metaconsole_get_report_agents($idReport); + $modules = []; + $modules = metaconsole_get_report_modules($idReport); + $types = []; + $types = metaconsole_get_report_types($idReport); +} else { + // FORM FILTER + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $rows = db_get_all_rows_sql( + ' SELECT t5.nombre, t5.id_agente FROM ( @@ -65,10 +68,13 @@ else { ) t4 INNER JOIN tagente t5 ON (t4.id_agent = t5.id_agente OR t4.id_agente = t5.id_agente) - WHERE t4.id_report = ' . $idReport); - break; - case "oracle": - $rows = db_get_all_rows_sql(' + WHERE t4.id_report = '.$idReport + ); + break; + + case 'oracle': + $rows = db_get_all_rows_sql( + ' SELECT t5.nombre, t5.id_agente FROM ( @@ -79,71 +85,81 @@ else { ) t4 INNER JOIN tagente t5 ON (t4.id_agent = t5.id_agente OR t4.id_agente = t5.id_agente) - WHERE t4.id_report = ' . $idReport); - - break; - } - - if ($rows === false) { - $rows = array(); - } - - $agents = array(); - foreach ($rows as $row) { - $alias = db_get_value ("alias","tagente","id_agente",$row['id_agente']); - $agents[$row['id_agente']] = $alias; - } - - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $rows = db_get_all_rows_sql(' + WHERE t4.id_report = '.$idReport + ); + + break; + } + + if ($rows === false) { + $rows = []; + } + + $agents = []; + foreach ($rows as $row) { + $alias = db_get_value('alias', 'tagente', 'id_agente', $row['id_agente']); + $agents[$row['id_agente']] = $alias; + } + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $rows = db_get_all_rows_sql( + ' SELECT t1.id_agent_module, t2.nombre FROM treport_content t1 INNER JOIN tagente_modulo t2 ON t1.id_agent_module = t2.id_agente_modulo - WHERE t1.id_report = ' . $idReport); - break; - case "oracle": - $rows = db_get_all_rows_sql(' + WHERE t1.id_report = '.$idReport + ); + break; + + case 'oracle': + $rows = db_get_all_rows_sql( + ' SELECT t1.id_agent_module, t2.nombre FROM treport_content t1 INNER JOIN tagente_modulo t2 ON t1.id_agent_module = t2.id_agente_modulo - WHERE t1.id_report = ' . $idReport); - break; - } - if ($rows === false) { - $rows = array(); - } - - $modules = array(); - foreach ($rows as $row) { - $modules[$row['id_agent_module']] = $row['nombre']; - } - - // Filter report items created from metaconsole in normal console list and the opposite - if (defined('METACONSOLE') and $config['metaconsole'] == 1) { - $where_types = ' AND ((server_name IS NOT NULL AND length(server_name) != 0) OR ' . $type_escaped . ' IN (\'general\',\'SLA\',\'exception\',\'top_n\'))'; - } - else - $where_types = ' AND ((server_name IS NULL OR length(server_name) = 0) OR ' . $type_escaped . ' IN (\'general\',\'SLA\',\'exception\',\'top_n\'))'; - - $rows = db_get_all_rows_sql(' - SELECT DISTINCT(' . $type_escaped . ') + WHERE t1.id_report = '.$idReport + ); + break; + } + + if ($rows === false) { + $rows = []; + } + + $modules = []; + foreach ($rows as $row) { + $modules[$row['id_agent_module']] = $row['nombre']; + } + + // Filter report items created from metaconsole in normal console list and the opposite + if (defined('METACONSOLE') and $config['metaconsole'] == 1) { + $where_types = ' AND ((server_name IS NOT NULL AND length(server_name) != 0) OR '.$type_escaped.' IN (\'general\',\'SLA\',\'exception\',\'top_n\'))'; + } else { + $where_types = ' AND ((server_name IS NULL OR length(server_name) = 0) OR '.$type_escaped.' IN (\'general\',\'SLA\',\'exception\',\'top_n\'))'; + } + + $rows = db_get_all_rows_sql( + ' + SELECT DISTINCT('.$type_escaped.') FROM treport_content - WHERE id_report = ' . $idReport . $where_types); - if ($rows === false) { - $rows = array(); - } - - $types = array(); - foreach ($rows as $row) { - if ($row['type'] == 'automatic_custom_graph') - $types['custom_graph'] = get_report_name($row['type']); - else - $types[$row['type']] = get_report_name($row['type']); - } + WHERE id_report = '.$idReport.$where_types + ); + if ($rows === false) { + $rows = []; + } + + $types = []; + foreach ($rows as $row) { + if ($row['type'] == 'automatic_custom_graph') { + $types['custom_graph'] = get_report_name($row['type']); + } else { + $types[$row['type']] = get_report_name($row['type']); + } + } } $agentFilter = get_parameter('agent_filter', 0); @@ -153,512 +169,597 @@ $typeFilter = get_parameter('type_filter', 0); $filterEnable = true; $urlFilter = ''; if (($agentFilter == 0) && ($moduleFilter == 0) && ($typeFilter == 0)) { - $filterEnable = false; + $filterEnable = false; } -$urlFilter = '&agent_filter=' . $agentFilter . '&module_filter=' . $moduleFilter . '&type_filter=' . $typeFilter; +$urlFilter = '&agent_filter='.$agentFilter.'&module_filter='.$moduleFilter.'&type_filter='.$typeFilter; -if (!defined("METACONSOLE")) { - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox filters'; - $table->data[0][0] = __('Agents'); - $table->data[0][0] .= html_print_select($agents, 'agent_filter', $agentFilter, '', __('All'), 0, true); - $table->data[0][1] = __('Modules'); - $table->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 .= '
    '; - $form .= html_print_submit_button(__('Filter'), 'filter', false, 'class="sub upd"',true); - $form .= html_print_input_hidden('action', 'filter',true); - $form .= '
    '; - $form .= '
    '; - - ui_toggle($form, __("Filters") ); -} -else { - $table = new stdClass(); - $table->width = '96%'; - $table->class = "databox_filters"; - $table->cellpadding = 0; - $table->cellspacing = 0; - $table->data[0][0] = __('Agents'); - $table->data[0][1] = html_print_select($agents, 'agent_filter', - $agentFilter, '', __('All'), 0, true); - $table->data[0][2] = __('Modules'); - $table->data[0][3] = html_print_select($modules, 'module_filter', - $moduleFilter, '', __('All'), 0, true); - $table->data[0][4] = __('Type'); - $table->data[0][5] = html_print_select($types, 'type_filter', - $typeFilter, '', __('All'), 0, true); - $table->style[6] = "text-align:right;"; - $table->data[0][6] = html_print_submit_button(__('Filter'), - 'filter', false, 'class="sub upd"',true) . - html_print_input_hidden('action', 'filter',true); - - $filters = '
    '; - - $filters .= html_print_table ($table,true); - $filters .= '
    '; - ui_toggle($filters, __("Show Options")); +if (!defined('METACONSOLE')) { + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox filters'; + $table->data[0][0] = __('Agents'); + $table->data[0][0] .= html_print_select($agents, 'agent_filter', $agentFilter, '', __('All'), 0, true); + $table->data[0][1] = __('Modules'); + $table->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 .= '
    '; + $form .= html_print_submit_button(__('Filter'), 'filter', false, 'class="sub upd"', true); + $form .= html_print_input_hidden('action', 'filter', true); + $form .= '
    '; + $form .= '
    '; + + ui_toggle($form, __('Filters')); +} else { + $table = new stdClass(); + $table->width = '96%'; + $table->class = 'databox_filters'; + $table->cellpadding = 0; + $table->cellspacing = 0; + $table->data[0][0] = __('Agents'); + $table->data[0][1] = html_print_select( + $agents, + 'agent_filter', + $agentFilter, + '', + __('All'), + 0, + true + ); + $table->data[0][2] = __('Modules'); + $table->data[0][3] = html_print_select( + $modules, + 'module_filter', + $moduleFilter, + '', + __('All'), + 0, + true + ); + $table->data[0][4] = __('Type'); + $table->data[0][5] = html_print_select( + $types, + 'type_filter', + $typeFilter, + '', + __('All'), + 0, + true + ); + $table->style[6] = 'text-align:right;'; + $table->data[0][6] = html_print_submit_button( + __('Filter'), + 'filter', + false, + 'class="sub upd"', + true + ).html_print_input_hidden('action', 'filter', true); + + $filters = '
    '; + + $filters .= html_print_table($table, true); + $filters .= '
    '; + ui_toggle($filters, __('Show Options')); } $where = '1=1'; if ($typeFilter != '0') { - if ($typeFilter == 'custom_graph') - $where .= ' AND (type = "' . $typeFilter . '" + if ($typeFilter == 'custom_graph') { + $where .= ' AND (type = "'.$typeFilter.'" OR type = "automatic_custom_graph") '; - else - $where .= ' AND type = "' . $typeFilter . '"'; + } else { + $where .= ' AND type = "'.$typeFilter.'"'; + } } + if ($agentFilter != 0) { - $where .= ' AND id_agent = ' . $agentFilter; + $where .= ' AND id_agent = '.$agentFilter; } + if ($moduleFilter != 0) { - $where .= ' AND id_agent_module = ' . $moduleFilter; + $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\'))'; + $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\'))'; +} else { + $where .= ' AND ((server_name IS NULL OR length(server_name) = 0) '.'OR '.$type_escaped.' IN (\'general\', \'SLA\', \'exception\', \'availability\', \'top_n\'))'; } -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('SELECT * +switch ($config['dbtype']) { + case 'mysql': + $items = db_get_all_rows_sql( + 'SELECT * FROM treport_content - WHERE ' . $where . ' AND id_report = ' . $idReport . ' + WHERE '.$where.' AND id_report = '.$idReport.' ORDER BY `order` - LIMIT ' . $offset . ', ' . $config["block_size"]); - break; - case "postgresql": - $items = db_get_all_rows_sql('SELECT * + LIMIT '.$offset.', '.$config['block_size'] + ); + break; + + case 'postgresql': + $items = db_get_all_rows_sql( + 'SELECT * FROM treport_content - WHERE ' . $where . ' AND id_report = ' . $idReport . ' + WHERE '.$where.' AND id_report = '.$idReport.' ORDER BY "order" - LIMIT ' . $config["block_size"] . ' OFFSET ' . $offset); - break; - case "oracle": - $set = array(); - $set['limit'] = $config["block_size"]; - $set['offset'] = $offset; - $items = oracle_recode_query ('SELECT * + LIMIT '.$config['block_size'].' OFFSET '.$offset + ); + break; + + case 'oracle': + $set = []; + $set['limit'] = $config['block_size']; + $set['offset'] = $offset; + $items = oracle_recode_query( + 'SELECT * FROM treport_content - WHERE ' . $where . ' AND id_report = ' . $idReport . ' - ORDER BY "order"', $set, 'AND', false); - // Delete rnum row generated by oracle_recode_query() function - if ($items !== false) { - for ($i=0; $i < count($items); $i++) { - unset($items[$i]['rnum']); - } - } - break; + WHERE '.$where.' AND id_report = '.$idReport.' + ORDER BY "order"', + $set, + 'AND', + false + ); + // Delete rnum row generated by oracle_recode_query() function + if ($items !== false) { + for ($i = 0; $i < count($items); $i++) { + unset($items[$i]['rnum']); + } + } + break; } -$countItems = db_get_sql('SELECT COUNT(id_rc) + +$countItems = db_get_sql( + 'SELECT COUNT(id_rc) FROM treport_content - WHERE ' . $where . ' AND id_report = ' . $idReport); + WHERE '.$where.' AND id_report = '.$idReport +); $table = null; $table->style[0] = 'text-align: right;'; if ($items) { - $table->width = '98%'; - if (defined("METACONSOLE")) { - $table->width = '100%'; - $table->class = "databox data"; - } - $table->size = array(); - $table->size[0] = '5px'; - $table->size[1] = '15%'; - $table->size[4] = '8%'; - $table->size[6] = '90px'; - $table->size[7] = '30px'; - - $table->head[0] = '' . __('P.') . ''; - $table->head[1] = __('Type'); - if (!$filterEnable) { - $table->head[1] .= ' ' . html_print_image("images/sort_up.png", true, array("title" => __('Ascendent'))) . '' . - '' . html_print_image("images/sort_down.png", true, array("title" => __('Descent'))) . ''; - } - $table->head[2] = __('Agent'); - if (!$filterEnable) { - $table->head[2] .= ' ' . html_print_image("images/sort_up.png", true, array("title" => __('Ascendent'))) . '' . - '' . html_print_image("images/sort_down.png", true, array("title" => __('Descent'))) . ''; - } - $table->head[3] = __('Module'); + $table->width = '98%'; + if (defined('METACONSOLE')) { + $table->width = '100%'; + $table->class = 'databox data'; + } - if (!$filterEnable) { - $table->head[3] .= ' ' . html_print_image("images/sort_up.png", true, array("title" => __('Ascendent'))) . '' . - '' . html_print_image("images/sort_down.png", true, array("title" => __('Descent'))) . ''; - } - $table->head[4] = __('Time lapse'); - $table->head[5] = __('Name') . " / " . __('Description'); - if (check_acl ($config['id_user'], 0, "RM")) { - $table->head[6] = '' . __('Op.') . ''; - if ($report_w || $report_m) { - $table->head[6] .= html_print_checkbox('all_delete', 0, false, true, false, - 'check_all_checkboxes();'); - } - } - $table->head[7] = __('Sort'); - - $table->align[6] = 'left'; - $table->align[7] = 'center'; -} -else { - ui_print_info_message ( array ( 'no_close' => true, 'message' => __('No items.') ) ); + $table->size = []; + $table->size[0] = '5px'; + $table->size[1] = '15%'; + $table->size[4] = '8%'; + $table->size[6] = '90px'; + $table->size[7] = '30px'; + + $table->head[0] = ''.__('P.').''; + $table->head[1] = __('Type'); + if (!$filterEnable) { + $table->head[1] .= ' '.html_print_image('images/sort_up.png', true, ['title' => __('Ascendent')]).''.''.html_print_image('images/sort_down.png', true, ['title' => __('Descent')]).''; + } + + $table->head[2] = __('Agent'); + if (!$filterEnable) { + $table->head[2] .= ' '.html_print_image('images/sort_up.png', true, ['title' => __('Ascendent')]).''.''.html_print_image('images/sort_down.png', true, ['title' => __('Descent')]).''; + } + + $table->head[3] = __('Module'); + + if (!$filterEnable) { + $table->head[3] .= ' '.html_print_image('images/sort_up.png', true, ['title' => __('Ascendent')]).''.''.html_print_image('images/sort_down.png', true, ['title' => __('Descent')]).''; + } + + $table->head[4] = __('Time lapse'); + $table->head[5] = __('Name').' / '.__('Description'); + if (check_acl($config['id_user'], 0, 'RM')) { + $table->head[6] = ''.__('Op.').''; + if ($report_w || $report_m) { + $table->head[6] .= html_print_checkbox( + 'all_delete', + 0, + false, + true, + false, + 'check_all_checkboxes();' + ); + } + } + + $table->head[7] = __('Sort'); + + $table->align[6] = 'left'; + $table->align[7] = 'center'; +} else { + ui_print_info_message([ 'no_close' => true, 'message' => __('No items.') ]); } $lastPage = true; -if (((($offset == 0) && ($config["block_size"] > $countItems)) || - ($countItems >= ($config["block_size"] + $offset))) && - ($countItems > $config["block_size"])) { - $lastPage = false; +if (((($offset == 0) && ($config['block_size'] > $countItems)) + || ($countItems >= ($config['block_size'] + $offset))) + && ($countItems > $config['block_size']) +) { + $lastPage = false; } $count = 0; $rowPair = true; if ($items === false) { - $items = array(); + $items = []; } $count = 0; foreach ($items as $item) { - if ($rowPair) - $table->rowclass[$count] = 'rowPair'; - else - $table->rowclass[$count] = 'rowOdd'; - $rowPair = !$rowPair; - - $row = array(); - - $row[0] = $count + $offset + 1; //The 1 is for do not start in 0. - - if ($filterEnable) { - $row[0] = ''; - } - - $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')) { - - $connection = metaconsole_get_connection($server_name); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_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 - 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 - if ($is_inventory_item) { - $external_source = json_decode($item['external_source'], true); - $agents = $external_source['id_agents']; - $modules = $external_source['inventory_modules']; - - $agent_name_db = array(); - foreach ($agents as $a) { - - $alias = db_get_value ("alias","tagente","id_agente",$a); - $agent_name_db[] = $alias; - } - $agent_name_db = implode('
    ',$agent_name_db); - - $module_name_db = implode('
    ',$modules); - } - else { - $agent_id = agents_get_agent_id_by_module_id($item['id_agent_module']); - $agent_name = agents_get_name($agent_id); - $agent_alias = agents_get_alias($agent_id); - $agent_name_db = '' .$alias . ''; - $module_name_db = db_get_value_filter('nombre', 'tagente_modulo', array('id_agente_modulo' => $item['id_agent_module'])); - $module_name_db = ui_print_truncate_text(io_safe_output($module_name_db), 'module_small'); - } - - $row[2] = $agent_name_db; - $row[3] = $module_name_db; - } - } - else { - $alias = agents_get_alias($item['id_agent']); - $row[2] = '' .$alias . ''; - - if ($item['id_agent_module'] == '') { - $row [3] = ''; - } - else { - $module_name_db = db_get_value_filter('nombre', 'tagente_modulo', array('id_agente_modulo' => $item['id_agent_module'])); - - $row[3] = - ui_print_truncate_text(io_safe_output($module_name_db), 'module_small'); - } - } - - if ($item['period'] > 0) { - $row[4] = human_time_description_raw($item['period']); - } - else { - $row[4] = '-'; - } - - 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] = ''; - - if (check_acl ($config['id_user'], $item['id_group'], "RM")) { - $row[6] .= '' . html_print_image("images/wrench_orange.png", true, array("title" => __('Edit'))) . ''; - $row[6] .= ' '; - $row[6] .= '' . html_print_image("images/cross.png", true, array("title" => __('Delete'))) .''; - $row[6] .= ' '; - $row[6] .= html_print_checkbox_extended ('delete_multiple[]', $item['id_rc'], false, false, '', 'class="check_delete"', true); - } - $row[7] = ''; - //You can sort the items if the filter is not enable. - if (!$filterEnable) { - $row[7] .= html_print_checkbox_extended('sorted_items[]', $item['id_rc'], false, false, '', 'class="selected_check"', true); - } - $table->data[] = $row; - $count++; - //Restore db connection - if (($config ['metaconsole'] == 1) && ($server_name != '') && defined('METACONSOLE')) { - metaconsole_restore_db(); - } + if ($rowPair) { + $table->rowclass[$count] = 'rowPair'; + } else { + $table->rowclass[$count] = 'rowOdd'; + } + + $rowPair = !$rowPair; + + $row = []; + + $row[0] = ($count + $offset + 1); + // The 1 is for do not start in 0. + if ($filterEnable) { + $row[0] = ''; + } + + $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')) { + $connection = metaconsole_get_connection($server_name); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_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 + 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 + if ($is_inventory_item) { + $external_source = json_decode($item['external_source'], true); + $agents = $external_source['id_agents']; + $modules = $external_source['inventory_modules']; + + $agent_name_db = []; + foreach ($agents as $a) { + $alias = db_get_value('alias', 'tagente', 'id_agente', $a); + $agent_name_db[] = $alias; + } + + $agent_name_db = implode('
    ', $agent_name_db); + + $module_name_db = implode('
    ', $modules); + } else { + $agent_id = agents_get_agent_id_by_module_id($item['id_agent_module']); + $agent_name = agents_get_name($agent_id); + $agent_alias = agents_get_alias($agent_id); + $agent_name_db = ''.$alias.''; + $module_name_db = db_get_value_filter('nombre', 'tagente_modulo', ['id_agente_modulo' => $item['id_agent_module']]); + $module_name_db = ui_print_truncate_text(io_safe_output($module_name_db), 'module_small'); + } + + $row[2] = $agent_name_db; + $row[3] = $module_name_db; + } + } else { + $alias = agents_get_alias($item['id_agent']); + $row[2] = ''.$alias.''; + + if ($item['id_agent_module'] == '') { + $row[3] = ''; + } else { + $module_name_db = db_get_value_filter('nombre', 'tagente_modulo', ['id_agente_modulo' => $item['id_agent_module']]); + + $row[3] = ui_print_truncate_text(io_safe_output($module_name_db), 'module_small'); + } + } + + if ($item['period'] > 0) { + $row[4] = human_time_description_raw($item['period']); + } else { + $row[4] = '-'; + } + + 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] = ''; + + if (check_acl($config['id_user'], $item['id_group'], 'RM')) { + $row[6] .= ''.html_print_image('images/wrench_orange.png', true, ['title' => __('Edit')]).''; + $row[6] .= ' '; + $row[6] .= ''.html_print_image('images/cross.png', true, ['title' => __('Delete')]).''; + $row[6] .= ' '; + $row[6] .= html_print_checkbox_extended('delete_multiple[]', $item['id_rc'], false, false, '', 'class="check_delete"', true); + } + + $row[7] = ''; + // You can sort the items if the filter is not enable. + if (!$filterEnable) { + $row[7] .= html_print_checkbox_extended('sorted_items[]', $item['id_rc'], false, false, '', 'class="selected_check"', true); + } + + $table->data[] = $row; + $count++; + // Restore db connection + if (($config['metaconsole'] == 1) && ($server_name != '') && defined('METACONSOLE')) { + metaconsole_restore_db(); + } } -if (defined("METACONSOLE")) { - if ($items != false) { - ui_pagination ($countItems, 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=list_items&action=edit&id_report=' . $idReport . $urlFilter); - html_print_table($table); - ui_pagination ($countItems, 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=list_items&action=edit&id_report=' . $idReport . $urlFilter); - echo "
    "; - echo "
    "; - - if (check_acl ($config['id_user'], 0, "RM")) { - html_print_input_hidden('ids_items_to_delete', ''); - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - } - echo "
    "; - echo "
    "; - } -} -else { - if ($items != false) { - ui_pagination ($countItems, - 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=list_items&action=edit&id_report=' . $idReport . $urlFilter); - html_print_table($table); - ui_pagination ($countItems, - 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=list_items&action=edit&id_report=' . $idReport . $urlFilter); - - echo "
    "; + + if (check_acl($config['id_user'], 0, 'RM')) { + html_print_input_hidden('ids_items_to_delete', ''); + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + } + + echo '
    '; + echo ''; + } +} else { + if ($items != false) { + ui_pagination( + $countItems, + 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=list_items&action=edit&id_report='.$idReport.$urlFilter + ); + html_print_table($table); + ui_pagination( + $countItems, + 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=list_items&action=edit&id_report='.$idReport.$urlFilter + ); + + echo "
    "; - echo "
    "; - - html_print_input_hidden('ids_items_to_delete', ''); - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); - echo "
    "; - echo "
    "; - } + echo "
    "; + + html_print_input_hidden('ids_items_to_delete', ''); + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete"'); + echo '
    '; + echo ''; + } } + $table = new stdClass(); $table->width = '100%'; $table->colspan[0][0] = 3; -$table->size = array(); +$table->size = []; $table->size[0] = '25%'; $table->size[1] = '25%'; $table->size[2] = '25%'; $table->size[3] = '25%'; -if (defined("METACONSOLE")) { - $table->class = "databox data"; - $table->head[0] = __("Sort items"); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; -} -else { - $table->data[0][0] = "". __("Sort items") . ""; +if (defined('METACONSOLE')) { + $table->class = 'databox data'; + $table->head[0] = __('Sort items'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; +} else { + $table->data[0][0] = ''.__('Sort items').''; } + $table->data[1][0] = __('Sort selected items from position: '); $table->data[1][1] = html_print_select_style( - array('before' => __('Move before to'), 'after' => __('Move after to')), 'move_to', - '', '', '', '', 0, true); -$table->data[1][2] = html_print_input_text_extended('position_to_sort', 1, - 'text-position_to_sort', '', 3, 10, false, "only_numbers('position_to_sort');", '', true); + [ + 'before' => __('Move before to'), + 'after' => __('Move after to'), + ], + 'move_to', + '', + '', + '', + '', + 0, + true +); +$table->data[1][2] = html_print_input_text_extended( + 'position_to_sort', + 1, + 'text-position_to_sort', + '', + 3, + 10, + false, + "only_numbers('position_to_sort');", + '', + true +); $table->data[1][2] .= html_print_input_hidden('ids_items_to_sort', '', true); $table->data[1][3] = html_print_submit_button(__('Sort'), 'sort_submit', false, 'class="sub upd"', true); -echo "
    "; html_print_table($table); -echo "
    "; +echo ''; $table = new stdClass(); $table->width = '100%'; $table->colspan[0][0] = 3; -$table->size = array(); +$table->size = []; $table->size[0] = '25%'; $table->size[1] = '25%'; $table->size[2] = '25%'; $table->size[3] = '25%'; -if (defined("METACONSOLE")) { - $table->class = "databox data"; - $table->head[0] = __("Delete items"); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; -} -else { - $table->data[0][0] = "". __("Delete items") . ""; +if (defined('METACONSOLE')) { + $table->class = 'databox data'; + $table->head[0] = __('Delete items'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; +} else { + $table->data[0][0] = ''.__('Delete items').''; } + $table->data[1][0] = __('Delete selected items from position: '); $table->data[1][1] = html_print_select_style( - array('above' => __('Delete above to'), 'below' => __('Delete below to')), 'delete_m', - '', '', '', '', 0, true); -$table->data[1][2] = html_print_input_text_extended('position_to_delete', 1, - 'text-position_to_delete', '', 3, 10, false, "only_numbers('position_to_delete');", '', true); + [ + 'above' => __('Delete above to'), + 'below' => __('Delete below to'), + ], + 'delete_m', + '', + '', + '', + '', + 0, + true +); +$table->data[1][2] = html_print_input_text_extended( + 'position_to_delete', + 1, + 'text-position_to_delete', + '', + 3, + 10, + false, + "only_numbers('position_to_delete');", + '', + true +); $table->data[1][2] .= html_print_input_hidden('ids_items_to_delete', '', true); $table->data[1][3] = html_print_submit_button(__('Delete'), 'delete_submit', false, 'class="sub upd"', true); -echo "
    "; html_print_table($table); -echo "
    "; +echo ''; ?> diff --git a/pandora_console/godmode/reporting/reporting_builder.main.php b/pandora_console/godmode/reporting/reporting_builder.main.php index 1c9fbaee8f..652de3552c 100755 --- a/pandora_console/godmode/reporting/reporting_builder.main.php +++ b/pandora_console/godmode/reporting/reporting_builder.main.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -14,136 +13,201 @@ global $config; // Login check -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "RW")) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'RW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } -require_once ($config['homedir'].'/include/functions_users.php'); +require_once $config['homedir'].'/include/functions_users.php'; -$groups = users_get_groups (); +$groups = users_get_groups(); switch ($action) { - case 'new': - $actionButtonHtml = html_print_submit_button(__('Save'), - 'add', false, 'class="sub wand"', true); - $hiddenFieldAction = 'save'; - break; - case 'update': - case 'edit': - $actionButtonHtml = html_print_submit_button(__('Update'), - 'edit', false, 'class="sub upd"', true); - $hiddenFieldAction = 'update'; - break; + case 'new': + $actionButtonHtml = html_print_submit_button( + __('Save'), + 'add', + false, + 'class="sub wand"', + true + ); + $hiddenFieldAction = 'save'; + break; + + case 'update': + case 'edit': + $actionButtonHtml = html_print_submit_button( + __('Update'), + 'edit', + false, + 'class="sub upd"', + true + ); + $hiddenFieldAction = 'update'; + break; } $table = new stdClass(); $table->width = '100%'; $table->id = 'add_alert_table'; $table->class = 'databox filters'; -$table->head = array (); +$table->head = []; if (is_metaconsole()) { - $table->head[0] = __('Main data'); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; + $table->head[0] = __('Main data'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; } -$table->data = array (); -$table->size = array (); -$table->size = array (); +$table->data = []; +$table->size = []; +$table->size = []; $table->size[0] = '15%'; $table->size[1] = '90%'; -if(!is_metaconsole()) - $table->style[0] = 'font-weight: bold; vertical-align: top;'; -else - $table->style[0] = 'font-weight: bold;'; +if (!is_metaconsole()) { + $table->style[0] = 'font-weight: bold; vertical-align: top;'; +} else { + $table->style[0] = 'font-weight: bold;'; +} + $table->data['name'][0] = __('Name'); -$table->data['name'][1] = html_print_input_text('name', $reportName, - __('Name'), 80, 100, true, false, true); +$table->data['name'][1] = html_print_input_text( + 'name', + $reportName, + __('Name'), + 80, + 100, + true, + false, + true +); $table->data['group'][0] = __('Group'); -$write_groups = users_get_groups_for_select(false, "AR", true, true, false, 'id_grupo'); +$write_groups = users_get_groups_for_select(false, 'AR', true, true, false, 'id_grupo'); - html_print_select_groups($config['id_user'], "AR", - true, 'id_group', $idGroup, '', '', '', true); + html_print_select_groups( + $config['id_user'], + 'AR', + true, + 'id_group', + $idGroup, + '', + '', + '', + true + ); - -// If the report group is not among the RW groups (special permission) we add it -if (!isset($write_groups[$idGroupReport]) && $idGroupReport) { - $write_groups[$idGroupReport] = groups_get_name($idGroupReport); -} -$table->data['group'][1] = html_print_select($write_groups, 'id_group', - $idGroupReport, false, '', '', true,false,false); + // If the report group is not among the RW groups (special permission) we add it + if (!isset($write_groups[$idGroupReport]) && $idGroupReport) { + $write_groups[$idGroupReport] = groups_get_name($idGroupReport); + } -if ($report_id_user == $config['id_user'] || - is_user_admin ($config["id_user"])) { - //S/he is the creator of report (or admin) and s/he can change the access. - $type_access = array('group_view' => __('Only the group can view the report'), - 'group_edit' => __('The next group can edit the report'), - 'user_edit' => __('Only the user and admin user can edit the report') - ); - $table->data['access'][0] = __('Write Access') . - ui_print_help_tip(__('For example, you want a report that the people of "All" groups can see but you want to edit only for you or your group.'), true); - $table->data['access'][1] = html_print_select ($type_access, 'type_access', - $type_access_selected, 'change_type_access(this)', '', 0, true); - - $style = "display: none;"; - if ($type_access_selected == 'group_edit') - $style = ""; - $table->data['access'][1] .= ' - ' . - html_print_select_groups(false, "RW", false, - 'id_group_edit', $id_group_edit, false, '', '', true) . ' + $table->data['group'][1] = html_print_select( + $write_groups, + 'id_group', + $idGroupReport, + false, + '', + '', + true, + false, + false + ); + + if ($report_id_user == $config['id_user'] + || is_user_admin($config['id_user']) + ) { + // S/he is the creator of report (or admin) and s/he can change the access. + $type_access = [ + 'group_view' => __('Only the group can view the report'), + 'group_edit' => __('The next group can edit the report'), + 'user_edit' => __('Only the user and admin user can edit the report'), + ]; + $table->data['access'][0] = __('Write Access').ui_print_help_tip(__('For example, you want a report that the people of "All" groups can see but you want to edit only for you or your group.'), true); + $table->data['access'][1] = html_print_select( + $type_access, + 'type_access', + $type_access_selected, + 'change_type_access(this)', + '', + 0, + true + ); + + $style = 'display: none;'; + if ($type_access_selected == 'group_edit') { + $style = ''; + } + + $table->data['access'][1] .= ' + '.html_print_select_groups( + false, + 'RW', + false, + 'id_group_edit', + $id_group_edit, + false, + '', + '', + true + ).' '; -} + } -if ($enterpriseEnable) { - $non_interactive_check = false; - if (isset($non_interactive)) { - $non_interactive_check = $non_interactive; - } - - $table->data['interactive_report'][0] = __('Non interactive report'); - $table->data['interactive_report'][1] =__('Yes') . - '   ' . - html_print_radio_button('non_interactive', 1, '', - $non_interactive_check, true) .'  '; - $table->data['interactive_report'][1] .= __('No') . - '   ' . - html_print_radio_button('non_interactive', 0, '', - $non_interactive_check, true); -} + if ($enterpriseEnable) { + $non_interactive_check = false; + if (isset($non_interactive)) { + $non_interactive_check = $non_interactive; + } -$table->data['description'][0] = __('Description'); -$table->data['description'][1] = html_print_textarea('description', 5, 15, $description, '', true); + $table->data['interactive_report'][0] = __('Non interactive report'); + $table->data['interactive_report'][1] = __('Yes').'   '.html_print_radio_button( + 'non_interactive', + 1, + '', + $non_interactive_check, + true + ).'  '; + $table->data['interactive_report'][1] .= __('No').'   '.html_print_radio_button( + 'non_interactive', + 0, + '', + $non_interactive_check, + true + ); + } -echo '
    '; -html_print_table ($table); + $table->data['description'][0] = __('Description'); + $table->data['description'][1] = html_print_textarea('description', 5, 15, $description, '', true); -echo '
    '; -echo $actionButtonHtml; -html_print_input_hidden('action', $hiddenFieldAction); -html_print_input_hidden('id_report', $idReport); -echo '
    '; -?> + echo '
    '; + html_print_table($table); + + echo '
    '; + echo $actionButtonHtml; + html_print_input_hidden('action', $hiddenFieldAction); + html_print_input_hidden('id_report', $idReport); + echo '
    '; + ?> diff --git a/pandora_console/godmode/reporting/reporting_builder.php b/pandora_console/godmode/reporting/reporting_builder.php index 229c5ab56f..abab21b8fe 100755 --- a/pandora_console/godmode/reporting/reporting_builder.php +++ b/pandora_console/godmode/reporting/reporting_builder.php @@ -1,56 +1,56 @@ $config['id_user'], - 'id_user_task' => $id_user_task, - 'args' => serialize ($parameters), - 'scheduled' => $scheduled, - 'flag_delete' => 1); - - $result = db_process_sql_insert('tuser_task_scheduled', $values); - - ui_print_result_message ($result, - __('Your report has been planned, and the system will email you a PDF with the report as soon as its finished'), - __('An error has ocurred')); - echo '
    '; + $id_user_task = 1; + $scheduled = 'no'; + $date = date(DATE_FORMAT); + $time = date(TIME_FORMAT); + $parameters[0] = get_parameter('id_schedule_report'); + // $parameters[1] = db_get_value('schedule_email', 'treport', 'id_report', $id_report); + $parameters[1] = get_parameter('schedule_email_address'); + $parameters[2] = get_parameter('schedule_subject', ''); + $parameters[3] = get_parameter('schedule_email', ''); + $parameters['first_execution'] = strtotime($date.' '.$time); + + $values = [ + 'id_usuario' => $config['id_user'], + 'id_user_task' => $id_user_task, + 'args' => serialize($parameters), + 'scheduled' => $scheduled, + 'flag_delete' => 1, + ]; + + $result = db_process_sql_insert('tuser_task_scheduled', $values); + + ui_print_result_message( + $result, + __('Your report has been planned, and the system will email you a PDF with the report as soon as its finished'), + __('An error has ocurred') + ); + echo '
    '; } -//Other Checks for the edit the reports +// Other Checks for the edit the reports if ($idReport != 0) { - $report = db_get_row_filter('treport', array('id_report' => $idReport)); - $type_access_selected = reports_get_type_access($report); - $edit = false; - switch ($type_access_selected) { - case 'group_view': - $edit = check_acl($config['id_user'], $report['id_group'], "RW"); - break; - case 'group_edit': - $edit = check_acl($config['id_user'], $report['id_group_edit'], "RW"); - break; - case 'user_edit': - if ($config['id_user'] == $report['id_user'] || - is_user_admin ($config["id_user"])) - $edit = true; - break; - } - - if (! $edit) { - // The user that created the report should can delete it. Despite its permissions. - $delete_report_bypass = false; - - if ($action == 'delete_report') { - if ($config['id_user'] == $report['id_user'] || is_user_admin ($config["id_user"])) { - $delete_report_bypass = true; - } - } - - if (!$delete_report_bypass) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; - } - } + $report = db_get_row_filter('treport', ['id_report' => $idReport]); + $type_access_selected = reports_get_type_access($report); + $edit = false; + switch ($type_access_selected) { + case 'group_view': + $edit = check_acl($config['id_user'], $report['id_group'], 'RW'); + break; + + case 'group_edit': + $edit = check_acl($config['id_user'], $report['id_group_edit'], 'RW'); + break; + + case 'user_edit': + if ($config['id_user'] == $report['id_user'] + || is_user_admin($config['id_user']) + ) { + $edit = true; + } + break; + } + + if (! $edit) { + // The user that created the report should can delete it. Despite its permissions. + $delete_report_bypass = false; + + if ($action == 'delete_report') { + if ($config['id_user'] == $report['id_user'] || is_user_admin($config['id_user'])) { + $delete_report_bypass = true; + } + } + + if (!$delete_report_bypass) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; + } + } } switch ($action) { - case 'sort_items': - switch ($activeTab) { - case 'list_items': - $resultOperationDB = null; - $position_to_sort = (int)get_parameter('position_to_sort', 1); - $ids_serialize = (string)get_parameter('ids_items_to_sort', ''); - $move_to = (string)get_parameter('move_to', 'after'); - - $countItems = db_get_sql(' + case 'sort_items': + switch ($activeTab) { + case 'list_items': + $resultOperationDB = null; + $position_to_sort = (int) get_parameter('position_to_sort', 1); + $ids_serialize = (string) get_parameter('ids_items_to_sort', ''); + $move_to = (string) get_parameter('move_to', 'after'); + + $countItems = db_get_sql( + ' SELECT COUNT(id_rc) FROM treport_content - WHERE id_report = ' . $idReport); - - if (($countItems < $position_to_sort) || ($position_to_sort < 1)) { - $resultOperationDB = false; - } - else if (!empty($ids_serialize)) { - $ids = explode('|', $ids_serialize); - - switch ($config["dbtype"]) { - case "mysql": - $items = db_get_all_rows_sql(' + WHERE id_report = '.$idReport + ); + + if (($countItems < $position_to_sort) || ($position_to_sort < 1)) { + $resultOperationDB = false; + } else if (!empty($ids_serialize)) { + $ids = explode('|', $ids_serialize); + + switch ($config['dbtype']) { + case 'mysql': + $items = db_get_all_rows_sql( + ' SELECT id_rc, `order` FROM treport_content - WHERE id_report = ' . $idReport . ' - ORDER BY `order`'); - break; - case "oracle": - case "postgresql": - $items = db_get_all_rows_sql(' + WHERE id_report = '.$idReport.' + ORDER BY `order`' + ); + break; + + case 'oracle': + case 'postgresql': + $items = db_get_all_rows_sql( + ' SELECT id_rc, "order" FROM treport_content - WHERE id_report = ' . $idReport . ' - ORDER BY "order"'); - break; - } - - if ($items === false) $items = array(); - - - // Clean the repeated order values - $order_temp = 1; - foreach ($items as $item) { - switch ($config["dbtype"]) { - case "mysql": - db_process_sql_update('treport_content', - array('`order`' => $order_temp), - array('id_rc' => $item['id_rc'])); - break; - case "postgresql": - case "oracle": - db_process_sql_update('treport_content', - array('"order"' => $order_temp), - array('id_rc' => $item['id_rc'])); - break; - } - - $order_temp++; - } - - - switch ($config["dbtype"]) { - case "mysql": - $items = db_get_all_rows_sql(' + WHERE id_report = '.$idReport.' + ORDER BY "order"' + ); + break; + } + + if ($items === false) { + $items = []; + } + + + // Clean the repeated order values + $order_temp = 1; + foreach ($items as $item) { + switch ($config['dbtype']) { + case 'mysql': + db_process_sql_update( + 'treport_content', + ['`order`' => $order_temp], + ['id_rc' => $item['id_rc']] + ); + break; + + case 'postgresql': + case 'oracle': + db_process_sql_update( + 'treport_content', + ['"order"' => $order_temp], + ['id_rc' => $item['id_rc']] + ); + break; + } + + $order_temp++; + } + + + switch ($config['dbtype']) { + case 'mysql': + $items = db_get_all_rows_sql( + ' SELECT id_rc, `order` FROM treport_content - WHERE id_report = ' . $idReport . ' - ORDER BY `order`'); - break; - case "oracle": - case "postgresql": - $items = db_get_all_rows_sql(' + WHERE id_report = '.$idReport.' + ORDER BY `order`' + ); + break; + + case 'oracle': + case 'postgresql': + $items = db_get_all_rows_sql( + ' SELECT id_rc, "order" FROM treport_content - WHERE id_report = ' . $idReport . ' - ORDER BY "order"'); - break; - } - - if ($items === false) $items = array(); - - - - $temp = array(); - - $temp = array(); - foreach ($items as $item) { - //Remove the contents from the block to sort - if (array_search($item['id_rc'], $ids) === false) { - $temp[$item['order']] = $item['id_rc']; - } - } - $items = $temp; - - - - $sorted_items = array(); - foreach ($items as $pos => $id_unsort) { - if ($pos == $position_to_sort) { - if ($move_to == 'after') { - $sorted_items[] = $id_unsort; - } - - foreach ($ids as $id) { - $sorted_items[] = $id; - } - - if ($move_to != 'after') { - $sorted_items[] = $id_unsort; - } - } - else { - $sorted_items[] = $id_unsort; - } - } - - $items = $sorted_items; - - - - foreach ($items as $order => $id) { - switch ($config["dbtype"]) { - case "mysql": - db_process_sql_update('treport_content', - array('`order`' => ($order + 1)), - array('id_rc' => $id)); - break; - case "postgresql": - case "oracle": - db_process_sql_update('treport_content', - array('"order"' => ($order + 1)), - array('id_rc' => $id)); - break; - } - } - - $resultOperationDB = true; - } - else { - $resultOperationDB = false; - } - break; - } - break; - case 'delete_items': - $resultOperationDB = null; - $ids_serialize = (string)get_parameter('ids_items_to_delete', ''); - - if (!empty($ids_serialize)) { - $sql = "DELETE FROM treport_content WHERE id_rc IN ($ids_serialize)"; - $resultOperationDB = db_process_sql($sql); - } - else { - $resultOperationDB = false; - } - - break; - case 'delete_items_pos': - $resultOperationDB = null; - $position_to_delete = (int)get_parameter('position_to_delete', 1); - $pos_delete = (string)get_parameter('delete_m', 'below'); - - $countItems = db_get_sql('SELECT COUNT(id_rc) - FROM treport_content WHERE id_report = ' . $idReport); - - if (($countItems < $position_to_delete) || ($position_to_delete < 1)) { - $resultOperationDB = false; - } - else { - $sql = "SELECT id_rc FROM treport_content WHERE id_report=$idReport ORDER BY '`order`'"; - $items = db_get_all_rows_sql($sql); - switch ($pos_delete) { - case 'above': - if ($position_to_delete == 1) { - $resultOperationDB = false; - } - else { - $i = 1; - foreach ($items as $key => $item) { - if ($i < $position_to_delete) { - $resultOperationDB = db_process_sql_delete('treport_content', array('id_rc' => $item['id_rc'])); - } - $i++; - } - } - break; - case 'below': - if ($position_to_delete == $countItems) { - $resultOperationDB = false; - } - else { - $i = 1; - foreach ($items as $key => $item) { - if ($i > $position_to_delete) { - $resultOperationDB = - db_process_sql_delete( - 'treport_content', - array('id_rc' => $item['id_rc'])); - } - $i++; - } - } - break; - } - } - break; - case 'delete_report': - case 'list': - $buttons = array( - 'list_reports' => array('active' => false, - 'text' => '' . - html_print_image("images/report_list.png", true, array ("title" => __('Reports list'))) .'') - ); - - if ($enterpriseEnable) { - $buttons = reporting_enterprise_add_main_Tabs($buttons); - } - - $subsection = ''; - switch ($activeTab) { - case 'main': - $buttons['list_reports']['active'] = true; - $subsection = __('Custom reporting'); - break; - default: - $subsection = reporting_enterprise_add_subsection_main($activeTab, $buttons); - break; - } - - // Page header for metaconsole - if ($enterpriseEnable and defined('METACONSOLE')) { - // Bread crumbs - ui_meta_add_breadcrumb( - array( - 'link' => 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&pure='.$pure, - 'text' => __('Reporting'))); - - ui_meta_print_page_header($nav_bar); - - // Print header - ui_meta_print_header(__('Reporting'), "", $buttons); - } - // Page header for normal console - else - ui_print_page_header (__('Custom reporting'), "images/op_reporting.png", false, "", false, $buttons,false,'',60); - - - if ($action == 'delete_report') { - $delete = false; - switch ($type_access_selected) { - case 'group_view': - if ($config['id_user'] == $report['id_user'] || is_user_admin ($config["id_user"])) { - $delete = true; //owner can delete - } else { - $delete = check_acl($config['id_user'], - $report['id_group'], "RM"); - } - break; - case 'group_edit': - if ($config['id_user'] == $report['id_user'] || is_user_admin ($config["id_user"])) { - $delete = true; //owner can delete - } else { - $delete = check_acl($config['id_user'], - $report['id_group'], "RM"); - } - break; - case 'user_edit': - if ($config['id_user'] == $report['id_user'] || - is_user_admin ($config["id_user"])) { - $delete = true; - } - break; - } - - if (! $delete) { - db_pandora_audit("ACL Violation", - "Trying to access report builder deletion"); - require ("general/noaccess.php"); - exit; - } - - $result = reports_delete_report ($idReport); - if ($result !== false) - db_pandora_audit("Report management", "Delete report #$idReport"); - else - db_pandora_audit("Report management", "Fail try to delete report #$idReport"); - - ui_print_result_message ($result, - __('Successfully deleted'), - __('Could not be deleted')); - } - - $id_group = (int) get_parameter ("id_group", 0); - $search = trim(get_parameter ("search", "")); - - $search_sql = ''; - if ($search != "") { - $search_name = "%$search%' OR description LIKE '%$search%"; - } - - $table_aux = new stdClass(); - $table_aux->width = '100%'; - $table_aux->class = 'databox filters'; - $table_aux->cellpadding = 0; - $table_aux->cellspacing = 0; - - $table_aux->colspan[0][0] = 4; - $table_aux->data[0][0] = "". __("Group") . ""; - - $table_aux->data[0][1] = html_print_select_groups(false, $access, true, 'id_group', $id_group, '', '', '', true, false, true, '', false, "", false, false, 'id_grupo', $strict_user). '
    '; - - $table_aux->data[0][2] = "". __("Free text for search: ") . ui_print_help_tip( - __('Search by report name or description, list matches.'),true) . ""; - $table_aux->data[0][3] = html_print_input_text ("search", $search, '', 30, '', true); - - $table_aux->data[0][6] = html_print_submit_button(__('Search'), 'search_submit', false, 'class="sub upd"', true); - - if (is_metaconsole()) { - $filter = "
    $id_unsort) { + if ($pos == $position_to_sort) { + if ($move_to == 'after') { + $sorted_items[] = $id_unsort; + } + + foreach ($ids as $id) { + $sorted_items[] = $id; + } + + if ($move_to != 'after') { + $sorted_items[] = $id_unsort; + } + } else { + $sorted_items[] = $id_unsort; + } + } + + $items = $sorted_items; + + + + foreach ($items as $order => $id) { + switch ($config['dbtype']) { + case 'mysql': + db_process_sql_update( + 'treport_content', + ['`order`' => ($order + 1)], + ['id_rc' => $id] + ); + break; + + case 'postgresql': + case 'oracle': + db_process_sql_update( + 'treport_content', + ['"order"' => ($order + 1)], + ['id_rc' => $id] + ); + break; + } + } + + $resultOperationDB = true; + } else { + $resultOperationDB = false; + } + break; + } + break; + + case 'delete_items': + $resultOperationDB = null; + $ids_serialize = (string) get_parameter('ids_items_to_delete', ''); + + if (!empty($ids_serialize)) { + $sql = "DELETE FROM treport_content WHERE id_rc IN ($ids_serialize)"; + $resultOperationDB = db_process_sql($sql); + } else { + $resultOperationDB = false; + } + break; + + case 'delete_items_pos': + $resultOperationDB = null; + $position_to_delete = (int) get_parameter('position_to_delete', 1); + $pos_delete = (string) get_parameter('delete_m', 'below'); + + $countItems = db_get_sql( + 'SELECT COUNT(id_rc) + FROM treport_content WHERE id_report = '.$idReport + ); + + if (($countItems < $position_to_delete) || ($position_to_delete < 1)) { + $resultOperationDB = false; + } else { + $sql = "SELECT id_rc FROM treport_content WHERE id_report=$idReport ORDER BY '`order`'"; + $items = db_get_all_rows_sql($sql); + switch ($pos_delete) { + case 'above': + if ($position_to_delete == 1) { + $resultOperationDB = false; + } else { + $i = 1; + foreach ($items as $key => $item) { + if ($i < $position_to_delete) { + $resultOperationDB = db_process_sql_delete('treport_content', ['id_rc' => $item['id_rc']]); + } + + $i++; + } + } + break; + + case 'below': + if ($position_to_delete == $countItems) { + $resultOperationDB = false; + } else { + $i = 1; + foreach ($items as $key => $item) { + if ($i > $position_to_delete) { + $resultOperationDB = db_process_sql_delete( + 'treport_content', + ['id_rc' => $item['id_rc']] + ); + } + + $i++; + } + } + break; + } + } + break; + + case 'delete_report': + case 'list': + $buttons = [ + 'list_reports' => [ + 'active' => false, + 'text' => ''.html_print_image('images/report_list.png', true, ['title' => __('Reports list')]).'', + ], + ]; + + if ($enterpriseEnable) { + $buttons = reporting_enterprise_add_main_Tabs($buttons); + } + + $subsection = ''; + switch ($activeTab) { + case 'main': + $buttons['list_reports']['active'] = true; + $subsection = __('Custom reporting'); + break; + + default: + $subsection = reporting_enterprise_add_subsection_main($activeTab, $buttons); + break; + } + + // Page header for metaconsole + if ($enterpriseEnable and defined('METACONSOLE')) { + // Bread crumbs + ui_meta_add_breadcrumb( + [ + 'link' => 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&pure='.$pure, + 'text' => __('Reporting'), + ] + ); + + ui_meta_print_page_header($nav_bar); + + // Print header + ui_meta_print_header(__('Reporting'), '', $buttons); + } + // Page header for normal console + else { + ui_print_page_header(__('Custom reporting'), 'images/op_reporting.png', false, '', false, $buttons, false, '', 60); + } + + + if ($action == 'delete_report') { + $delete = false; + switch ($type_access_selected) { + case 'group_view': + if ($config['id_user'] == $report['id_user'] || is_user_admin($config['id_user'])) { + $delete = true; + // owner can delete + } else { + $delete = check_acl( + $config['id_user'], + $report['id_group'], + 'RM' + ); + } + break; + + case 'group_edit': + if ($config['id_user'] == $report['id_user'] || is_user_admin($config['id_user'])) { + $delete = true; + // owner can delete + } else { + $delete = check_acl( + $config['id_user'], + $report['id_group'], + 'RM' + ); + } + break; + + case 'user_edit': + if ($config['id_user'] == $report['id_user'] + || is_user_admin($config['id_user']) + ) { + $delete = true; + } + break; + } + + if (! $delete) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder deletion' + ); + include 'general/noaccess.php'; + exit; + } + + $result = reports_delete_report($idReport); + if ($result !== false) { + db_pandora_audit('Report management', "Delete report #$idReport"); + } else { + db_pandora_audit('Report management', "Fail try to delete report #$idReport"); + } + + ui_print_result_message( + $result, + __('Successfully deleted'), + __('Could not be deleted') + ); + } + + $id_group = (int) get_parameter('id_group', 0); + $search = trim(get_parameter('search', '')); + + $search_sql = ''; + if ($search != '') { + $search_name = "%$search%' OR description LIKE '%$search%"; + } + + $table_aux = new stdClass(); + $table_aux->width = '100%'; + $table_aux->class = 'databox filters'; + $table_aux->cellpadding = 0; + $table_aux->cellspacing = 0; + + $table_aux->colspan[0][0] = 4; + $table_aux->data[0][0] = ''.__('Group').''; + + $table_aux->data[0][1] = html_print_select_groups(false, $access, true, 'id_group', $id_group, '', '', '', true, false, true, '', false, '', false, false, 'id_grupo', $strict_user).'
    '; + + $table_aux->data[0][2] = ''.__('Free text for search: ').ui_print_help_tip( + __('Search by report name or description, list matches.'), + true + ).''; + $table_aux->data[0][3] = html_print_input_text('search', $search, '', 30, '', true); + + $table_aux->data[0][6] = html_print_submit_button(__('Search'), 'search_submit', false, 'class="sub upd"', true); + + if (is_metaconsole()) { + $filter = ""; - $filter .= html_print_table($table_aux,true); - $filter .= "
    "; - ui_toggle($filter, __("Show Option")); - } - else { - echo "
    "; - html_print_table($table_aux); - echo "
    "; - } - - ui_require_jquery_file ('pandora.controls'); - ui_require_jquery_file ('ajaxqueue'); - ui_require_jquery_file ('bgiframe'); - ui_require_jquery_file ('autocomplete'); - - // Show only selected groups - if ($id_group > 0) { - $group = array("$id_group" => $id_group); - } - else { - $group = false; - } - - $own_info = get_user_info ($config['id_user']); - if ($own_info['is_admin'] || check_acl ($config['id_user'], 0, "RM")) - $return_all_group = true; - else - $return_all_group = false; - if ($search != "") { - $filter = array ( - 'name' => $search_name, - 'order' => 'name' - ); - } - else { - $filter = array ( - 'order' => 'name' - ); - } - - # Fix : group filter was not working - // Show only selected groups - if ($id_group > 0) { - $group = array("$id_group" => $id_group); - $filter['id_group'] = $id_group; - } - else { - $group = false; - } - - // Filter normal and metaconsole reports - if ($config['metaconsole'] == 1 and defined('METACONSOLE')) - $filter['metaconsole'] = 1; - else - $filter['metaconsole'] = 0; - - $reports = reports_get_reports ($filter, - array ( - 'name', - 'id_report', - 'description', - 'private', - 'id_user', - 'id_group', - 'non_interactive'), $return_all_group, $access, $group, $strict_user); - - $total_reports = (int) count(reports_get_reports ($filter, - array ('name'), $return_all_group, $access, $group, $strict_user)); - - - if (sizeof ($reports)) { - $url = "index.php?sec=reporting&sec2=godmode/reporting/reporting_builder"; - ui_pagination ($total_reports, $url, $offset, $pagination); - - $table = new stdClass(); - $table->id = 'report_list'; - $table->width = '100%'; - $table->class = 'databox data'; - $table->cellpadding = 0; - $table->cellspacing = 0; - - $table->head = array (); - $table->align = array (); - $table->align[2] = 'left'; - $table->align[3] = 'left'; - $table->align[4] = 'left'; - $table->data = array (); - $table->head[0] = __('Report name'); - $table->head[1] = __('Description'); - $table->head[2] = __('HTML'); - $table->head[3] = __('XML'); - $table->size[0] = '20%'; - $table->size[1] = '30%'; - $table->size[2] = '2%'; - $table->size[3] = '2%'; - $table->size[4] = '2%'; - $table->size[5] = '2%'; - $table->size[6] = '2%'; - $table->size['csv'] = '5%'; - - $next = 4; - //Calculate dinamically the number of the column - if (enterprise_hook ('load_custom_reporting_1') !== ENTERPRISE_NOT_HOOK) { - $next = 7; - } - - //Admin options only for RM flag - if (check_acl ($config['id_user'], 0, "RM")) { - - $table->head[$next] = __('Private'); - $table->size[$next] = '2%'; - if(defined('METACONSOLE')) - $table->align[$next] = ''; - else - $table->align[$next] = 'left'; - $next++; - $table->head[$next] = __('Group'); - $table->size[$next] = '15%'; - - $next++; - $op_column = false; - if(!defined('METACONSOLE')) { - $op_column = true; - $table->head[$next] = '' . - __('Op.') . ''.html_print_checkbox('all_delete', 0, false, true, false, - 'check_all_checkboxes();'); - } - - //$table->size = array (); - $table->size[$next] = '10%'; - $table->align[$next] = 'left'; - $table->headstyle[$next] = 'text-align:left;'; - - } - $columnview = false; - - $reports = array_slice($reports, $offset, $pagination); - - foreach ($reports as $report) { - - if (!is_user_admin ($config["id_user"])) { - if ($report["private"] && $report["id_user"] != $config['id_user']) - if (!check_acl ($config["id_user"], $report["id_group"], "RR") && - !check_acl ($config["id_user"], $report["id_group"], "RW") - && !check_acl ($config["id_user"], $report["id_group"], "RM")) - continue; - if (!check_acl ($config["id_user"], $report["id_group"], "RR") && - !check_acl ($config["id_user"], $report["id_group"], "RW") - && !check_acl ($config["id_user"], $report["id_group"], "RM")) - continue; - } - - $data = array (); - - if (check_acl ($config["id_user"], $report["id_group"], "RW") || check_acl ($config["id_user"], $report["id_group"], "RM")) { - $data[0] = ''.ui_print_truncate_text($report['name'], 70).''; - } - else { - $data[0] = ui_print_truncate_text($report['name'], 70); - } - - - $data[1] = ui_print_truncate_text($report['description'], 70); - - //Remove html and xml button if items are larger than limit - $item_count = db_get_num_rows ('SELECT * FROM treport_content WHERE id_report=' . $report['id_report']); - $report['overload'] = $item_count >= $config['report_limit']; - if ($report['overload']) { - $data[2] = html_print_image("images/application_not_writable.png", true, array('title' => __('This report exceeds the item limit for realtime operations'))); - $data[3] = null; - } - else if (!$report['non_interactive']) { - $data[2] = '' . - html_print_image("images/html.png", true, array('title' => __('HTML view'))) . ''; - $data[3] = '' . html_print_image("images/xml.png", true, array('title' => __('Export to XML'))) . ''; //I chose ajax.php because it's supposed to give XML anyway - } - else { - $data[2] = html_print_image( - "images/html_disabled.png", true); - $data[3] = html_print_image( - "images/xml_disabled.png", true); - } - - - //Calculate dinamically the number of the column - $next = 4; - if (enterprise_hook ('load_custom_reporting_2') !== ENTERPRISE_NOT_HOOK) { - $next = 7; - } - - - //Admin options only for RM flag - if (check_acl ($config['id_user'], 0, "RM")) { - - if ($report["private"] == 1) - $data[$next] = __('Yes'); - else - $data[$next] = __('No'); - - $next++; - - - $data[$next] = ui_print_group_icon( - $report['id_group'], true, "groups_small", '', !defined('METACONSOLE')); - $next++; - } - - $type_access_selected = reports_get_type_access($report); - $edit = false; - $delete = false; - - switch ($type_access_selected) { - case 'group_view': - $edit = check_acl($config['id_user'], $report['id_group'], "RW"); - $delete = - $edit || - is_user_admin ($config["id_user"]) || - $config['id_user'] == $report['id_user']; - break; - case 'group_edit': - $edit = check_acl($config['id_user'], $report['id_group_edit'], "RW"); - $delete = - $edit || - is_user_admin ($config["id_user"]) || - $config['id_user'] == $report['id_user']; - break; - case 'user_edit': - if ($config['id_user'] == $report['id_user'] || - is_user_admin ($config["id_user"])) { - $edit = true; - $delete = true; - } - break; - } - - if ($edit || $delete) { - $columnview = true; - if (!isset($table->head[$next])) { - $table->head[$next] = '' . __('Op.') . ''. - html_print_checkbox('all_delete', 0, false, true, false); - $table->size = array (); - //$table->size[$next] = '80px'; - $table->style[$next] = 'text-align:left;'; - } - - if ($edit) { - $data[$next] = '
    '; - $data[$next] .= html_print_input_hidden('id_report', - $report['id_report'], true); - $data[$next] .= html_print_input_image('edit', - 'images/config.png', 1, '', true, array ('title' => __('Edit'))); - $data[$next] .= '
    '; - } - - if ($delete) { - $data[$next] .= '
    '; - $data[$next] .= html_print_input_hidden ('id_report', $report['id_report'], true); - $data[$next] .= html_print_input_hidden ('action','delete_report', true); - $data[$next] .= html_print_input_image ('delete', 'images/cross.png', 1, 'margin-right: 10px;', - true, array ('title' => __('Delete'))); - - $data[$next] .= html_print_checkbox_extended ('massive_report_check', $report['id_report'], false, false, '', 'class="check_delete"', true); - - $data[$next] .= '
    '; - - } - } else { - if ($op_column) $data[$next] = ''; - } - - array_push ($table->data, $data); - - } - - if ($columnview){ - $count = 0; - foreach ($table->data as $datos) { - if (!isset($datos[9])) - $table->data[$count][9] = ''; - $count++; - } - } - html_print_table ($table); - } - else { - ui_print_info_message ( array ( 'no_close' => true, 'message' => __('No data found.') ) ); - } - if (check_acl ($config['id_user'], 0, "RW") || check_acl ($config['id_user'], 0, "RM")) { - echo '
    '; - if (defined("METACONSOLE")) - echo '
    '; - else - echo '
    '; - html_print_submit_button (__('Create report'), 'create', false, 'class="sub next"'); - - echo ""; - echo '
    '; - - foreach ($reports as $report) { - echo ''; - } - - echo ''; - html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete" style="margin-left:5px;"'); - echo '
    '; - echo "
    "; - - } - - enterprise_hook('close_meta_frame'); - - return; - break; - case 'new': - switch ($activeTab) { - case 'main': - $reportName = ''; - $idGroupReport = 0; //All groups - $description = ''; - $resultOperationDB = null; - $report_id_user = 0; - $type_access_selected = reports_get_type_access(false); - $id_group_edit = 0; - break; - case 'item_editor': - $resultOperationDB = null; - $report = db_get_row_filter('treport', - array('id_report' => $idReport)); - - $reportName = $report['name']; - $idGroupReport = $report['id_group']; - $description = $report['description']; - break; - } - break; - case 'update': - case 'save': - switch ($activeTab) { - case 'main': - $reportName = get_parameter('name'); - $idGroupReport = get_parameter('id_group'); - $description = get_parameter('description'); - $type_access_selected = get_parameter('type_access', 'group_view'); - $id_group_edit_param = (int)get_parameter('id_group_edit', 0); - $report_id_user = get_parameter('report_id_user'); - $non_interactive = get_parameter('non_interactive', 0); - - // Pretty font by default for pdf - $custom_font = 'FreeSans.ttf'; - - switch ($type_access_selected) { - case 'group_view': - $id_group_edit = 0; - $private = 0; - break; - case 'group_edit': - $id_group_edit = $id_group_edit_param; - $private = 0; - break; - case 'user_edit': - $id_group_edit = 0; - $private = 1; - break; - } - if ($action == 'update') { - if ($reportName != "" && $idGroupReport != "") { - $new_values = array('name' => $reportName, - 'id_group' => $idGroupReport, - 'description' => $description, - 'private' => $private, - 'id_group_edit' => $id_group_edit, - 'non_interactive' => $non_interactive); - - - $report = db_get_row_filter('treport', - array('id_report' => $idReport)); - $report_id_user = $report['id_user']; - if ($report_id_user != $config['id_user'] && - !is_user_admin ($config["id_user"])) { - unset($new_values['private']); - unset($new_values['id_group_edit']); - } - $resultOperationDB = (bool)db_process_sql_update( - 'treport', $new_values, - array('id_report' => $idReport)); - - if ($resultOperationDB !== false) - db_pandora_audit( "Report management", - "Update report #$idReport"); - else - db_pandora_audit( "Report management", - "Fail try to update report #$idReport"); - } - else { - $resultOperationDB = false; - } - - $action = 'edit'; - } - else if ($action == 'save') { - if ($reportName != "" && $idGroupReport != "") { - - // This flag allow to differentiate between normal console and metaconsole reports - $metaconsole_report = (int) is_metaconsole(); - - // Juanma (07/05/2014) New feature: Custom front page for reports - if ($config['custom_report_front']) { - - $custom_font = $config['custom_report_front_font']; - $logo = $config['custom_report_front_logo']; - $header = $config['custom_report_front_header']; - $first_page = $config['custom_report_front_firstpage']; - $footer = $config['custom_report_front_footer']; - - } - else { - - $start_url = ui_get_full_url(false, false, false, false); - $first_page = "<p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;"><img src="" . $start_url . "/images/pandora_report_logo.png" alt="" width="800" /></p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;"><span style="font-size: xx-large;">(_REPORT_NAME_)</span></p> <p style="text-align: center;"><span style="font-size: large;">(_DATETIME_)</span></p>"; - $logo = $header = $footer = null; - - } - - $idOrResult = db_process_sql_insert('treport', - array('name' => $reportName, - 'id_group' => $idGroupReport, - 'description' => $description, - 'first_page' => $first_page, - 'private' => $private, - 'id_group_edit' => $id_group_edit, - 'id_user' => $config['id_user'], - 'metaconsole' => $metaconsole_report, - 'non_interactive' => $non_interactive, - 'custom_font' => $custom_font, - 'custom_logo' => $logo, - 'header' => $header, - 'footer' => $footer)); - - if ($idOrResult !== false) - db_pandora_audit( "Report management", "Create report #$idOrResult"); - else - db_pandora_audit( "Report management", "Fail try to create report"); - } - else { - $idOrResult = false; - } - - if ($idOrResult === false) { - $resultOperationDB = false; - } - else { - $resultOperationDB = true; - $idReport = $idOrResult; - $report_id_user = $config['id_user']; - } - - $action = $resultOperationDB ? 'edit' : 'new'; - } - break; - case 'item_editor': - $resultOperationDB = null; - $report = db_get_row_filter('treport', - array('id_report' => $idReport)); - + html_print_table($table_aux); + echo ''; + } + + ui_require_jquery_file('pandora.controls'); + ui_require_jquery_file('ajaxqueue'); + ui_require_jquery_file('bgiframe'); + ui_require_jquery_file('autocomplete'); + + // Show only selected groups + if ($id_group > 0) { + $group = ["$id_group" => $id_group]; + } else { + $group = false; + } + + $own_info = get_user_info($config['id_user']); + if ($own_info['is_admin'] || check_acl($config['id_user'], 0, 'RM')) { + $return_all_group = true; + } else { + $return_all_group = false; + } + + if ($search != '') { + $filter = [ + 'name' => $search_name, + 'order' => 'name', + ]; + } else { + $filter = ['order' => 'name']; + } + + // Fix : group filter was not working + // Show only selected groups + if ($id_group > 0) { + $group = ["$id_group" => $id_group]; + $filter['id_group'] = $id_group; + } else { + $group = false; + } + + // Filter normal and metaconsole reports + if ($config['metaconsole'] == 1 and defined('METACONSOLE')) { + $filter['metaconsole'] = 1; + } else { + $filter['metaconsole'] = 0; + } + + $reports = reports_get_reports( + $filter, + [ + 'name', + 'id_report', + 'description', + 'private', + 'id_user', + 'id_group', + 'non_interactive', + ], + $return_all_group, + $access, + $group, + $strict_user + ); + + $total_reports = (int) count( + reports_get_reports( + $filter, + ['name'], + $return_all_group, + $access, + $group, + $strict_user + ) + ); + + + if (sizeof($reports)) { + $url = 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder'; + ui_pagination($total_reports, $url, $offset, $pagination); + + $table = new stdClass(); + $table->id = 'report_list'; + $table->width = '100%'; + $table->class = 'databox data'; + $table->cellpadding = 0; + $table->cellspacing = 0; + + $table->head = []; + $table->align = []; + $table->align[2] = 'left'; + $table->align[3] = 'left'; + $table->align[4] = 'left'; + $table->data = []; + $table->head[0] = __('Report name'); + $table->head[1] = __('Description'); + $table->head[2] = __('HTML'); + $table->head[3] = __('XML'); + $table->size[0] = '20%'; + $table->size[1] = '30%'; + $table->size[2] = '2%'; + $table->size[3] = '2%'; + $table->size[4] = '2%'; + $table->size[5] = '2%'; + $table->size[6] = '2%'; + $table->size['csv'] = '5%'; + + $next = 4; + // Calculate dinamically the number of the column + if (enterprise_hook('load_custom_reporting_1') !== ENTERPRISE_NOT_HOOK) { + $next = 7; + } + + // Admin options only for RM flag + if (check_acl($config['id_user'], 0, 'RM')) { + $table->head[$next] = __('Private'); + $table->size[$next] = '2%'; + if (defined('METACONSOLE')) { + $table->align[$next] = ''; + } else { + $table->align[$next] = 'left'; + } + + $next++; + $table->head[$next] = __('Group'); + $table->size[$next] = '15%'; + + $next++; + $op_column = false; + if (!defined('METACONSOLE')) { + $op_column = true; + $table->head[$next] = ''.__('Op.').''.html_print_checkbox( + 'all_delete', + 0, + false, + true, + false, + 'check_all_checkboxes();' + ); + } + + // $table->size = array (); + $table->size[$next] = '10%'; + $table->align[$next] = 'left'; + $table->headstyle[$next] = 'text-align:left;'; + } + + $columnview = false; + + $reports = array_slice($reports, $offset, $pagination); + + foreach ($reports as $report) { + if (!is_user_admin($config['id_user'])) { + if ($report['private'] && $report['id_user'] != $config['id_user']) { + if (!check_acl($config['id_user'], $report['id_group'], 'RR') + && !check_acl($config['id_user'], $report['id_group'], 'RW') + && !check_acl($config['id_user'], $report['id_group'], 'RM') + ) { + continue; + } + } + + if (!check_acl($config['id_user'], $report['id_group'], 'RR') + && !check_acl($config['id_user'], $report['id_group'], 'RW') + && !check_acl($config['id_user'], $report['id_group'], 'RM') + ) { + continue; + } + } + + $data = []; + + if (check_acl($config['id_user'], $report['id_group'], 'RW') || check_acl($config['id_user'], $report['id_group'], 'RM')) { + $data[0] = ''.ui_print_truncate_text($report['name'], 70).''; + } else { + $data[0] = ui_print_truncate_text($report['name'], 70); + } + + + $data[1] = ui_print_truncate_text($report['description'], 70); + + // Remove html and xml button if items are larger than limit + $item_count = db_get_num_rows('SELECT * FROM treport_content WHERE id_report='.$report['id_report']); + $report['overload'] = $item_count >= $config['report_limit']; + if ($report['overload']) { + $data[2] = html_print_image('images/application_not_writable.png', true, ['title' => __('This report exceeds the item limit for realtime operations')]); + $data[3] = null; + } else if (!$report['non_interactive']) { + $data[2] = ''.html_print_image('images/html.png', true, ['title' => __('HTML view')]).''; + $data[3] = ''.html_print_image('images/xml.png', true, ['title' => __('Export to XML')]).''; + // I chose ajax.php because it's supposed to give XML anyway + } else { + $data[2] = html_print_image( + 'images/html_disabled.png', + true + ); + $data[3] = html_print_image( + 'images/xml_disabled.png', + true + ); + } + + + // Calculate dinamically the number of the column + $next = 4; + if (enterprise_hook('load_custom_reporting_2') !== ENTERPRISE_NOT_HOOK) { + $next = 7; + } + + + // Admin options only for RM flag + if (check_acl($config['id_user'], 0, 'RM')) { + if ($report['private'] == 1) { + $data[$next] = __('Yes'); + } else { + $data[$next] = __('No'); + } + + $next++; + + + $data[$next] = ui_print_group_icon( + $report['id_group'], + true, + 'groups_small', + '', + !defined('METACONSOLE') + ); + $next++; + } + + $type_access_selected = reports_get_type_access($report); + $edit = false; + $delete = false; + + switch ($type_access_selected) { + case 'group_view': + $edit = check_acl($config['id_user'], $report['id_group'], 'RW'); + $delete = $edit || + is_user_admin($config['id_user']) || + $config['id_user'] == $report['id_user']; + break; + + case 'group_edit': + $edit = check_acl($config['id_user'], $report['id_group_edit'], 'RW'); + $delete = $edit || + is_user_admin($config['id_user']) || + $config['id_user'] == $report['id_user']; + break; + + case 'user_edit': + if ($config['id_user'] == $report['id_user'] + || is_user_admin($config['id_user']) + ) { + $edit = true; + $delete = true; + } + break; + } + + if ($edit || $delete) { + $columnview = true; + if (!isset($table->head[$next])) { + $table->head[$next] = ''.__('Op.').''.html_print_checkbox('all_delete', 0, false, true, false); + $table->size = []; + // $table->size[$next] = '80px'; + $table->style[$next] = 'text-align:left;'; + } + + if ($edit) { + $data[$next] = '
    '; + $data[$next] .= html_print_input_hidden( + 'id_report', + $report['id_report'], + true + ); + $data[$next] .= html_print_input_image( + 'edit', + 'images/config.png', + 1, + '', + true, + ['title' => __('Edit')] + ); + $data[$next] .= '
    '; + } + + if ($delete) { + $data[$next] .= '
    '; + $data[$next] .= html_print_input_hidden('id_report', $report['id_report'], true); + $data[$next] .= html_print_input_hidden('action', 'delete_report', true); + $data[$next] .= html_print_input_image( + 'delete', + 'images/cross.png', + 1, + 'margin-right: 10px;', + true, + ['title' => __('Delete')] + ); + + $data[$next] .= html_print_checkbox_extended('massive_report_check', $report['id_report'], false, false, '', 'class="check_delete"', true); + + $data[$next] .= '
    '; + } + } else { + if ($op_column) { + $data[$next] = ''; + } + } + + array_push($table->data, $data); + } + + if ($columnview) { + $count = 0; + foreach ($table->data as $datos) { + if (!isset($datos[9])) { + $table->data[$count][9] = ''; + } + + $count++; + } + } + + html_print_table($table); + } else { + ui_print_info_message([ 'no_close' => true, 'message' => __('No data found.') ]); + } + + if (check_acl($config['id_user'], 0, 'RW') || check_acl($config['id_user'], 0, 'RM')) { + echo '
    '; + if (defined('METACONSOLE')) { + echo '
    '; + } else { + echo '
    '; + } + + html_print_submit_button(__('Create report'), 'create', false, 'class="sub next"'); + + echo ''; + echo '
    '; + + foreach ($reports as $report) { + echo ''; + } + + echo ''; + html_print_submit_button(__('Delete'), 'delete_btn', false, 'class="sub delete" style="margin-left:5px;"'); + echo '
    '; + echo '
    '; + } + + enterprise_hook('close_meta_frame'); + + return; + + break; + case 'new': + switch ($activeTab) { + case 'main': + $reportName = ''; + $idGroupReport = 0; + // All groups + $description = ''; + $resultOperationDB = null; + $report_id_user = 0; + $type_access_selected = reports_get_type_access(false); + $id_group_edit = 0; + break; + + case 'item_editor': + $resultOperationDB = null; + $report = db_get_row_filter( + 'treport', + ['id_report' => $idReport] + ); + + $reportName = $report['name']; + $idGroupReport = $report['id_group']; + $description = $report['description']; + break; + } + break; + + case 'update': + case 'save': + switch ($activeTab) { + case 'main': + $reportName = get_parameter('name'); + $idGroupReport = get_parameter('id_group'); + $description = get_parameter('description'); + $type_access_selected = get_parameter('type_access', 'group_view'); + $id_group_edit_param = (int) get_parameter('id_group_edit', 0); + $report_id_user = get_parameter('report_id_user'); + $non_interactive = get_parameter('non_interactive', 0); + + // Pretty font by default for pdf + $custom_font = 'FreeSans.ttf'; + + switch ($type_access_selected) { + case 'group_view': + $id_group_edit = 0; + $private = 0; + break; + + case 'group_edit': + $id_group_edit = $id_group_edit_param; + $private = 0; + break; + + case 'user_edit': + $id_group_edit = 0; + $private = 1; + break; + } + + if ($action == 'update') { + if ($reportName != '' && $idGroupReport != '') { + $new_values = [ + 'name' => $reportName, + 'id_group' => $idGroupReport, + 'description' => $description, + 'private' => $private, + 'id_group_edit' => $id_group_edit, + 'non_interactive' => $non_interactive, + ]; + + + $report = db_get_row_filter( + 'treport', + ['id_report' => $idReport] + ); + $report_id_user = $report['id_user']; + if ($report_id_user != $config['id_user'] + && !is_user_admin($config['id_user']) + ) { + unset($new_values['private']); + unset($new_values['id_group_edit']); + } + + $resultOperationDB = (bool) db_process_sql_update( + 'treport', + $new_values, + ['id_report' => $idReport] + ); + + if ($resultOperationDB !== false) { + db_pandora_audit( + 'Report management', + "Update report #$idReport" + ); + } else { + db_pandora_audit( + 'Report management', + "Fail try to update report #$idReport" + ); + } + } else { + $resultOperationDB = false; + } + + $action = 'edit'; + } else if ($action == 'save') { + if ($reportName != '' && $idGroupReport != '') { + // This flag allow to differentiate between normal console and metaconsole reports + $metaconsole_report = (int) is_metaconsole(); + + // Juanma (07/05/2014) New feature: Custom front page for reports + if ($config['custom_report_front']) { + $custom_font = $config['custom_report_front_font']; + $logo = $config['custom_report_front_logo']; + $header = $config['custom_report_front_header']; + $first_page = $config['custom_report_front_firstpage']; + $footer = $config['custom_report_front_footer']; + } else { + $start_url = ui_get_full_url(false, false, false, false); + $first_page = '<p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;"><img src="'.$start_url.'/images/pandora_report_logo.png" alt="" width="800" /></p> <p style="text-align: center;">&nbsp;</p> <p style="text-align: center;"><span style="font-size: xx-large;">(_REPORT_NAME_)</span></p> <p style="text-align: center;"><span style="font-size: large;">(_DATETIME_)</span></p>'; + $logo = $header = $footer = null; + } + + $idOrResult = db_process_sql_insert( + 'treport', + [ + 'name' => $reportName, + 'id_group' => $idGroupReport, + 'description' => $description, + 'first_page' => $first_page, + 'private' => $private, + 'id_group_edit' => $id_group_edit, + 'id_user' => $config['id_user'], + 'metaconsole' => $metaconsole_report, + 'non_interactive' => $non_interactive, + 'custom_font' => $custom_font, + 'custom_logo' => $logo, + 'header' => $header, + 'footer' => $footer, + ] + ); + + if ($idOrResult !== false) { + db_pandora_audit('Report management', "Create report #$idOrResult"); + } else { + db_pandora_audit('Report management', 'Fail try to create report'); + } + } else { + $idOrResult = false; + } + + if ($idOrResult === false) { + $resultOperationDB = false; + } else { + $resultOperationDB = true; + $idReport = $idOrResult; + $report_id_user = $config['id_user']; + } + + $action = $resultOperationDB ? 'edit' : 'new'; + } + break; + + case 'item_editor': + $resultOperationDB = null; + $report = db_get_row_filter( + 'treport', + ['id_report' => $idReport] + ); - $reportName = $report['name']; - $idGroupReport = $report['id_group']; - $description = $report['description']; - $good_format = false; - switch ($action) { - case 'update': - $values = array(); - $values['id_report'] = $idReport; //--------------------------------------------------- - //$values['name'] = (string) get_parameter('name'); - $values['description'] = get_parameter('description'); - $values['type'] = get_parameter('type', null); - $values['recursion'] = get_parameter('recursion', null); - $label = get_parameter('label', ''); - - //Add macros name - $items_label = array(); - $items_label['type'] = get_parameter('type'); - $items_label['id_agent'] = get_parameter('id_agent'); - $items_label['id_agent_module'] = get_parameter('id_agent_module'); - $name_it = (string) get_parameter('name'); - $values['name'] = reporting_label_macro($items_label, $name_it); + $reportName = $report['name']; + $idGroupReport = $report['id_group']; + $description = $report['description']; + $good_format = false; + switch ($action) { + case 'update': - // Added support for projection graphs, prediction date and SLA reports - // 'top_n_value','top_n' and 'text' fields will be reused for these types of report - switch ($values['type']) { - case 'projection_graph': - $values['period'] = get_parameter('period1'); - $values['top_n_value'] = get_parameter('period2'); - $values['text'] = get_parameter('text'); - $good_format = true; - break; - case 'event_report_log': - $agents_to_report = get_parameter('id_agents2'); - $source = get_parameter('source', ""); - $search = get_parameter('search', ""); - $log_number = get_parameter('log_number', ""); - - $es['source'] = $source; - $es['id_agents'] = $agents_to_report; - $es['search']=$search; - $es['log_number']=$log_number; + $values = []; + $values['id_report'] = $idReport; + // --------------------------------------------------- + // $values['name'] = (string) get_parameter('name'); + $values['description'] = get_parameter('description'); + $values['type'] = get_parameter('type', null); + $values['recursion'] = get_parameter('recursion', null); + $label = get_parameter('label', ''); - $values['external_source'] = json_encode($es); - $values['period'] = get_parameter('period'); - $good_format = true; - break; - case 'prediction_date': - $values['period'] = get_parameter('period1'); - $values['top_n'] = get_parameter('radiobutton_max_min_avg'); - $values['top_n_value'] = get_parameter('quantity'); - $interval_max = get_parameter('max_interval'); - $interval_min = get_parameter('min_interval'); - // Checks intervals fields - if (preg_match('/^(\-)*[0-9]*\.?[0-9]+$/', $interval_max) and preg_match('/^(\-)*[0-9]*\.?[0-9]+$/', $interval_min)) { - $good_format = true; - } - $intervals = get_parameter('max_interval') . ';' . get_parameter('min_interval'); - $values['text'] = $intervals; - break; - case 'SLA_monthly': - case 'SLA_weekly': - case 'SLA_hourly': - case 'SLA_services': - case 'SLA': - case 'availability_graph': - $values['period'] = get_parameter('period'); - $values['top_n'] = get_parameter('combo_sla_sort_options',0); - $values['top_n_value'] = get_parameter('quantity'); - $values['text'] = get_parameter('text'); - $values['show_graph'] = get_parameter('combo_graph_options'); - - $good_format = true; - break; - case 'agent_module': - $agents_to_report = get_parameter('id_agents2'); - $modules_to_report = get_parameter('module', ""); + // Add macros name + $items_label = []; + $items_label['type'] = get_parameter('type'); + $items_label['id_agent'] = get_parameter('id_agent'); + $items_label['id_agent_module'] = get_parameter('id_agent_module'); + $name_it = (string) get_parameter('name'); + $values['name'] = reporting_label_macro($items_label, $name_it); - $es['module'] = get_same_modules($agents_to_report, $modules_to_report); - $es['id_agents'] = $agents_to_report; + // Added support for projection graphs, prediction date and SLA reports + // 'top_n_value','top_n' and 'text' fields will be reused for these types of report + switch ($values['type']) { + case 'projection_graph': + $values['period'] = get_parameter('period1'); + $values['top_n_value'] = get_parameter('period2'); + $values['text'] = get_parameter('text'); + $good_format = true; + break; - $values['external_source'] = json_encode($es); - $good_format = true; - break; - case 'inventory': - $values['period'] = 0; - $es['date'] = get_parameter('date'); - $es['id_agents'] = get_parameter('id_agents'); - $es['inventory_modules'] = get_parameter('inventory_modules'); - $description = get_parameter('description'); - $values['external_source'] = json_encode($es); - $good_format = true; - break; - case 'inventory_changes': - $values['period'] = get_parameter('period'); - $es['id_agents'] = get_parameter('id_agents'); - $es['inventory_modules'] = get_parameter('inventory_modules'); - $description = get_parameter('description'); - $values['external_source'] = json_encode($es); - $good_format = true; - break; - case 'netflow_area': - case 'netflow_pie': - case 'netflow_data': - case 'netflow_statistics': - case 'netflow_summary': - $values['text'] = get_parameter('netflow_filter'); - $values['description'] = get_parameter('description'); - $values['period'] = get_parameter('period'); - $values['top_n'] = get_parameter('resolution'); - $values['top_n_value'] = get_parameter('max_values'); - $good_format = true; - break; - case 'availability': - // HACK it is saved in show_graph field. - // Show interfaces instead the modules - $values['show_graph'] = - get_parameter('checkbox_show_address_agent'); - $values['period'] = get_parameter('period'); - $good_format = true; - break; - case 'simple_graph': - case 'simple_baseline_graph': - // HACK it is saved in show_graph field. - $values['show_graph'] = - (int)get_parameter('time_compare_overlapped'); - $values['period'] = get_parameter('period'); - $good_format = true; - break; - case 'min_value': - case 'max_value': - case 'avg_value': - $values['period'] = get_parameter('period'); - $values['lapse_calc'] = get_parameter('lapse_calc'); - $values['lapse'] = get_parameter('lapse'); - $values['visual_format'] = get_parameter('visual_format'); - $good_format = true; - break; - default: - $values['period'] = get_parameter('period'); - $values['top_n'] = get_parameter('radiobutton_max_min_avg',0); - $values['top_n_value'] = get_parameter('quantity'); - $values['text'] = get_parameter('text'); - $values['show_graph'] = get_parameter('combo_graph_options'); - $good_format = true; - } - - $values['id_agent'] = get_parameter('id_agent'); - $values['id_gs'] = get_parameter('id_custom_graph'); - - $values['id_agent_module'] = ''; - if (isset($values['type'])) { - if (($values['type'] == 'alert_report_agent') or ($values['type'] == 'event_report_agent') or ($values['type'] == 'agent_configuration') or ($values['type'] == 'group_configuration')) - $values['id_agent_module'] = ''; - else - $values['id_agent_module'] = get_parameter('id_agent_module'); - } - else - $values['id_agent_module'] = get_parameter('id_agent_module'); - - $values['only_display_wrong'] = (int)get_parameter('checkbox_only_display_wrong', 0); - $values['monday'] = get_parameter('monday', 0); - $values['tuesday'] = get_parameter('tuesday', 0); - $values['wednesday'] = get_parameter('wednesday', 0); - $values['thursday'] = get_parameter('thursday', 0); - $values['friday'] = get_parameter('friday', 0); - $values['saturday'] = get_parameter('saturday', 0); - $values['sunday'] = get_parameter('sunday', 0); - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $values['time_from'] = get_parameter('time_from'); - $values['time_to'] = get_parameter('time_to'); - break; - case "oracle": - $values['time_from'] = '#to_date(\'' . get_parameter('time_from') . '\',\'hh24:mi:ss\')'; - $values['time_to'] = '#to_date(\'' . get_parameter('time_to') . '\', \'hh24:mi:ss\')'; - break; - } - $values['group_by_agent'] = get_parameter ('checkbox_row_group_by_agent'); - $values['show_resume'] = get_parameter ('checkbox_show_resume'); - $values['order_uptodown'] = get_parameter ('radiobutton_order_uptodown'); - $values['exception_condition'] = (int)get_parameter('exception_condition', 0); - $values['exception_condition_value'] = get_parameter('exception_condition_value'); - $values['id_module_group'] = get_parameter('combo_modulegroup'); - $values['id_group'] = get_parameter ('combo_group'); - $values['server_name'] = get_parameter ('server_name'); - $server_id = (int)get_parameter('server_id'); - if ($server_id != 0) { - $connection = metaconsole_get_connection_by_id($server_id); - $values['server_name'] = $connection['server_name']; - } - if ($values['server_name'] == '') - $values['server_name'] = get_parameter ('combo_server'); - - if ((($values['type'] == 'custom_graph') or ($values['type'] == 'automatic_custom_graph')) && ($values['id_gs'] == 0 || $values['id_gs'] == '')) { - $resultOperationDB = false; - break; - } - $show_summary_group = get_parameter('show_summary_group', 0); - $filter_event_severity = get_parameter('filter_event_severity', 0); - $filter_event_type = get_parameter('filter_event_type', ''); - $filter_event_status = get_parameter('filter_event_status', 0); + case 'event_report_log': + $agents_to_report = get_parameter('id_agents2'); + $source = get_parameter('source', ''); + $search = get_parameter('search', ''); + $log_number = get_parameter('log_number', ''); - $event_graph_by_agent = get_parameter('event_graph_by_agent', 0); - $event_graph_by_user_validator = get_parameter('event_graph_by_user_validator', 0); - $event_graph_by_criticity = get_parameter('event_graph_by_criticity', 0); - $event_graph_validated_vs_unvalidated = get_parameter('event_graph_validated_vs_unvalidated', 0); - - $event_filter_search = get_parameter('filter_search', ''); - - // If metaconsole is activated - if ($config['metaconsole'] == 1 && defined('METACONSOLE')) { - if (($values['type'] == 'custom_graph') or ($values['type'] == 'automatic_custom_graph')) { - $id_gs = substr ($values['id_gs'], 0, strpos ($values['id_gs'], '|')); - if ($id_gs !== false) { - $server_name = strstr($values ['id_gs'], '|'); - $values ['id_gs'] = $id_gs; - $values['server_name'] = substr ($server_name, 1, strlen($server_name)); - } - } - - // Get agent and server name - $agent_name_server = io_safe_output(get_parameter('agent')); - - if (isset($agent_name_server)) { - - $separator_pos = strpos($agent_name_server, '('); - - if (($separator_pos != false) and ($separator_pos != 0)) { - - $server_name = substr($agent_name_server, $separator_pos); - $server_name = str_replace('(', '', $server_name); - $server_name = str_replace(')', '', $server_name); - // Will update server_name variable - $values['server_name'] = trim($server_name); - $agent_name = substr($agent_name_server, 0, $separator_pos); - - } - - } - } - - if (($values['type'] == 'sql') OR ($values['type'] == 'sql_graph_hbar') OR ($values['type'] == 'sql_graph_vbar') OR ($values['type'] == 'sql_graph_pie')) { - $values['treport_custom_sql_id'] = get_parameter('id_custom'); - if ($values['treport_custom_sql_id'] == 0) { - $values['external_source'] = get_parameter('sql'); - } - $values['historical_db'] = get_parameter('historical_db_check'); - $values['top_n_value'] = get_parameter('max_items'); - } - else if ($values['type'] == 'url') { - $values['external_source'] = get_parameter('url'); - } - else if ($values['type'] == 'event_report_group') { - $values['id_agent'] = get_parameter('group'); - } - - $values['header_definition'] = get_parameter('header'); - $values['column_separator'] = get_parameter('field'); - $values['line_separator'] = get_parameter('line'); - - $style = array(); - $style['show_in_same_row'] = get_parameter('show_in_same_row', 0); - $style['show_in_landscape'] = get_parameter('show_in_landscape', 0); - $style['hide_notinit_agents'] = get_parameter('hide_notinit_agents', 0); - $style['priority_mode'] = get_parameter('priority_mode', REPORT_PRIORITY_MODE_OK); - $style['dyn_height'] = get_parameter('dyn_height', 230); - - switch ($values['type']) { - case 'event_report_agent': - case 'event_report_group': - case 'event_report_module': - //Added for events items - $style['show_summary_group'] = $show_summary_group; - $style['filter_event_severity'] = json_encode($filter_event_severity); - $style['filter_event_type'] = json_encode($filter_event_type); - $style['filter_event_status'] = json_encode($filter_event_status); - - $style['event_graph_by_agent'] = $event_graph_by_agent; - $style['event_graph_by_user_validator'] = $event_graph_by_user_validator; - $style['event_graph_by_criticity'] = $event_graph_by_criticity; - $style['event_graph_validated_vs_unvalidated'] = $event_graph_validated_vs_unvalidated; - - $style['event_filter_search'] = $event_filter_search; - if ($label != '') - $style['label'] = $label; - else - $style['label'] = ''; - break; - case 'simple_graph': - // Warning. We are using this column to hold this value to avoid - // the modification of the database for compatibility reasons. - $style['percentil'] = (int) get_parameter('percentil'); - $style['fullscale'] = (int) get_parameter('fullscale'); - if ($label != '') - $style['label'] = $label; - else - $style['label'] = ''; - break; - case 'network_interfaces_report': - $style['fullscale'] = (int) get_parameter('fullscale'); - break; - case 'module_histogram_graph': - case 'agent_configuration': - case 'alert_report_agent': - case 'alert_report_module': - case 'historical_data': - case 'sumatory': - case 'database_serialized': - case 'monitor_report': - case 'min_value': - case 'max_value': - case 'avg_value': - case 'projection_graph': - case 'prediction_date': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': - case 'simple_baseline_graph': - if ($label != '') - $style['label'] = $label; - else - $style['label'] = ''; - break; - } - - $values['style'] = io_safe_input(json_encode($style)); - - if ($good_format) { - switch ($config["dbtype"]) { - case "oracle": - if (isset($values['type'])) { - $values[ - db_escape_key_identifier( - "type")] = $values['type']; - unset($values['type']); - } - break; - } - - $resultOperationDB = db_process_sql_update( - 'treport_content', - $values, - array('id_rc' => $idItem)); - } - else { - $resultOperationDB = false; - } - break; - case 'save': + $es['source'] = $source; + $es['id_agents'] = $agents_to_report; + $es['search'] = $search; + $es['log_number'] = $log_number; - $values = array(); - $values['id_report'] = $idReport; - $values['type'] = get_parameter('type', null); - //$values['name'] = (string) get_parameter('name'); - $values['description'] = get_parameter('description'); - $label = get_parameter('label', ''); - - //Add macros name - $items_label = array(); - $items_label['type'] = get_parameter('type'); - $items_label['id_agent'] = get_parameter('id_agent'); - $items_label['id_agent_module'] = get_parameter('id_agent_module'); - $name_it = (string) get_parameter('name'); - $values['recursion'] = get_parameter('recursion', null); - $values['name'] = reporting_label_macro($items_label, $name_it); - - // Support for projection graph, prediction date and SLA reports - // 'top_n_value', 'top_n' and 'text' fields will be reused for these types of report - switch ($values['type']) { - case 'projection_graph': - $values['period'] = get_parameter('period1'); - $values['top_n_value'] = get_parameter('period2'); - $values['text'] = get_parameter('text'); - $good_format = true; - break; - case 'prediction_date': - $values['period'] = get_parameter('period1'); - $values['top_n'] = get_parameter('radiobutton_max_min_avg'); - $values['top_n_value'] = get_parameter('quantity'); - $interval_max = get_parameter('max_interval'); - $interval_min = get_parameter('min_interval'); - // Checks intervals fields - if (preg_match('/^(\-)*[0-9]*\.?[0-9]+$/', $interval_max) and preg_match('/^(\-)*[0-9]*\.?[0-9]+$/', $interval_min)) { - $good_format = true; - } - $intervals = get_parameter('max_interval') . ';' . get_parameter('min_interval'); - $values['text'] = $intervals; - break; - case 'SLA': - $values['period'] = get_parameter('period'); - $values['top_n'] = get_parameter('combo_sla_sort_options',0); - $values['top_n_value'] = get_parameter('quantity'); - $values['text'] = get_parameter('text'); - $values['show_graph'] = get_parameter('combo_graph_options'); - - $good_format = true; - break; - case 'inventory': - $values['period'] = 0; - $es['date'] = get_parameter('date'); - $es['id_agents'] = get_parameter('id_agents'); - $es['inventory_modules'] = get_parameter('inventory_modules'); - $values['external_source'] = json_encode($es); - $good_format = true; - break; - case 'event_report_log': - $agents_to_report = get_parameter('id_agents2'); - $source = get_parameter('source', ""); - $search = get_parameter('search', ""); - $log_number = get_parameter('log_number', ""); - - $es['source'] = $source; - $es['id_agents'] = $agents_to_report; - $es['search']=$search; - $es['log_number']=$log_number; + $values['external_source'] = json_encode($es); + $values['period'] = get_parameter('period'); + $good_format = true; + break; - $values['external_source'] = json_encode($es); - $values['period'] = get_parameter('period'); - $good_format = true; - break; - case 'agent_module': - $agents_to_report = get_parameter('id_agents2'); - $modules_to_report = get_parameter('module', ""); + case 'prediction_date': + $values['period'] = get_parameter('period1'); + $values['top_n'] = get_parameter('radiobutton_max_min_avg'); + $values['top_n_value'] = get_parameter('quantity'); + $interval_max = get_parameter('max_interval'); + $interval_min = get_parameter('min_interval'); + // Checks intervals fields + if (preg_match('/^(\-)*[0-9]*\.?[0-9]+$/', $interval_max) and preg_match('/^(\-)*[0-9]*\.?[0-9]+$/', $interval_min)) { + $good_format = true; + } - $es['module'] = get_same_modules($agents_to_report, $modules_to_report); - $es['id_agents'] = $agents_to_report; + $intervals = get_parameter('max_interval').';'.get_parameter('min_interval'); + $values['text'] = $intervals; + break; - $values['external_source'] = json_encode($es); - $good_format = true; - break; - case 'inventory_changes': - $values['period'] = get_parameter('period'); - $es['id_agents'] = get_parameter('id_agents'); - $es['inventory_modules'] = get_parameter('inventory_modules'); - $values['external_source'] = json_encode($es); - $good_format = true; - break; - case 'agent_configuration': - $values['id_agent'] = get_parameter('id_agent'); - $good_format = true; - break; - case 'group_configuration': - $values['id_group'] = get_parameter('id_group'); - $good_format = true; - break; - case 'netflow_area': - case 'netflow_pie': - case 'netflow_data': - case 'netflow_statistics': - case 'netflow_summary': - $values['text'] = get_parameter('netflow_filter'); - $values['description'] = get_parameter('description'); - $values['period'] = get_parameter('period'); - $values['top_n'] = get_parameter('resolution'); - $values['top_n_value'] = get_parameter('max_values'); - $good_format = true; - break; - case 'availability': - $values['period'] = get_parameter('period'); - // HACK it is saved in show_graph field. - // Show interfaces instead the modules - $values['show_graph'] = - get_parameter('checkbox_show_address_agent'); - $good_format = true; - break; - case 'simple_graph': - case 'simple_baseline_graph': - // HACK it is saved in show_graph field. - $values['show_graph'] = - (int)get_parameter('time_compare_overlapped'); - $values['period'] = get_parameter('period'); - $good_format = true; - break; - case 'min_value': - case 'max_value': - case 'avg_value': - $values['period'] = get_parameter('period'); - $values['lapse_calc'] = get_parameter('lapse_calc'); - $values['lapse'] = get_parameter('lapse'); - $values['visual_format'] = get_parameter('visual_format'); - $good_format = true; - break; - default: - $values['period'] = get_parameter('period'); - $values['top_n'] = get_parameter('radiobutton_max_min_avg',0); - $values['top_n_value'] = get_parameter('quantity'); - $values['text'] = get_parameter('text'); - $values['show_graph'] = get_parameter('combo_graph_options'); - $good_format = true; - break; - } - - - - $values['server_name'] = get_parameter ('server_name'); - $server_id = (int)get_parameter('server_id'); - if ($server_id != 0) { - $connection = metaconsole_get_connection_by_id($server_id); - - $values['server_name'] = $connection['server_name']; - } - if ($values['server_name'] == '') - $values['server_name'] = get_parameter ('combo_server'); - - - if (is_metaconsole()) { - // For SQL Query check if it is setted in the meta - if ($values['type'] == "sql") { - if (empty($values['server_name'])) { - $good_format = false; - } - } - } - - - $values['id_agent'] = get_parameter('id_agent'); - $values['id_gs'] = get_parameter('id_custom_graph'); - if (($values['type'] == 'alert_report_agent') or ($values['type'] == 'event_report_agent') or ($values['type'] == 'agent_configuration') or ($values['type'] == 'group_configuration')) - $values['id_agent_module'] = ''; - else - $values['id_agent_module'] = get_parameter('id_agent_module'); - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $values['only_display_wrong'] = (int)get_parameter('checkbox_only_display_wrong', 0); - break; - case "oracle": - $only_display_wrong_tmp = get_parameter('checkbox_only_display_wrong'); - if (empty($only_display_wrong_tmp)) { - $values['only_display_wrong'] = 0; - } - else { - $values['only_display_wrong'] = $only_display_wrong_tmp; - } - break; - } - $values['monday'] = get_parameter('monday', 0); - $values['tuesday'] = get_parameter('tuesday', 0); - $values['wednesday'] = get_parameter('wednesday', 0); - $values['thursday'] = get_parameter('thursday', 0); - $values['friday'] = get_parameter('friday', 0); - $values['saturday'] = get_parameter('saturday', 0); - $values['sunday'] = get_parameter('sunday', 0); - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $values['time_from'] = get_parameter('time_from'); - $values['time_to'] = get_parameter('time_to'); - break; - case "oracle": - $values['time_from'] = '#to_date(\'' . get_parameter('time_from') . '\',\'hh24:mi:ss\')'; - $values['time_to'] = '#to_date(\'' . get_parameter('time_to') . '\', \'hh24:mi:ss\')'; - break; - } - $values['group_by_agent'] = get_parameter ('checkbox_row_group_by_agent',0); - $values['show_resume'] = get_parameter ('checkbox_show_resume',0); - $values['order_uptodown'] = get_parameter ('radiobutton_order_uptodown',0); - $values['exception_condition'] = (int)get_parameter('radiobutton_exception_condition', 0); - $values['exception_condition_value'] = get_parameter('exception_condition_value'); - $values['id_module_group'] = get_parameter('combo_modulegroup'); - $values['id_group'] = get_parameter ('combo_group'); - - - if ((($values['type'] == 'custom_graph') or ($values['type'] == 'automatic_custom_graph')) && ($values['id_gs'] == 0 || $values['id_gs'] == '')) { - $resultOperationDB = false; - break; - } - - if ($config['metaconsole'] == 1 && defined('METACONSOLE')) { - if (($values['type'] == 'custom_graph') or ($values['type'] == 'automatic_custom_graph')) { - $id_gs = substr ($values['id_gs'], 0, strpos ($values['id_gs'], '|')); - if ($id_gs !== false && $id_gs !== '') { - $server_name = strstr($values ['id_gs'], '|'); - $values ['id_gs'] = $id_gs; - $values['server_name'] = substr ($server_name, 1, strlen($server_name)); - } - } - } - - if (($values['type'] == 'sql') OR ($values['type'] == 'sql_graph_hbar') - OR ($values['type'] == 'sql_graph_vbar') OR ($values['type'] == 'sql_graph_pie')) { - - $values['treport_custom_sql_id'] = get_parameter('id_custom'); - if ($values['treport_custom_sql_id'] == 0) { - $values['external_source'] = get_parameter('sql'); - } - $values['historical_db'] = get_parameter('historical_db_check'); - $values['top_n_value'] = get_parameter('max_items'); - } - elseif ($values['type'] == 'url') { - $values['external_source'] = get_parameter('url'); - } - else if ($values['type'] == 'event_report_group') { - $values['id_agent'] = get_parameter('group'); - } - - $values['header_definition'] = get_parameter('header'); - $values['column_separator'] = get_parameter('field'); - $values['line_separator'] = get_parameter('line'); - - $style = array(); - $style['show_in_same_row'] = get_parameter('show_in_same_row', 0); - $style['show_in_landscape'] = get_parameter('show_in_landscape', 0); - $style['hide_notinit_agents'] = get_parameter('hide_notinit_agents', 0); - $style['priority_mode'] = get_parameter('priority_mode', REPORT_PRIORITY_MODE_OK); - $style['dyn_height'] = get_parameter('dyn_height', 230); - - switch ($values['type']) { - case 'event_report_agent': - case 'event_report_group': - case 'event_report_module': - $show_summary_group = get_parameter('show_summary_group', 0); - $filter_event_severity = get_parameter('filter_event_severity', ''); - $filter_event_type = get_parameter('filter_event_type', ''); - $filter_event_status = get_parameter('filter_event_status', ''); - - $event_graph_by_agent = get_parameter('event_graph_by_agent', 0); - $event_graph_by_user_validator = get_parameter('event_graph_by_user_validator', 0); - $event_graph_by_criticity = get_parameter('event_graph_by_criticity', 0); - $event_graph_validated_vs_unvalidated = get_parameter('event_graph_validated_vs_unvalidated', 0); - - $event_filter_search = get_parameter('filter_search', ''); - - //Added for events items - $style['show_summary_group'] = $show_summary_group; - $style['filter_event_severity'] = json_encode($filter_event_severity); - $style['filter_event_type'] = json_encode($filter_event_type); - $style['filter_event_status'] = json_encode($filter_event_status); + case 'SLA_monthly': + case 'SLA_weekly': + case 'SLA_hourly': + case 'SLA_services': + case 'SLA': + case 'availability_graph': + $values['period'] = get_parameter('period'); + $values['top_n'] = get_parameter('combo_sla_sort_options', 0); + $values['top_n_value'] = get_parameter('quantity'); + $values['text'] = get_parameter('text'); + $values['show_graph'] = get_parameter('combo_graph_options'); - $style['event_graph_by_agent'] = $event_graph_by_agent; - $style['event_graph_by_user_validator'] = $event_graph_by_user_validator; - $style['event_graph_by_criticity'] = $event_graph_by_criticity; - $style['event_graph_validated_vs_unvalidated'] = $event_graph_validated_vs_unvalidated; - - - switch ($values['type']) { - case 'event_report_group': - case 'event_report_agent': - $style['event_filter_search'] = $event_filter_search; - if ($label != '') - $style['label'] = $label; - else - $style['label'] = ''; - break; - } - - break; - case 'simple_graph': - // Warning. We are using this column to hold this value to avoid - // the modification of the database for compatibility reasons. - $style['percentil'] = (int) get_parameter('percentil'); - $style['fullscale'] = (int) get_parameter('fullscale'); - if ($label != '') - $style['label'] = $label; - else - $style['label'] = ''; - break; - case 'network_interfaces_report': - $style['fullscale'] = (int) get_parameter('fullscale'); - break; - case 'module_histogram_graph': - case 'agent_configuration': - case 'alert_report_agent': - case 'alert_report_module': - case 'historical_data': - case 'sumatory': - case 'database_serialized': - case 'monitor_report': - case 'min_value': - case 'max_value': - case 'avg_value': - case 'projection_graph': - case 'prediction_date': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': - case 'simple_baseline_graph': - if ($label != '') - $style['label'] = $label; - else - $style['label'] = ''; - break; - } - - $values['style'] = io_safe_input(json_encode($style)); - - if ($good_format) { - switch ($config["dbtype"]) { - case "oracle": - if (isset($values['type'])) { - $values[ - db_escape_key_identifier( - "type")] = $values['type']; - unset($values['type']); - } - break; - } - - $result = db_process_sql_insert( - 'treport_content', $values); - - if ($result === false) { - $resultOperationDB = false; - } - else { - $idItem = $result; - - switch ($config["dbtype"]) { - case "mysql": - $max = db_get_all_rows_sql( - 'SELECT max(`order`) AS max + $good_format = true; + break; + + case 'agent_module': + $agents_to_report = get_parameter('id_agents2'); + $modules_to_report = get_parameter('module', ''); + + $es['module'] = get_same_modules($agents_to_report, $modules_to_report); + $es['id_agents'] = $agents_to_report; + + $values['external_source'] = json_encode($es); + $good_format = true; + break; + + case 'inventory': + $values['period'] = 0; + $es['date'] = get_parameter('date'); + $es['id_agents'] = get_parameter('id_agents'); + $es['inventory_modules'] = get_parameter('inventory_modules'); + $description = get_parameter('description'); + $values['external_source'] = json_encode($es); + $good_format = true; + break; + + case 'inventory_changes': + $values['period'] = get_parameter('period'); + $es['id_agents'] = get_parameter('id_agents'); + $es['inventory_modules'] = get_parameter('inventory_modules'); + $description = get_parameter('description'); + $values['external_source'] = json_encode($es); + $good_format = true; + break; + + case 'netflow_area': + case 'netflow_pie': + case 'netflow_data': + case 'netflow_statistics': + case 'netflow_summary': + $values['text'] = get_parameter('netflow_filter'); + $values['description'] = get_parameter('description'); + $values['period'] = get_parameter('period'); + $values['top_n'] = get_parameter('resolution'); + $values['top_n_value'] = get_parameter('max_values'); + $good_format = true; + break; + + case 'availability': + // HACK it is saved in show_graph field. + // Show interfaces instead the modules + $values['show_graph'] = get_parameter('checkbox_show_address_agent'); + $values['period'] = get_parameter('period'); + $good_format = true; + break; + + case 'simple_graph': + case 'simple_baseline_graph': + // HACK it is saved in show_graph field. + $values['show_graph'] = (int) get_parameter('time_compare_overlapped'); + $values['period'] = get_parameter('period'); + $good_format = true; + break; + + case 'min_value': + case 'max_value': + case 'avg_value': + $values['period'] = get_parameter('period'); + $values['lapse_calc'] = get_parameter('lapse_calc'); + $values['lapse'] = get_parameter('lapse'); + $values['visual_format'] = get_parameter('visual_format'); + $good_format = true; + break; + + default: + $values['period'] = get_parameter('period'); + $values['top_n'] = get_parameter('radiobutton_max_min_avg', 0); + $values['top_n_value'] = get_parameter('quantity'); + $values['text'] = get_parameter('text'); + $values['show_graph'] = get_parameter('combo_graph_options'); + $good_format = true; + } + + $values['id_agent'] = get_parameter('id_agent'); + $values['id_gs'] = get_parameter('id_custom_graph'); + + $values['id_agent_module'] = ''; + if (isset($values['type'])) { + if (($values['type'] == 'alert_report_agent') or ($values['type'] == 'event_report_agent') or ($values['type'] == 'agent_configuration') or ($values['type'] == 'group_configuration')) { + $values['id_agent_module'] = ''; + } else { + $values['id_agent_module'] = get_parameter('id_agent_module'); + } + } else { + $values['id_agent_module'] = get_parameter('id_agent_module'); + } + + $values['only_display_wrong'] = (int) get_parameter('checkbox_only_display_wrong', 0); + $values['monday'] = get_parameter('monday', 0); + $values['tuesday'] = get_parameter('tuesday', 0); + $values['wednesday'] = get_parameter('wednesday', 0); + $values['thursday'] = get_parameter('thursday', 0); + $values['friday'] = get_parameter('friday', 0); + $values['saturday'] = get_parameter('saturday', 0); + $values['sunday'] = get_parameter('sunday', 0); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $values['time_from'] = get_parameter('time_from'); + $values['time_to'] = get_parameter('time_to'); + break; + + case 'oracle': + $values['time_from'] = '#to_date(\''.get_parameter('time_from').'\',\'hh24:mi:ss\')'; + $values['time_to'] = '#to_date(\''.get_parameter('time_to').'\', \'hh24:mi:ss\')'; + break; + } + + $values['group_by_agent'] = get_parameter('checkbox_row_group_by_agent'); + $values['show_resume'] = get_parameter('checkbox_show_resume'); + $values['order_uptodown'] = get_parameter('radiobutton_order_uptodown'); + $values['exception_condition'] = (int) get_parameter('exception_condition', 0); + $values['exception_condition_value'] = get_parameter('exception_condition_value'); + $values['id_module_group'] = get_parameter('combo_modulegroup'); + $values['id_group'] = get_parameter('combo_group'); + $values['server_name'] = get_parameter('server_name'); + $server_id = (int) get_parameter('server_id'); + if ($server_id != 0) { + $connection = metaconsole_get_connection_by_id($server_id); + $values['server_name'] = $connection['server_name']; + } + + if ($values['server_name'] == '') { + $values['server_name'] = get_parameter('combo_server'); + } + + if ((($values['type'] == 'custom_graph') or ($values['type'] == 'automatic_custom_graph')) && ($values['id_gs'] == 0 || $values['id_gs'] == '')) { + $resultOperationDB = false; + break; + } + + $show_summary_group = get_parameter('show_summary_group', 0); + $filter_event_severity = get_parameter('filter_event_severity', 0); + $filter_event_type = get_parameter('filter_event_type', ''); + $filter_event_status = get_parameter('filter_event_status', 0); + + $event_graph_by_agent = get_parameter('event_graph_by_agent', 0); + $event_graph_by_user_validator = get_parameter('event_graph_by_user_validator', 0); + $event_graph_by_criticity = get_parameter('event_graph_by_criticity', 0); + $event_graph_validated_vs_unvalidated = get_parameter('event_graph_validated_vs_unvalidated', 0); + + $event_filter_search = get_parameter('filter_search', ''); + + // If metaconsole is activated + if ($config['metaconsole'] == 1 && defined('METACONSOLE')) { + if (($values['type'] == 'custom_graph') or ($values['type'] == 'automatic_custom_graph')) { + $id_gs = substr($values['id_gs'], 0, strpos($values['id_gs'], '|')); + if ($id_gs !== false) { + $server_name = strstr($values['id_gs'], '|'); + $values['id_gs'] = $id_gs; + $values['server_name'] = substr($server_name, 1, strlen($server_name)); + } + } + + // Get agent and server name + $agent_name_server = io_safe_output(get_parameter('agent')); + + if (isset($agent_name_server)) { + $separator_pos = strpos($agent_name_server, '('); + + if (($separator_pos != false) and ($separator_pos != 0)) { + $server_name = substr($agent_name_server, $separator_pos); + $server_name = str_replace('(', '', $server_name); + $server_name = str_replace(')', '', $server_name); + // Will update server_name variable + $values['server_name'] = trim($server_name); + $agent_name = substr($agent_name_server, 0, $separator_pos); + } + } + } + + if (($values['type'] == 'sql') or ($values['type'] == 'sql_graph_hbar') or ($values['type'] == 'sql_graph_vbar') or ($values['type'] == 'sql_graph_pie')) { + $values['treport_custom_sql_id'] = get_parameter('id_custom'); + if ($values['treport_custom_sql_id'] == 0) { + $values['external_source'] = get_parameter('sql'); + } + + $values['historical_db'] = get_parameter('historical_db_check'); + $values['top_n_value'] = get_parameter('max_items'); + } else if ($values['type'] == 'url') { + $values['external_source'] = get_parameter('url'); + } else if ($values['type'] == 'event_report_group') { + $values['id_agent'] = get_parameter('group'); + } + + $values['header_definition'] = get_parameter('header'); + $values['column_separator'] = get_parameter('field'); + $values['line_separator'] = get_parameter('line'); + + $style = []; + $style['show_in_same_row'] = get_parameter('show_in_same_row', 0); + $style['show_in_landscape'] = get_parameter('show_in_landscape', 0); + $style['hide_notinit_agents'] = get_parameter('hide_notinit_agents', 0); + $style['priority_mode'] = get_parameter('priority_mode', REPORT_PRIORITY_MODE_OK); + $style['dyn_height'] = get_parameter('dyn_height', 230); + + switch ($values['type']) { + case 'event_report_agent': + case 'event_report_group': + case 'event_report_module': + // Added for events items + $style['show_summary_group'] = $show_summary_group; + $style['filter_event_severity'] = json_encode($filter_event_severity); + $style['filter_event_type'] = json_encode($filter_event_type); + $style['filter_event_status'] = json_encode($filter_event_status); + + $style['event_graph_by_agent'] = $event_graph_by_agent; + $style['event_graph_by_user_validator'] = $event_graph_by_user_validator; + $style['event_graph_by_criticity'] = $event_graph_by_criticity; + $style['event_graph_validated_vs_unvalidated'] = $event_graph_validated_vs_unvalidated; + + $style['event_filter_search'] = $event_filter_search; + if ($label != '') { + $style['label'] = $label; + } else { + $style['label'] = ''; + } + break; + + case 'simple_graph': + // Warning. We are using this column to hold this value to avoid + // the modification of the database for compatibility reasons. + $style['percentil'] = (int) get_parameter('percentil'); + $style['fullscale'] = (int) get_parameter('fullscale'); + if ($label != '') { + $style['label'] = $label; + } else { + $style['label'] = ''; + } + break; + + case 'network_interfaces_report': + $style['fullscale'] = (int) get_parameter('fullscale'); + break; + + case 'module_histogram_graph': + case 'agent_configuration': + case 'alert_report_agent': + case 'alert_report_module': + case 'historical_data': + case 'sumatory': + case 'database_serialized': + case 'monitor_report': + case 'min_value': + case 'max_value': + case 'avg_value': + case 'projection_graph': + case 'prediction_date': + case 'TTRT': + case 'TTO': + case 'MTBF': + case 'MTTR': + case 'simple_baseline_graph': + if ($label != '') { + $style['label'] = $label; + } else { + $style['label'] = ''; + } + break; + } + + $values['style'] = io_safe_input(json_encode($style)); + + if ($good_format) { + switch ($config['dbtype']) { + case 'oracle': + if (isset($values['type'])) { + $values[db_escape_key_identifier( + 'type' + )] = $values['type']; + unset($values['type']); + } + break; + } + + $resultOperationDB = db_process_sql_update( + 'treport_content', + $values, + ['id_rc' => $idItem] + ); + } else { + $resultOperationDB = false; + } + break; + + case 'save': + + $values = []; + $values['id_report'] = $idReport; + $values['type'] = get_parameter('type', null); + // $values['name'] = (string) get_parameter('name'); + $values['description'] = get_parameter('description'); + $label = get_parameter('label', ''); + + // Add macros name + $items_label = []; + $items_label['type'] = get_parameter('type'); + $items_label['id_agent'] = get_parameter('id_agent'); + $items_label['id_agent_module'] = get_parameter('id_agent_module'); + $name_it = (string) get_parameter('name'); + $values['recursion'] = get_parameter('recursion', null); + $values['name'] = reporting_label_macro($items_label, $name_it); + + // Support for projection graph, prediction date and SLA reports + // 'top_n_value', 'top_n' and 'text' fields will be reused for these types of report + switch ($values['type']) { + case 'projection_graph': + $values['period'] = get_parameter('period1'); + $values['top_n_value'] = get_parameter('period2'); + $values['text'] = get_parameter('text'); + $good_format = true; + break; + + case 'prediction_date': + $values['period'] = get_parameter('period1'); + $values['top_n'] = get_parameter('radiobutton_max_min_avg'); + $values['top_n_value'] = get_parameter('quantity'); + $interval_max = get_parameter('max_interval'); + $interval_min = get_parameter('min_interval'); + // Checks intervals fields + if (preg_match('/^(\-)*[0-9]*\.?[0-9]+$/', $interval_max) and preg_match('/^(\-)*[0-9]*\.?[0-9]+$/', $interval_min)) { + $good_format = true; + } + + $intervals = get_parameter('max_interval').';'.get_parameter('min_interval'); + $values['text'] = $intervals; + break; + + case 'SLA': + $values['period'] = get_parameter('period'); + $values['top_n'] = get_parameter('combo_sla_sort_options', 0); + $values['top_n_value'] = get_parameter('quantity'); + $values['text'] = get_parameter('text'); + $values['show_graph'] = get_parameter('combo_graph_options'); + + $good_format = true; + break; + + case 'inventory': + $values['period'] = 0; + $es['date'] = get_parameter('date'); + $es['id_agents'] = get_parameter('id_agents'); + $es['inventory_modules'] = get_parameter('inventory_modules'); + $values['external_source'] = json_encode($es); + $good_format = true; + break; + + case 'event_report_log': + $agents_to_report = get_parameter('id_agents2'); + $source = get_parameter('source', ''); + $search = get_parameter('search', ''); + $log_number = get_parameter('log_number', ''); + + $es['source'] = $source; + $es['id_agents'] = $agents_to_report; + $es['search'] = $search; + $es['log_number'] = $log_number; + + $values['external_source'] = json_encode($es); + $values['period'] = get_parameter('period'); + $good_format = true; + break; + + case 'agent_module': + $agents_to_report = get_parameter('id_agents2'); + $modules_to_report = get_parameter('module', ''); + + $es['module'] = get_same_modules($agents_to_report, $modules_to_report); + $es['id_agents'] = $agents_to_report; + + $values['external_source'] = json_encode($es); + $good_format = true; + break; + + case 'inventory_changes': + $values['period'] = get_parameter('period'); + $es['id_agents'] = get_parameter('id_agents'); + $es['inventory_modules'] = get_parameter('inventory_modules'); + $values['external_source'] = json_encode($es); + $good_format = true; + break; + + case 'agent_configuration': + $values['id_agent'] = get_parameter('id_agent'); + $good_format = true; + break; + + case 'group_configuration': + $values['id_group'] = get_parameter('id_group'); + $good_format = true; + break; + + case 'netflow_area': + case 'netflow_pie': + case 'netflow_data': + case 'netflow_statistics': + case 'netflow_summary': + $values['text'] = get_parameter('netflow_filter'); + $values['description'] = get_parameter('description'); + $values['period'] = get_parameter('period'); + $values['top_n'] = get_parameter('resolution'); + $values['top_n_value'] = get_parameter('max_values'); + $good_format = true; + break; + + case 'availability': + $values['period'] = get_parameter('period'); + // HACK it is saved in show_graph field. + // Show interfaces instead the modules + $values['show_graph'] = get_parameter('checkbox_show_address_agent'); + $good_format = true; + break; + + case 'simple_graph': + case 'simple_baseline_graph': + // HACK it is saved in show_graph field. + $values['show_graph'] = (int) get_parameter('time_compare_overlapped'); + $values['period'] = get_parameter('period'); + $good_format = true; + break; + + case 'min_value': + case 'max_value': + case 'avg_value': + $values['period'] = get_parameter('period'); + $values['lapse_calc'] = get_parameter('lapse_calc'); + $values['lapse'] = get_parameter('lapse'); + $values['visual_format'] = get_parameter('visual_format'); + $good_format = true; + break; + + default: + $values['period'] = get_parameter('period'); + $values['top_n'] = get_parameter('radiobutton_max_min_avg', 0); + $values['top_n_value'] = get_parameter('quantity'); + $values['text'] = get_parameter('text'); + $values['show_graph'] = get_parameter('combo_graph_options'); + $good_format = true; + break; + } + + + + $values['server_name'] = get_parameter('server_name'); + $server_id = (int) get_parameter('server_id'); + if ($server_id != 0) { + $connection = metaconsole_get_connection_by_id($server_id); + + $values['server_name'] = $connection['server_name']; + } + + if ($values['server_name'] == '') { + $values['server_name'] = get_parameter('combo_server'); + } + + + if (is_metaconsole()) { + // For SQL Query check if it is setted in the meta + if ($values['type'] == 'sql') { + if (empty($values['server_name'])) { + $good_format = false; + } + } + } + + + $values['id_agent'] = get_parameter('id_agent'); + $values['id_gs'] = get_parameter('id_custom_graph'); + if (($values['type'] == 'alert_report_agent') or ($values['type'] == 'event_report_agent') or ($values['type'] == 'agent_configuration') or ($values['type'] == 'group_configuration')) { + $values['id_agent_module'] = ''; + } else { + $values['id_agent_module'] = get_parameter('id_agent_module'); + } + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $values['only_display_wrong'] = (int) get_parameter('checkbox_only_display_wrong', 0); + break; + + case 'oracle': + $only_display_wrong_tmp = get_parameter('checkbox_only_display_wrong'); + if (empty($only_display_wrong_tmp)) { + $values['only_display_wrong'] = 0; + } else { + $values['only_display_wrong'] = $only_display_wrong_tmp; + } + break; + } + + $values['monday'] = get_parameter('monday', 0); + $values['tuesday'] = get_parameter('tuesday', 0); + $values['wednesday'] = get_parameter('wednesday', 0); + $values['thursday'] = get_parameter('thursday', 0); + $values['friday'] = get_parameter('friday', 0); + $values['saturday'] = get_parameter('saturday', 0); + $values['sunday'] = get_parameter('sunday', 0); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $values['time_from'] = get_parameter('time_from'); + $values['time_to'] = get_parameter('time_to'); + break; + + case 'oracle': + $values['time_from'] = '#to_date(\''.get_parameter('time_from').'\',\'hh24:mi:ss\')'; + $values['time_to'] = '#to_date(\''.get_parameter('time_to').'\', \'hh24:mi:ss\')'; + break; + } + + $values['group_by_agent'] = get_parameter('checkbox_row_group_by_agent', 0); + $values['show_resume'] = get_parameter('checkbox_show_resume', 0); + $values['order_uptodown'] = get_parameter('radiobutton_order_uptodown', 0); + $values['exception_condition'] = (int) get_parameter('radiobutton_exception_condition', 0); + $values['exception_condition_value'] = get_parameter('exception_condition_value'); + $values['id_module_group'] = get_parameter('combo_modulegroup'); + $values['id_group'] = get_parameter('combo_group'); + + + if ((($values['type'] == 'custom_graph') or ($values['type'] == 'automatic_custom_graph')) && ($values['id_gs'] == 0 || $values['id_gs'] == '')) { + $resultOperationDB = false; + break; + } + + if ($config['metaconsole'] == 1 && defined('METACONSOLE')) { + if (($values['type'] == 'custom_graph') or ($values['type'] == 'automatic_custom_graph')) { + $id_gs = substr($values['id_gs'], 0, strpos($values['id_gs'], '|')); + if ($id_gs !== false && $id_gs !== '') { + $server_name = strstr($values['id_gs'], '|'); + $values['id_gs'] = $id_gs; + $values['server_name'] = substr($server_name, 1, strlen($server_name)); + } + } + } + + if (($values['type'] == 'sql') or ($values['type'] == 'sql_graph_hbar') + or ($values['type'] == 'sql_graph_vbar') or ($values['type'] == 'sql_graph_pie') + ) { + $values['treport_custom_sql_id'] = get_parameter('id_custom'); + if ($values['treport_custom_sql_id'] == 0) { + $values['external_source'] = get_parameter('sql'); + } + + $values['historical_db'] = get_parameter('historical_db_check'); + $values['top_n_value'] = get_parameter('max_items'); + } else if ($values['type'] == 'url') { + $values['external_source'] = get_parameter('url'); + } else if ($values['type'] == 'event_report_group') { + $values['id_agent'] = get_parameter('group'); + } + + $values['header_definition'] = get_parameter('header'); + $values['column_separator'] = get_parameter('field'); + $values['line_separator'] = get_parameter('line'); + + $style = []; + $style['show_in_same_row'] = get_parameter('show_in_same_row', 0); + $style['show_in_landscape'] = get_parameter('show_in_landscape', 0); + $style['hide_notinit_agents'] = get_parameter('hide_notinit_agents', 0); + $style['priority_mode'] = get_parameter('priority_mode', REPORT_PRIORITY_MODE_OK); + $style['dyn_height'] = get_parameter('dyn_height', 230); + + switch ($values['type']) { + case 'event_report_agent': + case 'event_report_group': + case 'event_report_module': + $show_summary_group = get_parameter('show_summary_group', 0); + $filter_event_severity = get_parameter('filter_event_severity', ''); + $filter_event_type = get_parameter('filter_event_type', ''); + $filter_event_status = get_parameter('filter_event_status', ''); + + $event_graph_by_agent = get_parameter('event_graph_by_agent', 0); + $event_graph_by_user_validator = get_parameter('event_graph_by_user_validator', 0); + $event_graph_by_criticity = get_parameter('event_graph_by_criticity', 0); + $event_graph_validated_vs_unvalidated = get_parameter('event_graph_validated_vs_unvalidated', 0); + + $event_filter_search = get_parameter('filter_search', ''); + + // Added for events items + $style['show_summary_group'] = $show_summary_group; + $style['filter_event_severity'] = json_encode($filter_event_severity); + $style['filter_event_type'] = json_encode($filter_event_type); + $style['filter_event_status'] = json_encode($filter_event_status); + + $style['event_graph_by_agent'] = $event_graph_by_agent; + $style['event_graph_by_user_validator'] = $event_graph_by_user_validator; + $style['event_graph_by_criticity'] = $event_graph_by_criticity; + $style['event_graph_validated_vs_unvalidated'] = $event_graph_validated_vs_unvalidated; + + + switch ($values['type']) { + case 'event_report_group': + case 'event_report_agent': + $style['event_filter_search'] = $event_filter_search; + if ($label != '') { + $style['label'] = $label; + } else { + $style['label'] = ''; + } + break; + } + break; + + case 'simple_graph': + // Warning. We are using this column to hold this value to avoid + // the modification of the database for compatibility reasons. + $style['percentil'] = (int) get_parameter('percentil'); + $style['fullscale'] = (int) get_parameter('fullscale'); + if ($label != '') { + $style['label'] = $label; + } else { + $style['label'] = ''; + } + break; + + case 'network_interfaces_report': + $style['fullscale'] = (int) get_parameter('fullscale'); + break; + + case 'module_histogram_graph': + case 'agent_configuration': + case 'alert_report_agent': + case 'alert_report_module': + case 'historical_data': + case 'sumatory': + case 'database_serialized': + case 'monitor_report': + case 'min_value': + case 'max_value': + case 'avg_value': + case 'projection_graph': + case 'prediction_date': + case 'TTRT': + case 'TTO': + case 'MTBF': + case 'MTTR': + case 'simple_baseline_graph': + if ($label != '') { + $style['label'] = $label; + } else { + $style['label'] = ''; + } + break; + } + + $values['style'] = io_safe_input(json_encode($style)); + + if ($good_format) { + switch ($config['dbtype']) { + case 'oracle': + if (isset($values['type'])) { + $values[db_escape_key_identifier( + 'type' + )] = $values['type']; + unset($values['type']); + } + break; + } + + $result = db_process_sql_insert( + 'treport_content', + $values + ); + + if ($result === false) { + $resultOperationDB = false; + } else { + $idItem = $result; + + switch ($config['dbtype']) { + case 'mysql': + $max = db_get_all_rows_sql( + 'SELECT max(`order`) AS max FROM treport_content - WHERE id_report = ' . $idReport . ';'); - break; - case "postgresql": - case "oracle": - $max = db_get_all_rows_sql( - 'SELECT max("order") AS max + WHERE id_report = '.$idReport.';' + ); + break; + + case 'postgresql': + case 'oracle': + $max = db_get_all_rows_sql( + 'SELECT max("order") AS max FROM treport_content - WHERE id_report = ' . $idReport); - break; - } - if ($max === false) { - $max = 0; - } - else { - $max = $max[0]['max']; - } - switch ($config["dbtype"]) { - case "mysql": - db_process_sql_update('treport_content', - array('`order`' => $max + 1), - array('id_rc' => $idItem)); - break; - case "postgresql": - case "oracle": - db_process_sql_update('treport_content', - array('"order"' => $max + 1), - array('id_rc' => $idItem)); - break; - } - $resultOperationDB = true; - } - break; - } - // If fields dont have good format - else { - $resultOperationDB = false; - } - } - break; - default: - if ($enterpriseEnable and $activeTab != 'advanced') { - $resultOperationDB = reporting_enterprise_update_action(); - } - break; - } - break; - case 'filter': - case 'edit': - $resultOperationDB = null; - $report = db_get_row_filter('treport', - array('id_report' => $idReport)); - - $reportName = $report['name']; - $idGroupReport = $report['id_group']; - $description = $report['description']; - $type_access_selected = reports_get_type_access($report); - $id_group_edit = $report['id_group_edit']; - $report_id_user = $report['id_user']; - $non_interactive = $report['non_interactive']; - break; - case 'delete': - $idItem = get_parameter('id_item'); - - $report = db_get_row_filter('treport', array('id_report' => $idReport)); - $reportName = $report['name']; - - $resultOperationDB = db_process_sql_delete('treport_content_sla_combined', array('id_report_content' => $idItem)); - $resultOperationDB2 = db_process_sql_delete('treport_content_item', array('id_report_content' => $idItem)); - if ($resultOperationDB !== false) { - $resultOperationDB = db_process_sql_delete('treport_content', array('id_rc' => $idItem)); - } - if ($resultOperationDB2 !== false) { - $resultOperationDB2 = db_process_sql_delete('treport_content', array('id_rc' => $idItem)); - } - break; - case 'order': - $resultOperationDB = null; - $report = db_get_row_filter('treport', array('id_report' => $idReport)); - - $reportName = $report['name']; - $idGroupReport = $report['id_group']; - $description = $report['description']; - - $idItem = get_parameter('id_item'); - $dir = get_parameter('dir'); - $field = get_parameter('field', null); - - switch ($field) { - case 'module': - case 'agent': - case 'type': - - // Sort functionality for normal console - if (!defined('METACONSOLE')) { - switch ($field) { - case 'module': - $sql = " + WHERE id_report = '.$idReport + ); + break; + } + + if ($max === false) { + $max = 0; + } else { + $max = $max[0]['max']; + } + + switch ($config['dbtype']) { + case 'mysql': + db_process_sql_update( + 'treport_content', + ['`order`' => ($max + 1)], + ['id_rc' => $idItem] + ); + break; + + case 'postgresql': + case 'oracle': + db_process_sql_update( + 'treport_content', + ['"order"' => ($max + 1)], + ['id_rc' => $idItem] + ); + break; + } + + $resultOperationDB = true; + } + + break; + } + // If fields dont have good format + else { + $resultOperationDB = false; + } + } + break; + + default: + if ($enterpriseEnable and $activeTab != 'advanced') { + $resultOperationDB = reporting_enterprise_update_action(); + } + break; + } + break; + + case 'filter': + case 'edit': + $resultOperationDB = null; + $report = db_get_row_filter( + 'treport', + ['id_report' => $idReport] + ); + + $reportName = $report['name']; + $idGroupReport = $report['id_group']; + $description = $report['description']; + $type_access_selected = reports_get_type_access($report); + $id_group_edit = $report['id_group_edit']; + $report_id_user = $report['id_user']; + $non_interactive = $report['non_interactive']; + break; + + case 'delete': + $idItem = get_parameter('id_item'); + + $report = db_get_row_filter('treport', ['id_report' => $idReport]); + $reportName = $report['name']; + + $resultOperationDB = db_process_sql_delete('treport_content_sla_combined', ['id_report_content' => $idItem]); + $resultOperationDB2 = db_process_sql_delete('treport_content_item', ['id_report_content' => $idItem]); + if ($resultOperationDB !== false) { + $resultOperationDB = db_process_sql_delete('treport_content', ['id_rc' => $idItem]); + } + + if ($resultOperationDB2 !== false) { + $resultOperationDB2 = db_process_sql_delete('treport_content', ['id_rc' => $idItem]); + } + break; + + case 'order': + $resultOperationDB = null; + $report = db_get_row_filter('treport', ['id_report' => $idReport]); + + $reportName = $report['name']; + $idGroupReport = $report['id_group']; + $description = $report['description']; + + $idItem = get_parameter('id_item'); + $dir = get_parameter('dir'); + $field = get_parameter('field', null); + + switch ($field) { + case 'module': + case 'agent': + case 'type': + + // Sort functionality for normal console + if (!defined('METACONSOLE')) { + switch ($field) { + case 'module': + $sql = ' SELECT t1.id_rc, t2.nombre FROM treport_content t1 LEFT JOIN tagente_modulo t2 ON t1.id_agent_module = t2.id_agente_modulo WHERE %s ORDER BY nombre %s - "; - break; - case 'agent': - $sql = " + '; + break; + + case 'agent': + $sql = ' SELECT t4.id_rc, t5.nombre FROM ( @@ -1800,360 +1989,408 @@ switch ($action) { ON (t4.id_agent = t5.id_agente OR t4.id_agente = t5.id_agente) WHERE %s ORDER BY t5.nombre %s - "; - break; - case 'type': - $sql = "SELECT id_rc FROM treport_content WHERE %s ORDER BY type %s"; - break; - } - $sql = sprintf($sql, 'id_report = ' . $idReport, '%s'); - switch ($dir) { - case 'up': - $sql = sprintf($sql, 'ASC'); - break; - case 'down': - $sql = sprintf($sql, 'DESC'); - break; - } - - $ids = db_get_all_rows_sql($sql); - - } - // Sort functionality for metaconsole - else if ($config['metaconsole'] == 1) { - switch ($field) { - case 'agent': - case 'module': - $sql = "SELECT id_rc, id_agent, id_agent_module, server_name FROM treport_content WHERE %s ORDER BY server_name"; - $sql = sprintf($sql, 'id_report = ' . $idReport, '%s'); - - $report_items = db_get_all_rows_sql($sql); - - $ids = array(); - $temp_sort = array(); - $i = 0; - - if (!empty($report_items)) { - - foreach ($report_items as $report_item) { - - $connection = metaconsole_get_connection($report_item['server_name']); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_name); - } - - switch ($field) { - case 'agent': - $agents_name = agents_get_agents(array('id_agente' => $report_item['id_agent']), 'nombre'); - - // Item without agent - if (!$agents_name) - $element_name = ''; - else { - $agent_name = array_shift($agents_name); - $element_name = $agent_name['nombre']; - } - - break; - - case 'module': - $module_name = modules_get_agentmodule_name($report_item['id_agent_module']); - - // Item without module - if (!$module_name) - $element_name = ''; - else { - $element_name = $module_name; - } - - break; - } - - metaconsole_restore_db(); - - $temp_sort[$report_item['id_rc']] = $element_name; - - } - - // Performes sorting - switch ($dir) { - case 'up': - asort($temp_sort); - break; - case 'down': - arsort($temp_sort); - break; - } - - foreach ($temp_sort as $temp_element_key => $temp_element_val) { - $ids[$i]['id_rc'] = $temp_element_key; - $ids[$i]['element_name'] = $temp_element_val; - $i++; - } - - // Free resources - unset($temp_sort); - unset($report_items); - - } - - break; - // Type case only depends of local database - case 'type': - $sql = "SELECT id_rc + '; + break; + + case 'type': + $sql = 'SELECT id_rc FROM treport_content WHERE %s ORDER BY type %s'; + break; + } + + $sql = sprintf($sql, 'id_report = '.$idReport, '%s'); + switch ($dir) { + case 'up': + $sql = sprintf($sql, 'ASC'); + break; + + case 'down': + $sql = sprintf($sql, 'DESC'); + break; + } + + $ids = db_get_all_rows_sql($sql); + } + // Sort functionality for metaconsole + else if ($config['metaconsole'] == 1) { + switch ($field) { + case 'agent': + case 'module': + $sql = 'SELECT id_rc, id_agent, id_agent_module, server_name FROM treport_content WHERE %s ORDER BY server_name'; + $sql = sprintf($sql, 'id_report = '.$idReport, '%s'); + + $report_items = db_get_all_rows_sql($sql); + + $ids = []; + $temp_sort = []; + $i = 0; + + if (!empty($report_items)) { + foreach ($report_items as $report_item) { + $connection = metaconsole_get_connection($report_item['server_name']); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + } + + switch ($field) { + case 'agent': + $agents_name = agents_get_agents(['id_agente' => $report_item['id_agent']], 'nombre'); + + // Item without agent + if (!$agents_name) { + $element_name = ''; + } else { + $agent_name = array_shift($agents_name); + $element_name = $agent_name['nombre']; + } + break; + + case 'module': + $module_name = modules_get_agentmodule_name($report_item['id_agent_module']); + + // Item without module + if (!$module_name) { + $element_name = ''; + } else { + $element_name = $module_name; + } + break; + } + + metaconsole_restore_db(); + + $temp_sort[$report_item['id_rc']] = $element_name; + } + + // Performes sorting + switch ($dir) { + case 'up': + asort($temp_sort); + break; + + case 'down': + arsort($temp_sort); + break; + } + + foreach ($temp_sort as $temp_element_key => $temp_element_val) { + $ids[$i]['id_rc'] = $temp_element_key; + $ids[$i]['element_name'] = $temp_element_val; + $i++; + } + + // Free resources + unset($temp_sort); + unset($report_items); + } + break; + + // Type case only depends of local database + case 'type': + $sql = 'SELECT id_rc FROM treport_content - WHERE %s ORDER BY type %s"; - - $sql = sprintf($sql, - 'id_report = ' . $idReport, '%s'); - switch ($dir) { - case 'up': - $sql = sprintf($sql, 'ASC'); - break; - case 'down': - $sql = sprintf($sql, 'DESC'); - break; - } - - $ids = db_get_all_rows_sql($sql); - - break; - } - - - } - - $count = 1; - $resultOperationDB = true; - foreach($ids as $id) { - $result = db_process_sql_update('treport_content', array('order' => $count), array('id_rc' => $id['id_rc'])); - - if ($result === false) { - $resultOperationDB = false; - break; - } - - $count = $count + 1; - } - - break; - default: - switch ($config["dbtype"]) { - case "mysql": - $oldOrder = db_get_value_sql(' + WHERE %s ORDER BY type %s'; + + $sql = sprintf( + $sql, + 'id_report = '.$idReport, + '%s' + ); + switch ($dir) { + case 'up': + $sql = sprintf($sql, 'ASC'); + break; + + case 'down': + $sql = sprintf($sql, 'DESC'); + break; + } + + $ids = db_get_all_rows_sql($sql); + + break; + } + } + + $count = 1; + $resultOperationDB = true; + foreach ($ids as $id) { + $result = db_process_sql_update('treport_content', ['order' => $count], ['id_rc' => $id['id_rc']]); + + if ($result === false) { + $resultOperationDB = false; + break; + } + + $count = ($count + 1); + } + break; + + default: + switch ($config['dbtype']) { + case 'mysql': + $oldOrder = db_get_value_sql( + ' SELECT `order` FROM treport_content - WHERE id_rc = ' . $idItem); - break; - case "postgresql": - case "oracle": - $oldOrder = db_get_value_sql(' + WHERE id_rc = '.$idItem + ); + break; + + case 'postgresql': + case 'oracle': + $oldOrder = db_get_value_sql( + ' SELECT "order" FROM treport_content - WHERE id_rc = ' . $idItem); - break; - } - //db_get_value_filter('order', 'treport_content', array('id_rc' => $idItem)); - - switch ($dir) { - case 'up': - $newOrder = $oldOrder - 1; - break; - case 'down': - $newOrder = $oldOrder + 1; - break; - } - - switch ($config["dbtype"]) { - case "mysql": - $resultOperationDB = db_process_sql_update('treport_content', - array('`order`' => $oldOrder), - array('`order`' => $newOrder, - 'id_report' => $idReport)); - break; - case "postgresql": - $resultOperationDB = db_process_sql_update('treport_content', - array('"order"' => $oldOrder), - array('"order"' => $newOrder, - 'id_report' => $idReport)); - break; - case "oracle": - $resultOperationDB = db_process_sql_update('treport_content', - array('"order"' => $oldOrder), - array('"order"' => $newOrder, - 'id_report' => $idReport), - 'AND', false); - break; - } - if ($resultOperationDB !== false) { - switch ($config["dbtype"]) { - case "mysql": - $resultOperationDB = db_process_sql_update( - 'treport_content', - array('`order`' => $newOrder), array('id_rc' => $idItem)); - break; - case "postgresql": - $resultOperationDB = db_process_sql_update( - 'treport_content', - array('"order"' => $newOrder), array('id_rc' => $idItem)); - break; - case "oracle": - $resultOperationDB = db_process_sql_update( - 'treport_content', - array('"order"' => $newOrder), array('id_rc' => $idItem), - 'AND', false); - break; - } - } - - break; - } - break; - // Added for report templates - default: - if ($enterpriseEnable) { - $buttons = array( - 'list_reports' => array('active' => false, - 'text' => '' . - html_print_image("images/report_list.png", true, array ("title" => __('Reports list'))) .'') - ); - - $buttons = reporting_enterprise_add_main_Tabs($buttons); - - $subsection = ''; - switch ($activeTab) { - case 'main': - $buttons['list_reports']['active'] = true; - $subsection = __('Custom reporting'); - break; - default: - $subsection = reporting_enterprise_add_subsection_main($activeTab, $buttons); - break; - } - - // Page header for metaconsole - if ($enterpriseEnable and defined('METACONSOLE')) { - // Bread crumbs - ui_meta_add_breadcrumb( - array( - 'link' => 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&pure='.$pure, - 'text' => __('Reporting'))); - - ui_meta_print_page_header($nav_bar); - - // Print header - ui_meta_print_header(__('Reporting'), "", $buttons); - } - // Page header for normal console - else - ui_print_page_header ($subsection, "images/op_reporting.png", false, "", false, $buttons,false,'',60); - - - reporting_enterprise_select_main_tab($action); - - } - - return; - break; + WHERE id_rc = '.$idItem + ); + break; + } + + // db_get_value_filter('order', 'treport_content', array('id_rc' => $idItem)); + switch ($dir) { + case 'up': + $newOrder = ($oldOrder - 1); + break; + + case 'down': + $newOrder = ($oldOrder + 1); + break; + } + + switch ($config['dbtype']) { + case 'mysql': + $resultOperationDB = db_process_sql_update( + 'treport_content', + ['`order`' => $oldOrder], + [ + '`order`' => $newOrder, + 'id_report' => $idReport, + ] + ); + break; + + case 'postgresql': + $resultOperationDB = db_process_sql_update( + 'treport_content', + ['"order"' => $oldOrder], + [ + '"order"' => $newOrder, + 'id_report' => $idReport, + ] + ); + break; + + case 'oracle': + $resultOperationDB = db_process_sql_update( + 'treport_content', + ['"order"' => $oldOrder], + [ + '"order"' => $newOrder, + 'id_report' => $idReport, + ], + 'AND', + false + ); + break; + } + + if ($resultOperationDB !== false) { + switch ($config['dbtype']) { + case 'mysql': + $resultOperationDB = db_process_sql_update( + 'treport_content', + ['`order`' => $newOrder], + ['id_rc' => $idItem] + ); + break; + + case 'postgresql': + $resultOperationDB = db_process_sql_update( + 'treport_content', + ['"order"' => $newOrder], + ['id_rc' => $idItem] + ); + break; + + case 'oracle': + $resultOperationDB = db_process_sql_update( + 'treport_content', + ['"order"' => $newOrder], + ['id_rc' => $idItem], + 'AND', + false + ); + break; + } + } + break; + } + break; + + // Added for report templates + default: + if ($enterpriseEnable) { + $buttons = [ + 'list_reports' => [ + 'active' => false, + 'text' => ''.html_print_image('images/report_list.png', true, ['title' => __('Reports list')]).'', + ], + ]; + + $buttons = reporting_enterprise_add_main_Tabs($buttons); + + $subsection = ''; + switch ($activeTab) { + case 'main': + $buttons['list_reports']['active'] = true; + $subsection = __('Custom reporting'); + break; + + default: + $subsection = reporting_enterprise_add_subsection_main($activeTab, $buttons); + break; + } + + // Page header for metaconsole + if ($enterpriseEnable and defined('METACONSOLE')) { + // Bread crumbs + ui_meta_add_breadcrumb( + [ + 'link' => 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&pure='.$pure, + 'text' => __('Reporting'), + ] + ); + + ui_meta_print_page_header($nav_bar); + + // Print header + ui_meta_print_header(__('Reporting'), '', $buttons); + } + // Page header for normal console + else { + ui_print_page_header($subsection, 'images/op_reporting.png', false, '', false, $buttons, false, '', 60); + } + + + reporting_enterprise_select_main_tab($action); + } + return; + break; } if ($enterpriseEnable) { - $result = reporting_enterprise_actions_DB($action, $activeTab, $idReport); - if ($result !== null) { - $resultOperationDB = $result; - } + $result = reporting_enterprise_actions_DB($action, $activeTab, $idReport); + if ($result !== null) { + $resultOperationDB = $result; + } } -$buttons = array( - 'list_reports' => array('active' => false, - 'text' => '' . - html_print_image("images/report_list.png", true, array ("title" => __('Reports list'))) .''), - 'main' => array('active' => false, - 'text' => '' . - html_print_image("images/op_reporting.png", true, array ("title" => __('Main data'))) .''), - 'list_items' => array('active' => false, - 'text' => '' . - html_print_image("images/list.png", true, array ("title" => __('List items'))) .''), - 'item_editor' => array('active' => false, - 'text' => '' . - html_print_image("images/pen.png", true, array ("title" => __('Item editor'))) .'') - ); +$buttons = [ + 'list_reports' => [ + 'active' => false, + 'text' => ''.html_print_image('images/report_list.png', true, ['title' => __('Reports list')]).'', + ], + 'main' => [ + 'active' => false, + 'text' => ''.html_print_image('images/op_reporting.png', true, ['title' => __('Main data')]).'', + ], + 'list_items' => [ + 'active' => false, + 'text' => ''.html_print_image('images/list.png', true, ['title' => __('List items')]).'', + ], + 'item_editor' => [ + 'active' => false, + 'text' => ''.html_print_image('images/pen.png', true, ['title' => __('Item editor')]).'', + ], +]; if ($enterpriseEnable) { - $buttons = reporting_enterprise_add_Tabs($buttons, $idReport); + $buttons = reporting_enterprise_add_Tabs($buttons, $idReport); } -$buttons['view'] = array('active' => false, - 'text' => '' . - html_print_image("images/operation.png", true, array ("title" => __('View report'))) .''); +$buttons['view'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/operation.png', true, ['title' => __('View report')]).'', +]; $buttons[$activeTab]['active'] = true; if ($idReport != 0) { - $textReportName = $reportName; -} -else { - $temp = $buttons['main']; - $buttons = null; - $buttons = array( - 'main' => array('active' => true, - 'text' => '' . - html_print_image("images/report_list.png", true, array ("title" => __('Reports list'))) .'')); - $textReportName = __('Create Custom Report'); + $textReportName = $reportName; +} else { + $temp = $buttons['main']; + $buttons = null; + $buttons = [ + 'main' => [ + 'active' => true, + 'text' => ''.html_print_image('images/report_list.png', true, ['title' => __('Reports list')]).'', + ], + ]; + $textReportName = __('Create Custom Report'); } // Page header for metaconsole if ($enterpriseEnable and defined('METACONSOLE')) { - // Bread crumbs - ui_meta_add_breadcrumb( - array('link' => - 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&pure=' . $pure, - 'text' => __('Reporting'))); - - ui_meta_print_page_header($nav_bar); - - //Print header - ui_meta_print_header(__('Reporting'). $textReportName, "", $buttons); -} -else { - ui_print_page_header($textReportName, - "images/op_reporting.png", false, - "reporting_" . $activeTab . "_tab", false, $buttons,false,'',60); + // Bread crumbs + ui_meta_add_breadcrumb( + [ + 'link' => 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&pure='.$pure, + 'text' => __('Reporting'), + ] + ); + + ui_meta_print_page_header($nav_bar); + + // Print header + ui_meta_print_header(__('Reporting').$textReportName, '', $buttons); +} else { + ui_print_page_header( + $textReportName, + 'images/op_reporting.png', + false, + 'reporting_'.$activeTab.'_tab', + false, + $buttons, + false, + '', + 60 + ); } if ($resultOperationDB !== null) { - $err = ''; - switch ($_POST['type']) { - case 'custom_graph': - $err.='You must enter custom graph'; - break; - case 'SLA': - $err.='You must enter some character in SLA limit field'; - default: - $err.=''; - break; - } - ui_print_result_message ($resultOperationDB, __('Successfull action'), __('Unsuccessful action

    '.$err)); + $err = ''; + switch ($_POST['type']) { + case 'custom_graph': + $err .= 'You must enter custom graph'; + break; + + case 'SLA': + $err .= 'You must enter some character in SLA limit field'; + default: + $err .= ''; + break; + } + + ui_print_result_message($resultOperationDB, __('Successfull action'), __('Unsuccessful action

    '.$err)); } switch ($activeTab) { - case 'main': - require_once($config['homedir'] . - '/godmode/reporting/reporting_builder.main.php'); - break; - case 'list_items': - require_once($config['homedir'] . - '/godmode/reporting/reporting_builder.list_items.php'); - break; - case 'item_editor': - require_once($config['homedir'] . - '/godmode/reporting/reporting_builder.item_editor.php'); - break; - default: - reporting_enterprise_select_tab($activeTab); - break; + case 'main': + include_once $config['homedir'].'/godmode/reporting/reporting_builder.main.php'; + break; + + case 'list_items': + include_once $config['homedir'].'/godmode/reporting/reporting_builder.list_items.php'; + break; + + case 'item_editor': + include_once $config['homedir'].'/godmode/reporting/reporting_builder.item_editor.php'; + break; + + default: + reporting_enterprise_select_tab($activeTab); + break; } enterprise_hook('close_meta_frame'); -?> - diff --git a/pandora_console/godmode/reporting/visual_console_builder.data.php b/pandora_console/godmode/reporting/visual_console_builder.data.php index 1a620ae43f..0b765debad 100644 --- a/pandora_console/godmode/reporting/visual_console_builder.data.php +++ b/pandora_console/godmode/reporting/visual_console_builder.data.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,383 +10,422 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Login check global $config; -check_login (); +check_login(); if (empty($idVisualConsole)) { - // ACL for the a new visual console - // if (!isset($vconsole_read)) - // $vconsole_read = check_acl ($config['id_user'], 0, "VR"); - if (!isset($vconsole_write)) - $vconsole_write = check_acl ($config['id_user'], 0, "VW"); - if (!isset($vconsole_manage)) - $vconsole_manage = check_acl ($config['id_user'], 0, "VM"); -} -else { - // ACL for the existing visual console - // if (!isset($vconsole_read)) - // $vconsole_read = check_acl ($config['id_user'], $idGroup, "VR"); - if (!isset($vconsole_write)) - $vconsole_write = check_acl ($config['id_user'], $idGroup, "VW"); - if (!isset($vconsole_manage)) - $vconsole_manage = check_acl ($config['id_user'], $idGroup, "VM"); + // ACL for the a new visual console + // if (!isset($vconsole_read)) + // $vconsole_read = check_acl ($config['id_user'], 0, "VR"); + if (!isset($vconsole_write)) { + $vconsole_write = check_acl($config['id_user'], 0, 'VW'); + } + + if (!isset($vconsole_manage)) { + $vconsole_manage = check_acl($config['id_user'], 0, 'VM'); + } +} else { + // ACL for the existing visual console + // if (!isset($vconsole_read)) + // $vconsole_read = check_acl ($config['id_user'], $idGroup, "VR"); + if (!isset($vconsole_write)) { + $vconsole_write = check_acl($config['id_user'], $idGroup, 'VW'); + } + + if (!isset($vconsole_manage)) { + $vconsole_manage = check_acl($config['id_user'], $idGroup, 'VM'); + } } if (!$vconsole_write && !$vconsole_manage) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } -require_once ($config['homedir'] . '/include/functions_visual_map.php'); -require_once ($config['homedir'] . '/include/functions_users.php'); +require_once $config['homedir'].'/include/functions_visual_map.php'; +require_once $config['homedir'].'/include/functions_users.php'; $pure = get_parameter('pure', 0); switch ($action) { - case 'new': - if (!defined('METACONSOLE')) { - echo "
    "; - html_print_input_hidden('action', 'save'); - } - else { - echo ''; - html_print_input_hidden('action2', 'save'); - } - - break; - case 'update': - case 'save': - if (!defined('METACONSOLE')) { - echo ""; - html_print_input_hidden('action', 'update'); - } - else { - //echo ''; - echo ""; - html_print_input_hidden('action2', 'update'); - } - break; - case 'edit': - if (!defined('METACONSOLE')) { - echo ""; - html_print_input_hidden('action', 'update'); - } - else { - echo ""; - html_print_input_hidden('action2', 'update'); - } - break; + case 'new': + if (!defined('METACONSOLE')) { + echo ""; + html_print_input_hidden('action', 'save'); + } else { + echo ''; + html_print_input_hidden('action2', 'save'); + } + break; + + case 'update': + case 'save': + if (!defined('METACONSOLE')) { + echo ""; + html_print_input_hidden('action', 'update'); + } else { + // echo ''; + echo ""; + html_print_input_hidden('action2', 'update'); + } + break; + + case 'edit': + if (!defined('METACONSOLE')) { + echo ""; + html_print_input_hidden('action', 'update'); + } else { + echo ""; + html_print_input_hidden('action2', 'update'); + } + break; } $table = new stdClass(); $table->width = '100%'; if (defined('METACONSOLE')) { - $table->class = 'databox data'; - $table->head[0] = __("Create visual console"); - $table->head_colspan[0] = 5; - $table->headstyle[0] = 'text-align: center'; - $table->align[0] = 'left'; - $table->align[1] = 'left'; + $table->class = 'databox data'; + $table->head[0] = __('Create visual console'); + $table->head_colspan[0] = 5; + $table->headstyle[0] = 'text-align: center'; + $table->align[0] = 'left'; + $table->align[1] = 'left'; } + $table->class = 'databox filters'; $table->size[0] = '20%'; $table->size[1] = '20%'; $table->size[1] = '50%'; -$table->data = array (); -$table->data[0][0] = __('Name:') . - ui_print_help_tip(__("Use [ or ( as first character, for example '[*] Map name', to render this map name in main menu"), true); +$table->data = []; +$table->data[0][0] = __('Name:').ui_print_help_tip(__("Use [ or ( as first character, for example '[*] Map name', to render this map name in main menu"), true); -$table->data[0][1] = html_print_input_text('name', $visualConsoleName, - '', 80, 100, true); +$table->data[0][1] = html_print_input_text( + 'name', + $visualConsoleName, + '', + 80, + 100, + true +); $table->rowspan[0][2] = 6; if ($action == 'new') { - $table->data[0][2] = 'data[0][2] = ''; - $table->data[0][2] .= 'data[0][2] .= ''; -} -else { - if(defined('METACONSOLE')){ - $table->data[0][2] = 'data[0][2] = ''; - } else { - $table->data[0][2] = 'data[0][2] = ''; - } - - $table->data[0][2] .= 'data[0][2] .= ''; } - + $table->data[1][0] = __('Group:'); -$table->data[1][1] = html_print_select_groups($config['id_user'], "RW", - true, 'id_group', $idGroup, '', '', '', true); +$table->data[1][1] = html_print_select_groups( + $config['id_user'], + 'RW', + true, + 'id_group', + $idGroup, + '', + '', + '', + true +); $backgrounds_list = list_files( - $config['homedir'] . '/images/console/background/', "jpg", 1, 0); -$backgrounds_list = array_merge($backgrounds_list, - list_files($config['homedir'] . '/images/console/background/', "png", 1, 0)); + $config['homedir'].'/images/console/background/', + 'jpg', + 1, + 0 +); +$backgrounds_list = array_merge( + $backgrounds_list, + list_files($config['homedir'].'/images/console/background/', 'png', 1, 0) +); $table->data[2][0] = __('Background'); -$table->data[2][1] = html_print_select($backgrounds_list, 'background', - $background, '', 'None', 'None.png', true); +$table->data[2][1] = html_print_select( + $backgrounds_list, + 'background', + $background, + '', + 'None', + 'None.png', + true +); $table->data[3][0] = __('Background image'); -$table->data[3][1] = html_print_input_file('background_image',true); +$table->data[3][1] = html_print_input_file('background_image', true); $table->data[4][0] = __('Background color'); if ($action == 'new') { - $table->data[4][1] .= html_print_input_text ('background_color', - 'white', '', 8, 8, true); -} -else { - $table->data[4][1] .= html_print_input_text ('background_color', - $background_color, '', 8, 8, true); + $table->data[4][1] .= html_print_input_text( + 'background_color', + 'white', + '', + 8, + 8, + true + ); +} else { + $table->data[4][1] .= html_print_input_text( + 'background_color', + $background_color, + '', + 8, + 8, + true + ); } -if($idVisualConsole){ - $preimageh = db_get_value_sql('select height from tlayout where id ='.$idVisualConsole); - $preimagew = db_get_value_sql('select width from tlayout where id ='.$idVisualConsole); -} -else{ - $preimageh = 768; - $preimagew = 1024; +if ($idVisualConsole) { + $preimageh = db_get_value_sql('select height from tlayout where id ='.$idVisualConsole); + $preimagew = db_get_value_sql('select width from tlayout where id ='.$idVisualConsole); +} else { + $preimageh = 768; + $preimagew = 1024; } $table->data[5][0] = __('Layout size').': '.$preimagew.' x '.$preimageh.''; $table->data[5][1] = ''; + style="margin-right:20px;" value="modsize">'.__('Set custom size').''; -$table->data[5][1] .= ''; +$table->data[5][1] .= ''; $table->data[5][1] .= ''; + value="modsize">'.__('Get default image size').''; $table->data[6][0] = __('Favourite visual console'); $table->data[6][1] = html_print_checkbox('is_favourite', 0, $is_favourite, true); if ($action == 'new') { - $textButtonSubmit = __('Save'); - $classButtonSubmit = 'sub wand'; -} -else { - $textButtonSubmit = __('Update'); - $classButtonSubmit = 'sub upd'; + $textButtonSubmit = __('Save'); + $classButtonSubmit = 'sub wand'; +} else { + $textButtonSubmit = __('Update'); + $classButtonSubmit = 'sub upd'; } html_print_table($table); -echo '
    '; -html_print_submit_button ($textButtonSubmit, 'update_layout', false, - 'class="' . $classButtonSubmit . '"'); +echo '
    '; +html_print_submit_button( + $textButtonSubmit, + 'update_layout', + false, + 'class="'.$classButtonSubmit.'"' +); echo '
    '; -echo ""; -ui_require_css_file ("color-picker"); -ui_require_jquery_file ("colorpicker"); +echo ''; +ui_require_css_file('color-picker', 'include/styles/js/'); +ui_require_jquery_file('colorpicker'); ?> \ No newline at end of file diff --git a/pandora_console/godmode/reporting/visual_console_builder.editor.js b/pandora_console/godmode/reporting/visual_console_builder.editor.js index f6da2968e2..1ab1916927 100755 --- a/pandora_console/godmode/reporting/visual_console_builder.editor.js +++ b/pandora_console/godmode/reporting/visual_console_builder.editor.js @@ -26,4117 +26,5308 @@ var parents = {}; var obj_js_user_lines = null; - var SIZE_GRID = 16; //Const the size (for width and height) of grid. var img_handler_start; var img_handler_end; function toggle_advance_options_palette(close) { - if ($("#advance_options").css('display') == 'none') { - $("#advance_options").css('display', ''); - } - else { - $("#advance_options").css('display', 'none'); - } + if ($("#advance_options").css("display") == "none") { + $("#advance_options").css("display", ""); + } else { + $("#advance_options").css("display", "none"); + } - if (close == false) { - $("#advance_options").css('display', 'none'); - } + if (close == false) { + $("#advance_options").css("display", "none"); + } } // Main function, execute in event documentReady function visual_map_main() { - img_handler_start = "images/dot_red.png"; - img_handler_end = "images/dot_green.png"; - get_image_url(img_handler_start).done(function (data) { - img_handler_start = data; - }); - get_image_url(img_handler_end).done(function (data) { - img_handler_end = data; - }); + img_handler_start = "images/dot_red.png"; + img_handler_end = "images/dot_green.png"; + get_image_url(img_handler_start).done(function(data) { + img_handler_start = data; + }); + get_image_url(img_handler_end).done(function(data) { + img_handler_end = data; + }); - //Get the list of posible parents - parents = Base64.decode($("input[name='parents_load']").val()); - parents = eval("(" + parents + ")"); + //Get the list of posible parents + parents = Base64.decode($("input[name='parents_load']").val()); + parents = eval("(" + parents + ")"); - eventsBackground(); - eventsItems(); + eventsBackground(); + eventsItems(); - //Fixed to wait the load of images. - $(window).on('load', function() { - $('#module').change(function(){ - var txt = $("#module").val(); - if(selectedItem == 'simple_value' || creationItem == 'simple_value'){ - $.ajax({ - async:false, - type: "POST", - url: "ajax.php", - data: {"page" : "general/check_image_module", - "get_image" : txt, - }, - success: function(data) { - if(data == 0){ - $("#data_image_check").html('Off'); - $('#data_image_container').css('display','none'); - $('#data_image_check').css('display','none'); - $('#data_image_check_label').css('display','none'); - $('.block_tinymce').remove(); - $('#process_value_row').css('display','table-row'); - if($('#process_value').val() != '0'){ - $('#period_row').css('display','table-row'); - } - } - else{ - $('#data_image_container').css('display','inline'); - $('#data_image_check').css('display','inline'); - $('#data_image_check_label').css('display','inline'); - $("#data_image_check").html('On'); - $('#process_value_row').css('display','none'); - $('#period_row').css('display','none'); - $('#text-label_ifr').contents().find('#tinymce').html('_VALUE_'); - $('.block_tinymce').remove(); - $('#label_row').append('
    '); - } - } - }); - } - }); - - - // Begin - Background label color changer - - $( "#text-label_ifr" ).contents().find( "body" ).bind('mousewheel', function(e){ - e.preventDefault(); - - if($( "#text-label_ifr" ).contents().find( "body" ).css('background-color') == 'rgb(211, 211, 211)'){ - $( "#text-label_ifr" ).contents().find( "body" ).css('background-color','white'); - } - else{ - $( "#text-label_ifr" ).contents().find( "body" ).css('background-color','lightgray'); - } + //Fixed to wait the load of images. + $(window).on("load", function() { + $("#module").change(function() { + var txt = $("#module").val(); + if (selectedItem == "simple_value" || creationItem == "simple_value") { + $.ajax({ + async: false, + type: "POST", + url: "ajax.php", + data: { page: "general/check_image_module", get_image: txt }, + success: function(data) { + if (data == 0) { + $("#data_image_check").html("Off"); + $("#data_image_container").css("display", "none"); + $("#data_image_check").css("display", "none"); + $("#data_image_check_label").css("display", "none"); + $(".block_tinymce").remove(); + $("#process_value_row").css("display", "table-row"); + if ($("#process_value").val() != "0") { + $("#period_row").css("display", "table-row"); + } + } else { + $("#data_image_container").css("display", "inline"); + $("#data_image_check").css("display", "inline"); + $("#data_image_check_label").css("display", "inline"); + $("#data_image_check").html("On"); + $("#process_value_row").css("display", "none"); + $("#period_row").css("display", "none"); + $("#text-label_ifr") + .contents() + .find("#tinymce") + .html("_VALUE_"); + $(".block_tinymce").remove(); + $("#label_row").append( + '
    ' + ); + } + } + }); + } }); - - // End - Background label color changer - - $('#radiobtn0001').click(function(){ - $("#custom_graph option[value=0]").prop("selected", true); - }); - - $('.labelpos').click(function(event) { - if($("#hidden-metaconsole").val() == 1){ - $("#labelposup img").attr('src','../../images/label_up.png'); - $("#labelposdown img").attr('src','../../images/label_down.png'); - $("#labelposleft img").attr('src','../../images/label_left.png'); - $("#labelposright img").attr('src','../../images/label_right.png'); - $('.labelpos').attr('sel','no'); - $("#"+$(this).attr('id')+" img").attr('src','../../images/label_'+$(this).attr('id').replace('labelpos','')+'_2.png'); - $("#"+$(this).attr('id')).attr('sel','yes'); - } - else{ - $("#labelposup img").attr('src','images/label_up.png'); - $("#labelposdown img").attr('src','images/label_down.png'); - $("#labelposleft img").attr('src','images/label_left.png'); - $("#labelposright img").attr('src','images/label_right.png'); - $('.labelpos').attr('sel','no'); - $("#"+$(this).attr('id')+" img").attr('src','images/label_'+$(this).attr('id').replace('labelpos','')+'_2.png'); - $("#"+$(this).attr('id')).attr('sel','yes'); - } - - }); - - draw_lines(lines, 'background', true); - draw_user_lines("", 0, 0, 0 , 0, 0, true); + // Begin - Background label color changer - //~ center_labels(); - }); + $("#text-label_ifr") + .contents() + .find("body") + .bind("mousewheel", function(e) { + e.preventDefault(); - obj_js_user_lines = new jsGraphics("background"); + if ( + $("#text-label_ifr") + .contents() + .find("body") + .css("background-color") == "rgb(211, 211, 211)" + ) { + $("#text-label_ifr") + .contents() + .find("body") + .css("background-color", "white"); + } else { + $("#text-label_ifr") + .contents() + .find("body") + .css("background-color", "lightgray"); + } + }); - $("input[name='radio_choice']").on('change', function() { - var radio_value = $("input[name='radio_choice']:checked").val(); + // End - Background label color changer - if ((creationItem == 'module_graph') || (selectedItem == 'module_graph')) { - if (radio_value == "module_graph") { - $("#custom_graph_row").css('display', 'none'); - $("#agent_row").css('display', ''); - $("#module_row").css('display', ''); - $("#type_graph").css('display', ''); - } - else { - $("#custom_graph_row").css('display', ''); - $("#agent_row").css('display', 'none'); - $("#module_row").css('display', 'none'); - $("#type_graph").css('display', 'none'); - } - } - }); + $("#radiobtn0001").click(function() { + $("#custom_graph option[value=0]").prop("selected", true); + }); - //Resize the view to adapt the screen size. - if ($("#main").length) { - //Console - $("#frame_view").height($("#main").height() - 75); - } - else { - //Metaconsole - $("#frame_view").height($("#page").height() - 75); - } + $(".labelpos").click(function(event) { + if ($("#hidden-metaconsole").val() == 1) { + $("#labelposup img").attr("src", "../../images/label_up.png"); + $("#labelposdown img").attr("src", "../../images/label_down.png"); + $("#labelposleft img").attr("src", "../../images/label_left.png"); + $("#labelposright img").attr("src", "../../images/label_right.png"); + $(".labelpos").attr("sel", "no"); + $("#" + $(this).attr("id") + " img").attr( + "src", + "../../images/label_" + + $(this) + .attr("id") + .replace("labelpos", "") + + "_2.png" + ); + $("#" + $(this).attr("id")).attr("sel", "yes"); + } else { + $("#labelposup img").attr("src", "images/label_up.png"); + $("#labelposdown img").attr("src", "images/label_down.png"); + $("#labelposleft img").attr("src", "images/label_left.png"); + $("#labelposright img").attr("src", "images/label_right.png"); + $(".labelpos").attr("sel", "no"); + $("#" + $(this).attr("id") + " img").attr( + "src", + "images/label_" + + $(this) + .attr("id") + .replace("labelpos", "") + + "_2.png" + ); + $("#" + $(this).attr("id")).attr("sel", "yes"); + } + }); + + bindColorRangeEvents(); + + draw_lines(lines, "background", true); + + draw_user_lines("", 0, 0, 0, 0, 0, true); + + //~ center_labels(); + }); + + obj_js_user_lines = new jsGraphics("background"); + + $("input[name='radio_choice']").on("change", function() { + var radio_value = $("input[name='radio_choice']:checked").val(); + + if (creationItem == "module_graph" || selectedItem == "module_graph") { + if (radio_value == "module_graph") { + $("#custom_graph_row").css("display", "none"); + $("#agent_row").css("display", ""); + $("#module_row").css("display", ""); + $("#type_graph").css("display", ""); + } else { + $("#custom_graph_row").css("display", ""); + $("#agent_row").css("display", "none"); + $("#module_row").css("display", "none"); + $("#type_graph").css("display", "none"); + } + } + }); + + //Resize the view to adapt the screen size. + if ($("#main").length) { + //Console + $("#frame_view").height($("#main").height() - 75); + } else { + //Metaconsole + $("#frame_view").height($("#page").height() - 75); + } } function cancel_button_palette_callback() { - if (is_opened_palette) { - toggle_item_palette(); - } + if (is_opened_palette) { + toggle_item_palette(); + } } function get_url_ajax() { - if (is_metaconsole()) { - return "../../ajax.php"; - } - else { - return "ajax.php"; - } + if (is_metaconsole()) { + return "../../ajax.php"; + } else { + return "ajax.php"; + } } var metaconsole = null; function is_metaconsole() { - if (metaconsole === null) - metaconsole = $("input[name='metaconsole']").val(); + if (metaconsole === null) metaconsole = $("input[name='metaconsole']").val(); - if (metaconsole != 0) - return true; - else - return false; + if (metaconsole != 0) return true; + else return false; } function update_button_palette_callback() { + var values = {}; - var values = {}; + values = readFields(); - values = readFields(); + // TODO VALIDATE DATA + switch (selectedItem) { + case "background": + if (values["width"] < 1024 || values["height"] < 768) { + alert("Min allowed size is 1024x768"); + return false; + } - // TODO VALIDATE DATA - switch (selectedItem) { - case 'background': - if(values['width'] < 1024 || values['height'] < 768){ - alert('Min allowed size is 1024x768'); - return false; - } + if (values["width"] == 0 && values["height"] == 0) { + values["width"] = $("#hidden-background_original_width").val(); + values["height"] = $("#hidden-background_original_height").val(); + } + $("#background").css("width", values["width"]); + $("#background").css("height", values["height"]); - if(values['width'] == 0 && values['height'] == 0) { - values['width'] = - $("#hidden-background_original_width").val(); - values['height'] = - $("#hidden-background_original_height").val(); - } - $("#background").css('width', values['width']); - $("#background").css('height', values['height']); + var image = values["background"]; + $("#background_img").attr("src", "images/spinner.gif"); + set_image("background", null, image); - var image = values['background']; - $("#background_img").attr('src', "images/spinner.gif"); - set_image("background", null, image); + idElement = 0; + break; + case "box_item": + if ($("input[name=width_box]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height_box]").val() == "") { + alert("Undefined height"); + return false; + } - idElement = 0; - break; - case 'box_item': - if($('input[name=width_box]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height_box]').val() == ''){ - alert('Undefined height'); - return false; - } + $("#" + idItem + " div").css("background-color", values["fill_color"]); + $("#" + idItem + " div").css("border-color", values["border_color"]); + $("#" + idItem + " div").css( + "border-width", + values["border_width"] + "px" + ); - $("#" + idItem + " div").css('background-color', values['fill_color']); - $("#" + idItem + " div").css('border-color', values['border_color']); - $("#" + idItem + " div").css('border-width', values['border_width'] + "px"); + if (values["height_box"] == 0 || values["width_box"] == 0) { + $("#" + idItem + " div").css("width", "300px"); + $("#" + idItem + " div").css("height", "180px"); + } else { + $("#" + idItem + " div").css("height", values["height_box"] + "px"); + $("#" + idItem + " div").css("width", values["width_box"] + "px"); + } + break; + case "group_item": + if ( + (values["image"] == "" || values["image"] == "none") && + values["label"] == "" && + values["show_statistics"] == false + ) { + alert("Undefined image"); + return false; + } - if(values['height_box']==0 || values['width_box']==0){ - $("#" + idItem + " div").css('width', "300px"); - $("#" + idItem + " div").css('height', "180px"); - } - else{ - $("#" + idItem + " div").css('height', values['height_box'] + "px"); - $("#" + idItem + " div").css('width', values['width_box'] + "px"); - } - break; - case 'group_item': - if((values['image'] == '' || values['image'] == 'none') && (values['label'] == '') && (values['show_statistics'] == false)){ - alert('Undefined image'); - return false; - } + $("#text_" + idItem).html(values["label"]); - $("#text_" + idItem).html(values['label']); + if (values["show_statistics"] == 1) { + if (!$("#image_" + idItem).length) { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr("src", "images/console/icons/" + values["image"] + ".png") + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr("src", "images/console/icons/" + values["image"] + ".png") + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr("src", "images/console/icons/" + values["image"] + ".png"); + } - if(values['show_statistics'] == 1){ - if (!$('#image_'+idItem).length) { - if(values['label_position'] == 'left'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:right;'); - } - else if(values['label_position'] == 'right'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:left;'); - } - else{ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png"); - } + $("#" + idItem).append($image); + } - $('#'+idItem).append($image); - } + if (values["width"] == 0 || values["height"] == 0) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 520); + $("#image_" + idItem).attr("height", 80); + $("#image_" + idItem).css("width", "520px"); + $("#image_" + idItem).css("height", "80px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } + } else { + if (values["width"] == 0 || values["height"] == 0) { + if (values["image"] != "" && values["image"] != "none") { + if (!$("#image_" + idItem).length) { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ) + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ) + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ); + } - if ((values['width'] == 0) || (values['height'] == 0)) { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 520); - $("#image_" + idItem).attr('height', 80); - $("#image_" + idItem).css('width', '520px'); - $("#image_" + idItem).css('height', '80px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - } - else{ - if ((values['width'] == 0) || (values['height'] == 0)) { - if(values['image'] != '' && values['image'] != 'none'){ - if (!$('#image_'+idItem).length) { - if(values['label_position'] == 'left'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:right;'); - } - else if(values['label_position'] == 'right'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:left;'); - } - else{ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png"); - } + $("#" + idItem).append($image); + } - $('#'+idItem).append($image); - } + if ( + $("#preview > img").prop("naturalWidth") == null || + $("#preview > img")[0].naturalWidth > 150 || + $("#preview > img")[0].naturalHeight > 150 + ) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr( + "width", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).attr( + "height", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).css( + "width", + $("#preview > img")[0].naturalHeight + "px" + ); + $("#image_" + idItem).css( + "height", + $("#preview > img")[0].naturalHeight + "px" + ); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + $("#image_" + idItem).remove(); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + } + } + break; + case "static_graph": + if ($("input[name=width]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height]").val() == "") { + alert("Undefined height"); + return false; + } + if ( + (values["image"] == "" || values["image"] == "none") && + values["label"] == "" + ) { + alert("Undefined image"); + return false; + } - if($('#preview > img').prop('naturalWidth') == null || $('#preview > img')[0].naturalWidth > 150 || $('#preview > img')[0].naturalHeight > 150){ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).attr('height', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).css('width', $('#preview > img')[0].naturalHeight+'px'); - $("#image_" + idItem).css('height', $('#preview > img')[0].naturalHeight+'px'); - } - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - $("#image_" + idItem).remove(); - } - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - } - } - break; - case 'static_graph': - if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; - } - if(((values['image'] == '' || values['image'] == 'none') && (values['label'] == ''))){ - alert('Undefined image'); - return false; - } + $("#text_" + idItem).html(values["label"]); - $("#text_" + idItem).html(values['label']); + if (values["show_statistics"] == 1) { + if (values["width"] == 0 || values["height"] == 0) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 520); + $("#image_" + idItem).attr("height", 80); + $("#image_" + idItem).css("width", "520px"); + $("#image_" + idItem).css("height", "80px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } + } else { + if (values["width"] == 0 || values["height"] == 0) { + if (values["image"] != "" && values["image"] != "none") { + if (!$("#image_" + idItem).length) { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ) + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ) + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + idItem) + .attr("class", "image") + .attr( + "src", + "images/console/icons/" + values["image"] + ".png" + ); + } + $("#" + idItem).append($image); + } - if(values['show_statistics'] == 1){ - if ((values['width'] == 0) || (values['height'] == 0)) { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 520); - $("#image_" + idItem).attr('height', 80); - $("#image_" + idItem).css('width', '520px'); - $("#image_" + idItem).css('height', '80px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - } - else{ - if ((values['width'] == 0) || (values['height'] == 0)) { - if(values['image'] != '' && values['image'] != 'none'){ - if (!$('#image_'+idItem).length) { - if(values['label_position'] == 'left'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:right;'); - } - else if(values['label_position'] == 'right'){ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png") - .attr('style','float:left;'); - } - else{ - var $image = $('') - .attr('id', 'image_' + idItem) - .attr('class', 'image') - .attr('src', 'images/console/icons/'+values["image"]+".png"); - } - $('#'+idItem).append($image); - } + if ( + $("#preview > img").prop("naturalWidth") == null || + $("#preview > img")[0].naturalWidth > 150 || + $("#preview > img")[0].naturalHeight > 150 + ) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr( + "width", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).attr( + "height", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).css( + "width", + $("#preview > img")[0].naturalHeight + "px" + ); + $("#image_" + idItem).css( + "height", + $("#preview > img")[0].naturalHeight + "px" + ); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + $("#image_" + idItem).remove(); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + } + } + break; + case "percentile_bar": + case "percentile_item": + if ($("input[name=width_percentile]").val() == "") { + alert("Undefined width"); + return false; + } - if($('#preview > img').prop('naturalWidth') == null || $('#preview > img')[0].naturalWidth > 150 || $('#preview > img')[0].naturalHeight > 150){ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).attr('height', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).css('width', $('#preview > img')[0].naturalHeight+'px'); - $("#image_" + idItem).css('height', $('#preview > img')[0].naturalHeight+'px'); - } - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - $("#image_" + idItem).remove(); - } - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - } - } - break; - case 'percentile_bar': - case 'percentile_item': - if($('input[name=width_percentile]').val() == ''){ - alert('Undefined width'); - return false; - } + if ($("input[name=height_percentile]").val() == "") { + alert("Undefined height"); + return false; + } - if($('input[name=height_percentile]').val() == ''){ - alert('Undefined height'); - return false; - } + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); + if (values["type_percentile"] == "bubble") { + setPercentileBubble(idItem, values); + } else if (values["type_percentile"] == "circular_progress_bar") { + setPercentileCircular(idItem, values); + } else if ( + values["type_percentile"] == "interior_circular_progress_bar" + ) { + setPercentileInteriorCircular(idItem, values); + } else { + setPercentileBar(idItem, values); + } - if (values['type_percentile'] == 'bubble') { - setPercentileBubble(idItem, values); - } - else if (values['type_percentile'] == 'circular_progress_bar') { - setPercentileCircular(idItem, values); - } - else if (values['type_percentile'] == 'interior_circular_progress_bar') { - setPercentileInteriorCircular(idItem, values); - } - else { - setPercentileBar(idItem, values); - } + break; + case "module_graph": + if ($("#dir_items").html() == "horizontal") { + if ( + parseInt($("#text-left").val()) + + parseInt( + $("input[name=height_module_graph]").val() * + $("#count_items").html() + ) > + parseInt($("#background").css("width")) || + parseInt($("#text-left").val()) + + parseInt( + $("input[name=width_module_graph]").val() * + $("#count_items").html() + ) > + parseInt($("#background").css("width")) + ) { + alert( + $("#count_items").html() + + " joined graph items are wider than background" + ); + return false; + } + } - break; - case 'module_graph': - if($('#dir_items').html() == 'horizontal'){ - if(parseInt($('#text-left').val()) + (parseInt($('input[name=height_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('width')) - || parseInt($('#text-left').val()) + (parseInt($('input[name=width_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('width'))){ - - alert($('#count_items').html()+' joined graph items are wider than background'); - return false; - - } - } - - if($('#dir_items').html() == 'vertical'){ - if(parseInt($('#text-top').val()) + (parseInt($('input[name=height_module_graph]').val() * $('#count_items').html())) > parseInt($('#background').css('height'))){ - alert($('#count_items').html()+' joined graph items are higher than background'); - return false; - - } - } - - if($('input[name=width_module_graph]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height_module_graph]').val() == ''){ - alert('Undefined height'); - return false; - } - if($('#custom_graph_row').css('display') != 'none' && $("#custom_graph option:selected").html() == 'None'){ - alert('Undefined graph'); - return false; - } - - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); - setModuleGraph(idItem); - break; - case 'bars_graph': - if($('input[name=width_percentile]').val() == ''){ - alert('Undefined width'); - return false; - } + if ($("#dir_items").html() == "vertical") { + if ( + parseInt($("#text-top").val()) + + parseInt( + $("input[name=height_module_graph]").val() * + $("#count_items").html() + ) > + parseInt($("#background").css("height")) + ) { + alert( + $("#count_items").html() + + " joined graph items are higher than background" + ); + return false; + } + } - if($('input[name=bars_graph_height]').val() == ''){ - alert('Undefined height'); - return false; - } - - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); - - setBarsGraph(idItem, values); - break; - - case 'clock': - - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); - setClock(idItem, values); - break; - - case 'auto_sla_graph': - if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; - } - $("#text_" + idItem).html(values['label']); - $("#image_" + idItem).attr("src", "images/spinner.gif"); + if ($("input[name=width_module_graph]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height_module_graph]").val() == "") { + alert("Undefined height"); + return false; + } + if ( + $("#custom_graph_row").css("display") != "none" && + $("#custom_graph option:selected").html() == "None" + ) { + alert("Undefined graph"); + return false; + } - setEventsBar(idItem, values); - break; - case 'donut_graph': - $("#image_" + idItem).attr("src", "images/spinner.gif"); + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); + setModuleGraph(idItem); + break; + case "bars_graph": + if ($("input[name=width_percentile]").val() == "") { + alert("Undefined width"); + return false; + } - setDonutsGraph(idItem, values); - break; - case 'simple_value': - $("#" + idItem).html(values['label']); - - if($("#data_image_check").html() == "On"){ - $("#text_" + idItem).html(''); - $("#" + idItem).html(''); - } - else{ - $("#text_" + idItem).html( - '
    '+values["label"]+'
    ' - ) - $("#" + idItem).html( - '
    '+values["label"]+'
    ' - ) - } - break; - case 'label': - $("#text_" + idItem).html(values['label']); - break; - case 'icon': - if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; - } - if(values['image'] == '' || values['image'] == 'none'){ - alert('Undefined image'); - return false; - } - $("#image_" + idItem).attr('src', "images/spinner.gif"); - if ((values['width'] == 0) || (values['height'] == 0)) { - if($('#preview > img').prop('naturalWidth') == null || $('#preview > img')[0].naturalWidth > 150 || $('#preview > img')[0].naturalHeight > 150){ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 70); - $("#image_" + idItem).attr('height', 70); - $("#image_" + idItem).css('width', '70px'); - $("#image_" + idItem).css('height', '70px'); - } - else{ - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).attr('height', $('#preview > img')[0].naturalHeight); - $("#image_" + idItem).css('width', $('#preview > img')[0].naturalHeight+'px'); - $("#image_" + idItem).css('height', $('#preview > img')[0].naturalHeight+'px'); - } - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - } - var image = values['image'] + ".png"; - set_image("image", idItem, image); - break; - default: - if($('input[name=width]').val() == ''){ - alert('Undefined width'); - return false; - } - if($('input[name=height]').val() == ''){ - alert('Undefined height'); - return false; - } - //Maybe save in any Enterprise item. - if (typeof(enterprise_update_button_palette_callback) == 'function') { - enterprise_update_button_palette_callback(values); - } + if ($("input[name=bars_graph_height]").val() == "") { + alert("Undefined height"); + return false; + } - break; - - } + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); - updateDB(selectedItem, idItem , values); + setBarsGraph(idItem, values); + break; - toggle_item_palette(); - - if(values['label_position']=='left'){ - $("#" + idItem + ' table').css('float','left'); - $("#" + idItem + ' img').css('float','right'); - $("#" + idItem + ' img').css('margin-left',''); - $("#" + idItem + ' table').css('height',$("#" + idItem+ ' img').css('height')); - $("#" + idItem + ' table').css('width',''); - $("#" + idItem + ' img').css('margin-top',(parseInt($("#" + idItem).css('height'))/2)-(parseInt($("#" + idItem + " img").css('height'))/2)+'px'); - $("#" + idItem + ' > p').remove(); - } - else if(values['label_position']=='right'){ - $("#" + idItem + ' table').css('float','right'); - $("#" + idItem + ' img').css('float','left'); - $("#" + idItem + ' img').css('margin-left',''); - $("#" + idItem + ' table').css('height',$("#" + idItem+ ' img').css('height')); - $("#" + idItem + ' table').css('width',''); - $("#" + idItem + ' img').css('margin-top',(parseInt($("#" + idItem).css('height'))/2)-(parseInt($("#" + idItem + " img").css('height'))/2)+'px'); - $("#" + idItem + ' > p').remove(); - } - else if(values['label_position']=='down'){ - $("#" + idItem + ' table').css('float',''); - $("#" + idItem + ' img').css('float',''); - var tempoimg = $('#' + idItem + ' table').clone(); - $('#' + idItem + ' table').remove(); - $('#' + idItem).append(tempoimg); - $("#" + idItem + ' table').css('height',''); - if (selectedItem != 'simple_value') { - $("#" + idItem + ' table').css('width','70'); - $("#" + idItem + ' span').css('width','70'); - } - else { - $("#" + idItem + ' table').css('width',''); - $("#" + idItem + ' table').css('text-align','center'); - $("#" + idItem + ' span').css('width',''); - } - $("#" + idItem + ' img').css('margin-top',''); - - $("#" + idItem + ' > p').remove(); - } - else if(values['label_position']=='up'){ - $("#" + idItem + ' table').css('float',''); - $("#" + idItem + ' img').css('float',''); - var tempoimg = $('#' + idItem + ' img').clone(); - $('#' + idItem + ' img').remove(); - $('#' + idItem).append(tempoimg); - $("#" + idItem + ' table').css('height',''); - if (selectedItem != 'simple_value') { - $("#" + idItem + ' table').css('width','70'); - $("#" + idItem + ' span').css('width','70'); - } - else { - $("#" + idItem + ' table').css('width',''); - $("#" + idItem + ' table').css('text-align','center'); - $("#" + idItem + ' span').css('width',''); - } - $("#" + idItem + ' img').css('margin-top',''); + case "clock": + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); + setClock(idItem, values); + break; - $("#" + idItem + ' > p').remove(); - } + case "auto_sla_graph": + if ($("input[name=width]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height]").val() == "") { + alert("Undefined height"); + return false; + } + $("#text_" + idItem).html(values["label"]); + $("#image_" + idItem).attr("src", "images/spinner.gif"); + + setEventsBar(idItem, values); + break; + case "donut_graph": + $("#image_" + idItem).attr("src", "images/spinner.gif"); + + setDonutsGraph(idItem, values); + break; + case "simple_value": + $("#" + idItem).html(values["label"]); + + if ($("#data_image_check").html() == "On") { + $("#text_" + idItem).html( + '' + ); + $("#" + idItem).html( + '' + ); + } else { + $("#text_" + idItem).html( + '
    ' + + values["label"] + + "
    " + ); + $("#" + idItem).html( + '
    ' + + values["label"] + + "
    " + ); + } + break; + case "label": + $("#text_" + idItem).html(values["label"]); + break; + case "icon": + if ($("input[name=width]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height]").val() == "") { + alert("Undefined height"); + return false; + } + if (values["image"] == "" || values["image"] == "none") { + alert("Undefined image"); + return false; + } + $("#image_" + idItem).attr("src", "images/spinner.gif"); + if (values["width"] == 0 || values["height"] == 0) { + if ( + $("#preview > img").prop("naturalWidth") == null || + $("#preview > img")[0].naturalWidth > 150 || + $("#preview > img")[0].naturalHeight > 150 + ) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 70); + $("#image_" + idItem).attr("height", 70); + $("#image_" + idItem).css("width", "70px"); + $("#image_" + idItem).css("height", "70px"); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr( + "width", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).attr( + "height", + $("#preview > img")[0].naturalHeight + ); + $("#image_" + idItem).css( + "width", + $("#preview > img")[0].naturalHeight + "px" + ); + $("#image_" + idItem).css( + "height", + $("#preview > img")[0].naturalHeight + "px" + ); + } + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + } + var image = values["image"] + ".png"; + set_image("image", idItem, image); + break; + default: + if ($("input[name=width]").val() == "") { + alert("Undefined width"); + return false; + } + if ($("input[name=height]").val() == "") { + alert("Undefined height"); + return false; + } + //Maybe save in any Enterprise item. + if (typeof enterprise_update_button_palette_callback == "function") { + enterprise_update_button_palette_callback(values); + } + + break; + } + + updateDB(selectedItem, idItem, values); + + toggle_item_palette(); + + if (values["label_position"] == "left") { + $("#" + idItem + " table").css("float", "left"); + $("#" + idItem + " img").css("float", "right"); + $("#" + idItem + " img").css("margin-left", ""); + $("#" + idItem + " table").css( + "height", + $("#" + idItem + " img").css("height") + ); + $("#" + idItem + " table").css("width", ""); + $("#" + idItem + " img").css( + "margin-top", + parseInt($("#" + idItem).css("height")) / 2 - + parseInt($("#" + idItem + " img").css("height")) / 2 + + "px" + ); + $("#" + idItem + " > p").remove(); + } else if (values["label_position"] == "right") { + $("#" + idItem + " table").css("float", "right"); + $("#" + idItem + " img").css("float", "left"); + $("#" + idItem + " img").css("margin-left", ""); + $("#" + idItem + " table").css( + "height", + $("#" + idItem + " img").css("height") + ); + $("#" + idItem + " table").css("width", ""); + $("#" + idItem + " img").css( + "margin-top", + parseInt($("#" + idItem).css("height")) / 2 - + parseInt($("#" + idItem + " img").css("height")) / 2 + + "px" + ); + $("#" + idItem + " > p").remove(); + } else if (values["label_position"] == "down") { + $("#" + idItem + " table").css("float", ""); + $("#" + idItem + " img").css("float", ""); + var tempoimg = $("#" + idItem + " table").clone(); + $("#" + idItem + " table").remove(); + $("#" + idItem).append(tempoimg); + $("#" + idItem + " table").css("height", ""); + if (selectedItem != "simple_value") { + $("#" + idItem + " table").css("width", "70"); + $("#" + idItem + " span").css("width", "70"); + } else { + $("#" + idItem + " table").css("width", ""); + $("#" + idItem + " table").css("text-align", "center"); + $("#" + idItem + " span").css("width", ""); + } + $("#" + idItem + " img").css("margin-top", ""); + + $("#" + idItem + " > p").remove(); + } else if (values["label_position"] == "up") { + $("#" + idItem + " table").css("float", ""); + $("#" + idItem + " img").css("float", ""); + var tempoimg = $("#" + idItem + " img").clone(); + $("#" + idItem + " img").remove(); + $("#" + idItem).append(tempoimg); + $("#" + idItem + " table").css("height", ""); + if (selectedItem != "simple_value") { + $("#" + idItem + " table").css("width", "70"); + $("#" + idItem + " span").css("width", "70"); + } else { + $("#" + idItem + " table").css("width", ""); + $("#" + idItem + " table").css("text-align", "center"); + $("#" + idItem + " span").css("width", ""); + } + $("#" + idItem + " img").css("margin-top", ""); + + $("#" + idItem + " > p").remove(); + } } function readFields() { - - $("#text-label_ifr").contents().find("p").css('overflow','hidden'); - metaconsole = $("input[name='metaconsole']").val(); - var values = {}; - values['label'] = $("input[name=label]").val(); - var text = tinymce.get('text-label').getContent(); - values['label'] = text; + $("#text-label_ifr") + .contents() + .find("p") + .css("overflow", "hidden"); + metaconsole = $("input[name='metaconsole']").val(); + var values = {}; + values["label"] = $("input[name=label]").val(); + var text = tinymce.get("text-label").getContent(); + values["label"] = text; - if ($("input[name=percentile_label]").val().length > 0) { - values['percentile_label_color'] = $("input[name=percentile_label_color]").val(); - values['label'] = "" + $("input[name=percentile_label]").val() + ""; - } + if ($("input[name=percentile_label]").val().length > 0) { + values["percentile_label_color"] = $( + "input[name=percentile_label_color]" + ).val(); + values["label"] = + "" + + $("input[name=percentile_label]").val() + + ""; + } - values['line-height'] = $("#text-label_ifr").contents().find("p").css('line-height'); - values['type_graph'] = $("select[name=type_graph]").val(); - values['image'] = $("select[name=image]").val(); - values['background_color'] = $("select[name=background_color]").val(); - values['left'] = $("input[name=left]").val(); - values['top'] = $("input[name=top]").val(); - values['agent'] = $("input[name=agent]").val(); - values['id_agent'] = $("input[name=id_agent]").val(); - values['agent_string'] = $("input[name=agent_string]").val(); - values['id_agent_string'] = $("input[name=id_agent_string]").val(); - values['module'] = $("select[name=module]").val(); - values['process_simple_value'] = $("select[name=process_value]").val(); - values['background'] = $("#background_image").val(); - values['period'] = undefined != $("#hidden-period").val() ? $("#hidden-period").val() : $("#period").val(); - values['width'] = $("input[name=width]").val(); - values['width_data_image'] = $("#data_image_width").val(); - if(selectedItem == 'simple_value' || creationItem == 'simple_value'){ - if(values['width_data_image'] != 0){ - values['width'] = values['width_data_image']; - } - } - values['height'] = $("input[name=height]").val(); - values['bars_graph_type'] = $("select[name=bars_graph_type]").val(); - values['parent'] = $("select[name=parent]").val(); - values['map_linked'] = $("select[name=map_linked]").val(); - values['linked_map_node_id'] = $("input[name=linked_map_node_id]").val(); - values['linked_map_status_calculation_type'] = $("select[name=linked_map_status_calculation_type]").val(); - values['map_linked_weight'] = $("input[name=map_linked_weight]").val(); - values['linked_map_status_service_critical'] = $("input[name=linked_map_status_service_critical]").val(); - values['linked_map_status_service_warning'] = $("input[name=linked_map_status_service_warning]").val(); - values['element_group'] = $("select[name=element_group]").val(); - values['width_percentile'] = $("input[name=width_percentile]").val(); - values['bars_graph_height'] = $("input[name=bars_graph_height]").val(); - values['max_percentile'] = parseInt($("input[name=max_percentile]").val()); - values['width_module_graph'] = $("input[name=width_module_graph]").val(); - values['height_module_graph'] = $("input[name=height_module_graph]").val(); - values['event_max_time_row'] = $("select[name=event_max_time_row]").val(); - values['type_percentile'] = $("select[name=type_percentile]").val(); - values['percentile_color'] = $("input[name=percentile_color]").val(); - values['percentile_label'] = $("input[name=percentile_label]").val(); - values['value_show'] = $("select[name=value_show]").val(); - - values['enable_link'] = $("input[name=enable_link]").is(':checked') ? 1 : 0; - values['id_group'] = $("select[name=group]").val(); - values['id_custom_graph'] = $("#custom_graph option:selected").val(); - values['width_box'] = parseInt( - $("input[name='width_box']").val()); - values['height_box'] = parseInt( - $("input[name='height_box']").val()); - values['border_color'] = $("input[name='border_color']").val(); - values['resume_color'] = $("input[name='resume_color']").val(); - values['grid_color'] = $("input[name='grid_color']").val(); - values['border_width'] = parseInt( - $("input[name='border_width']").val()); - values['fill_color'] = $("input[name='fill_color']").val(); - values['line_width'] = parseInt( - $("input[name='line_width']").val()); - values['line_color'] = $("input[name='line_color']").val(); - values['label_position'] = $(".labelpos[sel=yes]").attr('position'); - values['show_statistics'] = $("input[name=show_statistics]").is(':checked') ? 1 : 0; - values['show_on_top'] = $("input[name=show_on_top]").is(':checked') ? 1 : 0; - values['time_format'] = $("select[name=time_format]").val(); - values['timezone'] = $("select[name=timezone]").val(); - values['clock_animation'] = $("select[name=clock_animation]").val(); - values['show_last_value'] = $("select[name=last_value]").val(); - - if (is_metaconsole()) { - values['metaconsole'] = 1; - values['id_agent'] = $("#hidden-agent").val(); - values['server_name'] = $("#id_server_name").val(); - values['server_id'] = $("input[name='id_server_metaconsole']").val(); - } - else { - values['metaconsole'] = 0; - } + values["line-height"] = $("#text-label_ifr") + .contents() + .find("p") + .css("line-height"); + values["type_graph"] = $("select[name=type_graph]").val(); + values["image"] = $("select[name=image]").val(); + values["background_color"] = $("select[name=background_color]").val(); + values["left"] = $("input[name=left]").val(); + values["top"] = $("input[name=top]").val(); + values["agent"] = $("input[name=agent]").val(); + values["id_agent"] = $("input[name=id_agent]").val(); + values["agent_string"] = $("input[name=agent_string]").val(); + values["id_agent_string"] = $("input[name=id_agent_string]").val(); + values["module"] = $("select[name=module]").val(); + values["process_simple_value"] = $("select[name=process_value]").val(); + values["background"] = $("#background_image").val(); + values["period"] = + undefined != $("#hidden-period").val() + ? $("#hidden-period").val() + : $("#period").val(); + values["width"] = $("input[name=width]").val(); + values["width_data_image"] = $("#data_image_width").val(); + if (selectedItem == "simple_value" || creationItem == "simple_value") { + if (values["width_data_image"] != 0) { + values["width"] = values["width_data_image"]; + } + } + values["height"] = $("input[name=height]").val(); + values["bars_graph_type"] = $("select[name=bars_graph_type]").val(); + values["parent"] = $("select[name=parent]").val(); + values["map_linked"] = $("select[name=map_linked]").val(); + values["linked_map_node_id"] = $("input[name=linked_map_node_id]").val(); + values["linked_map_status_calculation_type"] = $( + "select[name=linked_map_status_calculation_type]" + ).val(); + values["map_linked_weight"] = $("input[name=map_linked_weight]").val(); + values["linked_map_status_service_critical"] = $( + "input[name=linked_map_status_service_critical]" + ).val(); + values["linked_map_status_service_warning"] = $( + "input[name=linked_map_status_service_warning]" + ).val(); + values["element_group"] = $("select[name=element_group]").val(); + values["width_percentile"] = $("input[name=width_percentile]").val(); + values["bars_graph_height"] = $("input[name=bars_graph_height]").val(); + values["max_percentile"] = parseInt($("input[name=max_percentile]").val()); + values["width_module_graph"] = $("input[name=width_module_graph]").val(); + values["height_module_graph"] = $("input[name=height_module_graph]").val(); + values["event_max_time_row"] = $("select[name=event_max_time_row]").val(); + values["type_percentile"] = $("select[name=type_percentile]").val(); + values["percentile_color"] = $("input[name=percentile_color]").val(); + values["percentile_label"] = $("input[name=percentile_label]").val(); + values["value_show"] = $("select[name=value_show]").val(); - if (typeof(enterprise_readFields) == 'function') { - //The parameter is a object and the function can change or add - //attributes. - enterprise_readFields(values); - } + values["enable_link"] = $("input[name=enable_link]").is(":checked") ? 1 : 0; + values["id_group"] = $("select[name=group]").val(); + values["id_custom_graph"] = $("#custom_graph option:selected").val(); + values["width_box"] = parseInt($("input[name='width_box']").val()); + values["height_box"] = parseInt($("input[name='height_box']").val()); + values["border_color"] = $("input[name='border_color']").val(); + values["resume_color"] = $("input[name='resume_color']").val(); + values["grid_color"] = $("input[name='grid_color']").val(); + values["border_width"] = parseInt($("input[name='border_width']").val()); + values["fill_color"] = $("input[name='fill_color']").val(); + values["line_width"] = parseInt($("input[name='line_width']").val()); + values["line_color"] = $("input[name='line_color']").val(); + values["label_position"] = $(".labelpos[sel=yes]").attr("position"); + values["show_statistics"] = $("input[name=show_statistics]").is(":checked") + ? 1 + : 0; + values["show_on_top"] = $("input[name=show_on_top]").is(":checked") ? 1 : 0; + values["time_format"] = $("select[name=time_format]").val(); + values["timezone"] = $("select[name=timezone]").val(); + values["clock_animation"] = $("select[name=clock_animation]").val(); + values["show_last_value"] = $("select[name=last_value]").val(); - return values; + // Color Cloud values + if (selectedItem == "color_cloud" || creationItem == "color_cloud") { + var diameter = $("input[name=diameter]").val(); + values["diameter"] = values["width"] = values["height"] = diameter; + var defaultColor = $("input[name=default_color]").val(); + values["default_color"] = defaultColor; + + // Ranges + $('input[name="color_range_from_values[]"]').each(function(index, element) { + values["color_range_from_values[" + index + "]"] = $(element).val(); + }); + $('input[name="color_range_to_values[]"]').each(function(index, element) { + values["color_range_to_values[" + index + "]"] = $(element).val(); + }); + $('input[name="color_range_color_values[]"]').each(function( + index, + element + ) { + values["color_range_colors[" + index + "]"] = $(element).val(); + }); + } + + if (is_metaconsole()) { + values["metaconsole"] = 1; + values["id_agent"] = $("#hidden-agent").val(); + values["server_name"] = $("#id_server_name").val(); + values["server_id"] = $("input[name='id_server_metaconsole']").val(); + } else { + values["metaconsole"] = 0; + } + + if (typeof enterprise_readFields == "function") { + //The parameter is a object and the function can change or add + //attributes. + enterprise_readFields(values); + } + + return values; } function create_button_palette_callback() { - var values = readFields(); + var values = readFields(); - //VALIDATE DATA - var validate = true; - switch (creationItem) { - case 'box_item': - if (($("input[name='width_box']").val() == '')) { - alert('Undefined width'); - validate = false; - } - if (($("input[name='height_box']").val() == '')) { - alert('Undefined height'); - validate = false; - } - break; - case 'group_item': - if((values['image'] == '' || values['image'] == 'none') && (values['label'] == '') && (values['show_statistics'] == false)){ - alert('Undefined images'); - validate = false; - } - break; - case 'static_graph': - if ((values['width'] == '')) { - alert('Undefined width'); - validate = false; - } - if ((values['height'] == '')) { - alert('Undefined height'); - validate = false; - } - if((values['image'] == '' || values['image'] == 'none') && (values['label']) == false){ - alert('Undefined image'); - validate = false; - } - + //VALIDATE DATA + var validate = true; + switch (creationItem) { + case "box_item": + if ($("input[name='width_box']").val() == "") { + alert("Undefined width"); + validate = false; + } + if ($("input[name='height_box']").val() == "") { + alert("Undefined height"); + validate = false; + } + break; + case "group_item": + if ( + (values["image"] == "" || values["image"] == "none") && + values["label"] == "" && + values["show_statistics"] == false + ) { + alert("Undefined images"); + validate = false; + } + break; + case "static_graph": + if (values["width"] == "") { + alert("Undefined width"); + validate = false; + } + if (values["height"] == "") { + alert("Undefined height"); + validate = false; + } + if ( + (values["image"] == "" || values["image"] == "none") && + values["label"] == false + ) { + alert("Undefined image"); + validate = false; + } - break; - case 'auto_sla_graph': - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - break; - case 'donut_graph': - if ((values['agent_string'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - break; - case 'label': - if ((values['label'] == '')) { - alert($("#message_alert_no_label").html()); - validate = false; - } - break; - case 'icon': - if ((values['width'] == '')) { - alert('Undefined width'); - validate = false; - } - if ((values['height'] == '')) { - alert('Undefined height'); - validate = false; - } - if ((values['image'] == '' || values['image'] == 'none')) { - alert($("#message_alert_no_image").html()); - validate = false; - } - break; - case 'percentile_bar': - case 'percentile_item': - if ((values['width'] == '')) { - alert('Undefined width'); - validate = false; - } - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - if ((values['max_percentile'] == '')) { - alert($("#message_alert_no_max_percentile").html()); - validate = false; - } - if ((values['width_percentile'] == '')) { - alert($("#message_alert_no_width_percentile").html()); - validate = false; - } - break; - case 'module_graph': - if (values['width_module_graph'] == '') { - alert('Undefined width'); - validate = false; - } - if (values['height_module_graph'] == '') { - alert('Undefined height'); - validate = false; - } - if (values['id_custom_graph'] == 0) { - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - if ((values['period'] == 0)) { - alert($("#message_alert_no_period").html()); - validate = false; - } - } - break; - case 'bars_graph': - if ((values['agent_string'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - if ((values['width_percentile'] == '')) { - alert($("#message_alert_no_width_percentile").html()); - validate = false; - } - if ((values['bars_graph_height'] == '')) { - alert($("#message_alert_no_bars_graph_height").html()); - validate = false; - } - break; - case 'simple_value': - if ((values['agent'] == '')) { - alert($("#message_alert_no_agent").html()); - validate = false; - } - if ((values['module'] == 0)) { - alert($("#message_alert_no_module").html()); - validate = false; - } - break; - default: - //Maybe save in any Enterprise item. - if (typeof(enterprise_create_button_palette_callback) == 'function') { - validate = enterprise_create_button_palette_callback(values); - } - break; - } + break; + case "auto_sla_graph": + if (values["agent"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + break; + case "donut_graph": + if (values["agent_string"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + break; + case "label": + if (values["label"] == "") { + alert($("#message_alert_no_label").html()); + validate = false; + } + break; + case "icon": + if (values["width"] == "") { + alert("Undefined width"); + validate = false; + } + if (values["height"] == "") { + alert("Undefined height"); + validate = false; + } + if (values["image"] == "" || values["image"] == "none") { + alert($("#message_alert_no_image").html()); + validate = false; + } + break; + case "percentile_bar": + case "percentile_item": + if (values["width"] == "") { + alert("Undefined width"); + validate = false; + } + if (values["agent"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + if (values["module"] == 0) { + alert($("#message_alert_no_module").html()); + validate = false; + } + if (values["max_percentile"] == "") { + alert($("#message_alert_no_max_percentile").html()); + validate = false; + } + if (values["width_percentile"] == "") { + alert($("#message_alert_no_width_percentile").html()); + validate = false; + } + break; + case "module_graph": + if (values["width_module_graph"] == "") { + alert("Undefined width"); + validate = false; + } + if (values["height_module_graph"] == "") { + alert("Undefined height"); + validate = false; + } + if (values["id_custom_graph"] == 0) { + if (values["agent"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + if (values["module"] == 0) { + alert($("#message_alert_no_module").html()); + validate = false; + } + if (values["period"] == 0) { + alert($("#message_alert_no_period").html()); + validate = false; + } + } + break; + case "bars_graph": + if (values["agent_string"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + if (values["module"] == 0) { + alert($("#message_alert_no_module").html()); + validate = false; + } + if (values["width_percentile"] == "") { + alert($("#message_alert_no_width_percentile").html()); + validate = false; + } + if (values["bars_graph_height"] == "") { + alert($("#message_alert_no_bars_graph_height").html()); + validate = false; + } + break; + case "simple_value": + if (values["agent"] == "") { + alert($("#message_alert_no_agent").html()); + validate = false; + } + if (values["module"] == 0) { + alert($("#message_alert_no_module").html()); + validate = false; + } + break; + default: + //Maybe save in any Enterprise item. + if (typeof enterprise_create_button_palette_callback == "function") { + validate = enterprise_create_button_palette_callback(values); + } + break; + } - if (validate) { - switch (creationItem) { - case 'line_item': - create_line('step_1', values); - break; - default: - - insertDB(creationItem, values); - break; - } + if (validate) { + switch (creationItem) { + case "line_item": + create_line("step_1", values); + break; + default: + insertDB(creationItem, values); + break; + } - - toggle_item_palette(); - } + toggle_item_palette(); + } } function delete_user_line(idElement) { - var found = null; + var found = null; - jQuery.each(user_lines, function(iterator, user_line) { - if (user_line['id'] == idElement) { - found = iterator; - return; - } - }); + jQuery.each(user_lines, function(iterator, user_line) { + if (user_line["id"] == idElement) { + found = iterator; + return; + } + }); - if (found != null) { - user_lines.splice(found, 1); - } + if (found != null) { + user_lines.splice(found, 1); + } } function update_user_line(type, idElement, top, left) { - jQuery.each(user_lines, function(iterator, user_line) { + jQuery.each(user_lines, function(iterator, user_line) { + if (user_line["id"] != idElement) return; - if (user_line['id'] != idElement) - return; + switch (type) { + // -- line_item -- + case "handler_start": + // --------------- - switch (type) { - // -- line_item -- - case 'handler_start': - // --------------- + user_lines[iterator]["start_x"] = left; + user_lines[iterator]["start_y"] = top; - user_lines[iterator]['start_x'] = left; - user_lines[iterator]['start_y'] = top; + break; + // -- line_item -- + case "handler_end": + // --------------- - break; - // -- line_item -- - case 'handler_end': - // --------------- + user_lines[iterator]["end_x"] = left; + user_lines[iterator]["end_y"] = top; - user_lines[iterator]['end_x'] = left; - user_lines[iterator]['end_y'] = top; - - break; - } - }); + break; + } + }); } -function draw_user_lines(color, thickness, start_x, start_y , end_x, - end_y, only_defined_lines) { +function draw_user_lines( + color, + thickness, + start_x, + start_y, + end_x, + end_y, + only_defined_lines +) { + obj_js_user_lines.clear(); + // Draw the previous lines + for (iterator = 0; iterator < user_lines.length; iterator++) { + obj_js_user_lines.setStroke(user_lines[iterator]["line_width"]); + obj_js_user_lines.setColor(user_lines[iterator]["line_color"]); + obj_js_user_lines.drawLine( + parseInt(user_lines[iterator]["start_x"]), + parseInt(user_lines[iterator]["start_y"]), + parseInt(user_lines[iterator]["end_x"]), + parseInt(user_lines[iterator]["end_y"]) + ); + } - obj_js_user_lines.clear(); + if (typeof only_defined_lines == "undefined") { + only_defined_lines = false; + } - // Draw the previous lines - for (iterator = 0; iterator < user_lines.length; iterator++) { + if (!only_defined_lines) { + obj_js_user_lines.setStroke(thickness); + obj_js_user_lines.setColor(color); + obj_js_user_lines.drawLine(start_x, start_y, end_x, end_y); + } - obj_js_user_lines.setStroke(user_lines[iterator]['line_width']); - obj_js_user_lines.setColor(user_lines[iterator]['line_color']); - obj_js_user_lines.drawLine( - parseInt(user_lines[iterator]['start_x']), - parseInt(user_lines[iterator]['start_y']), - parseInt(user_lines[iterator]['end_x']), - parseInt(user_lines[iterator]['end_y'])); - } - - - if (typeof(only_defined_lines) == "undefined") { - only_defined_lines = false; - } - - if (!only_defined_lines) { - obj_js_user_lines.setStroke(thickness); - obj_js_user_lines.setColor(color); - obj_js_user_lines.drawLine(start_x, start_y, end_x, end_y); - } - - obj_js_user_lines.paint(); + obj_js_user_lines.paint(); } function create_line(step, values) { + $(".item").unbind("click"); + $(".item").unbind("dblclick"); + $(".item").unbind("dragstop"); + $(".item").unbind("dragstart"); - $('.item').unbind('click'); - $('.item').unbind('dblclick'); - $('.item').unbind('dragstop'); - $('.item').unbind('dragstart'); + $("#background").unbind("click"); + $("#background").unbind("dblclick"); - $('#background').unbind('click'); - $('#background').unbind('dblclick'); + switch (step) { + case "step_1": + $("#background *").css("cursor", "crosshair"); - switch (step) { - case 'step_1': - $("#background *").css("cursor", "crosshair"); + $("#background *").on("mousemove", function(e) { + $("#div_step_1").css({ + left: e.offsetX, + top: e.offsetY + }); + $("#div_step_1").show(); + // 2 for the black border of background + values["line_start_x"] = e.offsetX; + values["line_start_y"] = e.offsetY; + }); - $("#background *") - .on('mousemove', function(e) { + $("#background *").on("click", function(e) { + create_line("step_2", values); + }); - $('#div_step_1').css({ - left: e.offsetX, - top: e.offsetY - }); - $('#div_step_1').show(); + break; + case "step_2": + $("#div_step_1").hide(); + $("#background *").off("mousemove"); + $("#background *").off("click"); - // 2 for the black border of background - values['line_start_x'] = e.offsetX; - values['line_start_y'] = e.offsetY; + $("#background *").on("mousemove", function(e) { + $("#div_step_2").css({ + left: e.offsetX, + top: e.offsetY + }); + $("#div_step_2").show(); - }); + // 2 for the black border of background + values["line_end_x"] = e.offsetX; + values["line_end_y"] = e.offsetY; + draw_user_lines( + values["line_color"], + values["line_width"], + values["line_start_x"], + values["line_start_y"], + values["line_end_x"], + values["line_end_y"] + ); + }); - $("#background *") - .on('click', function(e) { - create_line('step_2', values); - }); + $("#background *").on("click", function(e) { + create_line("step_3", values); + }); + break; + case "step_3": + $("#div_step_2").hide(); + $("#background *").off("mousemove"); + $("#background *").off("click"); - break; - case 'step_2': - $('#div_step_1').hide(); - $("#background *").off('mousemove'); - $("#background *").off('click'); + $("#background *").css("cursor", ""); + insertDB("line_item", values); - $("#background *") - .on('mousemove', function(e) { - - $('#div_step_2').css({ - left: e.offsetX, - top: e.offsetY - }); - $('#div_step_2').show(); - - // 2 for the black border of background - values['line_end_x'] = e.offsetX; - values['line_end_y'] = e.offsetY; - - draw_user_lines( - values['line_color'], - values['line_width'], - values['line_start_x'], - values['line_start_y'], - values['line_end_x'], - values['line_end_y']); - }); - - $("#background *") - .on('click', function(e) { - create_line('step_3', values); - }); - break; - case 'step_3': - $('#div_step_2').hide(); - $("#background *").off('mousemove'); - $("#background *").off('click'); - - $("#background *").css("cursor", ""); - - insertDB("line_item", values); - - eventsItems(); - eventsBackground(); - break; - } + eventsItems(); + eventsBackground(); + break; + } } function toggle_item_palette() { - var item = null; + var item = null; - if (is_opened_palette) { - is_opened_palette = false; + if (is_opened_palette) { + is_opened_palette = false; - activeToolboxButton('static_graph', true); - activeToolboxButton('module_graph', true); - activeToolboxButton('bars_graph', true); - activeToolboxButton('simple_value', true); - activeToolboxButton('label', true); - activeToolboxButton('icon', true); - activeToolboxButton('clock', true); - activeToolboxButton('percentile_item', true); - activeToolboxButton('group_item', true); - activeToolboxButton('box_item', true); - activeToolboxButton('line_item', true); - activeToolboxButton('auto_sla_graph', true); - activeToolboxButton('donut_graph', true); + activeToolboxButton("static_graph", true); + activeToolboxButton("module_graph", true); + activeToolboxButton("bars_graph", true); + activeToolboxButton("simple_value", true); + activeToolboxButton("label", true); + activeToolboxButton("icon", true); + activeToolboxButton("clock", true); + activeToolboxButton("percentile_item", true); + activeToolboxButton("group_item", true); + activeToolboxButton("box_item", true); + activeToolboxButton("line_item", true); + activeToolboxButton("auto_sla_graph", true); + activeToolboxButton("donut_graph", true); + activeToolboxButton("color_cloud", true); - if (typeof(enterprise_activeToolboxButton) == 'function') { - enterprise_activeToolboxButton(true); - } + if (typeof enterprise_activeToolboxButton == "function") { + enterprise_activeToolboxButton(true); + } - $(".item").draggable("enable"); - $("#background").resizable('enable'); - $("#properties_panel").hide("fast"); + $(".item").draggable("enable"); + $("#background").resizable("enable"); + $("#properties_panel").hide("fast"); - toggle_advance_options_palette(false); - } - else { - is_opened_palette = true; + toggle_advance_options_palette(false); + } else { + is_opened_palette = true; - $(".item").draggable("disable"); - $("#background").resizable('disable'); + $(".item").draggable("disable"); + $("#background").resizable("disable"); - activeToolboxButton('static_graph', false); - activeToolboxButton('module_graph', false); - activeToolboxButton('bars_graph', false); - activeToolboxButton('auto_sla_graph', false); - activeToolboxButton('donut_graph', false); - activeToolboxButton('simple_value', false); - activeToolboxButton('label', false); - activeToolboxButton('icon', false); - activeToolboxButton('clock', false); - activeToolboxButton('percentile_item', false); - activeToolboxButton('group_item', false); - activeToolboxButton('box_item', false); - activeToolboxButton('line_item', false); + activeToolboxButton("static_graph", false); + activeToolboxButton("module_graph", false); + activeToolboxButton("bars_graph", false); + activeToolboxButton("auto_sla_graph", false); + activeToolboxButton("donut_graph", false); + activeToolboxButton("simple_value", false); + activeToolboxButton("label", false); + activeToolboxButton("icon", false); + activeToolboxButton("clock", false); + activeToolboxButton("percentile_item", false); + activeToolboxButton("group_item", false); + activeToolboxButton("box_item", false); + activeToolboxButton("line_item", false); + activeToolboxButton("color_cloud", false); - activeToolboxButton('copy_item', false); - activeToolboxButton('edit_item', false); - activeToolboxButton('delete_item', false); - activeToolboxButton('show_grid', false); + activeToolboxButton("copy_item", false); + activeToolboxButton("edit_item", false); + activeToolboxButton("delete_item", false); + activeToolboxButton("show_grid", false); - if (typeof(enterprise_activeToolboxButton) == 'function') { - enterprise_activeToolboxButton(false); - } + if (typeof enterprise_activeToolboxButton == "function") { + enterprise_activeToolboxButton(false); + } - if (creationItem != null) { - //Create a item + if (creationItem != null) { + //Create a item - activeToolboxButton(creationItem, true); - item = creationItem; - $("#button_update_row").css('display', 'none'); - $("#button_create_row").css('display', ''); - cleanFields(item); - unselectAll(); - } - else if (selectedItem != null) { - //Edit a item + activeToolboxButton(creationItem, true); + item = creationItem; + $("#button_update_row").css("display", "none"); + $("#button_create_row").css("display", ""); + cleanFields(item); + unselectAll(); + } else if (selectedItem != null) { + //Edit a item - item = selectedItem; - toolbuttonActive = item; + item = selectedItem; + toolbuttonActive = item; - switch (item) { - case 'handler_start': - case 'handler_end': - activeToolboxButton('line_item', true); - break; - default: - activeToolboxButton(toolbuttonActive, true); - break; - } + switch (item) { + case "handler_start": + case "handler_end": + activeToolboxButton("line_item", true); + break; + default: + activeToolboxButton(toolbuttonActive, true); + break; + } + $("#button_create_row").css("display", "none"); + $("#button_update_row").css("display", ""); + cleanFields(); - $("#button_create_row").css('display', 'none'); - $("#button_update_row").css('display', ''); - cleanFields(); + loadFieldsFromDB(item); + } - loadFieldsFromDB(item); - } + hiddenFields(item); - hiddenFields(item); - - $("#show_on_top_row").css('display', 'table-row'); - $("#show_on_top." + item).css('display', 'block'); + $("#show_on_top_row").css("display", "table-row"); + $("#show_on_top." + item).css("display", "block"); - $("#properties_panel").show("fast"); - - $( ".lineheighttd").remove(); - //$('.mceToolbarEndButton').before( - // '' - //); - $('.mceToolbarEndButton').before( - '' - ); - - $('.lineheight').click(function(){ - $( "#text-label_ifr" ).contents().find( "p" ).attr( "data-mce-style","line-height:"+$(this).val()+";"); - $( "#text-label_ifr" ).contents().find( "p" ).css("line-height",$(this).val()); - $( "#text-label_ifr" ).contents().find( "span" ).attr( "data-mce-style","line-height:"+$(this).val()+";"); - $( "#text-label_ifr" ).contents().find( "span" ).css("line-height",$(this).val()); - - }); - - $( "#text-label_ifr" ).contents().find( "p" ).css("line-height",$('#lineheight').val()); - $( "#text-label_ifr" ).contents().find( "span" ).css("line-height",$('#lineheight').val()); - $( "#text-label_ifr" ).contents().find( "body" ).css("background","lightgray"); - - } - - if(creationItem != 'simple_value'){ - $("#data_image_check").html('Off'); - $("#data_image_check").css('display','none'); - $("#data_image_check_label").css('display','none'); - $("#data_image_container").css('display','none'); - $('.block_tinymce').remove(); - } + $("#properties_panel").show("fast"); + + $(".lineheighttd").remove(); + //$('.mceToolbarEndButton').before( + // '' + //); + $(".mceToolbarEndButton").before( + '' + ); + + $(".lineheight").click(function() { + $("#text-label_ifr") + .contents() + .find("p") + .attr("data-mce-style", "line-height:" + $(this).val() + ";"); + $("#text-label_ifr") + .contents() + .find("p") + .css("line-height", $(this).val()); + $("#text-label_ifr") + .contents() + .find("span") + .attr("data-mce-style", "line-height:" + $(this).val() + ";"); + $("#text-label_ifr") + .contents() + .find("span") + .css("line-height", $(this).val()); + }); + + $("#text-label_ifr") + .contents() + .find("p") + .css("line-height", $("#lineheight").val()); + $("#text-label_ifr") + .contents() + .find("span") + .css("line-height", $("#lineheight").val()); + $("#text-label_ifr") + .contents() + .find("body") + .css("background", "lightgray"); + } + + if (creationItem != "simple_value") { + $("#data_image_check").html("Off"); + $("#data_image_check").css("display", "none"); + $("#data_image_check_label").css("display", "none"); + $("#data_image_container").css("display", "none"); + $(".block_tinymce").remove(); + } } function fill_parent_select(id_item) { - //Populate the parent widget - $("#parent option") - .filter(function() { if ($(this).attr('value') != 0) return true; }) - .remove(); - jQuery.each(parents, function(key, value) { - if (value == undefined) { - return; - } - if (id_item == key) { - return; //continue - } + //Populate the parent widget + $("#parent option") + .filter(function() { + if ($(this).attr("value") != 0) return true; + }) + .remove(); + jQuery.each(parents, function(key, value) { + if (value == undefined) { + return; + } + if (id_item == key) { + return; //continue + } - $("#parent").append($('')); - }); + $("#parent").append( + $('") + ); + }); } function loadFieldsFromDB(item) { - $("#loading_in_progress_dialog").dialog({ - resizable: true, - draggable: true, - modal: true, - height: 100, - width: 200, - overlay: { - opacity: 0.5, - background: "black" - } - }); + $("#loading_in_progress_dialog").dialog({ + resizable: true, + draggable: true, + modal: true, + height: 100, + width: 200, + overlay: { + opacity: 0.5, + background: "black" + } + }); - parameter = Array(); - parameter.push ({name: "page", - value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "load"}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - parameter.push ({name: "type", value: item}); - parameter.push ({name: "id_element", value: idItem}); + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "load" }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "type", value: item }); + parameter.push({ name: "id_element", value: idItem }); - set_label = false; + set_label = false; - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - var moduleId = 0; + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + var moduleId = 0; - fill_parent_select(idItem); - - jQuery.each(data, function(key, val) { - if (key == 'event_max_time_row') - $("select[name=event_max_time_row]").val(val); - if (key == 'background') - $("#background_image").val(val); - if (key == 'width') $("input[name=width]").val(val); - if (key == 'height') - $("input[name=height]").val(val); + fill_parent_select(idItem); - if (key == 'label') { - tinymce.get('text-label') - .setContent(""); - $("input[name=label]").val(""); + jQuery.each(data, function(key, val) { + if (key == "event_max_time_row") + $("select[name=event_max_time_row]").val(val); + if (key == "background") $("#background_image").val(val); + if (key == "width") $("input[name=width]").val(val); + if (key == "height") $("input[name=height]").val(val); - tinymce.get('text-label').setContent(val); - $("input[name=label]").val(val); - } - - $('#lineheight').val($("#text-label_ifr").contents().find("p").css('line-height')); + if (key == "label") { + tinymce.get("text-label").setContent(""); + $("input[name=label]").val(""); - if (key == 'enable_link') { - if (val == "1") { - $("input[name=enable_link]") - .prop("checked", true); - } - else { - $("input[name=enable_link]") - .prop("checked", false); - } - } - - if (key == 'show_statistics') { - if (val == "1") { - $("input[name=show_statistics]") - .prop("checked", true); - } - else { - $("input[name=show_statistics]") - .prop("checked", false); - } - } - - if (key == 'show_on_top') { - if (val == "1") { - $("input[name=show_on_top]") - .prop("checked", true); - } - else { - $("input[name=show_on_top]") - .prop("checked", false); - } - } - - if (key == 'type_graph') { - $("select[name=type_graph]").val(val); - } - - if (key == 'label_position') { - if($("#hidden-metaconsole").val() == 1){ - $('#labelposup'+" img").attr('src','../../images/label_up.png'); - $('#labelposdown'+" img").attr('src','../../images/label_down.png'); - $('#labelposleft'+" img").attr('src','../../images/label_left.png'); - $('#labelposright'+" img").attr('src','../../images/label_right.png'); - $('.labelpos').attr('sel','no'); - $('#labelpos'+val+" img").attr('src','../../images/label_'+$('#labelpos'+val).attr('id').replace('labelpos','')+'_2.png'); - $('#labelpos'+val).attr('sel','yes'); - } - else{ - $('#labelposup'+" img").attr('src','images/label_up.png'); - $('#labelposdown'+" img").attr('src','images/label_down.png'); - $('#labelposleft'+" img").attr('src','images/label_left.png'); - $('#labelposright'+" img").attr('src','images/label_right.png'); - $('.labelpos').attr('sel','no'); - $('#labelpos'+val+" img").attr('src','images/label_'+$('#labelpos'+val).attr('id').replace('labelpos','')+'_2.png'); - $('#labelpos'+val).attr('sel','yes'); - } - } - - if (key == 'image') { - //Load image preview - $("select[name=image]").val(val); - $("select[name=background_color]").val(val); - showPreview(val); - } + tinymce.get("text-label").setContent(val); + $("input[name=label]").val(val); + } - if (key == 'pos_x') $("input[name=left]").val(val); - if (key == 'pos_y') $("input[name=top]").val(val); - if (key == 'agent_name') { - $("input[name=agent]").val(val); - $("input[name=agent_string]").val(val); - //Reload no-sincrone the select of modules - } - - if (key == 'id_agent') { - $("input[name=id_agent]").val(val); - } - if (key == 'id_agent_string') { - $("input[name=id_agent_string]").val(val); - } - if (key == 'modules_html') { - $("select[name=module]").empty().html(val); - $("select[name=module]").val(moduleId); - } - if (key == 'id_agente_modulo') { - moduleId = val; - $("select[name=module]").val(val); - } - if (key == 'process_value') - $("select[name=process_value]").val(val); - if (key == 'period') { - var anySelected = false; - var periodId = $('#hidden-period').attr('class'); - $('#' + periodId + '_select option') - .each(function() { + $("#lineheight").val( + $("#text-label_ifr") + .contents() + .find("p") + .css("line-height") + ); - if($(this).val() == val) { - $(this).prop('selected', true); - $(this).trigger('change'); - anySelected = true; - } - }); - if (anySelected == false) { - $('#' + periodId + '_select option') - .eq(0).prop('selected', true); - $('#' + periodId + '_units option') - .eq(0).prop('selected', true); - $('#hidden-period').val(val); - $('#text-' + periodId + '_text').val(val); - adjustTextUnits(periodId); - $('#' + periodId + '_default').hide(); - $('#' + periodId + '_manual').show(); - } - } - if (key == 'width') - $("input[name=width]").val(val); - if (key == 'height') - $("input[name=height]").val(val); - if (key == 'parent_item') - $("select[name=parent]").val(val); - if (key == 'linked_layout_status_type') - $("select[name=linked_map_status_calculation_type]").val(val).change(); - if (key == 'id_layout_linked') { - if (val != 0) { - if (data['linked_layout_node_id'] == null) { - $("select[name=map_linked]").val(val).change(); - } else { - var $option = $("select[name=map_linked] > option[data-node-id=" + data['linked_layout_node_id'] + "][value=" + val + "]"); - if ($option.length === 0) $option = $("select[name=map_linked] > option[value=" + val + "]"); - $option.prop("selected", true).parent().change(); - } - } - } - if (key == 'linked_layout_node_id') - $("input[name=linked_map_node_id]").val(val); - if (key == 'id_layout_linked_weight') - $("input[name=map_linked_weight]").val(val); - if (key == 'linked_layout_status_as_service_critical') - $("input[name=linked_map_status_service_critical]").val(val); - if (key == 'linked_layout_status_as_service_warning') - $("input[name=linked_map_status_service_warning]").val(val); - if (key == 'element_group') - $("select[name=element_group]").val(val); - if (key == 'width_percentile') - $("input[name=width_percentile]").val(val); - if (key == 'bars_graph_height') - $("input[name=bars_graph_height]").val(val); - if (key == 'max_percentile') - $("input[name=max_percentile]").val(val); - if (key == 'width_module_graph') - $("input[name=width_module_graph]").val(val); - if (key == 'height_module_graph') - $("input[name=height_module_graph]").val(val); - if (key == 'bars_graph_type') - $("select[name=bars_graph_type]").val(val); - if (key == 'type_percentile') - $("select[name=type_percentile]").val(val); - if (key == 'percentile_label') - $("input[name=percentile_label]").val(val); - if (key == 'percentile_color') { - $("input[name=percentile_color]").val(val); - $("#percentile_item_row_5 .ColorPickerDivSample") - .css('background-color', val); - } - if (key == 'percentile_label_color') { - $("input[name=percentile_label_color]").val(val); - $("#percentile_item_row_6 .ColorPickerDivSample") - .css('background-color', val); - } - - if (key == 'show_last_value') { - $("select[name=last_value]").val(val); - } - - if (key == 'clock_animation') - $("select[name=clock_animation]").val(val); - if (key == 'time_format') - $("select[name=time_format]").val(val); - if (key == 'timezone') { - var zone = val.split("/"); - $("select[name=zone]").val(zone[0]); - - $.ajax({ - type: "POST", - url: "ajax.php", - data: "page=godmode/setup/setup&select_timezone=1&zone=" + zone[0], - dataType: "json", - success: function(data) { - $("#timezone").empty(); - jQuery.each (data, function (id, value) { - timezone = value; - var timezone_country = timezone.replace (/^.*\//g, ""); - $("select[name='timezone']").append($("" + ) + ); - var anyText = $("#any_text").html(); //Trick for catch the translate text. - $("#module") - .empty() - .append($('')); - - //Code for the graphs - $("input[name='radio_choice'][value='module_graph']") - .prop('checked', true); - $("input[name='radio_choice']").trigger('change'); - - //Select none custom graph - $("#custom_graph option[value=0]") - .prop('selected', true); + //Code for the graphs + $("input[name='radio_choice'][value='module_graph']").prop("checked", true); + $("input[name='radio_choice']").trigger("change"); + //Select none custom graph + $("#custom_graph option[value=0]").prop("selected", true); } function set_static_graph_status(idElement, image, status) { - $("#image_" + idElement).attr('src', "images/spinner.gif"); + $("#image_" + idElement).attr("src", "images/spinner.gif"); - if (typeof(status) == 'undefined') { - var parameter = Array(); - parameter.push ({ - name: "page", - value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({ - name: "get_element_status", - value: "1"}); - parameter.push ({ - name: "id_element", - value: idElement}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); + if (typeof status == "undefined") { + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ + name: "get_element_status", + value: "1" + }); + parameter.push({ + name: "id_element", + value: idElement + }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); - if (is_metaconsole()) { - parameter.push ({name: "metaconsole", value: 1}); - } - else { - parameter.push ({name: "metaconsole", value: 0}); - } + if (is_metaconsole()) { + parameter.push({ name: "metaconsole", value: 1 }); + } else { + parameter.push({ name: "metaconsole", value: 0 }); + } - $('#hidden-status_' + idElement).val(3); - jQuery.ajax ({ - type: 'POST', - url: get_url_ajax(), - data: parameter, - success: function (data) { - set_static_graph_status(idElement, image, data); - if(data['show_statistics'] == 1){ - if($('#'+idElement+' table').css('float') == 'right' || $('#'+idElement+ ' table').css('float') == 'left'){ - $('#'+idElement+ ' img').css('margin-top', parseInt($('#'+idElement).css('height'))/2 - parseInt($('#'+idElement+ ' img').css('height'))/2); - } - else{ - $('#'+idElement+ ' img').css('margin-left', parseInt($('#'+idElement).css('width'))/2 - parseInt($('#'+idElement+ ' img').css('width'))/2); - } - } - } - }); + $("#hidden-status_" + idElement).val(3); + jQuery.ajax({ + type: "POST", + url: get_url_ajax(), + data: parameter, + success: function(data) { + set_static_graph_status(idElement, image, data); + if (data["show_statistics"] == 1) { + if ( + $("#" + idElement + " table").css("float") == "right" || + $("#" + idElement + " table").css("float") == "left" + ) { + $("#" + idElement + " img").css( + "margin-top", + parseInt($("#" + idElement).css("height")) / 2 - + parseInt($("#" + idElement + " img").css("height")) / 2 + ); + } else { + $("#" + idElement + " img").css( + "margin-left", + parseInt($("#" + idElement).css("width")) / 2 - + parseInt($("#" + idElement + " img").css("width")) / 2 + ); + } + } + } + }); - return; - } + return; + } - switch (status) { - case '1': - //Critical (BAD) - suffix = "_bad.png"; - break; - case '4': - //Critical (ALERT) - suffix = "_bad.png"; - break; - case '0': - //Normal (OK) - suffix = "_ok.png"; - break; - case '2': - //Warning - suffix = "_warning.png"; - break; - case '3': - default: - //Unknown - suffix = ".png"; - break; - } - set_image("image", idElement, image + suffix); + switch (status) { + case "1": + //Critical (BAD) + suffix = "_bad.png"; + break; + case "4": + //Critical (ALERT) + suffix = "_bad.png"; + break; + case "0": + //Normal (OK) + suffix = "_ok.png"; + break; + case "2": + //Warning + suffix = "_warning.png"; + break; + case "3": + default: + //Unknown + suffix = ".png"; + break; + } + set_image("image", idElement, image + suffix); } function set_image(type, idElement, image) { - - if(image == 'show_statistics_bad.png' || image == 'show_statistics_ok.png' || image == 'show_statistics_warning.png' || image == 'show_statistics.png'){ - item = "#image_" + idElement; - img_src = "images/console/signes/group_status.png"; - } - else{ - - if (type == "image") { - item = "#image_" + idElement; - img_src = "images/console/icons/" + image; - } - else if (type == "background") { - item = "#background_img"; - img_src = "images/console/background/" + image; - } - - } - - - var params = []; - params.push("get_image_path=1"); - params.push("img_src=" + img_src); - params.push("page=include/ajax/skins.ajax"); - params.push("only_src=1"); - params.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: get_url_ajax(), - success: function (data) { - $(item).attr('src', data); - - if(image == 'show_statistics_bad.png' || image == 'show_statistics_ok.png' || image == 'show_statistics_warning.png' || image == 'show_statistics.png'){ - $(item).attr('width', 520); - $(item).attr('height', 80); - } - - } - }); + if ( + image == "show_statistics_bad.png" || + image == "show_statistics_ok.png" || + image == "show_statistics_warning.png" || + image == "show_statistics.png" + ) { + item = "#image_" + idElement; + img_src = "images/console/signes/group_status.png"; + } else { + if (type == "image") { + item = "#image_" + idElement; + img_src = "images/console/icons/" + image; + } else if (type == "background") { + item = "#background_img"; + img_src = "images/console/background/" + image; + } + } + + var params = []; + params.push("get_image_path=1"); + params.push("img_src=" + img_src); + params.push("page=include/ajax/skins.ajax"); + params.push("only_src=1"); + params.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: get_url_ajax(), + success: function(data) { + $(item).attr("src", data); + + if ( + image == "show_statistics_bad.png" || + image == "show_statistics_ok.png" || + image == "show_statistics_warning.png" || + image == "show_statistics.png" + ) { + $(item).attr("width", 520); + $(item).attr("height", 80); + } + } + }); } function setBarsGraph(id_data, values) { - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - width_percentile = values['width_percentile']; - bars_graph_height = values['bars_graph_height']; + width_percentile = values["width_percentile"]; + bars_graph_height = values["bars_graph_height"]; - parameter = Array(); - - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_type_string"}); - parameter.push ({name: "id_agent", value: values['id_agent_string']}); - parameter.push ({name: "module", value: values['module']}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/barras.png'); - - if (values['width_percentile'] == "0" && values["bars_graph_height"] == "0") { - // Image size - } - else{ - $("#" + id_data + " img").css('width', width_percentile + 'px'); - $("#" + id_data + " img").css('height', bars_graph_height + 'px'); - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left', parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - } - }); + parameter = Array(); + + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_type_string" }); + parameter.push({ name: "id_agent", value: values["id_agent_string"] }); + parameter.push({ name: "module", value: values["module"] }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/barras.png" + ); + + if ( + values["width_percentile"] == "0" && + values["bars_graph_height"] == "0" + ) { + // Image size + } else { + $("#" + id_data + " img").css("width", width_percentile + "px"); + $("#" + id_data + " img").css("height", bars_graph_height + "px"); + } + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } function setClock(id_data, values) { - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - parameter = Array(); - - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_type_string"}); - parameter.push ({name: "time_format", value: values['time_format']}); - parameter.push ({name: "timezone", value: values['timezone']}); - parameter.push ({name: "clock_animation", value: values['clock_animation']}); - parameter.push ({name: "label", value: values['label']}); - parameter.push ({name: "width", value: values['width_percentile']}); - parameter.push ({name: "always_on_top", value: values['always_on_top']}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - - if(values['clock_animation'] == 'analogic_1'){ - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/clock.png'); - } - else{ - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/digital-clock.png'); - } - - if (values['width_percentile'] == 0) { - if(values['clock_animation'] == 'analogic_1'){ - $("#" + id_data + " img").css('width', 200 + 'px'); - $("#" + id_data + " img").css('height', 240 + 'px'); - } - else{ - $("#" + id_data + " img").css('width', 200 + 'px'); - - if(values['time_format'] == 'time'){ - $("#" + id_data + " img").css('height', 71 + 'px'); - } - else{ - $("#" + id_data + " img").css('height', 91 + 'px'); - } - - } - - } - else{ - if(values['clock_animation'] == 'analogic_1'){ - $("#" + id_data + " img").css('width', values['width_percentile'] + 'px'); - $("#" + id_data + " img").css('height', parseInt(values['width_percentile'])+40 + 'px'); - } - else{ - $("#" + id_data + " img").css('width', values['width_percentile'] + 'px'); - - if(values['time_format'] == 'time'){ - $("#" + id_data + " img").css('height', parseInt(values['width_percentile'])/3.9+20 + 'px'); - } - else{ - $("#" + id_data + " img").css('height', parseInt(values['width_percentile'])/3.9+40 + 'px'); - } - } - - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left', parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - } - }); + parameter = Array(); + + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_type_string" }); + parameter.push({ name: "time_format", value: values["time_format"] }); + parameter.push({ name: "timezone", value: values["timezone"] }); + parameter.push({ name: "clock_animation", value: values["clock_animation"] }); + parameter.push({ name: "label", value: values["label"] }); + parameter.push({ name: "width", value: values["width_percentile"] }); + parameter.push({ name: "always_on_top", value: values["always_on_top"] }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (values["clock_animation"] == "analogic_1") { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/clock.png" + ); + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/digital-clock.png" + ); + } + + if (values["width_percentile"] == 0) { + if (values["clock_animation"] == "analogic_1") { + $("#" + id_data + " img").css("width", 200 + "px"); + $("#" + id_data + " img").css("height", 240 + "px"); + } else { + $("#" + id_data + " img").css("width", 200 + "px"); + + if (values["time_format"] == "time") { + $("#" + id_data + " img").css("height", 71 + "px"); + } else { + $("#" + id_data + " img").css("height", 91 + "px"); + } + } + } else { + if (values["clock_animation"] == "analogic_1") { + $("#" + id_data + " img").css( + "width", + values["width_percentile"] + "px" + ); + $("#" + id_data + " img").css( + "height", + parseInt(values["width_percentile"]) + 40 + "px" + ); + } else { + $("#" + id_data + " img").css( + "width", + values["width_percentile"] + "px" + ); + + if (values["time_format"] == "time") { + $("#" + id_data + " img").css( + "height", + parseInt(values["width_percentile"]) / 3.9 + 20 + "px" + ); + } else { + $("#" + id_data + " img").css( + "height", + parseInt(values["width_percentile"]) / 3.9 + 40 + "px" + ); + } + } + } + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } function setModuleGraph(id_data) { - var parameter = Array(); + var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_layout_data"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_layout_data" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - id_agente_modulo = data['id_agente_modulo']; - id_custom_graph = data['id_custom_graph']; - label = data['label']; - height = (data['height']); - width = (data['width']); - period = data['period']; - background_color = data['image']; + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + id_agente_modulo = data["id_agente_modulo"]; + id_custom_graph = data["id_custom_graph"]; + label = data["label"]; + height = data["height"]; + width = data["width"]; + period = data["period"]; + background_color = data["image"]; - if (is_metaconsole()) { - id_metaconsole = data['id_metaconsole']; - } + if (is_metaconsole()) { + id_metaconsole = data["id_metaconsole"]; + } - //Cleaned array - parameter = Array(); + //Cleaned array + parameter = Array(); - parameter.push ({name: "page", - value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_image_sparse"}); - parameter.push ({name: "id_agent_module", value: id_agente_modulo}); - parameter.push ({name: "id_custom_graph", value: id_custom_graph}); - if (is_metaconsole()) { - parameter.push ({name: "id_metaconsole", value: id_metaconsole}); - } - parameter.push ({name: "type", value: 'module_graph'}); - parameter.push ({name: "height", value: height}); - parameter.push ({name: "width", value: width}); - parameter.push ({name: "period", value: period}); - parameter.push ({name: "background_color", value: background_color}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) - { - - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } - - if (data['no_data'] == true) { - $('#' + id_data).html(data['url']); - } - else { - if($("#module_row").css('display')!='none'){ - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/module_graph.png'); - if($('#text-width_module_graph').val() == 0 || $('#text-height_module_graph').val() == 0){ - $("#" + id_data + " img").css('width', '300px'); - $("#" + id_data + " img").css('height', '180px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_module_graph').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-height_module_graph').val()+'px'); - } - }else{ - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/custom_graph.png'); - if($('#text-width_module_graph').val() == 0 || $('#text-height_module_graph').val() == 0){ - $("#" + id_data + " img").css('width', '300px'); - $("#" + id_data + " img").css('height', '180px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_module_graph').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-height_module_graph').val()+'px'); - } - } - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - - } - }); - } - }); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_image_sparse" }); + parameter.push({ name: "id_agent_module", value: id_agente_modulo }); + parameter.push({ name: "id_custom_graph", value: id_custom_graph }); + if (is_metaconsole()) { + parameter.push({ name: "id_metaconsole", value: id_metaconsole }); + } + parameter.push({ name: "type", value: "module_graph" }); + parameter.push({ name: "height", value: height }); + parameter.push({ name: "width", value: width }); + parameter.push({ name: "period", value: period }); + parameter.push({ name: "background_color", value: background_color }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } + if (data["no_data"] == true) { + $("#" + id_data).html(data["url"]); + } else { + if ($("#module_row").css("display") != "none") { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/module_graph.png" + ); + if ( + $("#text-width_module_graph").val() == 0 || + $("#text-height_module_graph").val() == 0 + ) { + $("#" + id_data + " img").css("width", "300px"); + $("#" + id_data + " img").css("height", "180px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_module_graph").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-height_module_graph").val() + "px" + ); + } + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/custom_graph.png" + ); + if ( + $("#text-width_module_graph").val() == 0 || + $("#text-height_module_graph").val() == 0 + ) { + $("#" + id_data + " img").css("width", "300px"); + $("#" + id_data + " img").css("height", "180px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_module_graph").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-height_module_graph").val() + "px" + ); + } + } + } + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); + } + }); } -function setModuleValue(id_data, process_simple_value, period, width_data_image) { - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "period", value: period}); - parameter.push ({name: "width", value: width_data_image}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - if (process_simple_value != undefined) { - parameter.push ({name: "process_simple_value", value: process_simple_value}); - } - - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - var currentValue = $("#text_" + id_data).html(); - - $("#text_" + id_data).html(currentValue); - } - }); +function setModuleValue( + id_data, + process_simple_value, + period, + width_data_image +) { + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "period", value: period }); + parameter.push({ name: "width", value: width_data_image }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + if (process_simple_value != undefined) { + parameter.push({ + name: "process_simple_value", + value: process_simple_value + }); + } + + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + var currentValue = $("#text_" + id_data).html(); + + $("#text_" + id_data).html(currentValue); + } + }); } function setPercentileBar(id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - max_percentile = values['max_percentile']; - width_percentile = values['width_percentile']; + max_percentile = values["max_percentile"]; + width_percentile = values["width_percentile"]; - var parameter = Array(); + var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "value_show", value: values['value_show']}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - module_value = data['value']; - max_percentile = data['max_percentile']; - width_percentile = data['width_percentile']; - unit_text = false; + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "value_show", value: values["value_show"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + module_value = data["value"]; + max_percentile = data["max_percentile"]; + width_percentile = data["width_percentile"]; + unit_text = false; - if ((data['unit_text'] != false) || typeof(data['unit_text']) != 'boolean') { - unit_text = data['unit_text']; - } + if (data["unit_text"] != false || typeof data["unit_text"] != "boolean") { + unit_text = data["unit_text"]; + } - colorRGB = data['colorRGB']; + colorRGB = data["colorRGB"]; - if ( max_percentile > 0) - var percentile = Math.round(module_value / max_percentile * 100); - else - var percentile = 100; + if (max_percentile > 0) + var percentile = Math.round((module_value / max_percentile) * 100); + else var percentile = 100; - if (unit_text == false && typeof(unit_text) == 'boolean') { - value_text = percentile + "%"; - } - else { - value_text = module_value + " " + unit_text; - } + if (unit_text == false && typeof unit_text == "boolean") { + value_text = percentile + "%"; + } else { + value_text = module_value + " " + unit_text; + } - var img = url_hack_metaconsole + 'include/graphs/fgraph.php?graph_type=progressbar&height=15&' + - 'width=' + width_percentile + '&mode=1&progress=' + percentile + - '&value_text=' + value_text + '&colorRGB=' + colorRGB; + var img = + url_hack_metaconsole + + "include/graphs/fgraph.php?graph_type=progressbar&height=15&" + + "width=" + + width_percentile + + "&mode=1&progress=" + + percentile + + "&value_text=" + + value_text + + "&colorRGB=" + + colorRGB; - $("#"+ id_data).attr('src', img); - - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/percentil.png'); - if($('#text-width_percentile').val() == 0){ - $("#" + id_data + " img").css('width', '130px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - } - - $("#" + id_data + " img").css('height', '30px'); - - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - - - } - }); + $("#" + id_data).attr("src", img); + + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/percentil.png" + ); + if ($("#text-width_percentile").val() == 0) { + $("#" + id_data + " img").css("width", "130px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + } + + $("#" + id_data + " img").css("height", "30px"); + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } -function setPercentileCircular (id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); +function setPercentileCircular(id_data, values) { + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - max_percentile = values['max_percentile']; - width_percentile = values['width_percentile']; + max_percentile = values["max_percentile"]; + width_percentile = values["width_percentile"]; - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "value_show", value: values['value_show']}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - module_value = data['value']; - max_percentile = data['max_percentile']; - width_percentile = data['width_percentile']; - unit_text = false; + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "value_show", value: values["value_show"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + module_value = data["value"]; + max_percentile = data["max_percentile"]; + width_percentile = data["width_percentile"]; + unit_text = false; - if ((data['unit_text'] != false) || typeof(data['unit_text']) != 'boolean') { - unit_text = data['unit_text']; - } + if (data["unit_text"] != false || typeof data["unit_text"] != "boolean") { + unit_text = data["unit_text"]; + } - colorRGB = data['colorRGB']; + colorRGB = data["colorRGB"]; - if ( max_percentile > 0) - var percentile = Math.round(module_value / max_percentile * 100); - else - var percentile = 100; + if (max_percentile > 0) + var percentile = Math.round((module_value / max_percentile) * 100); + else var percentile = 100; - if (unit_text == false && typeof(unit_text) == 'boolean') { - value_text = percentile + "%"; - } - else { - value_text = module_value + " " + unit_text; - } + if (unit_text == false && typeof unit_text == "boolean") { + value_text = percentile + "%"; + } else { + value_text = module_value + " " + unit_text; + } - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/circular-progress-bar.png'); - if($('#text-width_percentile').val() == 0){ - $("#" + id_data + " img").css('width', '130px'); - $("#" + id_data + " img").css('height', '130px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-width_percentile').val()+'px'); - } + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/circular-progress-bar.png" + ); + if ($("#text-width_percentile").val() == 0) { + $("#" + id_data + " img").css("width", "130px"); + $("#" + id_data + " img").css("height", "130px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-width_percentile").val() + "px" + ); + } - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - } - }); + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } -function setPercentileInteriorCircular (id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); +function setPercentileInteriorCircular(id_data, values) { + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - max_percentile = values['max_percentile']; - width_percentile = values['width_percentile']; + max_percentile = values["max_percentile"]; + width_percentile = values["width_percentile"]; - var parameter = Array(); + var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "value_show", value: values['value_show']}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - module_value = data['value']; - max_percentile = data['max_percentile']; - width_percentile = data['width_percentile']; - unit_text = false; + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "value_show", value: values["value_show"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + module_value = data["value"]; + max_percentile = data["max_percentile"]; + width_percentile = data["width_percentile"]; + unit_text = false; - if ((data['unit_text'] != false) || typeof(data['unit_text']) != 'boolean') { - unit_text = data['unit_text']; - } + if (data["unit_text"] != false || typeof data["unit_text"] != "boolean") { + unit_text = data["unit_text"]; + } - colorRGB = data['colorRGB']; + colorRGB = data["colorRGB"]; - if ( max_percentile > 0) - var percentile = Math.round(module_value / max_percentile * 100); - else - var percentile = 100; + if (max_percentile > 0) + var percentile = Math.round((module_value / max_percentile) * 100); + else var percentile = 100; - if (unit_text == false && typeof(unit_text) == 'boolean') { - value_text = percentile + "%"; - } - else { - value_text = module_value + " " + unit_text; - } - - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/circular-progress-bar-interior.png'); - if($('#text-width_percentile').val() == 0){ - $("#" + id_data + " img").css('width', '130px'); - $("#" + id_data + " img").css('height', '130px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-width_percentile').val()+'px'); - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - } - }); + if (unit_text == false && typeof unit_text == "boolean") { + value_text = percentile + "%"; + } else { + value_text = module_value + " " + unit_text; + } + + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + + "images/console/signes/circular-progress-bar-interior.png" + ); + if ($("#text-width_percentile").val() == 0) { + $("#" + id_data + " img").css("width", "130px"); + $("#" + id_data + " img").css("height", "130px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-width_percentile").val() + "px" + ); + } + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); } function setEventsBar(id_data, values) { - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - parameter = Array(); + parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_events"}); - parameter.push ({name: "id_agent", value: values['id_agent']}); - parameter.push ({name: "id_agent_module", value: values['module']}); - if (is_metaconsole()) { - parameter.push ({name: "id_metaconsole", value: values['server_id']}); - } - parameter.push ({name: "period", value: values['event_max_time_row']}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['no_data'] == true) { - if (values['width'] == "0" || values['height'] == "0") { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/module-events.png'); - } - else { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/module-events.png'); - $("#" + id_data + " img").css('width', values['width'] + 'px'); - $("#" + id_data + " img").css('height', values['height'] + 'px'); - } - } - else { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/module-events.png'); - - if($('#text-width').val() == 0 || $('#text-height').val() == 0){ - $("#" + id_data + " img").css('width', '300px'); - $("#" + id_data + " img").css('height', '180px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-height').val()+'px'); - } - } - } - }); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_events" }); + parameter.push({ name: "id_agent", value: values["id_agent"] }); + parameter.push({ name: "id_agent_module", value: values["module"] }); + if (is_metaconsole()) { + parameter.push({ name: "id_metaconsole", value: values["server_id"] }); + } + parameter.push({ name: "period", value: values["event_max_time_row"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["no_data"] == true) { + if (values["width"] == "0" || values["height"] == "0") { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/module-events.png" + ); + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/module-events.png" + ); + $("#" + id_data + " img").css("width", values["width"] + "px"); + $("#" + id_data + " img").css("height", values["height"] + "px"); + } + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/module-events.png" + ); + + if ($("#text-width").val() == 0 || $("#text-height").val() == 0) { + $("#" + id_data + " img").css("width", "300px"); + $("#" + id_data + " img").css("height", "180px"); + } else { + $("#" + id_data + " img").css("width", $("#text-width").val() + "px"); + $("#" + id_data + " img").css( + "height", + $("#text-height").val() + "px" + ); + } + } + } + }); } -function setDonutsGraph (id_data, values) { - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } +function setDonutsGraph(id_data, values) { + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - width_percentile = values['width_percentile']; + width_percentile = values["width_percentile"]; - parameter = Array(); + parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_type_string"}); - parameter.push ({name: "id_agent", value: values['id_agent_string']}); - parameter.push ({name: "module", value: values['module']}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['no_data'] == true) { - if (values['width'] == "0") { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/wrong_donut_graph.png'); - } - else { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/wrong_donut_graph.png'); - $("#" + id_data + " img").css('width', width_percentile + 'px'); - $("#" + id_data + " img").css('height', width_percentile + 'px'); - } - } - else { - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/donut-graph.png'); - - if($('#text-width_percentile').val() == 0){ - // Image size - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-width_percentile').val()+'px'); - } - } - } - }); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_type_string" }); + parameter.push({ name: "id_agent", value: values["id_agent_string"] }); + parameter.push({ name: "module", value: values["module"] }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["no_data"] == true) { + if (values["width"] == "0") { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/wrong_donut_graph.png" + ); + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/wrong_donut_graph.png" + ); + $("#" + id_data + " img").css("width", width_percentile + "px"); + $("#" + id_data + " img").css("height", width_percentile + "px"); + } + } else { + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/donut-graph.png" + ); + + if ($("#text-width_percentile").val() == 0) { + // Image size + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-width_percentile").val() + "px" + ); + } + } + } + }); } function setPercentileBubble(id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - max_percentile = values['max_percentile']; - width_percentile = values['width_percentile']; + max_percentile = values["max_percentile"]; + width_percentile = values["width_percentile"]; - var parameter = Array(); + var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_module_value"}); - parameter.push ({name: "id_element", value: id_data}); - parameter.push ({name: "value_show", value: values['value_show']}); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - module_value = data['value']; - max_percentile = data['max_percentile']; - width_percentile = data['width_percentile']; - unit_text = false - if ((data['unit_text'] != false) || typeof(data['unit_text']) != 'boolean') - unit_text = data['unit_text']; - colorRGB = data['colorRGB']; + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_module_value" }); + parameter.push({ name: "id_element", value: id_data }); + parameter.push({ name: "value_show", value: values["value_show"] }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + module_value = data["value"]; + max_percentile = data["max_percentile"]; + width_percentile = data["width_percentile"]; + unit_text = false; + if (data["unit_text"] != false || typeof data["unit_text"] != "boolean") + unit_text = data["unit_text"]; + colorRGB = data["colorRGB"]; - if ( max_percentile > 0) - var percentile = Math.round(module_value / max_percentile * 100); - else - var percentile = 100; + if (max_percentile > 0) + var percentile = Math.round((module_value / max_percentile) * 100); + else var percentile = 100; - if (unit_text == false && typeof(unit_text) == 'boolean') { - value_text = percentile + "%"; - } - else { - value_text = module_value + " " + unit_text; - } + if (unit_text == false && typeof unit_text == "boolean") { + value_text = percentile + "%"; + } else { + value_text = module_value + " " + unit_text; + } - var img = url_hack_metaconsole + 'include/graphs/fgraph.php?graph_type=progressbubble&height=' + width_percentile + '&' + - 'width=' + width_percentile + '&mode=1&progress=' + percentile + - '&value_text=' + value_text + '&colorRGB=' + colorRGB; + var img = + url_hack_metaconsole + + "include/graphs/fgraph.php?graph_type=progressbubble&height=" + + width_percentile + + "&" + + "width=" + + width_percentile + + "&mode=1&progress=" + + percentile + + "&value_text=" + + value_text + + "&colorRGB=" + + colorRGB; - $("#image_" + id_data).attr('src', img); - - $("#" + id_data + " img").attr('src', url_hack_metaconsole + 'images/console/signes/percentil_bubble.png'); - - - if($('#text-width_percentile').val() == 0){ - $("#" + id_data + " img").css('width', '130px'); - $("#" + id_data + " img").css('height', '130px'); - } - else{ - $("#" + id_data + " img").css('width', $('#text-width_percentile').val()+'px'); - $("#" + id_data + " img").css('height', $('#text-width_percentile').val()+'px'); - } - - if($('#'+id_data+' table').css('float') == 'right' || $('#'+id_data+ ' table').css('float') == 'left'){ - $('#'+id_data+ ' img').css('margin-top', parseInt($('#'+id_data).css('height'))/2 - parseInt($('#'+id_data+ ' img').css('height'))/2); - } - else{ - $('#'+id_data+ ' img').css('margin-left',parseInt($('#'+id_data).css('width'))/2 - parseInt($('#'+id_data+ ' img').css('width'))/2); - } - - } - }); + $("#image_" + id_data).attr("src", img); + + $("#" + id_data + " img").attr( + "src", + url_hack_metaconsole + "images/console/signes/percentil_bubble.png" + ); + + if ($("#text-width_percentile").val() == 0) { + $("#" + id_data + " img").css("width", "130px"); + $("#" + id_data + " img").css("height", "130px"); + } else { + $("#" + id_data + " img").css( + "width", + $("#text-width_percentile").val() + "px" + ); + $("#" + id_data + " img").css( + "height", + $("#text-width_percentile").val() + "px" + ); + } + + if ( + $("#" + id_data + " table").css("float") == "right" || + $("#" + id_data + " table").css("float") == "left" + ) { + $("#" + id_data + " img").css( + "margin-top", + parseInt($("#" + id_data).css("height")) / 2 - + parseInt($("#" + id_data + " img").css("height")) / 2 + ); + } else { + $("#" + id_data + " img").css( + "margin-left", + parseInt($("#" + id_data).css("width")) / 2 - + parseInt($("#" + id_data + " img").css("width")) / 2 + ); + } + } + }); +} + +function setColorCloud(visualConsoleId, dataId, $container) { + $container = $container || $("#" + dataId + ".item.color_cloud"); + if ($container.length === 0) return; + + var $spinner = $container.children("img"); + var $svg = $container.children("svg"); + + if ($svg.length === 0) { + $svg = $(""); + $container.append($svg); + } + + if ($spinner.length > 0) $svg.hide(); + + jQuery + .post( + get_url_ajax(), + { + page: "include/ajax/visual_console_builder.ajax", + action: "get_color_cloud", + id_visual_console: visualConsoleId, + id_element: dataId + }, + null, + "html" + ) + .done(function(data) { + var $newSvg = $(data); + // Check if $newSvg contains a svg + if ($newSvg.is("svg")) $svg.replaceWith($newSvg); + }) + .always(function() { + if ($spinner.length > 0) $spinner.remove(); + $svg.show(); + }); } function get_image_url(img_src) { - var img_url= null; - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/skins.ajax"}); - parameter.push ({name: "get_image_path", value: true}); - parameter.push ({name: "img_src", value: img_src}); - parameter.push ({name: "only_src", value: true}); + var img_url = null; + var parameter = Array(); + parameter.push({ name: "page", value: "include/ajax/skins.ajax" }); + parameter.push({ name: "get_image_path", value: true }); + parameter.push({ name: "img_src", value: img_src }); + parameter.push({ name: "only_src", value: true }); - return $.ajax ({ - type: 'GET', - url: get_url_ajax(), - cache: false, - data: parameter - }); + return $.ajax({ + type: "GET", + url: get_url_ajax(), + cache: false, + data: parameter + }); } function set_color_line_status(lines, id_data, values) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_color_line"}); - parameter.push ({name: "id_element", value: id_data}); + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_color_line" }); + parameter.push({ name: "id_element", value: id_data }); - var color = null; + var color = null; - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - color = data['color_line']; + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + color = data["color_line"]; - var line = { - "id": id_data, - "node_begin": values['parent'], - "node_end": id_data, - "color": color }; + var line = { + id: id_data, + node_begin: values["parent"], + node_end: id_data, + color: color + }; - lines.push(line); - - refresh_lines(lines, 'background', true); - } - }); + lines.push(line); + refresh_lines(lines, "background", true); + } + }); } - - - function createItem(type, values, id_data) { - var sizeStyle = ''; - var imageSize = ''; - var item = null; + var sizeStyle = ""; + var imageSize = ""; + var item = null; - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); + switch (type) { + case "box_item": + if (values["width_box"] == 0 || values["height_box"] == 0) { + item = $( + '
    ' + + "
    ' + + "
    " + + "
    " + + '' + ); + } else { + item = $( + '
    ' + + "
    ' + + "
    " + + "
    " + + '' + ); + } - switch (type) { - case 'box_item': - - if(values['width_box'] == 0 || values['height_box'] == 0){ - item = $('
    ' - + '
    ' - + '
    ' - + '
    ' - + '' - ); - } - else{ - item = $('
    ' - + '
    ' - + '
    ' - + '
    ' - + '' - ); - } - - - break; - case 'group_item': - - class_type = "group_item"; - + break; + case "group_item": + class_type = "group_item"; - img_src = "images/spinner.gif"; + img_src = "images/spinner.gif"; - item = $('
    ') - .attr('id', id_data) - .attr('class', 'item ' + class_type) - .css('text-align', 'left') - .css('position', 'absolute') - .css('display', 'inline-block') - .css('top', values['top'] + 'px') - .css('left', values['left'] + 'px'); - - - - if(values['show_statistics'] != 1){ - if(values['label_position'] == 'left'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', 'images/console/signes/group_status.png') - .attr('style','float:right;'); - - } - else if(values['label_position'] == 'right'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', 'images/console/signes/group_status.png') - .attr('style','float:left;'); - - } - else{ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', 'images/console/signes/group_status.png'); - - } - } - else{ - if(values['label_position'] == 'left'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src) - .attr('style','float:right;'); - - } - else if(values['label_position'] == 'right'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src) - .attr('style','float:left;'); - - } - else{ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src); - - } - } - - - - if(values['show_statistics'] != 1){ - - if ((values['width'] == 0) || (values['height'] == 0)) { - // Do none - if(values['image'] != '' && values['image'] != 'none'){ - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalHeight'] > 150){ - $image.attr('width', '70') - .attr('height', '70'); - } - else{ - $image.attr('width', values['naturalWidth']) - .attr('height', values['naturalHeight']); - } - } - else{ - $image.attr('width', '70') - .attr('height', '70'); - } - } - else { - $image.attr('width', values['width']) - .attr('height', values['height']); - } - } - - var $input = $('') - .attr('id', 'hidden-status_' + id_data) - .attr('type', 'hidden') - .attr('value', -1) - .attr('name', 'status_' + id_data); + item = $("
    ") + .attr("id", id_data) + .attr("class", "item " + class_type) + .css("text-align", "left") + .css("position", "absolute") + .css("display", "inline-block") + .css("top", values["top"] + "px") + .css("left", values["left"] + "px"); - if(values['label_position'] == 'up'){ - - if((values['image'] == '' || values['image'] == 'none') && values['show_statistics'] != 1){ - item - .append('
    '+values['label']+'
    ') - .append($input); - } - else{ - item - .append('
    '+values['label']+'
    ') - .append($image) - .append($input); - } - - } - else if(values['label_position'] == 'down'){ - if((values['image'] == '' || values['image'] == 'none') && values['show_statistics'] != 1){ - item - .append('
    '+values['label']+'
    ') - .append($input); - - } - else{ - item - .append($image) - .append('
    '+values['label']+'
    ') - .append($input); - } - - } - else if(values['label_position'] == 'left'){ - - if(values['height'] == 0){ - item - .append('
    '+values['label']+'
    '); - } - else{ - item - .append('
    '+values['label']+'
    ') - } - - if((values['image'] == '' || values['image'] == 'none') && values['show_statistics'] != 1){ - item - .append($input); - } - else{ - item - .append($image) - .append($input); - } - - - } - else if(values['label_position'] == 'right'){ - if(values['height'] == 0){ - item - .append('
    '+values['label']+'
    '); - } - else{ - item - .append('
    '+values['label']+'
    ') - } - - if((values['image'] == '' || values['image'] == 'none') && values['show_statistics'] != 1){ - item - .append($input); - } - else{ - item - .append($image) - .append($input); - } - - } - - if(values['show_statistics'] != 1){ - set_static_graph_status(id_data, values['image']); - } - else{ - set_static_graph_status(id_data, 'show_statistics'); - } - - if(values['show_statistics'] != 1){ - - if ((values['width'] == 0) || (values['height'] == 0)) { - - if(values['image'] != '' && values['image'] != 'none'){ - // Do none - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalHeight'] > 150){ - $image.attr('width', '70') - .attr('height', '70'); - } - else{ - $image.attr('width', values['naturalWidth']) - .attr('height', values['naturalHeight']); - } - } - else{ - $image.attr('width', '70') - .attr('height', '70'); - } - } - else { - $image.attr('width', values['width']) - .attr('height', values['height']); - } - } - else{ - if ((values['width'] == 0) || (values['height'] == 0)) { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', 520); - $("#image_" + idItem).attr('height', 80); - $("#image_" + idItem).css('width', '520px'); - $("#image_" + idItem).css('height', '80px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - - } - else { - $("#image_" + idItem).removeAttr('width'); - $("#image_" + idItem).removeAttr('height'); - $("#image_" + idItem).attr('width', values['width']); - $("#image_" + idItem).attr('height', values['height']); - $("#image_" + idItem).css('width', values['width'] + 'px'); - $("#image_" + idItem).css('height', values['height'] + 'px'); - $("#image_" + idItem).attr('src', 'images/console/signes/group_status.png'); - } - } + if (values["show_statistics"] != 1) { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", "images/console/signes/group_status.png") + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", "images/console/signes/group_status.png") + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", "images/console/signes/group_status.png"); + } + } else { + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src) + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src) + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src); + } + } - break; - - case 'static_graph': - class_type = "static_graph"; + if (values["show_statistics"] != 1) { + if (values["width"] == 0 || values["height"] == 0) { + // Do none + if (values["image"] != "" && values["image"] != "none") { + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalHeight"] > 150 + ) { + $image.attr("width", "70").attr("height", "70"); + } else { + $image + .attr("width", values["naturalWidth"]) + .attr("height", values["naturalHeight"]); + } + } else { + $image.attr("width", "70").attr("height", "70"); + } + } else { + $image + .attr("width", values["width"]) + .attr("height", values["height"]); + } + } - img_src = "images/spinner.gif"; + var $input = $("") + .attr("id", "hidden-status_" + id_data) + .attr("type", "hidden") + .attr("value", -1) + .attr("name", "status_" + id_data); - item = $('
    ') - .attr('id', id_data) - .attr('class', 'item ' + class_type) - .css('text-align', 'left') - .css('position', 'absolute') - .css('display', 'inline-block') - .css('top', values['top'] + 'px') - .css('left', values['left'] + 'px'); - - - - if(values['label_position'] == 'left'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src) - .attr('style','float:right;'); - - } - else if(values['label_position'] == 'right'){ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src) - .attr('style','float:left;'); - - } - else{ - - var $image = $('') - .attr('id', 'image_' + id_data) - .attr('class', 'image') - .attr('src', img_src); - - } - - if(values['show_statistics'] != 1){ - - if ((values['width'] == 0) || (values['height'] == 0)) { - // Do none - if(values['image'] != '' && values['image'] != 'none'){ - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalHeight'] > 150){ - $image.attr('width', '70') - .attr('height', '70'); - } - else{ - $image.attr('width', values['naturalWidth']) - .attr('height', values['naturalHeight']); - } - } - else{ - $image.attr('width', '70') - .attr('height', '70'); - } - - - } - else { - $image.attr('width', values['width']) - .attr('height', values['height']); - } - } - // else{ - // $('#image_'+id_data).css('width', values['width']+'px'); - // $('#image_'+id_data).css('height', values['height']+'px'); - // } -/* + if (values["label_position"] == "up") { + if ( + (values["image"] == "" || values["image"] == "none") && + values["show_statistics"] != 1 + ) { + item + .append( + '
    ' + + values["label"] + + "
    " + ) + .append($input); + } else { + item + .append( + '
    ' + + values["label"] + + "
    " + ) + .append($image) + .append($input); + } + } else if (values["label_position"] == "down") { + if ( + (values["image"] == "" || values["image"] == "none") && + values["show_statistics"] != 1 + ) { + item + .append( + '
    ' + + values["label"] + + "
    " + ) + .append($input); + } else { + item + .append($image) + .append( + '
    ' + + values["label"] + + "
    " + ) + .append($input); + } + } else if (values["label_position"] == "left") { + if (values["height"] == 0) { + item.append( + '
    ' + + values["label"] + + "
    " + ); + } else { + item.append( + '
    ' + + values["label"] + + "
    " + ); + } + + if ( + (values["image"] == "" || values["image"] == "none") && + values["show_statistics"] != 1 + ) { + item.append($input); + } else { + item.append($image).append($input); + } + } else if (values["label_position"] == "right") { + if (values["height"] == 0) { + item.append( + '
    ' + + values["label"] + + "
    " + ); + } else { + item.append( + '
    ' + + values["label"] + + "
    " + ); + } + + if ( + (values["image"] == "" || values["image"] == "none") && + values["show_statistics"] != 1 + ) { + item.append($input); + } else { + item.append($image).append($input); + } + } + + if (values["show_statistics"] != 1) { + set_static_graph_status(id_data, values["image"]); + } else { + set_static_graph_status(id_data, "show_statistics"); + } + + if (values["show_statistics"] != 1) { + if (values["width"] == 0 || values["height"] == 0) { + if (values["image"] != "" && values["image"] != "none") { + // Do none + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalHeight"] > 150 + ) { + $image.attr("width", "70").attr("height", "70"); + } else { + $image + .attr("width", values["naturalWidth"]) + .attr("height", values["naturalHeight"]); + } + } else { + $image.attr("width", "70").attr("height", "70"); + } + } else { + $image + .attr("width", values["width"]) + .attr("height", values["height"]); + } + } else { + if (values["width"] == 0 || values["height"] == 0) { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", 520); + $("#image_" + idItem).attr("height", 80); + $("#image_" + idItem).css("width", "520px"); + $("#image_" + idItem).css("height", "80px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } else { + $("#image_" + idItem).removeAttr("width"); + $("#image_" + idItem).removeAttr("height"); + $("#image_" + idItem).attr("width", values["width"]); + $("#image_" + idItem).attr("height", values["height"]); + $("#image_" + idItem).css("width", values["width"] + "px"); + $("#image_" + idItem).css("height", values["height"] + "px"); + $("#image_" + idItem).attr( + "src", + "images/console/signes/group_status.png" + ); + } + } + + break; + + case "static_graph": + class_type = "static_graph"; + + img_src = "images/spinner.gif"; + + item = $("
    ") + .attr("id", id_data) + .attr("class", "item " + class_type) + .css("text-align", "left") + .css("position", "absolute") + .css("display", "inline-block") + .css("top", values["top"] + "px") + .css("left", values["left"] + "px"); + + if (values["label_position"] == "left") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src) + .attr("style", "float:right;"); + } else if (values["label_position"] == "right") { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src) + .attr("style", "float:left;"); + } else { + var $image = $("") + .attr("id", "image_" + id_data) + .attr("class", "image") + .attr("src", img_src); + } + + if (values["show_statistics"] != 1) { + if (values["width"] == 0 || values["height"] == 0) { + // Do none + if (values["image"] != "" && values["image"] != "none") { + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalHeight"] > 150 + ) { + $image.attr("width", "70").attr("height", "70"); + } else { + $image + .attr("width", values["naturalWidth"]) + .attr("height", values["naturalHeight"]); + } + } else { + $image.attr("width", "70").attr("height", "70"); + } + } else { + $image + .attr("width", values["width"]) + .attr("height", values["height"]); + } + } + // else{ + // $('#image_'+id_data).css('width', values['width']+'px'); + // $('#image_'+id_data).css('height', values['height']+'px'); + // } + /* var $span = $('') .attr('id', 'text_' + id_data) .attr('class', 'text') .append(values['label']); */ - var $input = $('') - .attr('id', 'hidden-status_' + id_data) - .attr('type', 'hidden') - .attr('value', -1) - .attr('name', 'status_' + id_data); + var $input = $("") + .attr("id", "hidden-status_" + id_data) + .attr("type", "hidden") + .attr("value", -1) + .attr("name", "status_" + id_data); - if(values['label_position'] == 'up'){ - - if(values['image'] == '' || values['image'] == 'none'){ - item - .append('
    '+values['label']+'
    ') - .append($input); - } - else{ - item - .append('
    '+values['label']+'
    ') - .append($image) - .append($image) - .append($input); - } - - } - else if(values['label_position'] == 'down'){ - - if(values['image'] == '' || values['image'] == 'none'){ - item - .append('
    '+values['label']+'
    ') - .append($input); - - } - else{ - item - .append($image) - .append($image) - .append('
    '+values['label']+'
    ') - .append($input); - } - - } - else if(values['label_position'] == 'left'){ - - if(values['height'] == 0){ - item - .append('
    '+values['label']+'
    '); - } - else{ - item - .append('
    '+values['label']+'
    ') - } - - if(values['image'] == '' || values['image'] == 'none'){ - item - .append($input); - } - else{ - item - .append($image) - .append($image) - .append($input); - } - - - } - else if(values['label_position'] == 'right'){ - if(values['height'] == 0){ - item - .append('
    '+values['label']+'
    '); - } - else{ - item - .append('
    '+values['label']+'
    ') - } - - if(values['image'] == '' || values['image'] == 'none'){ - item - .append($input); - } - else{ - item - .append($image) - .append($image) - .append($input); - } - - - - } - - if(values['show_statistics'] != 1){ - set_static_graph_status(id_data, values['image']); - } - else{ - set_static_graph_status(id_data, 'show_statistics'); - } - - if(values['show_statistics'] != 1){ - - if ((values['width'] == 0) || (values['height'] == 0)) { - - if(values['image'] != '' && values['image'] != 'none'){ - // Do none - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalHeight'] > 150){ - $image.attr('width', '70') - .attr('height', '70'); - } - else{ - $image.attr('width', values['naturalWidth']) - .attr('height', values['naturalHeight']); - } - } - else{ - $image.attr('width', '70') - .attr('height', '70'); - } - } - else { - $image.attr('width', values['width']) - .attr('height', values['height']); - } - } + if (values["label_position"] == "up") { + if (values["image"] == "" || values["image"] == "none") { + item + .append( + '
    ' + + values["label"] + + "
    " + ) + .append($input); + } else { + item + .append( + '
    ' + + values["label"] + + "
    " + ) + .append($image) + .append($image) + .append($input); + } + } else if (values["label_position"] == "down") { + if (values["image"] == "" || values["image"] == "none") { + item + .append( + '
    ' + + values["label"] + + "
    " + ) + .append($input); + } else { + item + .append($image) + .append($image) + .append( + '
    ' + + values["label"] + + "
    " + ) + .append($input); + } + } else if (values["label_position"] == "left") { + if (values["height"] == 0) { + item.append( + '
    ' + + values["label"] + + "
    " + ); + } else { + item.append( + '
    ' + + values["label"] + + "
    " + ); + } - break; - case 'auto_sla_graph': - var sizeStyle = ''; - var imageSize = ''; - item = $('
    ' + - '
    ' + values['label'] + '
    ' + - '' + - '
    ' - ); + if (values["image"] == "" || values["image"] == "none") { + item.append($input); + } else { + item + .append($image) + .append($image) + .append($input); + } + } else if (values["label_position"] == "right") { + if (values["height"] == 0) { + item.append( + '
    ' + + values["label"] + + "
    " + ); + } else { + item.append( + '
    ' + + values["label"] + + "
    " + ); + } - setEventsBar(id_data, values); - break; - case 'donut_graph': - var sizeStyle = ''; - var imageSize = ''; - item = $('
    ' + - '' + - '
    ' - ); + if (values["image"] == "" || values["image"] == "none") { + item.append($input); + } else { + item + .append($image) + .append($image) + .append($input); + } + } - setDonutsGraph(id_data, values); - break; - case 'percentile_bar': - case 'percentile_item': - var sizeStyle = ''; - var imageSize = ''; + if (values["show_statistics"] != 1) { + set_static_graph_status(id_data, values["image"]); + } else { + set_static_graph_status(id_data, "show_statistics"); + } - if (values['type_percentile'] == 'percentile') { - - if(values['label_position'] == 'up'){ - item = $('
    ' + - '
    ' + values['label'] + '
    ' + - '' + - '
    ' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - else if(values['label_position'] == 'right'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - else if(values['label_position'] == 'left'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - - setPercentileBar(id_data, values); - } - else if (values['type_percentile'] == 'circular_progress_bar') { - if(values['label_position'] == 'up'){ - item = $('
    ' + - '
    ' + values['label'] + '
    ' + - '' + - '
    ' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - else if(values['label_position'] == 'right'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - else if(values['label_position'] == 'left'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - - setPercentileCircular(id_data, values); - } - else if (values['type_percentile'] == 'interior_circular_progress_bar') { - if(values['label_position'] == 'up'){ - item = $('
    ' + - '
    ' + values['label'] + '
    ' + - '' + - '
    ' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - else if(values['label_position'] == 'right'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - else if(values['label_position'] == 'left'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - - } - - setPercentileInteriorCircular(id_data, values); - } - else { - if(values['label_position'] == 'up'){ - item = $('
    ' + - '
    ' + values['label'] + '
    ' + - '' + - '
    ' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - else if(values['label_position'] == 'left'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - else if(values['label_position'] == 'right'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - setPercentileBubble(id_data, values); - } - break; - case 'module_graph': - sizeStyle = ''; - imageSize = ''; + if (values["show_statistics"] != 1) { + if (values["width"] == 0 || values["height"] == 0) { + if (values["image"] != "" && values["image"] != "none") { + // Do none + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalHeight"] > 150 + ) { + $image.attr("width", "70").attr("height", "70"); + } else { + $image + .attr("width", values["naturalWidth"]) + .attr("height", values["naturalHeight"]); + } + } else { + $image.attr("width", "70").attr("height", "70"); + } + } else { + $image + .attr("width", values["width"]) + .attr("height", values["height"]); + } + } - if(values['label_position'] == 'up'){ - item = $('
    ' + - '
    ' + values['label'] + '
    ' + - '' + - '
    ' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - else if(values['label_position'] == 'left'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - else if(values['label_position'] == 'right'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } + break; + case "auto_sla_graph": + var sizeStyle = ""; + var imageSize = ""; + item = $( + '
    ' + + '
    ' + + values["label"] + + "
    " + + '' + + "
    " + ); - - setModuleGraph(id_data); - break; - case 'bars_graph': - sizeStyle = ''; - imageSize = ''; + setEventsBar(id_data, values); + break; + case "donut_graph": + var sizeStyle = ""; + var imageSize = ""; + item = $( + '
    ' + + '' + + "
    " + ); - if(values['label_position'] == 'up'){ - item = $('
    ' + - '
    ' + values['label'] + '
    ' + - '' + - '
    ' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - else if(values['label_position'] == 'left'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - else if(values['label_position'] == 'right'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } + setDonutsGraph(id_data, values); + break; + case "percentile_bar": + case "percentile_item": + var sizeStyle = ""; + var imageSize = ""; - - setBarsGraph(id_data, values); - break; - case 'clock': - sizeStyle = ''; - imageSize = ''; + if (values["type_percentile"] == "percentile") { + if (values["label_position"] == "up") { + item = $( + '
    ' + + '
    ' + + values["label"] + + "
    " + + '' + + "
    " + ); + } else if (values["label_position"] == "down") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "right") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "left") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } - if(values['label_position'] == 'up'){ - item = $('
    ' + - '
    ' + values['label'] + '
    ' + - '' + - '
    ' - ); - } - else if(values['label_position'] == 'down'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - else if(values['label_position'] == 'left'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - else if(values['label_position'] == 'right'){ - item = $('
    ' + - '' + - '
    ' + values['label'] + '
    ' + - '
    ' - ); - } - - setClock(id_data, values); - - break; - case 'simple_value': - sizeStyle = ''; - imageSize = ''; - if($('#data_image_check').html() == 'On'){ - values['label'] = ''; - - } - item = $('
    ' + - ' ' + values['label'] + ' ' + '
    ' - ); - break; - case 'label': - item = $('
    ' + - '' + - values['label'] + - '' + - '
    ' - ); - break; - case 'icon': - if ((values['width'] == 0) || (values['height'] == 0)) { - if(values['naturalWidth'] == null || values['naturalWidth'] > 150 || values['naturalWidth'] > 150){ - sizeStyle = 'width: ' + '70' + 'px; height: ' + '70' + 'px;'; - imageSize = 'width="' + '70' + '" height="' + '70' + '"'; - } - } - else { - sizeStyle = 'width: ' + values['width'] + 'px; height: ' + values['height'] + 'px;'; - imageSize = 'width="' + values['width'] + '" height="' + values['height'] + '"'; - } + setPercentileBar(id_data, values); + } else if (values["type_percentile"] == "circular_progress_bar") { + if (values["label_position"] == "up") { + item = $( + '
    ' + + '
    ' + + values["label"] + + "
    " + + '' + + "
    " + ); + } else if (values["label_position"] == "down") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "right") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "left") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } - item = $('
    ' + - '
    ' + - '
    ' - ); - var image = values['image'] + ".png"; - set_image("image", id_data, image); - break; - default: - //Maybe create in any Enterprise item. - if (typeof(enterprise_createItem) == 'function') { - if (values['image'] == "") { - values['image'] = 'visualmap.services'; - } - temp_item = enterprise_createItem(type, values, id_data); - if (temp_item != false) { - item = temp_item; - } - $('#'+id_data).css({'width':'','height':''}); - } - break; - } + setPercentileCircular(id_data, values); + } else if ( + values["type_percentile"] == "interior_circular_progress_bar" + ) { + if (values["label_position"] == "up") { + item = $( + '
    ' + + '
    ' + + values["label"] + + "
    " + + '' + + "
    " + ); + } else if (values["label_position"] == "down") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "right") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "left") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } - $("#background").append(item); + setPercentileInteriorCircular(id_data, values); + } else { + if (values["label_position"] == "up") { + item = $( + '
    ' + + '
    ' + + values["label"] + + "
    " + + '' + + "
    " + ); + } else if (values["label_position"] == "down") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "left") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "right") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } + setPercentileBubble(id_data, values); + } + break; + case "module_graph": + sizeStyle = ""; + imageSize = ""; - if (values['parent'] != 0) { - var line = {"id": id_data, - "node_begin": values['parent'], - "node_end": id_data, - "color": '#cccccc' }; + if (values["label_position"] == "up") { + item = $( + '
    ' + + '
    ' + + values["label"] + + "
    " + + '' + + "
    " + ); + } else if (values["label_position"] == "down") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "left") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "right") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } - lines.push(line); + setModuleGraph(id_data); + break; + case "bars_graph": + sizeStyle = ""; + imageSize = ""; - set_color_line_status(lines, id_data, values); + if (values["label_position"] == "up") { + item = $( + '
    ' + + '
    ' + + values["label"] + + "
    " + + '' + + "
    " + ); + } else if (values["label_position"] == "down") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "left") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "right") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } - refresh_lines(lines, 'background', true); - } - - - if(values['label_position'] == 'right'){ - $('#text_'+id_data).css({'display':'block','float':'right'}); - } - else if(values['label_position'] == 'left'){ - $('#text_'+id_data).css({'display':'block','float':'left'}); - } - - if(values['show_on_top'] == 1){ - $("#" + id_data).css('z-index', '10'); - } - - if(values['show_on_top'] == 0){ - $("#" + id_data).css('z-index', '5'); - } - + setBarsGraph(id_data, values); + break; + case "clock": + sizeStyle = ""; + imageSize = ""; + + if (values["label_position"] == "up") { + item = $( + '
    ' + + '
    ' + + values["label"] + + "
    " + + '' + + "
    " + ); + } else if (values["label_position"] == "down") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "left") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } else if (values["label_position"] == "right") { + item = $( + '
    ' + + '' + + '
    ' + + values["label"] + + "
    " + + "
    " + ); + } + + setClock(id_data, values); + + break; + case "simple_value": + sizeStyle = ""; + imageSize = ""; + if ($("#data_image_check").html() == "On") { + values["label"] = + ''; + } + item = $( + '
    ' + + ' ' + + values["label"] + + " " + + "
    " + ); + break; + case "label": + item = $( + '
    " + + '' + + values["label"] + + "" + + "
    " + ); + break; + case "icon": + if (values["width"] == 0 || values["height"] == 0) { + if ( + values["naturalWidth"] == null || + values["naturalWidth"] > 150 || + values["naturalWidth"] > 150 + ) { + sizeStyle = "width: " + "70" + "px; height: " + "70" + "px;"; + imageSize = 'width="' + "70" + '" height="' + "70" + '"'; + } + } else { + sizeStyle = + "width: " + + values["width"] + + "px; height: " + + values["height"] + + "px;"; + imageSize = + 'width="' + values["width"] + '" height="' + values["height"] + '"'; + } + + item = $( + '
    ' + + '
    " + + "
    " + ); + var image = values["image"] + ".png"; + set_image("image", id_data, image); + break; + case "color_cloud": + var diameter = values["diameter"] || values["width"] || 100; + + item = $( + '
    ' + + '' + + "
    " + ); + setColorCloud(id_visual_console, id_data, item); + break; + default: + //Maybe create in any Enterprise item. + if (typeof enterprise_createItem == "function") { + if (values["image"] == "") { + values["image"] = "visualmap.services"; + } + temp_item = enterprise_createItem(type, values, id_data); + if (temp_item != false) { + item = temp_item; + } + $("#" + id_data).css({ width: "", height: "" }); + } + break; + } + + $("#background").append(item); + + if (values["parent"] != 0) { + var line = { + id: id_data, + node_begin: values["parent"], + node_end: id_data, + color: "#cccccc" + }; + + lines.push(line); + + set_color_line_status(lines, id_data, values); + + refresh_lines(lines, "background", true); + } + + if (values["label_position"] == "right") { + $("#text_" + id_data).css({ display: "block", float: "right" }); + } else if (values["label_position"] == "left") { + $("#text_" + id_data).css({ display: "block", float: "left" }); + } + + if (values["show_on_top"] == 1) { + $("#" + id_data).css("z-index", "10"); + } + + if (values["show_on_top"] == 0) { + $("#" + id_data).css("z-index", "5"); + } } function addItemSelectParents(id_data, text) { - parents[id_data] = text; - //$("#parent").append($('')); + parents[id_data] = text; + //$("#parent").append($('')); } function insertDB(type, values) { - - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - $("#saving_in_progress_dialog").dialog({ - resizable: true, - draggable: true, - modal: true, - height: 100, - width: 200, - overlay: { - opacity: 0.5, - background: "black" - } - }); + $("#saving_in_progress_dialog").dialog({ + resizable: true, + draggable: true, + modal: true, + height: 100, + width: 200, + overlay: { + opacity: 0.5, + background: "black" + } + }); - var id = null; + var id = null; - parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "insert"}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - parameter.push ({name: "type", value: type}); - jQuery.each(values, function(key, val) { - parameter.push ({name: key, value: val}); - }); + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "insert" }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "type", value: type }); + jQuery.each(values, function(key, val) { + parameter.push({ name: key, value: val }); + }); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['correct']) { - id = data['id_data']; - if((type === 'group_item') || (type === 'icon') || (type === 'static_graph')){ - values['naturalWidth'] = $('#preview > img')[0].naturalWidth; - values['naturalHeight'] = $('#preview > img')[0].naturalHeight; - } - createItem(type, values, id); - addItemSelectParents(id, data['text']); - //Reload all events for the item and new item. - eventsItems(); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["correct"]) { + id = data["id_data"]; + var image_to_show = $("#preview > img")[0]; + if ( + type === "group_item" || + type === "icon" || + (type === "static_graph" && typeof image_to_show !== "undefined") + ) { + values["naturalWidth"] = image_to_show.naturalWidth; + values["naturalHeight"] = image_to_show.naturalHeight; + } + createItem(type, values, id); + addItemSelectParents(id, data["text"]); + //Reload all events for the item and new item. + eventsItems(); - switch (type) { - case 'line_item': - var line = { - "id": id, - "start_x": values['line_start_x'], - "start_y": values['line_start_y'], - "end_x": values['line_end_x'], - "end_y": values['line_end_y'], - "line_width": values['line_width'], - "line_color": values['line_color']}; + switch (type) { + case "line_item": + var line = { + id: id, + start_x: values["line_start_x"], + start_y: values["line_start_y"], + end_x: values["line_end_x"], + end_y: values["line_end_y"], + line_width: values["line_width"], + line_color: values["line_color"] + }; - user_lines.push(line); + user_lines.push(line); - // Draw handlers - radious_handle = 6; + // Draw handlers + radious_handle = 6; - // Draw handler start - item = $('
    ' + + // Draw handler start + item = $( + '
    ' + + '' + + "
    " + ); + $("#background").append(item); - '' + + // Draw handler stop + item = $( + '
    ' + + '' + + "
    " + ); + $("#background").append(item); + break; + } - '
    ' - ); - $("#background").append(item); - - // Draw handler stop - item = $('
    ' + - - '' + - - '
    ' - ); - $("#background").append(item); - break; - } - - $("#saving_in_progress_dialog").dialog("close"); - //Reload all events for the item and new item. - eventsItems(); - } - else { - //TODO - } - } - }); + $("#saving_in_progress_dialog").dialog("close"); + //Reload all events for the item and new item. + eventsItems(); + } else { + //TODO + } + } + }); } -function updateDB_visual(type, idElement , values, event, top, left) { - metaconsole = $("input[name='metaconsole']").val(); +function updateDB_visual(type, idElement, values, event, top, left) { + metaconsole = $("input[name='metaconsole']").val(); - radious_handle = 6; + radious_handle = 6; - switch (type) { - case 'handler_start': - $("#handler_start_" + idElement) - .css('top', (top - radious_handle) + 'px'); - $("#handler_start_" + idElement) - .css('left', left + 'px'); - break; - case 'handler_end': + switch (type) { + case "handler_start": + $("#handler_start_" + idElement).css("top", top - radious_handle + "px"); + $("#handler_start_" + idElement).css("left", left + "px"); + break; + case "handler_end": + $("#handler_end_" + idElement).css("top", top - radious_handle + "px"); + $("#handler_end_" + idElement).css("left", left + "px"); + break; + case "group_item": + case "static_graph": + if ( + event != "resizestop" && + event != "show_grid" && + event != "dragstop" + ) { + if (values["show_statistics"] != 1) { + set_static_graph_status(idElement, values["image"]); + } + } + $("#" + idElement).css("left", left + "px"); + $("#" + idElement).css("top", top + "px"); + break; + case "percentile_item": + case "simple_value": + case "label": + case "icon": + case "module_graph": + case "bars_graph": + case "clock": + case "auto_sla_graph": + case "donut_graph": + if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + $("#" + idElement) + .css("top", "0px") + .css("top", top + "px"); + $("#" + idElement) + .css("left", "0px") + .css("left", left + "px"); + } else { + $("#" + idElement) + .css("top", "0px") + .css("top", top + "px"); + $("#" + idElement) + .css("left", "0px") + .css("left", left + "px"); + } - $("#handler_end_" + idElement).css('top', (top - radious_handle) + 'px'); - $("#handler_end_" + idElement).css('left', (left) + 'px'); - break; - case 'group_item': - case 'static_graph': - if ((event != 'resizestop') && (event != 'show_grid') - && (event != 'dragstop')) { - if(values['show_statistics'] != 1){ - set_static_graph_status(idElement, values['image']); - } - } - $("#" + idElement).css('left', left + 'px'); - $("#" + idElement).css('top', top + 'px'); - break; - case 'percentile_item': - case 'simple_value': - case 'label': - case 'icon': - case 'module_graph': - case 'bars_graph': - case 'clock': - case 'auto_sla_graph': - case 'donut_graph': - if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - $("#" + idElement).css('top', '0px').css('top', top + 'px'); - $("#" + idElement).css('left', '0px').css('left', left + 'px'); - } - else{ - $("#" + idElement).css('top', '0px').css('top', top + 'px'); - $("#" + idElement).css('left', '0px').css('left', left + 'px'); - } + //Update the lines + end_foreach = false; + found = false; + jQuery.each(lines, function(i, line) { + if (end_foreach) { + return; + } - //Update the lines - end_foreach = false; - found = false; - jQuery.each(lines, function(i, line) { - if (end_foreach) { - return; - } + if (lines[i]["node_end"] == idElement) { + found = true; + if (values["parent"] == 0) { + //Erased the line + lines.splice(i, 1); + end_foreach = true; + } else { + if ( + typeof values["mov_left"] == "undefined" && + typeof values["mov_top"] == "undefined" && + typeof values["absolute_left"] == "undefined" && + typeof values["absolute_top"] == "undefined" + ) { + lines[i]["node_begin"] = values["parent"]; + } + } + } + }); - if (lines[i]['node_end'] == idElement) { - found = true; - if (values['parent'] == 0) { - //Erased the line - lines.splice(i, 1); - end_foreach = true; - } - else { - if ((typeof(values['mov_left']) == 'undefined') && - (typeof(values['mov_top']) == 'undefined') && - (typeof(values['absolute_left']) == 'undefined') && - (typeof(values['absolute_top']) == 'undefined')) { - lines[i]['node_begin'] = values['parent']; - } - } - } - }); - - if (typeof(values['parent']) != 'undefined' && values['parent'] > 0 ) { - if (!found) { - set_color_line_status(lines, idElement, values); - } - } - - break; - case 'background': - if(values['width'] == '0' || values['height'] == '0'){ - $("#background").css('width', $("#hidden-background_width").val() + 'px'); - $("#background").css('height', $("#hidden-background_height").val() + 'px'); - } - else { - $("#background").css('width', values['width'] + 'px'); - $("#background").css('height', values['height'] + 'px'); - } - break; - case 'service': - refresh_lines(lines, 'background', true); - break; - } - - refresh_lines(lines, 'background', true); - draw_user_lines("", 0, 0, 0 , 0, 0, true); - - if(values['show_on_top'] == 1){ - $("#" + idElement).css('z-index',10); - } - - if(values['show_on_top'] == 0){ - $("#" + idElement).css('z-index',5); - } + if (typeof values["parent"] != "undefined" && values["parent"] > 0) { + if (!found) { + set_color_line_status(lines, idElement, values); + } + } + break; + case "color_cloud": + var diameter = values["diameter"]; + var $container = $("#" + idElement + ".item.color_cloud"); + if ($container.children("img").length === 0) { + $container.append( + '' + ); + } + setColorCloud(id_visual_console, idElement, $container); + break; + case "background": + if (values["width"] == "0" || values["height"] == "0") { + $("#background").css( + "width", + $("#hidden-background_width").val() + "px" + ); + $("#background").css( + "height", + $("#hidden-background_height").val() + "px" + ); + } else { + $("#background").css("width", values["width"] + "px"); + $("#background").css("height", values["height"] + "px"); + } + break; + case "service": + refresh_lines(lines, "background", true); + break; + } + + refresh_lines(lines, "background", true); + draw_user_lines("", 0, 0, 0, 0, 0, true); + + if (values["show_on_top"] == 1) { + $("#" + idElement).css("z-index", 10); + } + + if (values["show_on_top"] == 0) { + $("#" + idElement).css("z-index", 5); + } } -function updateDB(type, idElement , values, event) { - metaconsole = $("input[name='metaconsole']").val(); +function updateDB(type, idElement, values, event) { + metaconsole = $("input[name='metaconsole']").val(); - var top = typeof(values.top) != 'undefined' ? values.top : 0; - var left = typeof(values.left) != 'undefined' ? values.left : 0; + var top = typeof values.top != "undefined" ? values.top : 0; + var left = typeof values.left != "undefined" ? values.left : 0; - action = "update"; + action = "update"; - //Check if the event parameter in function is passed in the call. - if (event != null) { - switch (event) { - case 'show_grid': - case 'resizestop': - //Force to move action when resize a background, for to avoid - //lost the label. - case 'dragstop': + //Check if the event parameter in function is passed in the call. + if (event != null) { + switch (event) { + case "show_grid": + case "resizestop": + //Force to move action when resize a background, for to avoid + //lost the label. + case "dragstop": + switch (type) { + case "handler_start": + idElement = idElement.replace("handler_start_", ""); + break; + case "handler_end": + idElement = idElement.replace("handler_end_", ""); + break; + } - switch (type) { - case 'handler_start': - idElement = idElement.replace("handler_start_", ""); - break; - case 'handler_end': - idElement = idElement.replace("handler_end_", ""); - break; - } + action = "move"; + break; + } + } - action = "move"; - break; - } - } + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: action }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "type", value: type }); + parameter.push({ name: "id_element", value: idElement }); - parameter = Array(); - parameter.push({name: "page", - value: "include/ajax/visual_console_builder.ajax"}); - parameter.push({name: "action", value: action}); - parameter.push({name: "id_visual_console", - value: id_visual_console}); - parameter.push({name: "type", value: type}); - parameter.push({name: "id_element", value: idElement}); + jQuery.each(values, function(key, val) { + parameter.push({ name: key, value: val }); + }); - jQuery.each(values, function(key, val) { - parameter.push({name: key, value: val}); - }); + switch (type) { + // -- line_item -- + case "handler_start": + // --------------- - switch (type) { - // -- line_item -- - case 'handler_start': - // --------------- + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + top = parseInt( + $("#handler_start_" + idElement) + .css("top") + .replace("px", "") + ); + left = parseInt( + $("#handler_start_" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + top = values["absolute_top"]; + left = values["absolute_left"]; + } - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - top = parseInt($("#handler_start_" + idElement) - .css('top').replace('px', '')); - left = parseInt($("#handler_start_" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - top = values['absolute_top']; - left = values['absolute_left']; - } + //Added the radious of image point of handler + top = top + 6; + left = left + 6; - //Added the radious of image point of handler - top = top + 6; - left = left + 6; + update_user_line(type, idElement, top, left); + break; + // -- line_item -- + case "handler_end": + // --------------- + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + top = parseInt( + $("#handler_end_" + idElement) + .css("top") + .replace("px", "") + ); + left = parseInt( + $("#handler_end_" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + top = values["absolute_top"]; + left = values["absolute_left"]; + } - update_user_line(type, idElement, top, left); - break; - // -- line_item -- - case 'handler_end': - // --------------- - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - top = parseInt($("#handler_end_" + idElement) - .css('top').replace('px', '')); - left = parseInt($("#handler_end_" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - top = values['absolute_top']; - left = values['absolute_left']; - } + //Added the radious of image point of handler + top = top + 6; + left = left + 6; - //Added the radious of image point of handler - top = top + 6; - left = left + 6; + update_user_line(type, idElement, top, left); + break; + default: + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + top = parseInt( + $("#" + idElement) + .css("top") + .replace("px", "") + ); + left = parseInt( + $("#" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + top = values["absolute_top"]; + left = values["absolute_left"]; + } + break; + } - update_user_line(type, idElement, top, left); - break; - default: - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - top = parseInt($("#" + idElement) - .css('top').replace('px', '')); - left = parseInt($("#" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - top = values['absolute_top']; - left = values['absolute_left']; - } - break; - } + if (typeof top != "undefined" && typeof left != "undefined") { + if ( + typeof values["top"] == "undefined" && + typeof values["left"] == "undefined" + ) { + parameter.push({ name: "top", value: top }); + parameter.push({ name: "left", value: left }); + } else { + values["top"] = top; + values["left"] = left; + } + } - if ((typeof(top) != 'undefined') && (typeof(left) != 'undefined')) { - if ((typeof(values['top']) == 'undefined') && - (typeof(values['left']) == 'undefined')) { - parameter.push ({name: 'top', value: top}); - parameter.push ({name: 'left', value: left}); - } - else { - values['top'] = top; - values['left'] = left; - } - } + success_update = false; + if (!autosave) { + list_actions_pending_save.push(parameter); + //At the moment for to show correctly. + updateDB_visual(type, idElement, values, event, top, left); + } else { + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["correct"]) { + if (data["new_line"]) { + var line = { + id: idElement, + node_begin: values["parent"], + node_end: idElement, + color: "#cccccc" + }; - success_update = false; - if (!autosave) { - list_actions_pending_save.push(parameter); - //At the moment for to show correctly. - updateDB_visual(type, idElement , values, event, top, left); - } - else { - - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['correct']) { - if (data['new_line']) { - var line = {"id": idElement, - "node_begin": values['parent'], - "node_end": idElement, - "color": '#cccccc' }; - - lines.push(line); - } - updateDB_visual(type, idElement , values, event, top, left); - } - } - }); - } + lines.push(line); + } + updateDB_visual(type, idElement, values, event, top, left); + } + } + }); + } } function copyDB(idItem) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "copy"}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - parameter.push ({name: "id_element", value: idItem}); + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "copy" }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "id_element", value: idItem }); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) { - if (data['correct']) { - values = data['values']; - type = data['type']; - id = data['id_data']; - - if((type === 'group_item') || (type === 'icon') || (type === 'static_graph')){ - values['naturalWidth'] = $('#image_'+idItem).prop('naturalWidth'); - values['naturalHeight'] = $('#image_'+idItem).prop('naturalHeight'); - } - - createItem(type, values, id); - addItemSelectParents(id, data['text']); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["correct"]) { + values = data["values"]; + type = data["type"]; + id = data["id_data"]; - //Reload all events for the item and new item. - eventsItems(); - } - else { - //TODO - } - } - }); + if ( + type === "group_item" || + type === "icon" || + type === "static_graph" + ) { + values["naturalWidth"] = $("#image_" + idItem).prop("naturalWidth"); + values["naturalHeight"] = $("#image_" + idItem).prop("naturalHeight"); + } + + createItem(type, values, id); + addItemSelectParents(id, data["text"]); + + //Reload all events for the item and new item. + eventsItems(); + } else { + //TODO + } + } + }); } function deleteDB(idElement) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - $("#delete_in_progress_dialog").dialog({ - resizable: true, - draggable: true, - modal: true, - height: 100, - width: 200, - overlay: { - opacity: 0.5, - background: "black" - } - }); + $("#delete_in_progress_dialog").dialog({ + resizable: true, + draggable: true, + modal: true, + height: 100, + width: 200, + overlay: { + opacity: 0.5, + background: "black" + } + }); - parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "delete"}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); - parameter.push ({name: "id_element", value: idElement}); + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "delete" }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); + parameter.push({ name: "id_element", value: idElement }); - jQuery.ajax({ - url: get_url_ajax(), - data: parameter, - type: "POST", - dataType: 'json', - success: function (data) - { - if (data['correct']) { - $("#parent > option[value=" + idElement + "]").remove(); + jQuery.ajax({ + url: get_url_ajax(), + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (data["correct"]) { + $("#parent > option[value=" + idElement + "]").remove(); + jQuery.each(lines, function(i, line) { + if (typeof line == "undefined") { + return; //Continue + } - jQuery.each(lines, function(i, line) { - if (typeof(line) == 'undefined') { - return; //Continue - } + if (line["id"] == idElement || line["node_begin"] == idElement) { + lines.splice(i, 1); + } + }); - if ((line['id'] == idElement) - || (line['node_begin'] == idElement)) { + if ( + $("#handler_start_" + idElement).length || + $("#handler_end_" + idElement).length + ) { + // Line item - lines.splice(i, 1); - } - }); + $("#handler_start_" + idElement).remove(); + $("#handler_end_" + idElement).remove(); - if ($("#handler_start_" + idElement).length || - $("#handler_end_" + idElement).length) { + delete_user_line(idElement); + } - // Line item + refresh_lines(lines, "background", true); - $("#handler_start_" + idElement).remove(); - $("#handler_end_" + idElement).remove(); + draw_user_lines("", 0, 0, 0, 0, 0, true); - delete_user_line(idElement); - } + $("#" + idElement).remove(); + activeToolboxButton("delete_item", false); - - refresh_lines(lines, 'background', true); - - draw_user_lines("", 0, 0, 0 , 0, 0, true); - - $('#' + idElement).remove(); - activeToolboxButton('delete_item', false); - - $("#delete_in_progress_dialog").dialog("close"); - } - else { - //TODO - } - } - }); + $("#delete_in_progress_dialog").dialog("close"); + } else { + //TODO + } + } + }); } function activeToolboxButton(id, active) { - if ($("input." + id + "[name=button_toolbox2]").length == 0) { - return; - } + if ($("input." + id + "[name=button_toolbox2]").length == 0) { + return; + } - if (active) { - $("input." + id + "[name=button_toolbox2]") - .removeAttr('disabled'); - } - else { - $("input." + id + "[name=button_toolbox2]") - .attr('disabled', true); - } + if (active) { + $("input." + id + "[name=button_toolbox2]").removeAttr("disabled"); + } else { + $("input." + id + "[name=button_toolbox2]").attr("disabled", true); + } } function click_delete_item_callback() { - if(selectedItems == null){ - activeToolboxButton('edit_item', false); - deleteDB(idItem); - idItem = 0; - selectedItem = null; - } - else{ - idItem = 0; - selectedItem = null; - selectedItems.forEach( function(valor, indice, array) { - deleteDB(valor); - }); - } + if (selectedItems == null) { + activeToolboxButton("edit_item", false); + deleteDB(idItem); + idItem = 0; + selectedItem = null; + } else { + idItem = 0; + selectedItem = null; + selectedItems.forEach(function(valor, indice, array) { + deleteDB(valor); + }); + } } /** @@ -4144,1073 +5335,1272 @@ function click_delete_item_callback() { * drop. */ function eventsItems(drag) { - if (typeof(drag) == 'undefined') { - drag = false; - } + if (typeof drag == "undefined") { + drag = false; + } - $('.item').unbind('click'); - $('.item').unbind('dragstop'); - $('.item').unbind('dragstart'); + $(".item").unbind("click"); + $(".item").unbind("dragstop"); + $(".item").unbind("dragstart"); - //$(".item").resizable(); //Disable but run in ff and in the waste (aka micro$oft IE) show ungly borders + //$(".item").resizable(); //Disable but run in ff and in the waste (aka micro$oft IE) show ungly borders - $('.item').bind('click', function(event, ui) { - - event.stopPropagation(); - if (!is_opened_palette) { - var divParent = $(event.target); - while (!$(divParent).hasClass("item")) { - divParent = $(divParent).parent(); - } - unselectAll(); - $(divParent).attr('withborder','true'); - $(divParent).css('border', '1px blue dotted'); - $(divParent).css('left', '-=1px'); - $(divParent).css('top', '-=1px'); - - if ($(divParent).hasClass('box_item')) { - creationItem = null; - selectedItem = 'box_item'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('static_graph')) { - creationItem = null; - selectedItem = 'static_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('auto_sla_graph')) { - creationItem = null; - selectedItem = 'auto_sla_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('donut_graph')) { - creationItem = null; - selectedItem = 'donut_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('group_item')) { - creationItem = null; - selectedItem = 'group_item'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('percentile_item')) { - creationItem = null; - selectedItem = 'percentile_item'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('module_graph')) { - creationItem = null; - selectedItem = 'module_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('bars_graph')) { - creationItem = null; - selectedItem = 'bars_graph'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('simple_value')) { - creationItem = null; - selectedItem = 'simple_value'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('label')) { - creationItem = null; - selectedItem = 'label'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('icon')) { - creationItem = null; - selectedItem = 'icon'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('clock')) { - creationItem = null; - selectedItem = 'clock'; - idItem = $(divParent).attr('id'); - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('handler_start')) { - idItem = $(divParent).attr('id') - .replace("handler_start_", ""); - creationItem = null; - selectedItem = 'handler_start'; - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } - if ($(divParent).hasClass('handler_end')) { - idItem = $(divParent).attr('id') - .replace("handler_end_", ""); - creationItem = null; - selectedItem = 'handler_end'; - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - activeToolboxButton('show_grid', false); - } + $(".item").bind("click", function(event, ui) { + event.stopPropagation(); + if (!is_opened_palette) { + var divParent = $(event.target); + while (!$(divParent).hasClass("item")) { + divParent = $(divParent).parent(); + } + unselectAll(); + $(divParent).attr("withborder", "true"); + $(divParent).css("border", "1px blue dotted"); + $(divParent).css("left", "-=1px"); + $(divParent).css("top", "-=1px"); - //Maybe receive a click event any Enterprise item. - if (typeof(enterprise_click_item_callback) == 'function') { - enterprise_click_item_callback(divParent); - } - } - - - - if(!event.ctrlKey){ - firstItem = event.currentTarget.id; - selectedItems = null; - selectedItems = Array(); - selectedItems.push(event.currentTarget.id); + if ($(divParent).hasClass("box_item")) { + creationItem = null; + selectedItem = "box_item"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("static_graph")) { + creationItem = null; + selectedItem = "static_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("auto_sla_graph")) { + creationItem = null; + selectedItem = "auto_sla_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("donut_graph")) { + creationItem = null; + selectedItem = "donut_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("group_item")) { + creationItem = null; + selectedItem = "group_item"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("percentile_item")) { + creationItem = null; + selectedItem = "percentile_item"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("module_graph")) { + creationItem = null; + selectedItem = "module_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("bars_graph")) { + creationItem = null; + selectedItem = "bars_graph"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("simple_value")) { + creationItem = null; + selectedItem = "simple_value"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("label")) { + creationItem = null; + selectedItem = "label"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("icon")) { + creationItem = null; + selectedItem = "icon"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("clock")) { + creationItem = null; + selectedItem = "clock"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("color_cloud")) { + creationItem = null; + selectedItem = "color_cloud"; + idItem = $(divParent).attr("id"); + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("handler_start")) { + idItem = $(divParent) + .attr("id") + .replace("handler_start_", ""); + creationItem = null; + selectedItem = "handler_start"; + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } + if ($(divParent).hasClass("handler_end")) { + idItem = $(divParent) + .attr("id") + .replace("handler_end_", ""); + creationItem = null; + selectedItem = "handler_end"; + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + activeToolboxButton("show_grid", false); + } - } - else{ - - selectedItem = null; - - unselectAll(); - - if(selectedItems.indexOf(event.currentTarget.id) > -1){ - - $('#'+event.currentTarget.id).css('left', '+=1'); - $('#'+event.currentTarget.id).css('top', '+=1'); - $('#'+event.currentTarget.id).css('border', ''); - $('#'+event.currentTarget.id).attr('withborder') == 'false'; - - - selectedItems.splice(selectedItems.indexOf(event.currentTarget.id),1); - } - else{ - $('#'+event.currentTarget.id).css('left', '-=1'); - $('#'+event.currentTarget.id).css('top', '-=1'); - $('#'+event.currentTarget.id).css('border', '1px dotted rgb(0, 0, 255)'); - $('#'+event.currentTarget.id).attr('withborder') == 'true'; - - - selectedItems.push(event.currentTarget.id); - } - - - selectedItems.forEach( function(valor, indice, array) { - if(selectedItems.indexOf(valor) > -1 && $('#'+valor).css('border') != '1px dotted rgb(0, 0, 255)'){ - // $('#'+valor).css('left', '-=1'); - // $('#'+valor).css('top', '-=1'); - $('#'+valor).css('border', '1px dotted rgb(0, 0, 255)'); - $('#'+valor).attr('withborder') == 'true'; - } - }); - - $('#'+firstItem).css('left', '-=1'); - $('#'+firstItem).css('top', '-=1'); - - firstItem = null; - - } - - - - - }); + //Maybe receive a click event any Enterprise item. + if (typeof enterprise_click_item_callback == "function") { + enterprise_click_item_callback(divParent); + } + } - //Double click in the item - $('.item').bind('dblclick', function(event, ui) { + if (!event.ctrlKey) { + firstItem = event.currentTarget.id; + selectedItems = null; + selectedItems = Array(); + selectedItems.push(event.currentTarget.id); + } else { + selectedItem = null; - event.stopPropagation(); - if ((!is_opened_palette) && (autosave)) { - toggle_item_palette(); - } - - if(selectedItem == 'simple_value'){ - $('#data_image_width').val(event.currentTarget.clientWidth); - - parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "action", value: "get_image_from_module"}); - parameter.push ({name: "id_element", value: idItem}); - parameter.push ({name: "id_visual_console", value: id_visual_console}); + unselectAll(); - jQuery.ajax({ - url: "ajax.php", - data: parameter, - type: "POST", - dataType: "json", - success: function(data) { - if(!data['correct']){ - $("#data_image_check").html('Off'); - $('#data_image_container').css('display','none'); - $('#data_image_check').css('display','none'); - $('#data_image_check_label').css('display','none'); - $('.block_tinymce').remove(); - $('#process_value_row').css('display','table-row'); - if($('#process_value').val() != '0'){ - $('#period_row').css('display','table-row'); - } - } - else{ - $('#data_image_container').css('display','inline'); - $('#data_image_check').css('display','inline'); - $('#data_image_check_label').css('display','inline'); - $("#data_image_check").html('On'); - $('#process_value_row').css('display','none'); - $('#period_row').css('display','none'); - $('#text-label_ifr').contents().find('#tinymce').html('_VALUE_'); - $('.block_tinymce').remove(); - $('#label_row').append('
    '); - } - } - }); - } - else{ - $("#data_image_check").css('display','none'); - $("#data_image_check_label").css('display','none'); - $('#data_image_container').css('display','none'); - } - - }); + if (selectedItems.indexOf(event.currentTarget.id) > -1) { + $("#" + event.currentTarget.id).css("left", "+=1"); + $("#" + event.currentTarget.id).css("top", "+=1"); + $("#" + event.currentTarget.id).css("border", ""); + $("#" + event.currentTarget.id).attr("withborder") == "false"; - //Set the limit of draggable in the div with id "background" and set drag - //by default is false. - $(".item").draggable({containment: "#background", grid: drag}); + selectedItems.splice(selectedItems.indexOf(event.currentTarget.id), 1); + } else { + $("#" + event.currentTarget.id).css("left", "-=1"); + $("#" + event.currentTarget.id).css("top", "-=1"); + $("#" + event.currentTarget.id).css( + "border", + "1px dotted rgb(0, 0, 255)" + ); + $("#" + event.currentTarget.id).attr("withborder") == "true"; - $('.item').bind('dragstart', function(event, ui) { - - if(selectedItems == null || selectedItems.length < 2){ - event.stopPropagation(); - if (!is_opened_palette) { - unselectAll(); - $(event.target).css('border', '1px blue dotted'); + selectedItems.push(event.currentTarget.id); + } - selectedItem = null; - if ($(event.target).hasClass('box_item')) { - selectedItem = 'box_item'; - } - if ($(event.target).hasClass('static_graph')) { - selectedItem = 'static_graph'; - } - if ($(event.target).hasClass('auto_sla_graph')) { - selectedItem = 'auto_sla_graph'; - } - if ($(event.target).hasClass('donut_graph')) { - selectedItem = 'donut_graph'; - } - if ($(event.target).hasClass('group_item')) { - selectedItem = 'group_item'; - } - if ($(event.target).hasClass('percentile_item')) { - selectedItem = 'percentile_item'; - } - if ($(event.target).hasClass('module_graph')) { - selectedItem = 'module_graph'; - } - if ($(event.target).hasClass('bars_graph')) { - selectedItem = 'bars_graph'; - } - if ($(event.target).hasClass('simple_value')) { - selectedItem = 'simple_value'; - } - if ($(event.target).hasClass('label')) { - selectedItem = 'label'; - } - if ($(event.target).hasClass('icon')) { - selectedItem = 'icon'; - } - if ($(event.target).hasClass('clock')) { - selectedItem = 'clock'; - } - if ($(event.target).hasClass('handler_start')) { - selectedItem = 'handler_start'; - } - if ($(event.target).hasClass('handler_end')) { - selectedItem = 'handler_end'; - } + selectedItems.forEach(function(valor, indice, array) { + if ( + selectedItems.indexOf(valor) > -1 && + $("#" + valor).css("border") != "1px dotted rgb(0, 0, 255)" + ) { + // $('#'+valor).css('left', '-=1'); + // $('#'+valor).css('top', '-=1'); + $("#" + valor).css("border", "1px dotted rgb(0, 0, 255)"); + $("#" + valor).attr("withborder") == "true"; + } + }); - if (selectedItem == null) { - //Maybe receive a click event any Enterprise item. - if (typeof(enterprise_dragstart_item_callback) == 'function') { - selectedItem = enterprise_dragstart_item_callback(event); - } - } + $("#" + firstItem).css("left", "-=1"); + $("#" + firstItem).css("top", "-=1"); - if (selectedItem != null) { - creationItem = null; + firstItem = null; + } + }); - switch (selectedItem) { - // -- line_item -- - case 'handler_start': - // --------------- - idItem = $(event.target).attr('id') - .replace("handler_end_", ""); - idItem = $(event.target).attr('id') - .replace("handler_start_", ""); - break; - // -- line_item -- - case 'handler_end': - // --------------- - idItem = $(event.target).attr('id') - .replace("handler_end_", ""); - idItem = $(event.target).attr('id') - .replace("handler_end_", ""); - break; - default: - idItem = $(event.target).attr('id'); - - break; - } - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', true); - } - } - } - else{ - multiDragStart(event); - - } - }); + //Double click in the item + $(".item").bind("dblclick", function(event, ui) { + event.stopPropagation(); + if (!is_opened_palette && autosave) { + toggle_item_palette(); + } - $('.item').bind('dragstop', function(event, ui) { - if(selectedItems == null || selectedItems.length < 2){ - event.stopPropagation(); + if (selectedItem == "simple_value") { + $("#data_image_width").val(event.currentTarget.clientWidth); - var values = {}; - values['mov_left'] = ui.position.left; - values['mov_top'] = ui.position.top; + parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "action", value: "get_image_from_module" }); + parameter.push({ name: "id_element", value: idItem }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); - updateDB(selectedItem, idItem, values, 'dragstop'); - } - else{ - multidragStop(event); - } - }); + jQuery.ajax({ + url: "ajax.php", + data: parameter, + type: "POST", + dataType: "json", + success: function(data) { + if (!data["correct"]) { + $("#data_image_check").html("Off"); + $("#data_image_container").css("display", "none"); + $("#data_image_check").css("display", "none"); + $("#data_image_check_label").css("display", "none"); + $(".block_tinymce").remove(); + $("#process_value_row").css("display", "table-row"); + if ($("#process_value").val() != "0") { + $("#period_row").css("display", "table-row"); + } + } else { + $("#data_image_container").css("display", "inline"); + $("#data_image_check").css("display", "inline"); + $("#data_image_check_label").css("display", "inline"); + $("#data_image_check").html("On"); + $("#process_value_row").css("display", "none"); + $("#period_row").css("display", "none"); + $("#text-label_ifr") + .contents() + .find("#tinymce") + .html("_VALUE_"); + $(".block_tinymce").remove(); + $("#label_row").append( + '
    ' + ); + } + } + }); + } else { + $("#data_image_check").css("display", "none"); + $("#data_image_check_label").css("display", "none"); + $("#data_image_container").css("display", "none"); + } + }); - $('.item').bind('drag', function(event, ui) { - if(selectedItems == null || selectedItems.length < 2){ - if ($(event.target).hasClass('handler_start')) { - selectedItem = 'handler_start'; - } - if ($(event.target).hasClass('handler_end')) { - selectedItem = 'handler_end'; - } + //Set the limit of draggable in the div with id "background" and set drag + //by default is false. + $(".item").draggable({ containment: "#background", grid: drag }); - var values = {}; - values['mov_left'] = ui.position.left; - values['mov_top'] = ui.position.top; + $(".item").bind("dragstart", function(event, ui) { + if (selectedItems == null || selectedItems.length < 2) { + event.stopPropagation(); + if (!is_opened_palette) { + unselectAll(); + $(event.target).css("border", "1px blue dotted"); - switch (selectedItem) { - // -- line_item -- - case 'handler_start': - // --------------- - idElement = $(event.target).attr('id') - .replace("handler_end_", ""); - idElement = $(event.target).attr('id') - .replace("handler_start_", ""); - break; - // -- line_item -- - case 'handler_end': - // --------------- - idElement = $(event.target).attr('id') - .replace("handler_end_", ""); - idElement = $(event.target).attr('id') - .replace("handler_end_", ""); - break; - } + selectedItem = null; + if ($(event.target).hasClass("box_item")) { + selectedItem = "box_item"; + } + if ($(event.target).hasClass("static_graph")) { + selectedItem = "static_graph"; + } + if ($(event.target).hasClass("auto_sla_graph")) { + selectedItem = "auto_sla_graph"; + } + if ($(event.target).hasClass("donut_graph")) { + selectedItem = "donut_graph"; + } + if ($(event.target).hasClass("group_item")) { + selectedItem = "group_item"; + } + if ($(event.target).hasClass("percentile_item")) { + selectedItem = "percentile_item"; + } + if ($(event.target).hasClass("module_graph")) { + selectedItem = "module_graph"; + } + if ($(event.target).hasClass("bars_graph")) { + selectedItem = "bars_graph"; + } + if ($(event.target).hasClass("simple_value")) { + selectedItem = "simple_value"; + } + if ($(event.target).hasClass("label")) { + selectedItem = "label"; + } + if ($(event.target).hasClass("icon")) { + selectedItem = "icon"; + } + if ($(event.target).hasClass("clock")) { + selectedItem = "clock"; + } + if ($(event.target).hasClass("color_cloud")) { + selectedItem = "color_cloud"; + } + if ($(event.target).hasClass("handler_start")) { + selectedItem = "handler_start"; + } + if ($(event.target).hasClass("handler_end")) { + selectedItem = "handler_end"; + } - switch (selectedItem) { - // -- line_item -- - case 'handler_start': - // --------------- - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - var top = parseInt($("#handler_start_" + idElement) - .css('top').replace('px', '')); - var left = parseInt($("#handler_start_" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - var top = values['absolute_top']; - var left = values['absolute_left']; - } + if (selectedItem == null) { + //Maybe receive a click event any Enterprise item. + if (typeof enterprise_dragstart_item_callback == "function") { + selectedItem = enterprise_dragstart_item_callback(event); + } + } - //Added the radious of image point of handler - top = top + 6; - left = left + 6; + if (selectedItem != null) { + creationItem = null; - update_user_line('handler_start', idElement, top, left); + switch (selectedItem) { + // -- line_item -- + case "handler_start": + // --------------- + idItem = $(event.target) + .attr("id") + .replace("handler_end_", ""); + idItem = $(event.target) + .attr("id") + .replace("handler_start_", ""); + break; + // -- line_item -- + case "handler_end": + // --------------- + idItem = $(event.target) + .attr("id") + .replace("handler_end_", ""); + idItem = $(event.target) + .attr("id") + .replace("handler_end_", ""); + break; + default: + idItem = $(event.target).attr("id"); - draw_user_lines("", 0, 0, 0 , 0, 0, true); - break; - // -- line_item -- - case 'handler_end': - // --------------- - if ((typeof(values['mov_left']) != 'undefined') && - (typeof(values['mov_top']) != 'undefined')) { - top = parseInt($("#handler_end_" + idElement) - .css('top').replace('px', '')); - left = parseInt($("#handler_end_" + idElement) - .css('left').replace('px', '')); - } - else if ((typeof(values['absolute_left']) != 'undefined') && - (typeof(values['absolute_top']) != 'undefined')) { - top = values['absolute_top']; - left = values['absolute_left']; - } + break; + } + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", true); + } + } + } else { + multiDragStart(event); + } + }); - //Added the radious of image point of handler - top = top + 6; - left = left + 6; + $(".item").bind("dragstop", function(event, ui) { + if (selectedItems == null || selectedItems.length < 2) { + event.stopPropagation(); - update_user_line('handler_end', idElement, top, left); + var values = {}; + values["mov_left"] = ui.position.left; + values["mov_top"] = ui.position.top; - draw_user_lines("", 0, 0, 0 , 0, 0, true); - break; - } - } - }); + updateDB(selectedItem, idItem, values, "dragstop"); + } else { + multidragStop(event); + } + }); + + $(".item").bind("drag", function(event, ui) { + if (selectedItems == null || selectedItems.length < 2) { + if ($(event.target).hasClass("handler_start")) { + selectedItem = "handler_start"; + } + if ($(event.target).hasClass("handler_end")) { + selectedItem = "handler_end"; + } + + var values = {}; + values["mov_left"] = ui.position.left; + values["mov_top"] = ui.position.top; + + switch (selectedItem) { + // -- line_item -- + case "handler_start": + // --------------- + idElement = $(event.target) + .attr("id") + .replace("handler_end_", ""); + idElement = $(event.target) + .attr("id") + .replace("handler_start_", ""); + break; + // -- line_item -- + case "handler_end": + // --------------- + idElement = $(event.target) + .attr("id") + .replace("handler_end_", ""); + idElement = $(event.target) + .attr("id") + .replace("handler_end_", ""); + break; + } + + switch (selectedItem) { + // -- line_item -- + case "handler_start": + // --------------- + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + var top = parseInt( + $("#handler_start_" + idElement) + .css("top") + .replace("px", "") + ); + var left = parseInt( + $("#handler_start_" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + var top = values["absolute_top"]; + var left = values["absolute_left"]; + } + + //Added the radious of image point of handler + top = top + 6; + left = left + 6; + + update_user_line("handler_start", idElement, top, left); + + draw_user_lines("", 0, 0, 0, 0, 0, true); + break; + // -- line_item -- + case "handler_end": + // --------------- + if ( + typeof values["mov_left"] != "undefined" && + typeof values["mov_top"] != "undefined" + ) { + top = parseInt( + $("#handler_end_" + idElement) + .css("top") + .replace("px", "") + ); + left = parseInt( + $("#handler_end_" + idElement) + .css("left") + .replace("px", "") + ); + } else if ( + typeof values["absolute_left"] != "undefined" && + typeof values["absolute_top"] != "undefined" + ) { + top = values["absolute_top"]; + left = values["absolute_left"]; + } + + //Added the radious of image point of handler + top = top + 6; + left = left + 6; + + update_user_line("handler_end", idElement, top, left); + + draw_user_lines("", 0, 0, 0, 0, 0, true); + break; + } + } + }); } /** * Events for the background (click, resize and doubleclick). */ function eventsBackground() { - $("#background").resizable(); + $("#background").resizable(); - $('#background').bind('resizestart', function(event, ui) { - if (!is_opened_palette) { - $("#background").css('border', '2px red solid'); - } - }); + $("#background").bind("resizestart", function(event, ui) { + if (!is_opened_palette) { + $("#background").css("border", "2px red solid"); + } + }); - $('#background').bind('resizestop', function(event, ui) { - if (!is_opened_palette) { - unselectAll(); - - var launch_message = false; - var dont_resize = false; - var values = {}; - var actual_width = $('#background').css('width').replace('px', ''); - var actual_height = $('#background').css('height').replace('px', ''); - - if (actual_width < 1024) { - actual_width = 1024; - $('#background').css('width', 1024); - launch_message = true; - dont_resize = true; - } - if (actual_height < 768) { - actual_height = 768; - $('#background').css('height', 768); - launch_message = true; - dont_resize = true; - } - - values['width'] = actual_width; - values['height'] = actual_height; - - if (!dont_resize) { - updateDB('background', 0, values, 'resizestop'); - - width = ui.size['width']; - height = ui.size['height']; + $("#background").bind("resizestop", function(event, ui) { + if (!is_opened_palette) { + unselectAll(); - original_width = ui.originalSize['width']; - original_height = ui.originalSize['height']; - - move_elements_resize(original_width, original_height, width, height); + var launch_message = false; + var dont_resize = false; + var values = {}; + var actual_width = $("#background") + .css("width") + .replace("px", ""); + var actual_height = $("#background") + .css("height") + .replace("px", ""); - $('#background_grid').css('width', width); - $('#background_grid').css('height', height); - } - else{ - updateDB('background', 0, values, 'resizestop'); - } - if (launch_message) - alert($('#hidden-message_size').val()); - } - }); + if (actual_width < 1024) { + actual_width = 1024; + $("#background").css("width", 1024); + launch_message = true; + dont_resize = true; + } + if (actual_height < 768) { + actual_height = 768; + $("#background").css("height", 768); + launch_message = true; + dont_resize = true; + } - // Event click for background - $("#background").click(function(event) { - selectedItems = null; - selectedItems = Array(); - event.stopPropagation(); - if (!is_opened_palette) { - unselectAll(); - $("#background").css('border', '1px blue dotted'); - activeToolboxButton('copy_item', false); - activeToolboxButton('edit_item', true); - activeToolboxButton('delete_item', false); - activeToolboxButton('show_grid', true); + values["width"] = actual_width; + values["height"] = actual_height; - idItem = 0; - creationItem = null; - selectedItem = 'background'; - } - }); + if (!dont_resize) { + updateDB("background", 0, values, "resizestop"); - $('#background').bind('dblclick', function(event, ui) { - event.stopPropagation(); - if ((!is_opened_palette) && (autosave)) { - toggle_item_palette(); - } - $("#show_on_top_row").css('display', 'none'); - $("#show_on_top." + item).css('display', ''); - }); + width = ui.size["width"]; + height = ui.size["height"]; + + original_width = ui.originalSize["width"]; + original_height = ui.originalSize["height"]; + + move_elements_resize(original_width, original_height, width, height); + + $("#background_grid").css("width", width); + $("#background_grid").css("height", height); + } else { + updateDB("background", 0, values, "resizestop"); + } + if (launch_message) alert($("#hidden-message_size").val()); + } + }); + + // Event click for background + $("#background").click(function(event) { + selectedItems = null; + selectedItems = Array(); + event.stopPropagation(); + if (!is_opened_palette) { + unselectAll(); + $("#background").css("border", "1px blue dotted"); + activeToolboxButton("copy_item", false); + activeToolboxButton("edit_item", true); + activeToolboxButton("delete_item", false); + activeToolboxButton("show_grid", true); + + idItem = 0; + creationItem = null; + selectedItem = "background"; + } + }); + + $("#background").bind("dblclick", function(event, ui) { + event.stopPropagation(); + if (!is_opened_palette && autosave) { + toggle_item_palette(); + } + $("#show_on_top_row").css("display", "none"); + $("#show_on_top." + item).css("display", ""); + }); } function move_elements_resize(original_width, original_height, width, height) { - jQuery.each($(".item"), function(key, value) { - item = value; - idItem = $(item).attr('id'); - classItem = $(item).attr('class').replace('item', '') - .replace('ui-draggable', '').replace('ui-draggable-disabled', '') - .replace(/^\s+/g,'').replace(/\s+$/g,''); + jQuery.each($(".item"), function(key, value) { + item = value; + idItem = $(item).attr("id"); + classItem = $(item) + .attr("class") + .replace("item", "") + .replace("ui-draggable", "") + .replace("ui-draggable-disabled", "") + .replace(/^\s+/g, "") + .replace(/\s+$/g, ""); - old_height = parseInt($(item).css('top').replace('px', '')); - old_width = parseInt($(item).css('left').replace('px', '')); + old_height = parseInt( + $(item) + .css("top") + .replace("px", "") + ); + old_width = parseInt( + $(item) + .css("left") + .replace("px", "") + ); - ratio_width = width / original_width; - ratio_height = height / original_height; + ratio_width = width / original_width; + ratio_height = height / original_height; - new_height = old_height * ratio_height; - new_width = old_width * ratio_width; + new_height = old_height * ratio_height; + new_width = old_width * ratio_width; - var values = {}; + var values = {}; - values['absolute_left'] = new_width; - values['absolute_top'] = new_height; + values["absolute_left"] = new_width; + values["absolute_top"] = new_height; - updateDB(classItem, idItem, values, "resizestop"); - }); + updateDB(classItem, idItem, values, "resizestop"); + }); } function unselectAll() { - $("#background").css('border', '1px lightgray solid'); - $(".item").each(function(){ - $(this).css('border', ''); - if($(this).attr('withborder') == 'true'){ - $(this).css('top', '+=1'); - $(this).css('left', '+=1'); - $(this).attr('withborder', 'false'); - } - - }); - selectedItem = null; + $("#background").css("border", "1px lightgray solid"); + $(".item").each(function() { + $(this).css("border", ""); + if ($(this).attr("withborder") == "true") { + $(this).css("top", "+=1"); + $(this).css("left", "+=1"); + $(this).attr("withborder", "false"); + } + }); + selectedItem = null; } function click_button_toolbox(id) { - switch (id) { - case 'static_graph': - toolbuttonActive = creationItem = 'static_graph'; - toggle_item_palette(); - break; - case 'percentile_bar': - case 'percentile_item': - toolbuttonActive = creationItem = 'percentile_item'; - toggle_item_palette(); - break; - case 'module_graph': - toolbuttonActive = creationItem = 'module_graph'; - toggle_item_palette(); - break; - case 'bars_graph': - toolbuttonActive = creationItem = 'bars_graph'; - toggle_item_palette(); - break; - case 'auto_sla_graph': - toolbuttonActive = creationItem = 'auto_sla_graph'; - toggle_item_palette(); - break; - case 'donut_graph': - toolbuttonActive = creationItem = 'donut_graph'; - toggle_item_palette(); - break; - case 'simple_value': - toolbuttonActive = creationItem = 'simple_value'; - toggle_item_palette(); - $("#period_row." + id).css('display', 'none'); - break; - case 'label': - $("#data_image_width").val(100); - toolbuttonActive = creationItem = 'label'; - toggle_item_palette(); - break; - case 'icon': - toolbuttonActive = creationItem = 'icon'; - toggle_item_palette(); - break; - case 'clock': - toolbuttonActive = creationItem = 'clock'; - toggle_item_palette(); - break; - case 'group_item': - toolbuttonActive = creationItem = 'group_item'; - toggle_item_palette(); - break; - case 'box_item': - toolbuttonActive = creationItem = 'box_item'; - toggle_item_palette(); - break; - case 'line_item': - toolbuttonActive = creationItem = 'line_item'; - toggle_item_palette(); - break; - case 'copy_item': - click_copy_item_callback(); - break; - case 'edit_item': - toggle_item_palette(); - break; - case 'delete_item': - click_delete_item_callback(); - break; - case 'show_grid': - showGrid(); - break; - case 'auto_save': - if (autosave) { - activeToolboxButton('save_visualmap', true); - autosave = false; + switch (id) { + case "static_graph": + toolbuttonActive = creationItem = "static_graph"; + toggle_item_palette(); + break; + case "percentile_bar": + case "percentile_item": + toolbuttonActive = creationItem = "percentile_item"; + toggle_item_palette(); + break; + case "module_graph": + toolbuttonActive = creationItem = "module_graph"; + toggle_item_palette(); + break; + case "bars_graph": + toolbuttonActive = creationItem = "bars_graph"; + toggle_item_palette(); + break; + case "auto_sla_graph": + toolbuttonActive = creationItem = "auto_sla_graph"; + toggle_item_palette(); + break; + case "donut_graph": + toolbuttonActive = creationItem = "donut_graph"; + toggle_item_palette(); + break; + case "simple_value": + toolbuttonActive = creationItem = "simple_value"; + toggle_item_palette(); + $("#period_row." + id).css("display", "none"); + break; + case "label": + $("#data_image_width").val(100); + toolbuttonActive = creationItem = "label"; + toggle_item_palette(); + break; + case "icon": + toolbuttonActive = creationItem = "icon"; + toggle_item_palette(); + break; + case "clock": + toolbuttonActive = creationItem = "clock"; + toggle_item_palette(); + break; + case "group_item": + toolbuttonActive = creationItem = "group_item"; + toggle_item_palette(); + break; + case "box_item": + toolbuttonActive = creationItem = "box_item"; + toggle_item_palette(); + break; + case "line_item": + toolbuttonActive = creationItem = "line_item"; + toggle_item_palette(); + break; + case "color_cloud": + toolbuttonActive = creationItem = "color_cloud"; + toggle_item_palette(); + break; + case "copy_item": + click_copy_item_callback(); + break; + case "edit_item": + toggle_item_palette(); + break; + case "delete_item": + click_delete_item_callback(); + break; + case "show_grid": + showGrid(); + break; + case "auto_save": + if (autosave) { + activeToolboxButton("save_visualmap", true); + autosave = false; - //Disable all toolbox buttons. - //Because when it is not autosave only trace the movements - //the other actions need to contant with the apache server. - //And it is necesary to re-code more parts of code to change - //this method. - activeToolboxButton('static_graph', false); - activeToolboxButton('percentile_item', false); - activeToolboxButton('module_graph', false); - activeToolboxButton('bars_graph', false); - activeToolboxButton('simple_value', false); - activeToolboxButton('label', false); - activeToolboxButton('icon', false); - activeToolboxButton('clock', false); - activeToolboxButton('service', false); - activeToolboxButton('group_item', false); - activeToolboxButton('auto_sla_graph', false); - activeToolboxButton('donut_graph', false); - activeToolboxButton('copy_item', false); - activeToolboxButton('edit_item', false); - activeToolboxButton('delete_item', false); - activeToolboxButton('show_grid', false); - } - else { - activeToolboxButton('save', false); - autosave = true; + //Disable all toolbox buttons. + //Because when it is not autosave only trace the movements + //the other actions need to contant with the apache server. + //And it is necesary to re-code more parts of code to change + //this method. + activeToolboxButton("static_graph", false); + activeToolboxButton("percentile_item", false); + activeToolboxButton("module_graph", false); + activeToolboxButton("bars_graph", false); + activeToolboxButton("simple_value", false); + activeToolboxButton("label", false); + activeToolboxButton("icon", false); + activeToolboxButton("clock", false); + activeToolboxButton("service", false); + activeToolboxButton("group_item", false); + activeToolboxButton("auto_sla_graph", false); + activeToolboxButton("donut_graph", false); + activeToolboxButton("color_cloud", false); + activeToolboxButton("copy_item", false); + activeToolboxButton("edit_item", false); + activeToolboxButton("delete_item", false); + activeToolboxButton("show_grid", false); + } else { + activeToolboxButton("save", false); + autosave = true; - //Reactive the buttons. + //Reactive the buttons. - if ((selectedItem != 'background') && (selectedItem != null)) { - activeToolboxButton('delete_item', true); - } - if (selectedItem == 'background') { - activeToolboxButton('show_grid', true); - } - if (selectedItem != null) { - activeToolboxButton('copy_item', true); - activeToolboxButton('edit_item', true); - } + if (selectedItem != "background" && selectedItem != null) { + activeToolboxButton("delete_item", true); + } + if (selectedItem == "background") { + activeToolboxButton("show_grid", true); + } + if (selectedItem != null) { + activeToolboxButton("copy_item", true); + activeToolboxButton("edit_item", true); + } - activeToolboxButton('static_graph', true); - activeToolboxButton('percentile_item', true); - activeToolboxButton('module_graph', true); - activeToolboxButton('bars_graph', true); - activeToolboxButton('simple_value', true); - activeToolboxButton('label', true); - activeToolboxButton('icon', true); - activeToolboxButton('clock', true); - activeToolboxButton('group_item', true); - activeToolboxButton('auto_sla_graph', true); - activeToolboxButton('donut_graph', true); - } - break; - case 'save_visualmap': - $("#saving_in_progress_dialog").dialog({ - resizable: true, - draggable: true, - modal: true, - height: 100, - width: 200, - overlay: { - opacity: 0.5, - background: "black" - } - }); + activeToolboxButton("static_graph", true); + activeToolboxButton("percentile_item", true); + activeToolboxButton("module_graph", true); + activeToolboxButton("bars_graph", true); + activeToolboxButton("simple_value", true); + activeToolboxButton("label", true); + activeToolboxButton("icon", true); + activeToolboxButton("clock", true); + activeToolboxButton("group_item", true); + activeToolboxButton("auto_sla_graph", true); + activeToolboxButton("donut_graph", true); + activeToolboxButton("color_cloud", true); + } + break; + case "save_visualmap": + $("#saving_in_progress_dialog").dialog({ + resizable: true, + draggable: true, + modal: true, + height: 100, + width: 200, + overlay: { + opacity: 0.5, + background: "black" + } + }); - var status = true; - activeToolboxButton('save', false); - jQuery.each(list_actions_pending_save, function(key, action_pending_save) { - jQuery.ajax ({ - type: 'POST', - url: action="ajax.php", - data: action_pending_save, - dataType: 'json', - success: function (data) { - if (data == '0') { - status = false; - } + var status = true; + activeToolboxButton("save", false); + jQuery.each(list_actions_pending_save, function( + key, + action_pending_save + ) { + jQuery.ajax({ + type: "POST", + url: (action = "ajax.php"), + data: action_pending_save, + dataType: "json", + success: function(data) { + if (data == "0") { + status = false; + } - $("#saving_in_progress_dialog").dialog("close"); + $("#saving_in_progress_dialog").dialog("close"); - if (status) { - alert($('#hack_translation_correct_save').html()); - } - else { - alert($('#hack_translation_incorrect_save').html()); - } - activeToolboxButton('save', true); - } - }); - }); + if (status) { + alert($("#hack_translation_correct_save").html()); + } else { + alert($("#hack_translation_incorrect_save").html()); + } + activeToolboxButton("save", true); + } + }); + }); - - break; - default: - //Maybe click in any Enterprise button in toolbox. - if (typeof(enterprise_click_button_toolbox) == 'function') { - enterprise_click_button_toolbox(id); - } - break; - } - $('.ColorPickerDivSample').css('background-color',"black"); + break; + default: + //Maybe click in any Enterprise button in toolbox. + if (typeof enterprise_click_button_toolbox == "function") { + enterprise_click_button_toolbox(id); + } + break; + } + $(".ColorPickerDivSample").css("background-color", "black"); } function showPreview(image) { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - switch (toolbuttonActive) { - case 'group_item': - case 'static_graph': - showPreviewStaticGraph(image); - break; - case 'icon': - showPreviewIcon(image); - break; - case 'service': - if (image && image.length > 0) showPreviewIcon(image); - break; - } + switch (toolbuttonActive) { + case "group_item": + case "static_graph": + showPreviewStaticGraph(image); + break; + case "icon": + showPreviewIcon(image); + break; + case "service": + if (image && image.length > 0) showPreviewIcon(image); + break; + } } function showPreviewStaticGraph(staticGraph) { - metaconsole = $("input[name='metaconsole']").val(); - var $spinner = $(""); - $spinner.prop("src", "images/spinner.gif"); + metaconsole = $("input[name='metaconsole']").val(); + var $spinner = $(""); + $spinner.prop("src", "images/spinner.gif"); - if (is_metaconsole()) { - $spinner.prop("src", "../../images/spinner.gif"); - } + if (is_metaconsole()) { + $spinner.prop("src", "../../images/spinner.gif"); + } - $("#preview") - .empty() - .css('text-align', 'right') - .append($spinner); + // If no image configured do not show anything + if (staticGraph === null) return; - if(staticGraph == '' || staticGraph == 'none'){ - - if (is_metaconsole()) { - $spinner.prop("src", "../../images/image_problem_area.png"); - } - else{ - $spinner.prop("src", "images/image_problem_area.png"); - } - $('#preview > img').css({'max-width':'100px','max-height':'100px'}); - } - else{ - imgBase = "images/console/icons/" + staticGraph; + $("#preview") + .empty() + .css("text-align", "right") + .append($spinner); - var parameter = Array(); - parameter.push ({name: "page", value: "include/ajax/visual_console_builder.ajax"}); - parameter.push ({name: "get_image_path_status", value: "1"}); - parameter.push ({name: "img_src", value: imgBase }); - parameter.push ({name: "id_visual_console", - value: id_visual_console}); + if (staticGraph == "" || staticGraph == "none") { + if (is_metaconsole()) { + $spinner.prop("src", "../../images/image_problem_area.png"); + } else { + $spinner.prop("src", "images/image_problem_area.png"); + } + $("#preview > img").css({ "max-width": "100px", "max-height": "100px" }); + } else { + imgBase = "images/console/icons/" + staticGraph; - jQuery.ajax ({ - type: 'POST', - url: get_url_ajax(), - data: parameter, - dataType: 'json', - error: function (xhr, textStatus, errorThrown) { - $("#preview").empty(); - }, - success: function (data) { - $("#preview").empty(); + var parameter = Array(); + parameter.push({ + name: "page", + value: "include/ajax/visual_console_builder.ajax" + }); + parameter.push({ name: "get_image_path_status", value: "1" }); + parameter.push({ name: "img_src", value: imgBase }); + parameter.push({ name: "id_visual_console", value: id_visual_console }); - jQuery.each(data, function(i, line) { - $("#preview").append(line); - $('#preview > img').css({'max-width':'70px','max-height':'70px'}); - }); - } - }); + jQuery.ajax({ + type: "POST", + url: get_url_ajax(), + data: parameter, + dataType: "json", + error: function(xhr, textStatus, errorThrown) { + $("#preview").empty(); + }, + success: function(data) { + $("#preview").empty(); - } + jQuery.each(data, function(i, line) { + $("#preview").append(line); + $("#preview > img").css({ + "max-width": "70px", + "max-height": "70px" + }); + }); + } + }); + } } function showPreviewIcon(icon) { - var metaconsole = $("input[name='metaconsole']").val(); - var $spinner = $(""); - $spinner.prop("src", "images/spinner.gif"); + var metaconsole = $("input[name='metaconsole']").val(); + var $spinner = $(""); + $spinner.prop("src", "images/spinner.gif"); - if (is_metaconsole()) { - $spinner.prop("src", "../../images/spinner.gif"); - } + if (is_metaconsole()) { + $spinner.prop("src", "../../images/spinner.gif"); + } - $("#preview") - .empty() - .css('text-align', 'left') - .append($spinner); + $("#preview") + .empty() + .css("text-align", "left") + .append($spinner); + if (icon == "" || icon == "none") { + if (is_metaconsole()) { + $spinner.prop("src", "../../images/image_problem_area.png"); + } else { + $spinner.prop("src", "images/image_problem_area.png"); + } + $("#preview > img").css({ "max-width": "100px", "max-height": "100px" }); + } else { + imgBase = "images/console/icons/" + icon; - if (icon == '' || icon == 'none') { - if (is_metaconsole()) { - $spinner.prop("src", "../../images/image_problem_area.png"); - } - else{ - $spinner.prop("src", "images/image_problem_area.png"); - } - $('#preview > img').css({'max-width':'100px','max-height':'100px'}); - } - else{ - imgBase = "images/console/icons/" + icon; - - var params = []; - params.push("get_image_path=1"); - params.push("img_src=" + imgBase + ".png"); - params.push("page=include/ajax/skins.ajax"); - params.push ({ - name: "id_visual_console", - value: id_visual_console - }); - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: get_url_ajax(), - error: function (xhr, textStatus, errorThrown) { - $("#preview").empty(); - }, - success: function (data) { - $("#preview") - .empty() - .append(data); - $('#preview > img').css({'max-width':'70px','max-height':'70px'}); - } - }); - } + var params = []; + params.push("get_image_path=1"); + params.push("img_src=" + imgBase + ".png"); + params.push("page=include/ajax/skins.ajax"); + params.push({ + name: "id_visual_console", + value: id_visual_console + }); + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: get_url_ajax(), + error: function(xhr, textStatus, errorThrown) { + $("#preview").empty(); + }, + success: function(data) { + $("#preview") + .empty() + .append(data); + $("#preview > img").css({ "max-width": "70px", "max-height": "70px" }); + } + }); + } } function click_copy_item_callback() { - copyDB(idItem); + copyDB(idItem); } function showGrid() { - metaconsole = $("input[name='metaconsole']").val(); + metaconsole = $("input[name='metaconsole']").val(); - var url_hack_metaconsole = ''; - if (is_metaconsole()) { - url_hack_metaconsole = '../../'; - } - - var display = $("#background_grid").css('display'); - - if (display == 'none') { - $("#background_grid").css('display', ''); - $("#background_img").css('opacity', '0.55'); - $("#background_img").css('filter', 'alpha(opacity=55)'); - $("#background_grid").css('background', - 'url("' + url_hack_metaconsole + 'images/console/background/white_boxed.jpg")'); + var url_hack_metaconsole = ""; + if (is_metaconsole()) { + url_hack_metaconsole = "../../"; + } - //Snap to grid all elements. - jQuery.each($(".item"), function(key, value) { - item = value; - idItem = $(item).attr('id'); - classItem = $(item).attr('class').replace('item', '') - .replace('ui-draggable', '').replace('ui-draggable-disabled', '') - .replace(/^\s+/g,'').replace(/\s+$/g,''); + var display = $("#background_grid").css("display"); - pos_y = parseInt($(item).css('top').replace('px', '')); - pos_x = parseInt($(item).css('left').replace('px', '')); + if (display == "none") { + $("#background_grid").css("display", ""); + $("#background_img").css("opacity", "0.55"); + $("#background_img").css("filter", "alpha(opacity=55)"); + $("#background_grid").css( + "background", + 'url("' + + url_hack_metaconsole + + 'images/console/background/white_boxed.jpg")' + ); - pos_y = Math.floor(pos_y / SIZE_GRID) * SIZE_GRID; - pos_x = Math.floor(pos_x / SIZE_GRID) * SIZE_GRID; + //Snap to grid all elements. + jQuery.each($(".item"), function(key, value) { + item = value; + idItem = $(item).attr("id"); + classItem = $(item) + .attr("class") + .replace("item", "") + .replace("ui-draggable", "") + .replace("ui-draggable-disabled", "") + .replace(/^\s+/g, "") + .replace(/\s+$/g, ""); - var values = {}; + pos_y = parseInt( + $(item) + .css("top") + .replace("px", "") + ); + pos_x = parseInt( + $(item) + .css("left") + .replace("px", "") + ); - values['absolute_left'] = pos_x; - values['absolute_top'] = pos_y; - - updateDB(classItem, idItem, values, 'show_grid'); - }); + pos_y = Math.floor(pos_y / SIZE_GRID) * SIZE_GRID; + pos_x = Math.floor(pos_x / SIZE_GRID) * SIZE_GRID; - eventsItems([SIZE_GRID, SIZE_GRID]); - } - else { - $("#background_grid").css('display', 'none'); - $("#background_img").css('opacity', '1'); - $("#background_img").css('filter', 'alpha(opacity=100)'); + var values = {}; - eventsItems(); - } + values["absolute_left"] = pos_x; + values["absolute_top"] = pos_y; + + updateDB(classItem, idItem, values, "show_grid"); + }); + + eventsItems([SIZE_GRID, SIZE_GRID]); + } else { + $("#background_grid").css("display", "none"); + $("#background_img").css("opacity", "1"); + $("#background_img").css("filter", "alpha(opacity=100)"); + + eventsItems(); + } } -function multiDragStart(event){ - multiDragMouse(event); - +function multiDragStart(event) { + multiDragMouse(event); } -function multidragStop(event){ - $('#background').off("mousemove"); - values = []; - selectedItems.forEach( function(valor, indice, array) { - $('#'+valor).css('left','+=1'); - $('#'+valor).css('top','+=1'); - classItem = $('#'+valor).attr('class').replace(/item|ui-draggable|ui-draggable-dragging|-dragging/g, '').trim(); - values['mov_left'] = parseInt($('#'+valor).css('left')); - values['mov_top'] = parseInt($('#'+valor).css('top')); - updateDB(classItem, valor, values,'dragstop'); - }); - +function multidragStop(event) { + $("#background").off("mousemove"); + values = []; + selectedItems.forEach(function(valor, indice, array) { + $("#" + valor).css("left", "+=1"); + $("#" + valor).css("top", "+=1"); + classItem = $("#" + valor) + .attr("class") + .replace(/item|ui-draggable|ui-draggable-dragging|-dragging/g, "") + .trim(); + values["mov_left"] = parseInt($("#" + valor).css("left")); + values["mov_top"] = parseInt($("#" + valor).css("top")); + updateDB(classItem, valor, values, "dragstop"); + }); } +function multiDragMouse(eventDrag) { + var preX = []; + var preY = []; + selectedItems.forEach(function(valor, indice, array) { + preX[indice] = $("#" + valor).css("left"); + preY[indice] = $("#" + valor).css("top"); + }); -function multiDragMouse(eventDrag){ - var preX = []; - var preY = []; - - selectedItems.forEach( function(valor, indice, array) { - preX[indice] = $('#'+valor).css('left'); - preY[indice] = $('#'+valor).css('top'); - }); - - $('#background').on('mousemove',function(event){ - var moveDiffX = event.clientX - eventDrag.clientX; - var moveDiffY = event.clientY - eventDrag.clientY; - selectedItems.forEach( function(valor, indice, array) { - if(!(parseInt($('#'+valor).css('left')) < 0 && parseInt(moveDiffX)+parseInt(preX[indice]) < 0) && - !(parseInt($('#'+valor).css('left')) + parseInt($('#'+valor).css('width')) > parseInt($('#background').css('width')) && parseInt(moveDiffX+preX[indice]) > 0)){ - $('#'+valor).css('left',parseInt(moveDiffX)+parseInt(preX[indice])+'px'); - } - if(!(parseInt($('#'+valor).css('top')) < 0 && parseInt(moveDiffY)+parseInt(preY[indice]) < 0) && - !(parseInt($('#'+valor).css('top')) + parseInt($('#'+valor).css('height')) > parseInt($('#background').css('height')) && parseInt(moveDiffY+preY[indice]) > 0)){ - $('#'+valor).css('top',parseInt(moveDiffY)+parseInt(preY[indice])+'px'); - } - }); - }); + $("#background").on("mousemove", function(event) { + var moveDiffX = event.clientX - eventDrag.clientX; + var moveDiffY = event.clientY - eventDrag.clientY; + selectedItems.forEach(function(valor, indice, array) { + if ( + !( + parseInt($("#" + valor).css("left")) < 0 && + parseInt(moveDiffX) + parseInt(preX[indice]) < 0 + ) && + !( + parseInt($("#" + valor).css("left")) + + parseInt($("#" + valor).css("width")) > + parseInt($("#background").css("width")) && + parseInt(moveDiffX + preX[indice]) > 0 + ) + ) { + $("#" + valor).css( + "left", + parseInt(moveDiffX) + parseInt(preX[indice]) + "px" + ); + } + if ( + !( + parseInt($("#" + valor).css("top")) < 0 && + parseInt(moveDiffY) + parseInt(preY[indice]) < 0 + ) && + !( + parseInt($("#" + valor).css("top")) + + parseInt($("#" + valor).css("height")) > + parseInt($("#background").css("height")) && + parseInt(moveDiffY + preY[indice]) > 0 + ) + ) { + $("#" + valor).css( + "top", + parseInt(moveDiffY) + parseInt(preY[indice]) + "px" + ); + } + }); + }); } -function linkedMapStatusCalculationTypeChanged ($linkedMapStatusCalcRow, value) { - if ($linkedMapStatusCalcRow.length === 0) return; +function linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, value) { + if ($linkedMapStatusCalcRow.length === 0) return; - switch (value) { - case "weight": - // Show weight input - $linkedMapStatusCalcRow - .siblings("#map_linked_weight") - .show() - .siblings("#linked_map_status_service_critical_row") - .hide() - .siblings("#linked_map_status_service_warning_row") - .hide(); - break; - case "service": - // Show critical and warning values - $linkedMapStatusCalcRow - .siblings("#map_linked_weight") - .hide() - .siblings("#linked_map_status_service_critical_row") - .show() - .siblings("#linked_map_status_service_warning_row") - .show(); - break; - default: - // Hide inputs - $linkedMapStatusCalcRow - .siblings("#map_linked_weight") - .hide() - .siblings("#linked_map_status_service_critical_row") - .hide() - .siblings("#linked_map_status_service_warning_row") - .hide(); - break; - } + switch (value) { + case "weight": + // Show weight input + $linkedMapStatusCalcRow + .siblings("#map_linked_weight") + .show() + .siblings("#linked_map_status_service_critical_row") + .hide() + .siblings("#linked_map_status_service_warning_row") + .hide(); + break; + case "service": + // Show critical and warning values + $linkedMapStatusCalcRow + .siblings("#map_linked_weight") + .hide() + .siblings("#linked_map_status_service_critical_row") + .show() + .siblings("#linked_map_status_service_warning_row") + .show(); + break; + default: + // Hide inputs + $linkedMapStatusCalcRow + .siblings("#map_linked_weight") + .hide() + .siblings("#linked_map_status_service_critical_row") + .hide() + .siblings("#linked_map_status_service_warning_row") + .hide(); + break; + } } -function linkedMapChanged ($linkedMapRow, value) { - if ($linkedMapRow.length === 0) return; +function linkedMapChanged($linkedMapRow, value) { + if ($linkedMapRow.length === 0) return; - if (value === 0) { - $linkedMapRow - .siblings("#linked_map_status_calculation_row") - .hide() - .siblings("#map_linked_weight") - .hide() - .siblings("#linked_map_status_service_critical_row") - .hide() - .siblings("#linked_map_status_service_warning_row") - .hide(); - } else { - var $linkedMapStatusCalcRow = $linkedMapRow.siblings("#linked_map_status_calculation_row"); - var calcType = $linkedMapStatusCalcRow.find("select").val(); - $linkedMapStatusCalcRow.show(); - linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, calcType); - } + if (value === 0) { + $linkedMapRow + .siblings("#linked_map_status_calculation_row") + .hide() + .siblings("#map_linked_weight") + .hide() + .siblings("#linked_map_status_service_critical_row") + .hide() + .siblings("#linked_map_status_service_warning_row") + .hide(); + } else { + var $linkedMapStatusCalcRow = $linkedMapRow.siblings( + "#linked_map_status_calculation_row" + ); + var calcType = $linkedMapStatusCalcRow.find("select").val(); + $linkedMapStatusCalcRow.show(); + linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, calcType); + } } -function onLinkedMapChange (event) { - var $linkedMapRow = $(event.target).parent().parent(); - var value = Number.parseInt(event.target.value); - linkedMapChanged($linkedMapRow, value); +function onLinkedMapChange(event) { + var $linkedMapRow = $(event.target) + .parent() + .parent(); + var value = Number.parseInt(event.target.value); + linkedMapChanged($linkedMapRow, value); } -function onLinkedMapStatusCalculationTypeChange (event) { - var $linkedMapStatusCalcRow = $(event.target).parent().parent(); - var value = event.target.value || "default"; - linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, value); +function onLinkedMapStatusCalculationTypeChange(event) { + var $linkedMapStatusCalcRow = $(event.target) + .parent() + .parent(); + var value = event.target.value || "default"; + linkedMapStatusCalculationTypeChanged($linkedMapStatusCalcRow, value); +} + +function validateColorRange(values) { + return ( + (values["from_value"].length > 0 || values["to_value"].length > 0) && + values["color"].length > 0 && + !Number.isNaN(Number.parseFloat(values["from_value"])) && + !Number.isNaN(Number.parseFloat(values["to_value"])) + ); +} + +function getColorRangeTable($colorRangeCreationTable, values) { + var $colorRangeTable = $colorRangeCreationTable.clone(); + $colorRangeTable.attr("id", "").removeClass("color-range-creation"); + + // ref inputs + var $fromValueInput = $colorRangeTable.find('input[name="from_value_new"]'); + var $toValueInput = $colorRangeTable.find('input[name="to_value_new"]'); + var $colorInput = $colorRangeTable.find('input[name="color_new"]'); + + // Override input values + if (values != null) { + if (values["from_value"] != null) { + $fromValueInput.val(values["from_value"]); + } + if (values["to_value"] != null) { + $toValueInput.val(values["to_value"]); + } + if (values["color"] != null) { + $colorInput.val(values["color"]); + } + } + + // Change the name of the new inputs (and clear the id attr) + $fromValueInput.attr("name", "color_range_from_values[]").attr("id", ""); + $toValueInput.attr("name", "color_range_to_values[]").attr("id", ""); + $colorInput.attr("name", "color_range_color_values[]").attr("id", ""); + + // Change the add button + $colorRangeAddBtn = $colorRangeTable.find("a.color-range-add"); + if ($colorRangeAddBtn.length > 0) { + $colorRangeAddBtn + .removeClass("color-range-add") + .addClass("color-range-delete") + .click(function(e) { + e.preventDefault(); + e.stopPropagation(); + $colorRangeTable.remove(); + }); + + // Change img + $colorRangeAddImg = $colorRangeAddBtn.children("img"); + if ($colorRangeAddImg.length > 0) { + var src = + $("#hidden-metaconsole").val() == 1 + ? "../../images/delete.png" + : "images/delete.png"; + $colorRangeAddImg.prop("src", src); + } + } + + return $colorRangeTable; +} + +function handleColorRangeCreation(event) { + event.preventDefault(); + event.stopPropagation(); + + var $creationBtn = $(event.target); + var $colorRangeCreationTable = $creationBtn.parents( + "table.color-range-creation" + ); + + // ref inputs + var $fromValueInput = $colorRangeCreationTable.find( + 'input[name="from_value_new"]' + ); + var $toValueInput = $colorRangeCreationTable.find( + 'input[name="to_value_new"]' + ); + var $colorInput = $colorRangeCreationTable.find('input[name="color_new"]'); + + // TODO: Show info about validation + var values = { + from_value: $fromValueInput.val(), + to_value: $toValueInput.val(), + color: $colorInput.val() + }; + if (!validateColorRange(values)) return; + + var $newColorRangeTable = getColorRangeTable($colorRangeCreationTable); + + // Clear creation inputs + $fromValueInput.val(""); + $toValueInput.val(""); + $colorInput.val("#FFFFFF"); + + // Add the new table + $newColorRangeTable.insertBefore($colorRangeCreationTable); +} + +function bindColorRangeEvents() { + $("a.color-range-add").click(handleColorRangeCreation); } diff --git a/pandora_console/godmode/reporting/visual_console_builder.editor.php b/pandora_console/godmode/reporting/visual_console_builder.editor.php index 6f8bfefb55..9ba8c56716 100755 --- a/pandora_console/godmode/reporting/visual_console_builder.editor.php +++ b/pandora_console/godmode/reporting/visual_console_builder.editor.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,43 +10,49 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; // Login check -check_login (); +check_login(); // Visual console required if (empty($visualConsole)) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } // ACL for the existing visual console // if (!isset($vconsole_read)) -// $vconsole_read = check_acl ($config['id_user'], $visualConsole['id_group'], "VR"); -if (!isset($vconsole_write)) - $vconsole_write = check_acl ($config['id_user'], $visualConsole['id_group'], "VW"); -if (!isset($vconsole_manage)) - $vconsole_manage = check_acl ($config['id_user'], $visualConsole['id_group'], "VM"); +// $vconsole_read = check_acl ($config['id_user'], $visualConsole['id_group'], "VR"); +if (!isset($vconsole_write)) { + $vconsole_write = check_acl($config['id_user'], $visualConsole['id_group'], 'VW'); +} + +if (!isset($vconsole_manage)) { + $vconsole_manage = check_acl($config['id_user'], $visualConsole['id_group'], 'VM'); +} if (!$vconsole_write && !$vconsole_manage) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } $metaconsole_hack = ''; if (defined('METACONSOLE')) { - $metaconsole_hack = '../../'; + $metaconsole_hack = '../../'; } -require_once($config['homedir'] . '/include/functions_visual_map.php'); -require_once($config['homedir'] . '/include/functions_visual_map_editor.php'); +require_once $config['homedir'].'/include/functions_visual_map.php'; +require_once $config['homedir'].'/include/functions_visual_map_editor.php'; enterprise_include_once('include/functions_visual_map_editor.php'); visual_map_editor_print_toolbox(); @@ -56,69 +61,89 @@ $background = $visualConsole['background']; $widthBackground = $visualConsole['width']; $heightBackground = $visualConsole['height']; -$layoutDatas = db_get_all_rows_field_filter ('tlayout_data', - 'id_layout', $idVisualConsole); -if ($layoutDatas === false) - $layoutDatas = array(); +$layoutDatas = db_get_all_rows_field_filter( + 'tlayout_data', + 'id_layout', + $idVisualConsole +); +if ($layoutDatas === false) { + $layoutDatas = []; +} -//Set the hidden value for the javascript +// Set the hidden value for the javascript if (defined('METACONSOLE')) { - html_print_input_hidden('metaconsole', 1); -} -else { - html_print_input_hidden('metaconsole', 0); + html_print_input_hidden('metaconsole', 1); +} else { + html_print_input_hidden('metaconsole', 0); } + visual_map_editor_print_hack_translate_strings(); visual_map_editor_print_item_palette($visualConsole['id'], $background); if (!defined('METACONSOLE')) { - echo '
    '; -} -else { - echo '
    '; + echo '
    '; +} else { + echo '
    '; } + echo '
    '; +margin: 0px auto;border: 1px lightgray solid; width: '.$widthBackground.'px; height: '.$heightBackground.'px;background-color: '.$visualConsole['background_color'].';">'; echo ""; + background: url(".ui_get_full_url('images/console/background/white_boxed.jpg', false, false, false).'); + background-repeat: repeat; width: '.$widthBackground.'px; height: '.$heightBackground."px;'>
    "; -//Print the layout datas from the DB. +// Print the layout datas from the DB. foreach ($layoutDatas as $layoutData) { - $layoutData['status_calculated'] = visual_map_get_status_element($layoutData); - - // Pending delete and disable modules must be ignored - $delete_pending_module = db_get_value ("delete_pending", - "tagente_modulo", "id_agente_modulo", $layoutData["id_agente_modulo"]); - $disabled_module = db_get_value ("disabled", - "tagente_modulo", "id_agente_modulo", $layoutData["id_agente_modulo"]); - - if ($delete_pending_module == 1 || $disabled_module == 1) - continue; - - switch ($layoutData['type']) { - case LINE_ITEM: - visual_map_print_user_line_handles($layoutData); - visual_map_print_user_lines($layoutData); - break; - default: - visual_map_print_item("write", $layoutData, - null, true, false, false); - break; - } - - - - - html_print_input_hidden('status_' . $layoutData['id'], - $layoutData['status_calculated']); - + $layoutData['status_calculated'] = visual_map_get_status_element($layoutData); + + // Pending delete and disable modules must be ignored + $delete_pending_module = db_get_value( + 'delete_pending', + 'tagente_modulo', + 'id_agente_modulo', + $layoutData['id_agente_modulo'] + ); + $disabled_module = db_get_value( + 'disabled', + 'tagente_modulo', + 'id_agente_modulo', + $layoutData['id_agente_modulo'] + ); + + if ($delete_pending_module == 1 || $disabled_module == 1) { + continue; + } + + switch ($layoutData['type']) { + case LINE_ITEM: + visual_map_print_user_line_handles($layoutData); + visual_map_print_user_lines($layoutData); + break; + + default: + visual_map_print_item( + 'write', + $layoutData, + null, + true, + false, + false + ); + break; + } + + + + + html_print_input_hidden( + 'status_'.$layoutData['id'], + $layoutData['status_calculated'] + ); } -echo ""; +echo ""; echo '
    '; echo '
    '; @@ -127,7 +152,8 @@ html_print_input_hidden('background_width', $widthBackground); html_print_input_hidden('background_height', $heightBackground); $backgroundSizes = getimagesize( - $config['homedir'] . '/images/console/background/' . $background); + $config['homedir'].'/images/console/background/'.$background +); html_print_input_hidden('background_original_width', $backgroundSizes[0]); html_print_input_hidden('background_original_height', $backgroundSizes[1]); html_print_input_hidden('id_visual_console', $visualConsole['id']); @@ -135,26 +161,17 @@ html_print_input_hidden('message_size', __('Min allowed size is 1024x768')); // Loading dialog -echo ""; +echo "'; -echo ""; +echo "'; -echo ""; +echo "'; -//CSS -ui_require_css_file ('color-picker'); -ui_require_css_file ('jquery-ui.min'); +// CSS +ui_require_css_file('color-picker', 'include/styles/js/'); +ui_require_css_file('jquery-ui.min', 'include/styles/js/'); -//Javascript +// Javascript ui_require_jquery_file('colorpicker'); ui_require_javascript_file('wz_jsgraphics'); ui_require_javascript_file('pandora_visual_console'); @@ -162,90 +179,89 @@ ui_require_javascript_file('visual_console_builder.editor', 'godmode/reporting/' ui_require_javascript_file_enterprise('functions_visualmap', defined('METACONSOLE')); ui_require_javascript_file('tiny_mce', 'include/javascript/tiny_mce/'); -// Javascript file for base 64 encoding of label parameter -ui_require_javascript_file ('encode_decode_base64'); +// Javascript file for base 64 encoding of label parameter +ui_require_javascript_file('encode_decode_base64'); ?> diff --git a/pandora_console/godmode/reporting/visual_console_builder.elements.php b/pandora_console/godmode/reporting/visual_console_builder.elements.php index 898c9b09ff..d2849ce5e0 100755 --- a/pandora_console/godmode/reporting/visual_console_builder.elements.php +++ b/pandora_console/godmode/reporting/visual_console_builder.elements.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,688 +10,801 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Login check global $config; -check_login (); +check_login(); // Visual console required if (empty($visualConsole)) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } // ACL for the existing visual console // if (!isset($vconsole_read)) -// $vconsole_read = check_acl ($config['id_user'], $visualConsole['id_group'], "VR"); -if (!isset($vconsole_write)) - $vconsole_write = check_acl($config['id_user'], - $visualConsole['id_group'], "VW"); -if (!isset($vconsole_manage)) - $vconsole_manage = check_acl($config['id_user'], - $visualConsole['id_group'], "VM"); - -if (!$vconsole_write && !$vconsole_manage) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; +// $vconsole_read = check_acl ($config['id_user'], $visualConsole['id_group'], "VR"); +if (!isset($vconsole_write)) { + $vconsole_write = check_acl( + $config['id_user'], + $visualConsole['id_group'], + 'VW' + ); } -require_once ($config['homedir'].'/include/functions_visual_map.php'); -require_once ($config['homedir'].'/include/functions_agents.php'); +if (!isset($vconsole_manage)) { + $vconsole_manage = check_acl( + $config['id_user'], + $visualConsole['id_group'], + 'VM' + ); +} + +if (!$vconsole_write && !$vconsole_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; +} + +require_once $config['homedir'].'/include/functions_visual_map.php'; +require_once $config['homedir'].'/include/functions_agents.php'; enterprise_include_once('include/functions_visual_map.php'); enterprise_include_once('meta/include/functions_agents_meta.php'); enterprise_include_once('meta/include/functions_users_meta.php'); -//Arrays for select box. +// Arrays for select box. $backgrounds_list = list_files( - $config['homedir'] . '/images/console/background/', "jpg", 1, 0); -$backgrounds_list = array_merge($backgrounds_list, - list_files($config['homedir'] . '/images/console/background/', "png", 1, 0)); + $config['homedir'].'/images/console/background/', + 'jpg', + 1, + 0 +); +$backgrounds_list = array_merge( + $backgrounds_list, + list_files($config['homedir'].'/images/console/background/', 'png', 1, 0) +); -$images_list = array (); -$all_images = list_files ($config['homedir'] . '/images/console/icons/', - "png", 1, 0); +$images_list = []; +$all_images = list_files( + $config['homedir'].'/images/console/icons/', + 'png', + 1, + 0 +); foreach ($all_images as $image_file) { - if (strpos ($image_file, "_bad")) - continue; - if (strpos ($image_file, "_ok")) - continue; - if (strpos ($image_file, "_warning")) - continue; - $image_file = substr ($image_file, 0, strlen ($image_file) - 4); - $images_list[$image_file] = $image_file; + if (strpos($image_file, '_bad')) { + continue; + } + + if (strpos($image_file, '_ok')) { + continue; + } + + if (strpos($image_file, '_warning')) { + continue; + } + + $image_file = substr($image_file, 0, (strlen($image_file) - 4)); + $images_list[$image_file] = $image_file; } $table = new stdClass(); $table->width = '100%'; $table->class = 'databox data'; -$table->head = array(); +$table->head = []; $table->head['icon'] = ''; -$table->head[0] = __('Label') . '
    ' . __('Agent') . ' / ' . __('Group'); -$table->head[1] = __('Image') . '
    ' . __('Module') . ' / ' . __('Custom graph'); +$table->head[0] = __('Label').'
    '.__('Agent').' / '.__('Group'); +$table->head[1] = __('Image').'
    '.__('Module').' / '.__('Custom graph'); $table->head[2] = __('Width x Height
    Max value'); -$table->head[3] = __('Position') . '
    ' . __('Period'); -$table->head[4] = __('Parent') . '
    ' . __('Map linked'); -$table->head[5] = ""; -$table->head[5] .= '   ' . html_print_checkbox('head_multiple_delete', - '', false, true, false, 'toggle_checkbox_multiple_delete();'); -$table->head[5] .= '   ' . - __('A.') . ''; +$table->head[3] = __('Position').'
    '.__('Period'); +$table->head[4] = __('Parent').'
    '.__('Map linked'); +$table->head[5] = ''; +$table->head[5] .= '   '.html_print_checkbox( + 'head_multiple_delete', + '', + false, + true, + false, + 'toggle_checkbox_multiple_delete();' +); +$table->head[5] .= '   '.__('A.').''; -$table->size = array(); +$table->size = []; $table->size['icon'] = '1%'; $table->size[0] = '25%'; -$table->align = array(); +$table->align = []; if (!defined('METACONSOLE')) { - $table->headstyle[0] = "text-align:left;"; - $table->headstyle[1] = "text-align:left"; - $table->headstyle[2] = "text-align:left"; - $table->headstyle[3] = "text-align:left"; - $table->headstyle[4] = "text-align:left"; - $table->headstyle[5] = "text-align:left"; - $table->align[0] = "left"; - $table->align[1] = "left"; - $table->align[2] = "left"; - $table->align[3] = "left"; - $table->align[4] = "left"; - $table->align[5] = "left"; + $table->headstyle[0] = 'text-align:left;'; + $table->headstyle[1] = 'text-align:left'; + $table->headstyle[2] = 'text-align:left'; + $table->headstyle[3] = 'text-align:left'; + $table->headstyle[4] = 'text-align:left'; + $table->headstyle[5] = 'text-align:left'; + $table->align[0] = 'left'; + $table->align[1] = 'left'; + $table->align[2] = 'left'; + $table->align[3] = 'left'; + $table->align[4] = 'left'; + $table->align[5] = 'left'; } -$table->data = array(); -//Background +$table->data = []; + +// Background $table->data[0]['icon'] = ''; $table->data[0][0] = '
    '.__('Background').'
    '; $table->data[0][1] = '
    '.html_print_select($backgrounds_list, 'background', $visualConsole['background'], '', 'None', '', true, false, true, '', false, 'width: 120px;').'
    '; -$table->data[0][2] = '
    '.html_print_input_text('width', $visualConsole['width'], '', 3, 5, true) . - ' x ' . - html_print_input_text('height', $visualConsole['height'], '', 3, 5, true).'
    '; +$table->data[0][2] = '
    '.html_print_input_text('width', $visualConsole['width'], '', 3, 5, true).' x '.html_print_input_text('height', $visualConsole['height'], '', 3, 5, true).'
    '; $table->data[0][3] = $table->data[0][4] = $table->data[0][5] = ''; $i = 1; -$layoutDatas = db_get_all_rows_field_filter ('tlayout_data', - 'id_layout', $idVisualConsole); -if ($layoutDatas === false) - $layoutDatas = array(); +$layoutDatas = db_get_all_rows_field_filter( + 'tlayout_data', + 'id_layout', + $idVisualConsole +); +if ($layoutDatas === false) { + $layoutDatas = []; +} $alternativeStyle = true; foreach ($layoutDatas as $layoutData) { - $idLayoutData = $layoutData['id']; - - //line between rows - $table->data[$i][0] = '
    '; - $table->colspan[$i][0] = '8'; - - switch ($layoutData['type']) { - case STATIC_GRAPH: - $table->data[$i + 1]['icon'] = - html_print_image('images/camera.png', true, - array('title' => __('Static Graph'))); - break; - case PERCENTILE_BAR: - $table->data[$i + 1]['icon'] = - html_print_image('images/chart_bar.png', true, - array('title' => __('Percentile Bar'))); - break; - case PERCENTILE_BUBBLE: - $table->data[$i + 1]['icon'] = - html_print_image('images/dot_red.png', true, - array('title' => __('Percentile Bubble'))); - break; - case MODULE_GRAPH: - $table->data[$i + 1]['icon'] = - html_print_image('images/chart_curve.png', true, - array('title' => __('Module Graph'))); - break; - case AUTO_SLA_GRAPH: - $table->data[$i + 1]['icon'] = - html_print_image('images/auto_sla_graph.png', true, - array('title' => __('Auto SLA Graph'))); - break; - case SIMPLE_VALUE: - $table->data[$i + 1]['icon'] = - html_print_image('images/binary.png', true, - array('title' => __('Simple Value'))); - break; - case SIMPLE_VALUE_MAX: - $table->data[$i + 1]['icon'] = - html_print_image('images/binary.png', true, - array('title' => __('Simple Value (Process Max)'))); - break; - case SIMPLE_VALUE_MIN: - $table->data[$i + 1]['icon'] = - html_print_image('images/binary.png', true, - array('title' => __('Simple Value (Process Min)'))); - break; - case SIMPLE_VALUE_AVG: - $table->data[$i + 1]['icon'] = - html_print_image('images/binary.png', true, - array('title' => __('Simple Value (Process Avg)'))); - break; - case LABEL: - $table->data[$i + 1]['icon'] = - html_print_image('images/tag_red.png', true, - array('title' => __('Label'))); - break; - case ICON: - $table->data[$i + 1]['icon'] = - html_print_image('images/photo.png', true, - array('title' => __('Icon'))); - break; - case BOX_ITEM: - $table->data[$i + 1]['icon'] = - html_print_image('images/box_item.png', true, - array('title' => __('Box'))); - break; - case GROUP_ITEM: - $table->data[$i + 1]['icon'] = - html_print_image('images/group_green.png', true, - array('title' => __('Group'))); - break; - case LINE_ITEM: - $table->data[$i + 1]['icon'] = - html_print_image('images/line_item.png', true, - array('title' => __('Line'))); - break; - default: - if (enterprise_installed()) { - $table->data[$i + 1]['icon'] = - enterprise_visual_map_print_list_element('icon', $layoutData); - } - else { - $table->data[$i + 1]['icon'] = ''; - } - break; - } - - - - //First row - - //Label - switch ($layoutData['type']) { - case ICON: - case BOX_ITEM: - case LINE_ITEM: - // hasn't the label. - $table->data[$i + 1][0] = ''; - break; - default: - $table->data[$i + 1][0] = '' . - html_print_input_hidden('label_' . $idLayoutData, $layoutData['label'], true) . - '' . __('Edit label') .'' . - ''; - break; - } - - - //Image - switch ($layoutData['type']) { - case STATIC_GRAPH: - case ICON: - case GROUP_ITEM: - case SERVICE: - $table->data[$i + 1][1] = - html_print_select ($images_list, - 'image_' . $idLayoutData, $layoutData['image'], '', - 'None', '', true, false, true, '', false, - "width: 120px"); - break; - default: - $table->data[$i + 1][1] = ''; - break; - } - - - - //Width and height - switch ($layoutData['type']) { - case LINE_ITEM: - // hasn't the width and height. - $table->data[$i + 1][2] = ''; - break; - default: - $table->data[$i + 1][2] = html_print_input_text('width_' . $idLayoutData, $layoutData['width'], '', 2, 5, true) . - ' x ' . - html_print_input_text('height_' . $idLayoutData, $layoutData['height'], '', 2, 5, true); - break; - } - - //Position - switch ($layoutData['type']) { - case LINE_ITEM: - // hasn't the width and height. - $table->data[$i + 1][3] = ''; - break; - default: - $table->data[$i + 1][3] = '( ' . html_print_input_text('left_' . $idLayoutData, $layoutData['pos_x'], '', 2, 5, true) . - ' , ' . html_print_input_text('top_' . $idLayoutData, $layoutData['pos_y'], '', 2, 5, true) . - ' )'; - break; - } - - - //Parent - switch ($layoutData['type']) { - case BOX_ITEM: - case LINE_ITEM: - $table->data[$i + 1][4] = ""; - break; - default: - $parents = visual_map_get_items_parents($idVisualConsole); - $table->data[$i + 1][4] = html_print_select($parents, - 'parent_' . $idLayoutData, $layoutData['parent_item'], - '', __('None'), 0, true); - } - - //Delete row button - if (!defined('METACONSOLE')) { - $url_delete = "index.php?" . - "sec=network&" . - "sec2=godmode/reporting/visual_console_builder&" . - "tab=" . $activeTab . "&" . - "action=delete&" . - "id_visual_console=" . $visualConsole["id"] . "&" . - "id_element=" . $idLayoutData; - } - else { - $url_delete = "index.php?" . - "operation=edit_visualmap&" . - "sec=screen&" . - "sec2=screens/screens&" . - "action=visualmap&" . - "pure=" . (int)get_parameter('pure', 0) . "&" . - "tab=list_elements&" . - "action2=delete&" . - "id_visual_console=" . $visualConsole["id"] . "&" . - "id_element=" . $idLayoutData; - - } - - $table->data[$i + 1][5] = ""; - $table->data[$i + 1][5] .= html_print_checkbox('multiple_delete_items', $idLayoutData, false, true); - $table->data[$i + 1][5] .= '' . - html_print_image('images/cross.png', true) . ''; - - //Second row - $table->data[$i + 2]['icon'] = ''; - - - //Agent - switch ($layoutData['type']) { - case GROUP_ITEM: - $own_info = get_user_info($config['id_user']); - if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, "PM")) - $return_all_group = false; - else - $return_all_group = true; - $table->data[$i + 2][0] = html_print_select_groups(false, "AR", - $return_all_group, 'group_' . $idLayoutData, - $layoutData['id_group'], '', '', 0, true); - break; - case BOX_ITEM: - case ICON: - case LABEL: - case LINE_ITEM: - $table->data[$i + 2][0] = ''; - break; - default: - $cell_content_enterprise = false; - if (enterprise_installed()) { - $cell_content_enterprise = - enterprise_visual_map_print_list_element('agent', $layoutData); - } - if ($cell_content_enterprise === false) { - $params = array(); - $params['return'] = true; - $params['show_helptip'] = true; - $params['size'] = 20; - $params['input_name'] = 'agent_' . $idLayoutData; - $params['javascript_is_function_select'] = true; - $params['selectbox_id'] = 'module_' . $idLayoutData; - if (defined('METACONSOLE')) { - $params['javascript_ajax_page'] = '../../ajax.php'; - $params['disabled_javascript_on_blur_function'] = true; - - $params['print_input_id_server'] = true; - $params['input_id_server_id'] = $params['input_id_server_name'] = 'id_server_id_' . $idLayoutData; - $params['input_id_server_value'] = $layoutData['id_metaconsole']; - $params['metaconsole_enabled'] = true; - $params['print_hidden_input_idagent'] = true; - $params['hidden_input_idagent_name'] = 'id_agent_' . $idLayoutData; - $params['hidden_input_idagent_value'] = $layoutData['id_agent']; - - $params['value'] = agents_meta_get_alias($layoutData['id_agent'], - "none", $layoutData['id_metaconsole'], true); - } - else { - $params['print_hidden_input_idagent'] = true; - $params['hidden_input_idagent_name'] = 'id_agent_' . $idLayoutData; - $params['hidden_input_idagent_value'] = $layoutData['id_agent']; - $params['value'] = db_get_value ("alias","tagente","id_agente",$layoutData['id_agent']); - } - - if ($layoutData['id_agent'] == 0 and $layoutData['id_custom_graph'] != 0) { - $table->data[$i + 2][0] = __("Custom graph"); - } else { - $table->data[$i + 2][0] = ui_print_agent_autocomplete_input($params); - } - } - else { - $table->data[$i + 2][0] = $cell_content_enterprise; - } - break; - } - - - //Module - switch ($layoutData['type']) { - case ICON: - case LABEL: - case BOX_ITEM: - case LINE_ITEM: - case GROUP_ITEM: - $table->data[$i + 2][1] = ''; - break; - default: - if ($layoutData['id_layout_linked'] != 0) { - //It is a item that links with other visualmap - break; - } - - $cell_content_enterprise = false; - if (enterprise_installed()) { - $cell_content_enterprise = - enterprise_visual_map_print_list_element('module', $layoutData); - } - if ($cell_content_enterprise === false) { - if (!defined('METACONSOLE')) { - $modules = agents_get_modules($layoutData['id_agent']); - } - else { - if ($layoutData['id_agent'] != 0) { - $server = db_get_row('tmetaconsole_setup', 'id', $layoutData['id_metaconsole']); - if (metaconsole_connect($server) == NOERR) { - $modules = agents_get_modules($layoutData['id_agent']); - metaconsole_restore_db(); - } - } - } + $idLayoutData = $layoutData['id']; - $modules = io_safe_output($modules); + // line between rows + $table->data[$i][0] = '
    '; + $table->colspan[$i][0] = '8'; - if ($layoutData['id_agent'] == 0 and $layoutData['id_custom_graph'] != 0) { - if(is_metaconsole()){ - $graphs = array(); - $graphs = metaconsole_get_custom_graphs(true); - $table->data[$i + 2][1] = html_print_select( - $graphs, 'custom_graph_' . $idLayoutData, - $layoutData['id_custom_graph'] . "|" . $layoutData['id_metaconsole'], - '', __('None'), 0, true - ); - } - else{ - $table->data[$i + 2][1] = html_print_select_from_sql( - "SELECT id_graph, name FROM tgraph", - 'custom_graph_' . $idLayoutData, - $layoutData['id_custom_graph'], - '', __('None'), 0, true - ); - } - } else { - $table->data[$i + 2][1] = html_print_select($modules, - 'module_' . $idLayoutData, - $layoutData['id_agente_modulo'], '', '---', 0, true, - false, true, '', false, "width: 120px"); - } - } - else { - $table->data[$i + 2][1] = $cell_content_enterprise; - } - break; - } + switch ($layoutData['type']) { + case STATIC_GRAPH: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/camera.png', + true, + ['title' => __('Static Graph')] + ); + break; - //Empty - $table->data[$i + 2][2] = ''; + case PERCENTILE_BAR: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/chart_bar.png', + true, + ['title' => __('Percentile Bar')] + ); + break; - //Period - switch ($layoutData['type']) { - case MODULE_GRAPH: - case SIMPLE_VALUE_MAX: - case SIMPLE_VALUE_MIN: - case SIMPLE_VALUE_AVG: - $table->data[$i + 2][3] = - html_print_extended_select_for_time( - 'period_' . $idLayoutData, - $layoutData['period'], '', '--', '0', 10, true); - break; - default: - $table->data[$i + 2][3] = ''; - break; - } - - //Map linked - switch ($layoutData['type']) { - case LINE_ITEM: - case BOX_ITEM: - case AUTO_SLA_GRAPH: - $table->data[$i + 2][4] = ""; - break; - default: - $table->data[$i + 2][4] = html_print_select_from_sql( - 'SELECT id, name + case PERCENTILE_BUBBLE: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/dot_red.png', + true, + ['title' => __('Percentile Bubble')] + ); + break; + + case MODULE_GRAPH: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/chart_curve.png', + true, + ['title' => __('Module Graph')] + ); + break; + + case AUTO_SLA_GRAPH: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/auto_sla_graph.png', + true, + ['title' => __('Auto SLA Graph')] + ); + break; + + case SIMPLE_VALUE: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/binary.png', + true, + ['title' => __('Simple Value')] + ); + break; + + case SIMPLE_VALUE_MAX: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/binary.png', + true, + ['title' => __('Simple Value (Process Max)')] + ); + break; + + case SIMPLE_VALUE_MIN: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/binary.png', + true, + ['title' => __('Simple Value (Process Min)')] + ); + break; + + case SIMPLE_VALUE_AVG: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/binary.png', + true, + ['title' => __('Simple Value (Process Avg)')] + ); + break; + + case LABEL: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/tag_red.png', + true, + ['title' => __('Label')] + ); + break; + + case ICON: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/photo.png', + true, + ['title' => __('Icon')] + ); + break; + + case BOX_ITEM: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/box_item.png', + true, + ['title' => __('Box')] + ); + break; + + case GROUP_ITEM: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/group_green.png', + true, + ['title' => __('Group')] + ); + break; + + case LINE_ITEM: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/line_item.png', + true, + ['title' => __('Line')] + ); + break; + + case COLOR_CLOUD: + $table->data[($i + 1)]['icon'] = html_print_image( + 'images/color_cloud_item.png', + true, + ['title' => __('Color cloud')] + ); + break; + + default: + if (enterprise_installed()) { + $table->data[($i + 1)]['icon'] = enterprise_visual_map_print_list_element('icon', $layoutData); + } else { + $table->data[($i + 1)]['icon'] = ''; + } + break; + } + + + + // First row + // Label + switch ($layoutData['type']) { + case ICON: + case BOX_ITEM: + case LINE_ITEM: + // hasn't the label. + $table->data[($i + 1)][0] = ''; + break; + + default: + $table->data[($i + 1)][0] = ''.html_print_input_hidden('label_'.$idLayoutData, $layoutData['label'], true).''.__('Edit label').''.''; + break; + } + + + // Image + switch ($layoutData['type']) { + case STATIC_GRAPH: + case ICON: + case GROUP_ITEM: + case SERVICE: + $table->data[($i + 1)][1] = html_print_select( + $images_list, + 'image_'.$idLayoutData, + $layoutData['image'], + '', + 'None', + '', + true, + false, + true, + '', + false, + 'width: 120px' + ); + break; + + default: + $table->data[($i + 1)][1] = ''; + break; + } + + + + // Width and height + switch ($layoutData['type']) { + case LINE_ITEM: + // hasn't the width and height. + $table->data[($i + 1)][2] = ''; + break; + + case COLOR_CLOUD: + $table->data[($i + 1)][2] = html_print_input_text('width_'.$idLayoutData, $layoutData['width'], '', 2, 5, true).' x '.html_print_input_text('height_'.$idLayoutData, $layoutData['width'], '', 2, 5, true); + break; + + default: + $table->data[($i + 1)][2] = html_print_input_text('width_'.$idLayoutData, $layoutData['width'], '', 2, 5, true).' x '.html_print_input_text('height_'.$idLayoutData, $layoutData['height'], '', 2, 5, true); + break; + } + + // Position + switch ($layoutData['type']) { + case LINE_ITEM: + // hasn't the width and height. + $table->data[($i + 1)][3] = ''; + break; + + default: + $table->data[($i + 1)][3] = '( '.html_print_input_text('left_'.$idLayoutData, $layoutData['pos_x'], '', 2, 5, true).' , '.html_print_input_text('top_'.$idLayoutData, $layoutData['pos_y'], '', 2, 5, true).' )'; + break; + } + + + // Parent + switch ($layoutData['type']) { + case BOX_ITEM: + case LINE_ITEM: + case COLOR_CLOUD: + $table->data[($i + 1)][4] = ''; + break; + + default: + $parents = visual_map_get_items_parents($idVisualConsole); + $table->data[($i + 1)][4] = html_print_select( + $parents, + 'parent_'.$idLayoutData, + $layoutData['parent_item'], + '', + __('None'), + 0, + true + ); + } + + // Delete row button + if (!defined('METACONSOLE')) { + $url_delete = 'index.php?'.'sec=network&'.'sec2=godmode/reporting/visual_console_builder&'.'tab='.$activeTab.'&'.'action=delete&'.'id_visual_console='.$visualConsole['id'].'&'.'id_element='.$idLayoutData; + } else { + $url_delete = 'index.php?'.'operation=edit_visualmap&'.'sec=screen&'.'sec2=screens/screens&'.'action=visualmap&'.'pure='.(int) get_parameter('pure', 0).'&'.'tab=list_elements&'.'action2=delete&'.'id_visual_console='.$visualConsole['id'].'&'.'id_element='.$idLayoutData; + } + + $table->data[($i + 1)][5] = ''; + $table->data[($i + 1)][5] .= html_print_checkbox('multiple_delete_items', $idLayoutData, false, true); + $table->data[($i + 1)][5] .= ''.html_print_image('images/cross.png', true).''; + + // Second row + $table->data[($i + 2)]['icon'] = ''; + + + // Agent + switch ($layoutData['type']) { + case GROUP_ITEM: + $own_info = get_user_info($config['id_user']); + if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'PM')) { + $return_all_group = false; + } else { + $return_all_group = true; + } + + $table->data[($i + 2)][0] = html_print_select_groups( + false, + 'AR', + $return_all_group, + 'group_'.$idLayoutData, + $layoutData['id_group'], + '', + '', + 0, + true + ); + break; + + case BOX_ITEM: + case ICON: + case LABEL: + case LINE_ITEM: + $table->data[($i + 2)][0] = ''; + break; + + default: + $cell_content_enterprise = false; + if (enterprise_installed()) { + $cell_content_enterprise = enterprise_visual_map_print_list_element('agent', $layoutData); + } + + if ($cell_content_enterprise === false) { + $params = []; + $params['return'] = true; + $params['show_helptip'] = true; + $params['size'] = 20; + $params['input_name'] = 'agent_'.$idLayoutData; + $params['javascript_is_function_select'] = true; + $params['selectbox_id'] = 'module_'.$idLayoutData; + if (defined('METACONSOLE')) { + $params['javascript_ajax_page'] = '../../ajax.php'; + $params['disabled_javascript_on_blur_function'] = true; + + $params['print_input_id_server'] = true; + $params['input_id_server_id'] = $params['input_id_server_name'] = 'id_server_id_'.$idLayoutData; + $params['input_id_server_value'] = $layoutData['id_metaconsole']; + $params['metaconsole_enabled'] = true; + $params['print_hidden_input_idagent'] = true; + $params['hidden_input_idagent_name'] = 'id_agent_'.$idLayoutData; + $params['hidden_input_idagent_value'] = $layoutData['id_agent']; + + $params['value'] = agents_meta_get_alias( + $layoutData['id_agent'], + 'none', + $layoutData['id_metaconsole'], + true + ); + } else { + $params['print_hidden_input_idagent'] = true; + $params['hidden_input_idagent_name'] = 'id_agent_'.$idLayoutData; + $params['hidden_input_idagent_value'] = $layoutData['id_agent']; + $params['value'] = db_get_value('alias', 'tagente', 'id_agente', $layoutData['id_agent']); + } + + if ($layoutData['id_agent'] == 0 and $layoutData['id_custom_graph'] != 0) { + $table->data[($i + 2)][0] = __('Custom graph'); + } else { + $table->data[($i + 2)][0] = ui_print_agent_autocomplete_input($params); + } + } else { + $table->data[($i + 2)][0] = $cell_content_enterprise; + } + break; + } + + + // Module + switch ($layoutData['type']) { + case ICON: + case LABEL: + case BOX_ITEM: + case LINE_ITEM: + case GROUP_ITEM: + $table->data[($i + 2)][1] = ''; + break; + + default: + if ($layoutData['id_layout_linked'] != 0) { + // It is a item that links with other visualmap + break; + } + + $cell_content_enterprise = false; + if (enterprise_installed()) { + $cell_content_enterprise = enterprise_visual_map_print_list_element('module', $layoutData); + } + + if ($cell_content_enterprise === false) { + if (!defined('METACONSOLE')) { + $modules = agents_get_modules($layoutData['id_agent']); + } else { + if ($layoutData['id_agent'] != 0) { + $server = db_get_row('tmetaconsole_setup', 'id', $layoutData['id_metaconsole']); + if (metaconsole_connect($server) == NOERR) { + $modules = agents_get_modules($layoutData['id_agent']); + metaconsole_restore_db(); + } + } + } + + $modules = io_safe_output($modules); + + if ($layoutData['id_agent'] == 0 and $layoutData['id_custom_graph'] != 0) { + if (is_metaconsole()) { + $graphs = []; + $graphs = metaconsole_get_custom_graphs(true); + $table->data[($i + 2)][1] = html_print_select( + $graphs, + 'custom_graph_'.$idLayoutData, + $layoutData['id_custom_graph'].'|'.$layoutData['id_metaconsole'], + '', + __('None'), + 0, + true + ); + } else { + $table->data[($i + 2)][1] = html_print_select_from_sql( + 'SELECT id_graph, name FROM tgraph', + 'custom_graph_'.$idLayoutData, + $layoutData['id_custom_graph'], + '', + __('None'), + 0, + true + ); + } + } else { + $table->data[($i + 2)][1] = html_print_select( + $modules, + 'module_'.$idLayoutData, + $layoutData['id_agente_modulo'], + '', + '---', + 0, + true, + false, + true, + '', + false, + 'width: 120px' + ); + } + } else { + $table->data[($i + 2)][1] = $cell_content_enterprise; + } + break; + } + + // Empty + $table->data[($i + 2)][2] = ''; + + // Period + switch ($layoutData['type']) { + case MODULE_GRAPH: + case SIMPLE_VALUE_MAX: + case SIMPLE_VALUE_MIN: + case SIMPLE_VALUE_AVG: + $table->data[($i + 2)][3] = html_print_extended_select_for_time( + 'period_'.$idLayoutData, + $layoutData['period'], + '', + '--', + '0', + 10, + true + ); + break; + + default: + $table->data[($i + 2)][3] = ''; + break; + } + + // Map linked + switch ($layoutData['type']) { + case LINE_ITEM: + case BOX_ITEM: + case AUTO_SLA_GRAPH: + case COLOR_CLOUD: + $table->data[($i + 2)][4] = ''; + break; + + default: + $table->data[($i + 2)][4] = html_print_select_from_sql( + 'SELECT id, name FROM tlayout - WHERE id != ' . $idVisualConsole, - 'map_linked_' . $idLayoutData, - $layoutData['id_layout_linked'], '', 'None', '', true, - false, true, '', false, "width: 120px"); - break; - } - - $table->data[$i + 2][5] = ''; - - if ($alternativeStyle) { - $table->rowclass[$i + 1] = 'rowOdd'; - $table->rowclass[$i + 2] = 'rowOdd'; - } - else { - $table->rowclass[$i + 1] = 'rowPair'; - $table->rowclass[$i + 2] = 'rowPair'; - } - $alternativeStyle = !$alternativeStyle; - - $i = $i + 3; + WHERE id != '.$idVisualConsole, + 'map_linked_'.$idLayoutData, + $layoutData['id_layout_linked'], + '', + 'None', + '', + true, + false, + true, + '', + false, + 'width: 120px' + ); + break; + } + + $table->data[($i + 2)][5] = ''; + + if ($alternativeStyle) { + $table->rowclass[($i + 1)] = 'rowOdd'; + $table->rowclass[($i + 2)] = 'rowOdd'; + } else { + $table->rowclass[($i + 1)] = 'rowPair'; + $table->rowclass[($i + 2)] = 'rowPair'; + } + + $alternativeStyle = !$alternativeStyle; + + $i = ($i + 3); } $pure = get_parameter('pure', 0); if (!defined('METACONSOLE')) { - echo '
    '; + echo ''; +} else { + echo ""; } -else { - echo ""; -} -if (!defined('METACONSOLE')) - echo '
    '; + if (!defined('METACONSOLE')) { - html_print_input_hidden ('action', 'update'); + echo '
    '; } -else { - html_print_input_hidden ('action2', 'update'); + +if (!defined('METACONSOLE')) { + html_print_input_hidden('action', 'update'); +} else { + html_print_input_hidden('action2', 'update'); } html_print_table($table); -echo '
    '; -html_print_submit_button (__('Update'), 'go', false, 'class="sub next"'); -echo " "; +echo '
    '; +html_print_submit_button(__('Update'), 'go', false, 'class="sub next"'); +echo ' '; html_print_button(__('Delete'), 'delete', false, 'submit_delete_multiple_items();', 'class="sub delete"'); echo '
    '; echo ''; // Form for multiple delete if (!defined('METACONSOLE')) { - $url_multiple_delete = "index.php?" . - "sec=network&" . - "sec2=godmode/reporting/visual_console_builder&" . - "tab=" . $activeTab . "&" . - "id_visual_console=" . $visualConsole["id"]; - - echo '
    '; -} -else { - $url_multiple_delete = "index.php?" . - "operation=edit_visualmap&" . - "sec=screen&" . - "sec2=screens/screens&" . - "action=visualmap&" . - "pure=0&" . - "tab=list_elements&" . - "id_visual_console=" . $idVisualConsole; - - echo ""; + $url_multiple_delete = 'index.php?'.'sec=network&'.'sec2=godmode/reporting/visual_console_builder&'.'tab='.$activeTab.'&'.'id_visual_console='.$visualConsole['id']; + + echo ''; +} else { + $url_multiple_delete = 'index.php?'.'operation=edit_visualmap&'.'sec=screen&'.'sec2=screens/screens&'.'action=visualmap&'.'pure=0&'.'tab=list_elements&'.'id_visual_console='.$idVisualConsole; + + echo "'; -//Trick for it have a traduct text for javascript. -echo ''; +// Trick for it have a traduct text for javascript. +echo ''; ?>
    - - + +
    diff --git a/pandora_console/godmode/reporting/visual_console_builder.php b/pandora_console/godmode/reporting/visual_console_builder.php index b7d1030dad..2e54ceb698 100755 --- a/pandora_console/godmode/reporting/visual_console_builder.php +++ b/pandora_console/godmode/reporting/visual_console_builder.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,720 +10,834 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Login check global $config; global $statusProcessInDB; -check_login (); +check_login(); -require_once ($config['homedir'] . '/include/functions_visual_map.php'); -require_once($config['homedir'] . "/include/functions_agents.php"); +require_once $config['homedir'].'/include/functions_visual_map.php'; +require_once $config['homedir'].'/include/functions_agents.php'; enterprise_include_once('include/functions_visual_map.php'); // Retrieve the visual console id -set_unless_defined ($idVisualConsole, 0); // Set default +set_unless_defined($idVisualConsole, 0); +// Set default $idVisualConsole = get_parameter('id_visual_console', $idVisualConsole); if (!defined('METACONSOLE')) { - $action_name_parameter = 'action'; -} -else { - $action_name_parameter = 'action2'; + $action_name_parameter = 'action'; +} else { + $action_name_parameter = 'action2'; } -$action = get_parameterBetweenListValues($action_name_parameter, - array('new', 'save', 'edit', 'update', 'delete', 'multiple_delete'), - 'new'); +$action = get_parameterBetweenListValues( + $action_name_parameter, + [ + 'new', + 'save', + 'edit', + 'update', + 'delete', + 'multiple_delete', + ], + 'new' +); -$activeTab = get_parameterBetweenListValues('tab', - array('data', 'list_elements', 'wizard', 'wizard_services', 'editor'), - 'data'); +$activeTab = get_parameterBetweenListValues( + 'tab', + [ + 'data', + 'list_elements', + 'wizard', + 'wizard_services', + 'editor', + ], + 'data' +); // Visual console creation tab and actions if (empty($idVisualConsole)) { - $visualConsole = null; - - // General ACL - //$vconsole_read = check_acl ($config['id_user'], 0, "VR"); - $vconsole_write = check_acl ($config['id_user'], 0, "VW"); - $vconsole_manage = check_acl ($config['id_user'], 0, "VM"); + $visualConsole = null; + + // General ACL + // $vconsole_read = check_acl ($config['id_user'], 0, "VR"); + $vconsole_write = check_acl($config['id_user'], 0, 'VW'); + $vconsole_manage = check_acl($config['id_user'], 0, 'VM'); } // The visual console exists else if ($activeTab != 'data' || ($activeTab == 'data' && $action != 'new')) { - - // Load the visual console data - $visualConsole = db_get_row_filter('tlayout', array('id' => $idVisualConsole)); - - // The visual console should exist. - if (empty($visualConsole)) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - return; - } - - // The default group id is 0 - set_unless_defined ($visualConsole['id_group'], 0); - - // ACL for the existing visual console - //$vconsole_read = check_acl ($config['id_user'], $visualConsole['id_group'], "VR"); - $vconsole_write = check_acl ($config['id_user'], $visualConsole['id_group'], "VW"); - $vconsole_manage = check_acl ($config['id_user'], $visualConsole['id_group'], "VM"); -} -else { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - return; + // Load the visual console data + $visualConsole = db_get_row_filter('tlayout', ['id' => $idVisualConsole]); + + // The visual console should exist. + if (empty($visualConsole)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + return; + } + + // The default group id is 0 + set_unless_defined($visualConsole['id_group'], 0); + + // ACL for the existing visual console + // $vconsole_read = check_acl ($config['id_user'], $visualConsole['id_group'], "VR"); + $vconsole_write = check_acl($config['id_user'], $visualConsole['id_group'], 'VW'); + $vconsole_manage = check_acl($config['id_user'], $visualConsole['id_group'], 'VM'); +} else { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + return; } // This section is only to manage the visual console if (!$vconsole_write && !$vconsole_manage) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } -$pure = (int) get_parameter ('pure', 0); -$refr = (int) get_parameter ('refr', $config['vc_refr']); +$pure = (int) get_parameter('pure', 0); +$refr = (int) get_parameter('refr', $config['vc_refr']); $id_layout = 0; -//Save/Update data in DB +// Save/Update data in DB global $statusProcessInDB; -if (empty($statusProcessInDB)) - $statusProcessInDB = null; -switch ($activeTab) { - case 'data': - switch ($action) { - case 'new': - $idGroup = ''; - $background = ''; - $background_color = ''; - $width = ''; - $height = ''; - $visualConsoleName = ''; - $is_favourite = 0; - break; - - case 'update': - case 'save': - $idGroup = (int) get_parameter('id_group'); - $background = (string) get_parameter('background'); - $background_color = (string) get_parameter('background_color'); - $width = (int) get_parameter('width'); - $height = (int) get_parameter('height'); - $visualConsoleName = (string) get_parameter('name'); - $is_favourite = (int) get_parameter('is_favourite_sent'); - - // ACL for the new visual console - //$vconsole_read_new = check_acl ($config['id_user'], $idGroup, "VR"); - $vconsole_write_new = check_acl ($config['id_user'], $idGroup, "VW"); - $vconsole_manage_new = check_acl ($config['id_user'], $idGroup, "VM"); - - // The user should have permissions on the new group - if (!$vconsole_write_new && !$vconsole_manage_new) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; - } - - $values = array( - 'name' => $visualConsoleName, - 'id_group' => $idGroup, - 'background' => $background, - 'background_color' => $background_color, - 'width' => $width, - 'height' => $height, - 'is_favourite' => $is_favourite - ); - - $error = $_FILES['background_image']['error']; - $upload_file = true; - $uploadOK = true; - switch ($error) { - case UPLOAD_ERR_OK: - $tmpName = $_FILES['background_image']['tmp_name']; - $pathname = $config['homedir'] . '/images/console/background/'; - $nameImage = str_replace(' ','_',$_FILES["background_image"]["name"]); - $target_file = $pathname . basename($nameImage); - $imageFileType = strtolower( pathinfo($target_file,PATHINFO_EXTENSION)); - - $check = getimagesize($_FILES["background_image"]["tmp_name"]); - if($check !== false) { - $uploadOK = 1; - } else { - $uploadOK = false; - $error_message = __("This file isn't image"); - $statusProcessInDB = array('flag' => false, 'message' => ui_print_error_message(__("This file isn't image."), '', true)); - } - if (file_exists($target_file)) { - $uploadOK = false; - $error_message = __("File already are exists."); - $statusProcessInDB = array('flag' => false, 'message' => ui_print_error_message(__('File already are exists.'), '', true)); - } - - if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" - && $imageFileType != "gif" ) { - $uploadOK = false; - $error_message = __("The file have not image extension."); - $statusProcessInDB = array('flag' => false, 'message' => ui_print_error_message(__('The file have not image extension.'), '', true)); - } - - if ($uploadOK == 1) { - if (move_uploaded_file($_FILES["background_image"]["tmp_name"], $target_file)) { - $background = $nameImage; - $values['background'] = $background; - $error2 = chmod($target_file, 0644); - $uploadOK = $error2; - } else { - $uploadOK = false; - $error_message = __("Problems with move file to target."); - $statusProcessInDB = array('flag' => false, 'message' => ui_print_error_message(__('Problems with move file to target.'), '', true)); - - } - } - break; - case UPLOAD_ERR_INI_SIZE: - $uploadOK = false; - $statusProcessInDB = array('flag' => false, 'message' => ui_print_error_message(__('Problems with move file to target.'), '', true)); - case UPLOAD_ERR_PARTIAL: - $uploadOK = false; - $statusProcessInDB = array('flag' => false, 'message' => ui_print_error_message(__('Problems with move file to target.'), '', true)); - break; - case UPLOAD_ERR_NO_FILE: - $upload_file = false; - break; - } - - if ( $upload_file && !$uploadOK){ - db_pandora_audit( "Visual console builder", $error_message); - break; - } - - // If the background is changed the size is reseted - $background_now = $visualConsole['background']; - - $values['width'] = $width; - $values['height'] = $height; - switch ($action) { - case 'update': - $result = false; - if ($values['name'] != "" && $values['background']) - $result = db_process_sql_update('tlayout', $values, array('id' => $idVisualConsole)); - if ($result !== false) { - db_pandora_audit( "Visual console builder", "Update visual console #$idVisualConsole"); - $action = 'edit'; - $statusProcessInDB = array('flag' => true, 'message' => ui_print_success_message(__('Successfully update.'), '', true)); - - // Return the updated visual console - $visualConsole = db_get_row_filter('tlayout', - array('id' => $idVisualConsole)); - // Update the ACL - //$vconsole_read = $vconsole_read_new; - $vconsole_write = $vconsole_write_new; - $vconsole_manage = $vconsole_manage_new; - } - else { - db_pandora_audit( "Visual console builder", "Fail update visual console #$idVisualConsole"); - $statusProcessInDB = array('flag' => false, 'message' => ui_print_error_message(__('Could not be update.'), '', true)); - } - break; - - case 'save': - if ($values['name'] != "" && $values['background']) - $idVisualConsole = db_process_sql_insert('tlayout', $values); - else - $idVisualConsole = false; - - if ($idVisualConsole !== false) { - db_pandora_audit( "Visual console builder", "Create visual console #$idVisualConsole"); - $action = 'edit'; - $statusProcessInDB = array('flag' => true, - 'message' => ui_print_success_message(__('Successfully created.'), '', true)); - - // Return the updated visual console - $visualConsole = db_get_row_filter('tlayout', - array('id' => $idVisualConsole)); - // Update the ACL - //$vconsole_read = $vconsole_read_new; - $vconsole_write = $vconsole_write_new; - $vconsole_manage = $vconsole_manage_new; - } - else { - db_pandora_audit( "Visual console builder", "Fail try to create visual console"); - $statusProcessInDB = array('flag' => false, - 'message' => ui_print_error_message(__('Could not be created.'), '', true)); - } - break; - } - break; - - case 'edit': - $visualConsoleName = $visualConsole['name']; - $idGroup = $visualConsole['id_group']; - $background = $visualConsole['background']; - $background_color = $visualConsole['background_color']; - $width = $visualConsole['width']; - $height = $visualConsole['height']; - $is_favourite = $visualConsole['is_favourite']; - break; - } - break; - - case 'list_elements': - switch ($action) { - case 'multiple_delete': - $delete_items_json = io_safe_output( - get_parameter("id_item_json", - json_encode(array()))); - - $delete_items = json_decode($delete_items_json, true); - - if (!empty($delete_items)) { - $result = (bool)db_process_sql_delete( - 'tlayout_data', - array('id_layout' => $idVisualConsole, - 'id' => $delete_items)); - - } - else { - $result = false; - } - - $statusProcessInDB = array( - 'flag' => true, - 'message' => ui_print_result_message($result, - __('Successfully multiple delete.'), - __('Unsuccessful multiple delete.'), '', true)); - break; - case 'update': - //Update background - - $background = get_parameter('background'); - $background_color = get_parameter('background_color'); - $width = get_parameter('width'); - $height = get_parameter('height'); - - if ($width == 0 && $height == 0) { - $sizeBackground = getimagesize( - $config['homedir'] . '/images/console/background/' . $background); - $width = $sizeBackground[0]; - $height = $sizeBackground[1]; - } - - db_process_sql_update('tlayout', - array('background' => $background, - 'background_color' => $background_color, - 'width' => $width, - 'height' => $height), - array('id' => $idVisualConsole)); - - // Return the updated visual console - $visualConsole = db_get_row_filter('tlayout', - array('id' => $idVisualConsole)); - - //Update elements in visual map - $idsElements = db_get_all_rows_filter('tlayout_data', - array('id_layout' => $idVisualConsole), array('id')); - - if ($idsElements === false) { - $idsElements = array(); - } - - foreach ($idsElements as $idElement) { - $id = $idElement['id']; - $values = array(); - $values['label'] = get_parameter('label_' . $id, ''); - $values['image'] = get_parameter('image_' . $id, ''); - $values['width'] = get_parameter('width_' . $id, 0); - $values['height'] = get_parameter('height_' . $id, 0); - $values['pos_x'] = get_parameter('left_' . $id, 0); - $values['pos_y'] = get_parameter('top_' . $id, 0); - $type = db_get_value('type', 'tlayout_data', 'id', $id); - switch ($type) { - case MODULE_GRAPH: - case SIMPLE_VALUE_MAX: - case SIMPLE_VALUE_MIN: - case SIMPLE_VALUE_AVG: - $values['period'] = get_parameter('period_' . $id, 0); - break; - case GROUP_ITEM: - $values['id_group'] = get_parameter('group_' . $id, 0); - $values['show_statistics'] = get_parameter('show_statistics', 0); - break; - } - $agentName = get_parameter('agent_' . $id, ''); - if (defined('METACONSOLE')) { - $values['id_metaconsole'] = (int) get_parameter('id_server_id_' . $id, ''); - $values['id_agent'] = (int) get_parameter('id_agent_' . $id, 0); - } - else { - $agent_id = (int) get_parameter('id_agent_' . $id, 0); - $values['id_agent'] = $agent_id; - } - $values['id_agente_modulo'] = get_parameter('module_' . $id, 0); - $values['id_custom_graph'] = get_parameter('custom_graph_' . $id, 0); - $values['parent_item'] = get_parameter('parent_' . $id, 0); - $values['id_layout_linked'] = get_parameter('map_linked_' . $id, 0); - - if (enterprise_installed()) { - enterprise_visual_map_update_action_from_list_elements($type, $values, $id); - } - - db_process_sql_update('tlayout_data', $values, array('id' => $id)); - } - break; - case 'delete': - $id_element = get_parameter('id_element'); - $result = db_process_sql_delete('tlayout_data', array('id' => $id_element)); - if ($result !== false) { - $statusProcessInDB = array('flag' => true, 'message' => ui_print_success_message(__('Successfully delete.'), '', true)); - } - break; - } - $visualConsoleName = $visualConsole['name']; - $action = 'edit'; - break; - case 'wizard': - $visualConsoleName = $visualConsole['name']; - $background = $visualConsole['background']; - - $fonts = get_parameter ('fonts'); - $fontf = get_parameter ('fontf'); - - - switch ($action) { - case 'update': - $id_agents = get_parameter ('id_agents', array ()); - $name_modules = get_parameter ('module', array ()); - - $type = (int)get_parameter('type', STATIC_GRAPH); - $image = get_parameter ('image'); - $range = (int) get_parameter ("range", 50); - $width = (int) get_parameter ("width", 0); - $height = (int) get_parameter ("height", 0); - $period = (int) get_parameter ("period", 0); - $show_statistics = get_parameter ("show_statistics", 0); - $process_value = (int) get_parameter ("process_value", 0); - $percentileitem_width = (int) get_parameter ("percentileitem_width", 0); - $max_value = (int) get_parameter ("max_value", 0); - $type_percentile = get_parameter ("type_percentile", 'percentile'); - $value_show = get_parameter ("value_show", 'percent'); - $label_type = get_parameter ("label_type", 'agent_module'); - $enable_link = get_parameter ("enable_link", 'enable_link'); - $show_on_top = get_parameter ("show_on_top", 0); - - // This var switch between creation of items, item_per_agent = 0 => item per module; item_per_agent <> 0 => item per agent - $item_per_agent = get_parameter ("item_per_agent", 0); - $id_server = (int)get_parameter('servers', 0); - - $kind_relationship = (int)get_parameter('kind_relationship', - VISUAL_MAP_WIZARD_PARENTS_NONE); - $item_in_the_map = (int)get_parameter('item_in_the_map', 0); - - $message = ''; - - if (($width == 0) && ($height == 0) && ($type == MODULE_GRAPH)) { - $width = 400; - $height = 180; - } - - // One item per agent - if ($item_per_agent == 1) { - $id_agents_result = array(); - foreach ($id_agents as $id_agent_key => $id_agent_id) { - if (defined("METACONSOLE")) { - $row = db_get_row_filter( - 'tmetaconsole_agent', - array('id_tagente' => $id_agent_id)); - $id_server = $row['id_tmetaconsole_setup']; - $id_agent_id = $row['id_tagente']; - - $id_agents_result[] = array( - 'id_agent' => $id_agent_id, - 'id_server' => $id_server); - } - else { - $id_agents_result[] = $id_agent_id; - } - } - - $message .= visual_map_process_wizard_add_agents( - $id_agents_result, - $image, - $idVisualConsole, - $range, - $width, - $height, - $period, - $process_value, - $percentileitem_width, - $max_value, - $type_percentile, - $value_show, - $label_type, - $type, - $enable_link, - $id_server, - $kind_relationship, - $item_in_the_map,$fontf,$fonts); - - $statusProcessInDB = array('flag' => true, - 'message' => $message); - - } - else { - - - // One item per module - if (empty($name_modules)) { - $statusProcessInDB = array('flag' => true, - 'message' => ui_print_error_message ( - __('No modules selected'), '', true)); - } - else { - - - if (defined("METACONSOLE")) { - $agents_ids = array(); - foreach ($id_agents as $id_agent_id) { - $server_and_agent = explode("|",$id_agent_id); - - $agents_ids[] = $server_and_agent[1]; - } - $rows = db_get_all_rows_filter( - 'tmetaconsole_agent', - array('id_tagente' => $agents_ids)); - - $agents = array(); - foreach ($rows as $row) { - $agents[$row['id_tmetaconsole_setup']][] = - $row['id_tagente']; - } - } - else { - $agents[0] = $id_agents; - } - } - - - - foreach ($agents as $id_server => $id_agents) { - - - - //Any module - if ($name_modules[0] == '0') { - - $message .= visual_map_process_wizard_add_agents( - $id_agents, - $image, - $idVisualConsole, - $range, - $width, - $height, - $period, - $process_value, - $percentileitem_width, - $max_value, - $type_percentile, - $value_show, - 'agent', - $type, - $enable_link, - $id_server, - $kind_relationship, - $item_in_the_map,$fontf,$fonts); - - - } - else { - $id_modules = array(); - - if ($id_server != 0) { - foreach ($name_modules as $serial_data) { - $modules_serial = explode(';', $serial_data); - - foreach ($modules_serial as $data_serialized) { - $data = explode('|', $data_serialized); - $id_modules[] = $data[0]; - } - } - } - else { - foreach ($name_modules as $mod) { - - foreach ($id_agents as $ag) { - $id_module = agents_get_modules($ag, - array('id_agente_modulo'), - array('nombre' => $mod)); - - - - if (empty($id_module)) - continue; - else { - $id_module = reset($id_module); - $id_module = $id_module['id_agente_modulo']; - } - - $id_modules[] = $id_module; - } - } - } - - $message .= visual_map_process_wizard_add_modules( - $id_modules, - $image, - $idVisualConsole, - $range, - $width, - $height, - $period, - $process_value, - $percentileitem_width, - $max_value, - $type_percentile, - $value_show, - $label_type, - $type, - $enable_link, - $id_server, - $kind_relationship, - $item_in_the_map,$fontf,$fonts); - } - - - } - - $statusProcessInDB = array( - 'flag' => true, 'message' => $message); - } - $action = 'edit'; - break; - } - break; - case 'wizard_services': - $visualConsoleName = $visualConsole['name']; - switch ($action) { - case 'update': - enterprise_include_once("/include/functions_visual_map.php"); - - $icon = (string) get_parameter('icon'); - $id_services = (array) get_parameter('services_selected'); - - $result = enterprise_hook('enterprise_visual_map_process_services_wizard_add', array($id_services, $idVisualConsole, $icon)); - if ($result != ENTERPRISE_NOT_HOOK) { - $statusProcessInDB = array('flag' => $result['status'], 'message' => $result['message']); - } - - $action = 'edit'; - break; - } - break; - case 'editor': - switch ($action) { - case 'new': - case 'update': - case 'edit': - $visualConsoleName = $visualConsole['name']; - $action = 'edit'; - break; - } - break; +if (empty($statusProcessInDB)) { + $statusProcessInDB = null; } -if (isset($config['vc_refr']) and $config['vc_refr'] != 0) - $view_refresh = $config['vc_refr']; -else - $view_refresh = '300'; +switch ($activeTab) { + case 'data': + switch ($action) { + case 'new': + $idGroup = ''; + $background = ''; + $background_color = ''; + $width = ''; + $height = ''; + $visualConsoleName = ''; + $is_favourite = 0; + break; + + case 'update': + case 'save': + $idGroup = (int) get_parameter('id_group'); + $background = (string) get_parameter('background'); + $background_color = (string) get_parameter('background_color'); + $width = (int) get_parameter('width'); + $height = (int) get_parameter('height'); + $visualConsoleName = (string) get_parameter('name'); + $is_favourite = (int) get_parameter('is_favourite_sent'); + + // ACL for the new visual console + // $vconsole_read_new = check_acl ($config['id_user'], $idGroup, "VR"); + $vconsole_write_new = check_acl($config['id_user'], $idGroup, 'VW'); + $vconsole_manage_new = check_acl($config['id_user'], $idGroup, 'VM'); + + // The user should have permissions on the new group + if (!$vconsole_write_new && !$vconsole_manage_new) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; + } + + $values = [ + 'name' => $visualConsoleName, + 'id_group' => $idGroup, + 'background' => $background, + 'background_color' => $background_color, + 'width' => $width, + 'height' => $height, + 'is_favourite' => $is_favourite, + ]; + + $error = $_FILES['background_image']['error']; + $upload_file = true; + $uploadOK = true; + switch ($error) { + case UPLOAD_ERR_OK: + $tmpName = $_FILES['background_image']['tmp_name']; + $pathname = $config['homedir'].'/images/console/background/'; + $nameImage = str_replace(' ', '_', $_FILES['background_image']['name']); + $target_file = $pathname.basename($nameImage); + $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); + + $check = getimagesize($_FILES['background_image']['tmp_name']); + if ($check !== false) { + $uploadOK = 1; + } else { + $uploadOK = false; + $error_message = __("This file isn't image"); + $statusProcessInDB = [ + 'flag' => false, + 'message' => ui_print_error_message(__("This file isn't image."), '', true), + ]; + } + + if (file_exists($target_file)) { + $uploadOK = false; + $error_message = __('File already are exists.'); + $statusProcessInDB = [ + 'flag' => false, + 'message' => ui_print_error_message(__('File already are exists.'), '', true), + ]; + } + + if ($imageFileType != 'jpg' && $imageFileType != 'png' && $imageFileType != 'jpeg' + && $imageFileType != 'gif' + ) { + $uploadOK = false; + $error_message = __('The file have not image extension.'); + $statusProcessInDB = [ + 'flag' => false, + 'message' => ui_print_error_message(__('The file have not image extension.'), '', true), + ]; + } + + if ($uploadOK == 1) { + if (move_uploaded_file($_FILES['background_image']['tmp_name'], $target_file)) { + $background = $nameImage; + $values['background'] = $background; + $error2 = chmod($target_file, 0644); + $uploadOK = $error2; + } else { + $uploadOK = false; + $error_message = __('Problems with move file to target.'); + $statusProcessInDB = [ + 'flag' => false, + 'message' => ui_print_error_message(__('Problems with move file to target.'), '', true), + ]; + } + } + break; + + case UPLOAD_ERR_INI_SIZE: + $uploadOK = false; + $statusProcessInDB = [ + 'flag' => false, + 'message' => ui_print_error_message(__('Problems with move file to target.'), '', true), + ]; + case UPLOAD_ERR_PARTIAL: + $uploadOK = false; + $statusProcessInDB = [ + 'flag' => false, + 'message' => ui_print_error_message(__('Problems with move file to target.'), '', true), + ]; + break; + + case UPLOAD_ERR_NO_FILE: + $upload_file = false; + break; + } + + if ($upload_file && !$uploadOK) { + db_pandora_audit('Visual console builder', $error_message); + break; + } + + // If the background is changed the size is reseted + $background_now = $visualConsole['background']; + + $values['width'] = $width; + $values['height'] = $height; + switch ($action) { + case 'update': + $result = false; + if ($values['name'] != '' && $values['background']) { + $result = db_process_sql_update('tlayout', $values, ['id' => $idVisualConsole]); + } + + if ($result !== false) { + db_pandora_audit('Visual console builder', "Update visual console #$idVisualConsole"); + $action = 'edit'; + $statusProcessInDB = [ + 'flag' => true, + 'message' => ui_print_success_message(__('Successfully update.'), '', true), + ]; + + // Return the updated visual console + $visualConsole = db_get_row_filter( + 'tlayout', + ['id' => $idVisualConsole] + ); + // Update the ACL + // $vconsole_read = $vconsole_read_new; + $vconsole_write = $vconsole_write_new; + $vconsole_manage = $vconsole_manage_new; + } else { + db_pandora_audit('Visual console builder', "Fail update visual console #$idVisualConsole"); + $statusProcessInDB = [ + 'flag' => false, + 'message' => ui_print_error_message(__('Could not be update.'), '', true), + ]; + } + break; + + case 'save': + if ($values['name'] != '' && $values['background']) { + $idVisualConsole = db_process_sql_insert('tlayout', $values); + } else { + $idVisualConsole = false; + } + + if ($idVisualConsole !== false) { + db_pandora_audit('Visual console builder', "Create visual console #$idVisualConsole"); + $action = 'edit'; + $statusProcessInDB = [ + 'flag' => true, + 'message' => ui_print_success_message(__('Successfully created.'), '', true), + ]; + + // Return the updated visual console + $visualConsole = db_get_row_filter( + 'tlayout', + ['id' => $idVisualConsole] + ); + // Update the ACL + // $vconsole_read = $vconsole_read_new; + $vconsole_write = $vconsole_write_new; + $vconsole_manage = $vconsole_manage_new; + } else { + db_pandora_audit('Visual console builder', 'Fail try to create visual console'); + $statusProcessInDB = [ + 'flag' => false, + 'message' => ui_print_error_message(__('Could not be created.'), '', true), + ]; + } + break; + } + break; + + case 'edit': + $visualConsoleName = $visualConsole['name']; + $idGroup = $visualConsole['id_group']; + $background = $visualConsole['background']; + $background_color = $visualConsole['background_color']; + $width = $visualConsole['width']; + $height = $visualConsole['height']; + $is_favourite = $visualConsole['is_favourite']; + break; + } + break; + + case 'list_elements': + switch ($action) { + case 'multiple_delete': + $delete_items_json = io_safe_output( + get_parameter( + 'id_item_json', + json_encode([]) + ) + ); + + $delete_items = json_decode($delete_items_json, true); + + if (!empty($delete_items)) { + $result = (bool) db_process_sql_delete( + 'tlayout_data', + [ + 'id_layout' => $idVisualConsole, + 'id' => $delete_items, + ] + ); + } else { + $result = false; + } + + $statusProcessInDB = [ + 'flag' => true, + 'message' => ui_print_result_message( + $result, + __('Successfully multiple delete.'), + __('Unsuccessful multiple delete.'), + '', + true + ), + ]; + break; + + case 'update': + // Update background + $background = get_parameter('background'); + $background_color = get_parameter('background_color'); + $width = get_parameter('width'); + $height = get_parameter('height'); + + if ($width == 0 && $height == 0) { + $sizeBackground = getimagesize( + $config['homedir'].'/images/console/background/'.$background + ); + $width = $sizeBackground[0]; + $height = $sizeBackground[1]; + } + + db_process_sql_update( + 'tlayout', + [ + 'background' => $background, + 'background_color' => $background_color, + 'width' => $width, + 'height' => $height, + ], + ['id' => $idVisualConsole] + ); + + // Return the updated visual console + $visualConsole = db_get_row_filter( + 'tlayout', + ['id' => $idVisualConsole] + ); + + // Update elements in visual map + $idsElements = db_get_all_rows_filter( + 'tlayout_data', + ['id_layout' => $idVisualConsole], + ['id'] + ); + + if ($idsElements === false) { + $idsElements = []; + } + + foreach ($idsElements as $idElement) { + $id = $idElement['id']; + $values = []; + $values['label'] = get_parameter('label_'.$id, ''); + $values['image'] = get_parameter('image_'.$id, ''); + $values['width'] = get_parameter('width_'.$id, 0); + $values['height'] = get_parameter('height_'.$id, 0); + $values['pos_x'] = get_parameter('left_'.$id, 0); + $values['pos_y'] = get_parameter('top_'.$id, 0); + $type = db_get_value('type', 'tlayout_data', 'id', $id); + switch ($type) { + case MODULE_GRAPH: + case SIMPLE_VALUE_MAX: + case SIMPLE_VALUE_MIN: + case SIMPLE_VALUE_AVG: + $values['period'] = get_parameter('period_'.$id, 0); + break; + + case GROUP_ITEM: + $values['id_group'] = get_parameter('group_'.$id, 0); + $values['show_statistics'] = get_parameter('show_statistics', 0); + break; + } + + $agentName = get_parameter('agent_'.$id, ''); + if (defined('METACONSOLE')) { + $values['id_metaconsole'] = (int) get_parameter('id_server_id_'.$id, ''); + $values['id_agent'] = (int) get_parameter('id_agent_'.$id, 0); + } else { + $agent_id = (int) get_parameter('id_agent_'.$id, 0); + $values['id_agent'] = $agent_id; + } + + $values['id_agente_modulo'] = get_parameter('module_'.$id, 0); + $values['id_custom_graph'] = get_parameter('custom_graph_'.$id, 0); + $values['parent_item'] = get_parameter('parent_'.$id, 0); + $values['id_layout_linked'] = get_parameter('map_linked_'.$id, 0); + + if (enterprise_installed()) { + enterprise_visual_map_update_action_from_list_elements($type, $values, $id); + } + + db_process_sql_update('tlayout_data', $values, ['id' => $id]); + } + break; + + case 'delete': + $id_element = get_parameter('id_element'); + $result = db_process_sql_delete('tlayout_data', ['id' => $id_element]); + if ($result !== false) { + $statusProcessInDB = [ + 'flag' => true, + 'message' => ui_print_success_message(__('Successfully delete.'), '', true), + ]; + } + break; + } + + $visualConsoleName = $visualConsole['name']; + $action = 'edit'; + break; + + case 'wizard': + $visualConsoleName = $visualConsole['name']; + $background = $visualConsole['background']; + + $fonts = get_parameter('fonts'); + $fontf = get_parameter('fontf'); + + + switch ($action) { + case 'update': + $id_agents = get_parameter('id_agents', []); + $name_modules = get_parameter('module', []); + + $type = (int) get_parameter('type', STATIC_GRAPH); + $image = get_parameter('image'); + $range = (int) get_parameter('range', 50); + $width = (int) get_parameter('width', 0); + $height = (int) get_parameter('height', 0); + $period = (int) get_parameter('period', 0); + $show_statistics = get_parameter('show_statistics', 0); + $process_value = (int) get_parameter('process_value', 0); + $percentileitem_width = (int) get_parameter('percentileitem_width', 0); + $max_value = (int) get_parameter('max_value', 0); + $type_percentile = get_parameter('type_percentile', 'percentile'); + $value_show = get_parameter('value_show', 'percent'); + $label_type = get_parameter('label_type', 'agent_module'); + $enable_link = get_parameter('enable_link', 'enable_link'); + $show_on_top = get_parameter('show_on_top', 0); + + // This var switch between creation of items, item_per_agent = 0 => item per module; item_per_agent <> 0 => item per agent + $item_per_agent = get_parameter('item_per_agent', 0); + $id_server = (int) get_parameter('servers', 0); + + $kind_relationship = (int) get_parameter( + 'kind_relationship', + VISUAL_MAP_WIZARD_PARENTS_NONE + ); + $item_in_the_map = (int) get_parameter('item_in_the_map', 0); + + $message = ''; + + if (($width == 0) && ($height == 0) && ($type == MODULE_GRAPH)) { + $width = 400; + $height = 180; + } + + // One item per agent + if ($item_per_agent == 1) { + $id_agents_result = []; + foreach ($id_agents as $id_agent_key => $id_agent_id) { + if (defined('METACONSOLE')) { + $row = db_get_row_filter( + 'tmetaconsole_agent', + ['id_tagente' => $id_agent_id] + ); + $id_server = $row['id_tmetaconsole_setup']; + $id_agent_id = $row['id_tagente']; + + $id_agents_result[] = [ + 'id_agent' => $id_agent_id, + 'id_server' => $id_server, + ]; + } else { + $id_agents_result[] = $id_agent_id; + } + } + + $message .= visual_map_process_wizard_add_agents( + $id_agents_result, + $image, + $idVisualConsole, + $range, + $width, + $height, + $period, + $process_value, + $percentileitem_width, + $max_value, + $type_percentile, + $value_show, + $label_type, + $type, + $enable_link, + $id_server, + $kind_relationship, + $item_in_the_map, + $fontf, + $fonts + ); + + $statusProcessInDB = [ + 'flag' => true, + 'message' => $message, + ]; + } else { + // One item per module + if (empty($name_modules)) { + $statusProcessInDB = [ + 'flag' => true, + 'message' => ui_print_error_message( + __('No modules selected'), + '', + true + ), + ]; + } else { + if (defined('METACONSOLE')) { + $agents_ids = []; + foreach ($id_agents as $id_agent_id) { + $server_and_agent = explode('|', $id_agent_id); + + $agents_ids[] = $server_and_agent[1]; + } + + $rows = db_get_all_rows_filter( + 'tmetaconsole_agent', + ['id_tagente' => $agents_ids] + ); + + $agents = []; + foreach ($rows as $row) { + $agents[$row['id_tmetaconsole_setup']][] = $row['id_tagente']; + } + } else { + $agents[0] = $id_agents; + } + } + + + + foreach ($agents as $id_server => $id_agents) { + // Any module + if ($name_modules[0] == '0') { + $message .= visual_map_process_wizard_add_agents( + $id_agents, + $image, + $idVisualConsole, + $range, + $width, + $height, + $period, + $process_value, + $percentileitem_width, + $max_value, + $type_percentile, + $value_show, + 'agent', + $type, + $enable_link, + $id_server, + $kind_relationship, + $item_in_the_map, + $fontf, + $fonts + ); + } else { + $id_modules = []; + + if ($id_server != 0) { + foreach ($name_modules as $serial_data) { + $modules_serial = explode(';', $serial_data); + + foreach ($modules_serial as $data_serialized) { + $data = explode('|', $data_serialized); + $id_modules[] = $data[0]; + } + } + } else { + foreach ($name_modules as $mod) { + foreach ($id_agents as $ag) { + $id_module = agents_get_modules( + $ag, + ['id_agente_modulo'], + ['nombre' => $mod] + ); + + + + if (empty($id_module)) { + continue; + } else { + $id_module = reset($id_module); + $id_module = $id_module['id_agente_modulo']; + } + + $id_modules[] = $id_module; + } + } + } + + $message .= visual_map_process_wizard_add_modules( + $id_modules, + $image, + $idVisualConsole, + $range, + $width, + $height, + $period, + $process_value, + $percentileitem_width, + $max_value, + $type_percentile, + $value_show, + $label_type, + $type, + $enable_link, + $id_server, + $kind_relationship, + $item_in_the_map, + $fontf, + $fonts + ); + } + } + + $statusProcessInDB = [ + 'flag' => true, + 'message' => $message, + ]; + } + + $action = 'edit'; + break; + } + break; + + case 'wizard_services': + $visualConsoleName = $visualConsole['name']; + switch ($action) { + case 'update': + enterprise_include_once('/include/functions_visual_map.php'); + + $icon = (string) get_parameter('icon'); + $id_services = (array) get_parameter('services_selected'); + + $result = enterprise_hook('enterprise_visual_map_process_services_wizard_add', [$id_services, $idVisualConsole, $icon]); + if ($result != ENTERPRISE_NOT_HOOK) { + $statusProcessInDB = [ + 'flag' => $result['status'], + 'message' => $result['message'], + ]; + } + + $action = 'edit'; + break; + } + break; + + case 'editor': + switch ($action) { + case 'new': + case 'update': + case 'edit': + $visualConsoleName = $visualConsole['name']; + $action = 'edit'; + break; + } + break; +} + +if (isset($config['vc_refr']) and $config['vc_refr'] != 0) { + $view_refresh = $config['vc_refr']; +} else { + $view_refresh = '300'; +} if (!defined('METACONSOLE')) { - $url_base = 'index.php?sec=network&sec2=godmode/reporting/visual_console_builder&action='; - $url_view = 'index.php?sec=network&sec2=operation/visual_console/render_view&id=' . $idVisualConsole . '&refr=' . $view_refresh; -} -else { - $url_base = 'index.php?operation=edit_visualmap&sec=screen&sec2=screens/screens&action=visualmap&pure=' . $pure . '&action2='; - $url_view = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=0&id_visualmap=' . $idVisualConsole . '&refr=' . $view_refresh; + $url_base = 'index.php?sec=network&sec2=godmode/reporting/visual_console_builder&action='; + $url_view = 'index.php?sec=network&sec2=operation/visual_console/render_view&id='.$idVisualConsole.'&refr='.$view_refresh; +} else { + $url_base = 'index.php?operation=edit_visualmap&sec=screen&sec2=screens/screens&action=visualmap&pure='.$pure.'&action2='; + $url_view = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=0&id_visualmap='.$idVisualConsole.'&refr='.$view_refresh; } // Hash for auto-auth in public link -$hash = md5($config["dbpass"] . $idVisualConsole . $config["id_user"]); +$hash = md5($config['dbpass'].$idVisualConsole.$config['id_user']); -$buttons = array(); +$buttons = []; -$buttons['consoles_list'] = array('active' => false, - 'text' => '' . - html_print_image ("images/visual_console.png", true, array ("title" => __('Visual consoles list'))) .''); -$buttons['public_link'] = array('active' => false, - 'text' => ''. - html_print_image ("images/camera_mc.png", true, array ("title" => __('Show link to public Visual Console'))).''); -$buttons['data'] = array('active' => false, - 'text' => '' . - html_print_image ("images/op_reporting.png", true, array ("title" => __('Main data'))) .''); -$buttons['list_elements'] = array('active' => false, - 'text' => '' . - html_print_image ("images/list.png", true, array ("title" => __('List elements'))) .''); +$buttons['consoles_list'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/visual_console.png', true, ['title' => __('Visual consoles list')]).'', +]; +$buttons['public_link'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/camera_mc.png', true, ['title' => __('Show link to public Visual Console')]).'', +]; +$buttons['data'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/op_reporting.png', true, ['title' => __('Main data')]).'', +]; +$buttons['list_elements'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/list.png', true, ['title' => __('List elements')]).'', +]; if (enterprise_installed()) { - $buttons['wizard_services'] = array('active' => false, - 'text' => '' . - html_print_image ("images/wand_services.png", true, array ("title" => __('Services wizard'))) .''); + $buttons['wizard_services'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/wand_services.png', true, ['title' => __('Services wizard')]).'', + ]; } -$buttons['wizard'] = array('active' => false, - 'text' => '' . - html_print_image ("images/wand.png", true, array ("title" => __('Wizard'))) .''); -$buttons['editor'] = array('active' => false, - 'text' => '' . - html_print_image ("images/builder.png", true, array ("title" => __('Builder'))) .''); -$buttons['view'] = array('active' => false, - 'text' => '' . - html_print_image ("images/operation.png", true, array ("title" => __('View'))) .''); +$buttons['wizard'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/wand.png', true, ['title' => __('Wizard')]).'', +]; +$buttons['editor'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/builder.png', true, ['title' => __('Builder')]).'', +]; +$buttons['view'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/operation.png', true, ['title' => __('View')]).'', +]; if ($action == 'new' || $idVisualConsole === false) { - $buttons = array('data' => $buttons['data']); //Show only the data tab - // If it is a fail try, reset the values - $action = 'new'; - $visualConsoleName = __("New visual console"); + $buttons = ['data' => $buttons['data']]; + // Show only the data tab + // If it is a fail try, reset the values + $action = 'new'; + $visualConsoleName = __('New visual console'); } $buttons[$activeTab]['active'] = true; if (!defined('METACONSOLE')) { - ui_print_page_header($visualConsoleName, - "images/visual_console.png", false, - "visual_console_editor_" . $activeTab . "_tab", false, - $buttons); + ui_print_page_header( + $visualConsoleName, + 'images/visual_console.png', + false, + 'visual_console_editor_'.$activeTab.'_tab', + false, + $buttons + ); } if ($statusProcessInDB !== null) { - echo $statusProcessInDB['message']; + echo $statusProcessInDB['message']; } -//The source code for PAINT THE PAGE +// The source code for PAINT THE PAGE switch ($activeTab) { - case 'wizard': - require_once($config['homedir'] . '/godmode/reporting/visual_console_builder.wizard.php'); - break; - case 'wizard_services': - if (enterprise_installed()) { - enterprise_include('/godmode/reporting/visual_console_builder.wizard_services.php'); - } - break; - case 'data': - require_once($config['homedir'] . '/godmode/reporting/visual_console_builder.data.php'); - break; - case 'list_elements': - require_once($config['homedir'] . '/godmode/reporting/visual_console_builder.elements.php'); - break; - case 'editor': - require_once($config['homedir'] . '/godmode/reporting/visual_console_builder.editor.php'); - break; + case 'wizard': + include_once $config['homedir'].'/godmode/reporting/visual_console_builder.wizard.php'; + break; + + case 'wizard_services': + if (enterprise_installed()) { + enterprise_include('/godmode/reporting/visual_console_builder.wizard_services.php'); + } + break; + + case 'data': + include_once $config['homedir'].'/godmode/reporting/visual_console_builder.data.php'; + break; + + case 'list_elements': + include_once $config['homedir'].'/godmode/reporting/visual_console_builder.elements.php'; + break; + + case 'editor': + include_once $config['homedir'].'/godmode/reporting/visual_console_builder.editor.php'; + break; } -?> diff --git a/pandora_console/godmode/reporting/visual_console_builder.wizard.php b/pandora_console/godmode/reporting/visual_console_builder.wizard.php index dea672b5eb..955d4f88a9 100644 --- a/pandora_console/godmode/reporting/visual_console_builder.wizard.php +++ b/pandora_console/godmode/reporting/visual_console_builder.wizard.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,370 +10,552 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Login check global $config; -check_login (); +check_login(); // Visual console required if (empty($visualConsole)) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; } -$strict_user = db_get_value('strict_acl', 'tusuario', 'id_user', - $config['id_user']); +$strict_user = db_get_value( + 'strict_acl', + 'tusuario', + 'id_user', + $config['id_user'] +); // ACL for the existing visual console // if (!isset($vconsole_read)) -// $vconsole_read = check_acl ($config['id_user'], $visualConsole['id_group'], "VR"); -if (!isset($vconsole_write)) - $vconsole_write = check_acl( - $config['id_user'], $visualConsole['id_group'], "VW"); -if (!isset($vconsole_manage)) - $vconsole_manage = check_acl( - $config['id_user'], $visualConsole['id_group'], "VM"); - -if (!$vconsole_write && !$vconsole_manage) { - db_pandora_audit("ACL Violation", - "Trying to access report builder"); - require ("general/noaccess.php"); - exit; +// $vconsole_read = check_acl ($config['id_user'], $visualConsole['id_group'], "VR"); +if (!isset($vconsole_write)) { + $vconsole_write = check_acl( + $config['id_user'], + $visualConsole['id_group'], + 'VW' + ); } -require_once ($config['homedir'] . '/include/functions_visual_map.php'); -require_once($config['homedir'] . "/include/functions_agents.php"); +if (!isset($vconsole_manage)) { + $vconsole_manage = check_acl( + $config['id_user'], + $visualConsole['id_group'], + 'VM' + ); +} + +if (!$vconsole_write && !$vconsole_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access report builder' + ); + include 'general/noaccess.php'; + exit; +} + +require_once $config['homedir'].'/include/functions_visual_map.php'; +require_once $config['homedir'].'/include/functions_agents.php'; $table = new stdClass(); $table->id = 'wizard_table'; -$table->head = array (); +$table->head = []; if (!is_metaconsole()) { - $metaconsole_hack = ''; - $table->width = '100%'; - $table->class = 'databox filters'; -} -else { - $metaconsole_hack = '../../'; - $table->width = '100%'; - $table->class = 'databox filters'; - $table->styleTable = ' margin-top:0px'; - require_once($config['homedir'] . - "/enterprise/meta/include/functions_html_meta.php"); + $metaconsole_hack = ''; + $table->width = '100%'; + $table->class = 'databox filters'; +} else { + $metaconsole_hack = '../../'; + $table->width = '100%'; + $table->class = 'databox filters'; + $table->styleTable = ' margin-top:0px'; + include_once $config['homedir'].'/enterprise/meta/include/functions_html_meta.php'; } -$table->style = array (); +$table->style = []; $table->style[0] = 'font-weight: bold; '; $table->style[2] = 'font-weight: bold; '; -$table->size = array (); -$table->size[0] = "15%"; -$table->size[1] = "15%"; -$table->size[2] = "15%"; -$table->size[3] = "15%"; +$table->size = []; +$table->size[0] = '15%'; +$table->size[1] = '15%'; +$table->size[2] = '15%'; +$table->size[3] = '15%'; -$table->align = array(); +$table->align = []; $table->align[0] = 'left'; $table->align[1] = 'left'; $table->align[2] = 'left'; $table->align[3] = 'left'; -$table->data = array (); +$table->data = []; -$images_list = array (); -$all_images = list_files ( - $config['homedir'] . '/images/console/icons/', "png", 1, 0); +$images_list = []; +$all_images = list_files( + $config['homedir'].'/images/console/icons/', + 'png', + 1, + 0 +); foreach ($all_images as $image_file) { - if (strpos ($image_file, "_bad")) - continue; - if (strpos ($image_file, "_ok")) - continue; - if (strpos ($image_file, "_warning")) - continue; - $image_file = substr ($image_file, 0, strlen ($image_file) - 4); - $images_list[$image_file] = $image_file; + if (strpos($image_file, '_bad')) { + continue; + } + + if (strpos($image_file, '_ok')) { + continue; + } + + if (strpos($image_file, '_warning')) { + continue; + } + + $image_file = substr($image_file, 0, (strlen($image_file) - 4)); + $images_list[$image_file] = $image_file; } -$type_list = array( - STATIC_GRAPH => __('Static Graph'), - PERCENTILE_BAR => __('Percentile Item'), - MODULE_GRAPH => __('Module graph'), - SIMPLE_VALUE => __('Simple value')); +$type_list = [ + STATIC_GRAPH => __('Static Graph'), + PERCENTILE_BAR => __('Percentile Item'), + MODULE_GRAPH => __('Module graph'), + SIMPLE_VALUE => __('Simple value'), +]; -$table->rowstyle["all_0"] = 'display: none;'; -$table->data["all_0"][0] = __('Type'); -$table->colspan["all_0"][1] = "3"; -$table->data["all_0"][1] = html_print_select ($type_list, 'type', '', - 'hidden_rows()', '', '', true, false, false); +$table->rowstyle['all_0'] = 'display: none;'; +$table->data['all_0'][0] = __('Type'); +$table->colspan['all_0'][1] = '3'; +$table->data['all_0'][1] = html_print_select( + $type_list, + 'type', + '', + 'hidden_rows()', + '', + '', + true, + false, + false +); -$table->rowstyle["staticgraph"] = 'display: none;'; -$table->data["staticgraph"][0] = __('Image'); -$table->colspan["staticgraph"][1] = "3"; -$table->data["staticgraph"][1] = html_print_select($images_list, - 'image', '', '', '', '', true); +$table->rowstyle['staticgraph'] = 'display: none;'; +$table->data['staticgraph'][0] = __('Image'); +$table->colspan['staticgraph'][1] = '3'; +$table->data['staticgraph'][1] = html_print_select( + $images_list, + 'image', + '', + '', + '', + '', + true +); -$table->rowstyle["all_1"] = 'display: none;'; -$table->data["all_1"][0] = __('Range between elements (px)'); -$table->colspan["all_1"][1] = "3"; -$table->data["all_1"][1] = html_print_input_text('range', 50, '', 5, 5, - true); +$table->rowstyle['all_1'] = 'display: none;'; +$table->data['all_1'][0] = __('Range between elements (px)'); +$table->colspan['all_1'][1] = '3'; +$table->data['all_1'][1] = html_print_input_text( + 'range', + 50, + '', + 5, + 5, + true +); -$table->rowstyle["staticgraph_modulegraph"] = 'display: none;'; -$table->data["staticgraph_modulegraph"][0] = __('Size (px)'); -$table->colspan["staticgraph_modulegraph"][1] = "3"; -$table->data["staticgraph_modulegraph"][1] = __('Width').': ' . - html_print_input_text ('width', 0, '', 5, 5, true); -$table->data["staticgraph_modulegraph"][1] .= '   ' . - __('Height') . ': ' . - html_print_input_text('height', 0, '', 5, 5, true); - - $fontf = array('Roboto' => 'Roboto', - 'lato' => 'Lato', - 'opensans' => 'Open Sans', - 'nunito' => 'Nunito', - 'leaguegothic' => 'League Gothic' - ); - - $fonts = array('4pt' => '4pt','6pt' => '6pt','8pt' => '8pt','10pt' => '10pt','12pt' => '12pt','14pt' => '14pt','18pt' => '18pt','24pt' => '24pt','28pt' => '28pt','36pt' => '36pt','48pt' => '48pt','60pt' => '60pt','72pt' => '72pt','84pt' => '84pt','96pt' => '96pt','116pt' => '116pt','128pt' => '128pt','140pt' => '140pt','154pt' => '154pt','196pt' => '196pt'); - - /* - $fontf = array('andale mono,times' => 'Andale Mono', - 'arial,helvetica,sans-serif' => 'Arial', - 'arial black,avant garde' => 'Arial Black', - 'comic sans ms,sans-serif' => 'Comic Sans MS', - 'courier new,courier' => 'Courier New', - 'georgia,palatino' => 'Georgia', - 'helvetica,impact' => 'Helvetica', - 'impact,chicago' => 'Impact', - 'symbol' => 'Symbol', - 'tahoma,arial,helvetica,sans-serif' => 'Tahoma', - 'terminal,monaco' => 'Terminal', - 'times new roman,times' => 'Times New Roman', - 'trebuchet ms,geneva' => 'Trebuchet MS', - 'verdana,geneva' => 'Verdana', - 'Webdings' => 'Webdings', - 'Wingdings' => 'Wingdings' - ); - */ - - $table->rowstyle['all_9'] = 'display: none;'; - $table->data['all_9'][0] = __('Font'); - $table->colspan['all_9'][1] = "3"; - $table->data["all_9"][1] = html_print_select($fontf, - 'fontf', $fontf['Roboto'], '', '', '', true); - - - - $table->rowstyle['all_10'] = 'display: none;'; - $table->data['all_10'][0] = __('Font size'); - $table->colspan['all_10'][1] = "3"; - $table->data["all_10"][1] = html_print_select($fonts, - 'fonts', $fonts['12pt'], '', '', '', true); +$table->rowstyle['staticgraph_modulegraph'] = 'display: none;'; +$table->data['staticgraph_modulegraph'][0] = __('Size (px)'); +$table->colspan['staticgraph_modulegraph'][1] = '3'; +$table->data['staticgraph_modulegraph'][1] = __('Width').': '.html_print_input_text('width', 0, '', 5, 5, true); +$table->data['staticgraph_modulegraph'][1] .= '   '.__('Height').': '.html_print_input_text('height', 0, '', 5, 5, true); + +$fontf = [ + 'Roboto' => 'Roboto', + 'lato' => 'Lato', + 'opensans' => 'Open Sans', + 'nunito' => 'Nunito', + 'leaguegothic' => 'League Gothic', +]; + +$fonts = [ + '4pt' => '4pt', + '6pt' => '6pt', + '8pt' => '8pt', + '10pt' => '10pt', + '12pt' => '12pt', + '14pt' => '14pt', + '18pt' => '18pt', + '24pt' => '24pt', + '28pt' => '28pt', + '36pt' => '36pt', + '48pt' => '48pt', + '60pt' => '60pt', + '72pt' => '72pt', + '84pt' => '84pt', + '96pt' => '96pt', + '116pt' => '116pt', + '128pt' => '128pt', + '140pt' => '140pt', + '154pt' => '154pt', + '196pt' => '196pt', +]; + +/* + $fontf = array('andale mono,times' => 'Andale Mono', + 'arial,helvetica,sans-serif' => 'Arial', + 'arial black,avant garde' => 'Arial Black', + 'comic sans ms,sans-serif' => 'Comic Sans MS', + 'courier new,courier' => 'Courier New', + 'georgia,palatino' => 'Georgia', + 'helvetica,impact' => 'Helvetica', + 'impact,chicago' => 'Impact', + 'symbol' => 'Symbol', + 'tahoma,arial,helvetica,sans-serif' => 'Tahoma', + 'terminal,monaco' => 'Terminal', + 'times new roman,times' => 'Times New Roman', + 'trebuchet ms,geneva' => 'Trebuchet MS', + 'verdana,geneva' => 'Verdana', + 'Webdings' => 'Webdings', + 'Wingdings' => 'Wingdings' + ); +*/ + +$table->rowstyle['all_9'] = 'display: none;'; +$table->data['all_9'][0] = __('Font'); +$table->colspan['all_9'][1] = '3'; +$table->data['all_9'][1] = html_print_select( + $fontf, + 'fontf', + $fontf['Roboto'], + '', + '', + '', + true +); + +$table->rowstyle['all_10'] = 'display: none;'; +$table->data['all_10'][0] = __('Font size'); +$table->colspan['all_10'][1] = '3'; +$table->data['all_10'][1] = html_print_select( + $fonts, + 'fonts', + $fonts['12pt'], + '', + '', + '', + true +); -$table->rowstyle["modulegraph_simplevalue"] = 'display: none;'; -$table->data["modulegraph_simplevalue"][0] = __('Period'); -$table->colspan["modulegraph_simplevalue"][1] = "3"; -$table->data["modulegraph_simplevalue"][1] = - html_print_extended_select_for_time('period', '', '', '', '', false, - true); +$table->rowstyle['modulegraph_simplevalue'] = 'display: none;'; +$table->data['modulegraph_simplevalue'][0] = __('Period'); +$table->colspan['modulegraph_simplevalue'][1] = '3'; +$table->data['modulegraph_simplevalue'][1] = html_print_extended_select_for_time( + 'period', + '', + '', + '', + '', + false, + true +); -$table->rowstyle["simplevalue"] = 'display: none;'; -$table->data["simplevalue"][0] = __('Process'); -$table->data["simplevalue"][1] = html_print_select ( - array ( - PROCESS_VALUE_MIN => __('Min value'), - PROCESS_VALUE_MAX => __('Max value'), - PROCESS_VALUE_AVG => __('Avg value')), - 'process_value', PROCESS_VALUE_AVG, '', __('None'), - PROCESS_VALUE_NONE, true); +$table->rowstyle['simplevalue'] = 'display: none;'; +$table->data['simplevalue'][0] = __('Process'); +$table->data['simplevalue'][1] = html_print_select( + [ + PROCESS_VALUE_MIN => __('Min value'), + PROCESS_VALUE_MAX => __('Max value'), + PROCESS_VALUE_AVG => __('Avg value'), + ], + 'process_value', + PROCESS_VALUE_AVG, + '', + __('None'), + PROCESS_VALUE_NONE, + true +); -$table->rowstyle["percentileitem_1"] = 'display: none;'; -$table->data["percentileitem_1"][0] = __('Width (px)'); -$table->data["percentileitem_1"][1] = - html_print_input_text ('percentileitem_width', 0, '', 5, 5, true); +$table->rowstyle['percentileitem_1'] = 'display: none;'; +$table->data['percentileitem_1'][0] = __('Width (px)'); +$table->data['percentileitem_1'][1] = html_print_input_text('percentileitem_width', 0, '', 5, 5, true); -$table->rowstyle["percentileitem_2"] = 'display: none;'; -$table->data["percentileitem_2"][0] = __('Max value'); -$table->data["percentileitem_2"][1] = - html_print_input_text ('max_value', 0, '', 5, 5, true); +$table->rowstyle['percentileitem_2'] = 'display: none;'; +$table->data['percentileitem_2'][0] = __('Max value'); +$table->data['percentileitem_2'][1] = html_print_input_text('max_value', 0, '', 5, 5, true); -$table->rowstyle["percentileitem_3"] = 'display: none;'; -$table->data["percentileitem_3"][0] = __('Type'); -$table->colspan["percentileitem_3"][1] = "3"; -$table->data["percentileitem_3"][1] = __('Percentile') . - '   ' . - html_print_radio_button_extended('type_percentile', 'percentile', '', '', false, - '', '', true) . - '  '; -$table->data["percentileitem_3"][1] .= __('Bubble') . - '   ' . - html_print_radio_button_extended('type_percentile', 'bubble', '', '', false, - '', '', true) . - '  '; +$table->rowstyle['percentileitem_3'] = 'display: none;'; +$table->data['percentileitem_3'][0] = __('Type'); +$table->colspan['percentileitem_3'][1] = '3'; +$table->data['percentileitem_3'][1] = __('Percentile').'   '.html_print_radio_button_extended( + 'type_percentile', + 'percentile', + '', + '', + false, + '', + '', + true +).'  '; +$table->data['percentileitem_3'][1] .= __('Bubble').'   '.html_print_radio_button_extended( + 'type_percentile', + 'bubble', + '', + '', + false, + '', + '', + true +).'  '; -$table->rowstyle["percentileitem_4"] = 'display: none;'; -$table->data["percentileitem_4"][0] = __('Value to show'); -$table->colspan["percentileitem_4"][1] = "3"; -$table->data["percentileitem_4"][1] = __('Percent') . - '   ' . - html_print_radio_button_extended('value_show', 'percent', '', '', false, - '', '', true) . - '  '; -$table->data["percentileitem_4"][1] .= __('Value') . - '   ' . - html_print_radio_button_extended('value_show', 'value', '', '', false, - '', '', true) . - '  '; +$table->rowstyle['percentileitem_4'] = 'display: none;'; +$table->data['percentileitem_4'][0] = __('Value to show'); +$table->colspan['percentileitem_4'][1] = '3'; +$table->data['percentileitem_4'][1] = __('Percent').'   '.html_print_radio_button_extended( + 'value_show', + 'percent', + '', + '', + false, + '', + '', + true +).'  '; +$table->data['percentileitem_4'][1] .= __('Value').'   '.html_print_radio_button_extended( + 'value_show', + 'value', + '', + '', + false, + '', + '', + true +).'  '; if (is_metaconsole()) { - $table->rowstyle["all_2"] = 'display: none;'; - $table->data["all_2"][0] = __('Servers'); - if ($strict_user) - $table->data["all_2"][1] = html_print_select('','servers', - '', 'metaconsole_init();', __('All'), '0', true); - else - $sql = 'SELECT id, server_name - FROM tmetaconsole_setup'; - $table->data["all_2"][1] = html_print_select_from_sql( - $sql, 'servers', '', 'metaconsole_init();', __('All'), - '0', true); + $table->rowstyle['all_2'] = 'display: none;'; + $table->data['all_2'][0] = __('Servers'); + if ($strict_user) { + $table->data['all_2'][1] = html_print_select( + '', + 'servers', + '', + 'metaconsole_init();', + __('All'), + '0', + true + ); + } else { + $sql = 'SELECT id, server_name + FROM tmetaconsole_setup'; + } + + $table->data['all_2'][1] = html_print_select_from_sql( + $sql, + 'servers', + '', + 'metaconsole_init();', + __('All'), + '0', + true + ); } -$table->rowstyle["all_3"] = 'display: none;'; -$table->data["all_3"][0] = __('Groups'); -$table->colspan["all_3"][1] = "3"; -$table->data["all_3"][1] = html_print_select_groups( - $config['id_user'], "AR", true, 'groups', '', '', '', 0, true); +$table->rowstyle['all_3'] = 'display: none;'; +$table->data['all_3'][0] = __('Groups'); +$table->colspan['all_3'][1] = '3'; +$table->data['all_3'][1] = html_print_select_groups( + $config['id_user'], + 'AR', + true, + 'groups', + '', + '', + '', + 0, + true +); -$table->rowstyle["all_one_item_per_agent"] = 'display: none'; -$table->data["all_one_item_per_agent"][0] = __('One item per agent'); -$table->colspan["all_one_item_per_agent"][1] = "3"; -$table->data["all_one_item_per_agent"][1] = __('Yes') . - '   ' . - html_print_radio_button_extended('item_per_agent', 1, '', '', false, - 'item_per_agent_change(1)', '', true) . - '  '; -$table->data["all_one_item_per_agent"][1] .= __('No') . - '   ' . html_print_radio_button_extended( - 'item_per_agent', 0, '', 0, false, 'item_per_agent_change(0)', - '', true); -$table->data["all_one_item_per_agent"][1] .= html_print_input_hidden( - 'item_per_agent_test', 0, true); +$table->rowstyle['all_one_item_per_agent'] = 'display: none'; +$table->data['all_one_item_per_agent'][0] = __('One item per agent'); +$table->colspan['all_one_item_per_agent'][1] = '3'; +$table->data['all_one_item_per_agent'][1] = __('Yes').'   '.html_print_radio_button_extended( + 'item_per_agent', + 1, + '', + '', + false, + 'item_per_agent_change(1)', + '', + true +).'  '; +$table->data['all_one_item_per_agent'][1] .= __('No').'   '.html_print_radio_button_extended( + 'item_per_agent', + 0, + '', + 0, + false, + 'item_per_agent_change(0)', + '', + true +); +$table->data['all_one_item_per_agent'][1] .= html_print_input_hidden( + 'item_per_agent_test', + 0, + true +); -$table->rowstyle["all_4"] = 'display: none;'; -$table->data["all_4"][0] = __('Agents'); +$table->rowstyle['all_4'] = 'display: none;'; +$table->data['all_4'][0] = __('Agents'); -$agents_list = array(); -if (!is_metaconsole()) - $agents_list = agents_get_group_agents(0, false, "none", false, - true); +$agents_list = []; +if (!is_metaconsole()) { + $agents_list = agents_get_group_agents( + 0, + false, + 'none', + false, + true + ); +} -$table->data["all_4"][1] = html_print_select($agents_list, - 'id_agents[]', 0, false, '', '', true, true); -$table->data["all_4"][2] = ' ' . - __('Modules') . ''; -$table->data["all_4"][3] = html_print_select (array (), 'module[]', 0, - false, __('None'), -1, true, true); +$table->data['all_4'][1] = html_print_select( + $agents_list, + 'id_agents[]', + 0, + false, + '', + '', + true, + true +); +$table->data['all_4'][2] = ' '.__('Modules').''; +$table->data['all_4'][3] = html_print_select( + [], + 'module[]', + 0, + false, + __('None'), + -1, + true, + true +); -$table->rowstyle["all_6"] = 'display: none;'; -$table->data["all_6"][0] = __('Label'); -$label_type = array ('agent_module' => __('Agent - Module'), - 'module' => __('Module'), - 'agent' => __('Agent'), - 'none' => __('None')); -$table->colspan["all_6"][1] = "3"; -$table->data["all_6"][1] = html_print_select ($label_type, 'label_type', - 'agent_module', '', '', '', true); +$table->rowstyle['all_6'] = 'display: none;'; +$table->data['all_6'][0] = __('Label'); +$label_type = [ + 'agent_module' => __('Agent - Module'), + 'module' => __('Module'), + 'agent' => __('Agent'), + 'none' => __('None'), +]; +$table->colspan['all_6'][1] = '3'; +$table->data['all_6'][1] = html_print_select( + $label_type, + 'label_type', + 'agent_module', + '', + '', + '', + true +); -$table->data["all_7"][0] = __('Enable link agent'); -$table->colspan["all_7"][1] = "3"; -$table->data["all_7"][1] = __('Yes') . '   ' . - html_print_radio_button_extended('enable_link', 1, '', 1, false, '', '', true) . - '  '; -$table->data["all_7"][1] .= __('No') . '   ' . - html_print_radio_button_extended('enable_link', 0, '', 1, false, '', '', true); +$table->data['all_7'][0] = __('Enable link agent'); +$table->colspan['all_7'][1] = '3'; +$table->data['all_7'][1] = __('Yes').'   '.html_print_radio_button_extended('enable_link', 1, '', 1, false, '', '', true).'  '; +$table->data['all_7'][1] .= __('No').'   '.html_print_radio_button_extended('enable_link', 0, '', 1, false, '', '', true); -$parents = visual_map_get_items_parents($visualConsole["id"]); -if (empty($parents)) - $parents = array(); -$table->data["all_8"][0] = __('Set Parent'); -$table->data["all_8"][1] = html_print_select( - array (VISUAL_MAP_WIZARD_PARENTS_ITEM_MAP => __('Item created in the visualmap'), - VISUAL_MAP_WIZARD_PARENTS_AGENT_RELANTIONSHIP => __('Use the agents relationship (from selected agents)')), 'kind_relationship', - 0, '', __('None'), VISUAL_MAP_WIZARD_PARENTS_NONE, true); -$table->data["all_8"][2] = '' . - __('Item in the map') . '' . - '' . - ui_print_help_tip( - __('The parenting relationships in %s will be drawn on the map.', get_product_name()), true) . - ''; -$table->data["all_8"][3] = '' . - html_print_select($parents, 'item_in_the_map', 0, '', - __('None'), 0, true) . ''; +$parents = visual_map_get_items_parents($visualConsole['id']); +if (empty($parents)) { + $parents = []; +} + +$table->data['all_8'][0] = __('Set Parent'); +$table->data['all_8'][1] = html_print_select( + [ + VISUAL_MAP_WIZARD_PARENTS_ITEM_MAP => __('Item created in the visualmap'), + VISUAL_MAP_WIZARD_PARENTS_AGENT_RELANTIONSHIP => __('Use the agents relationship (from selected agents)'), + ], + 'kind_relationship', + 0, + '', + __('None'), + VISUAL_MAP_WIZARD_PARENTS_NONE, + true +); +$table->data['all_8'][2] = ''.__('Item in the map').''.''.ui_print_help_tip( + __('The parenting relationships in %s will be drawn on the map.', get_product_name()), + true +).''; +$table->data['all_8'][3] = ''.html_print_select( + $parents, + 'item_in_the_map', + 0, + '', + __('None'), + 0, + true +).''; if (is_metaconsole()) { - $pure = get_parameter('pure', 0); - - echo ''; -} -else { - echo ''; } -if (defined("METACONSOLE")) { - echo "
    " . - __('Wizard') . "
    "; +if (defined('METACONSOLE')) { + echo "
    ".__('Wizard').'
    '; } -html_print_table ($table); +html_print_table($table); echo '
    '; if (is_metaconsole()) { - html_print_input_hidden ('action2', 'update'); + html_print_input_hidden('action2', 'update'); +} else { + html_print_input_hidden('action', 'update'); } -else { - html_print_input_hidden ('action', 'update'); -} -html_print_input_hidden ('id_visual_console', $visualConsole["id"]); -html_print_submit_button (__('Add'), 'go', false, 'class="sub wizard wand"'); + +html_print_input_hidden('id_visual_console', $visualConsole['id']); +html_print_submit_button(__('Add'), 'go', false, 'class="sub wizard wand"'); echo '
    '; echo '
    '; -//Trick for it have a traduct text for javascript. -echo ''; -echo ''; -echo ''; +// Trick for it have a traduct text for javascript. +echo ''; +echo ''; +echo ''; ?> diff --git a/pandora_console/godmode/reporting/visual_console_favorite.php b/pandora_console/godmode/reporting/visual_console_favorite.php index a660a81007..df13291539 100644 --- a/pandora_console/godmode/reporting/visual_console_favorite.php +++ b/pandora_console/godmode/reporting/visual_console_favorite.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2018 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,161 +10,185 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -require_once ($config['homedir'] . '/include/functions_visual_map.php'); +require_once $config['homedir'].'/include/functions_visual_map.php'; // ACL for the general permission -$vconsoles_read = check_acl ($config['id_user'], 0, "VR"); -$vconsoles_write = check_acl ($config['id_user'], 0, "VW"); -$vconsoles_manage = check_acl ($config['id_user'], 0, "VM"); +$vconsoles_read = check_acl($config['id_user'], 0, 'VR'); +$vconsoles_write = check_acl($config['id_user'], 0, 'VW'); +$vconsoles_manage = check_acl($config['id_user'], 0, 'VM'); $is_enterprise = enterprise_include_once('include/functions_policies.php'); $is_metaconsole = is_metaconsole(); if (!$vconsoles_read && !$vconsoles_write && !$vconsoles_manage) { - db_pandora_audit("ACL Violation", - "Trying to access map builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access map builder' + ); + include 'general/noaccess.php'; + exit; } -if(!$is_metaconsole){ +if (!$is_metaconsole) { $url_visual_console = 'index.php?sec=network&sec2=godmode/reporting/map_builder'; $url_visual_console_favorite = 'index.php?sec=network&sec2=godmode/reporting/visual_console_favorite'; $url_visual_console_template = 'index.php?sec=network&sec2=enterprise/godmode/reporting/visual_console_template'; $url_visual_console_template_wizard = 'index.php?sec=network&sec2=enterprise/godmode/reporting/visual_console_template_wizard'; -} -else{ +} else { $url_visual_console = 'index.php?sec=screen&sec2=screens/screens&action=visualmap'; $url_visual_console_favorite = 'index.php?sec=screen&sec2=screens/screens&action=visualmap_favorite'; $url_visual_console_template = 'index.php?sec=screen&sec2=screens/screens&action=visualmap_template'; $url_visual_console_template_wizard = 'index.php?sec=screen&sec2=screens/screens&action=visualmap_wizard'; + $url_visual_console_manager = 'index.php?sec=screen&sec2=enterprise/extensions/visual_console_manager'; } -$buttons['visual_console'] = array( +$buttons['visual_console'] = [ 'active' => false, - 'text' => '' . - html_print_image ("images/visual_console.png", true, array ("title" => __('Visual Console List'))) .'' -); + 'text' => ''.html_print_image('images/visual_console.png', true, ['title' => __('Visual Console List')]).'', +]; -$buttons['visual_console_favorite'] = array( +$buttons['visual_console_favorite'] = [ 'active' => true, - 'text' => '' . - html_print_image ("images/list.png", true, array ("title" => __('Visual Favourite Console'))) .'' -); + 'text' => ''.html_print_image('images/list.png', true, ['title' => __('Visual Favourite Console')]).'', +]; -if($is_enterprise && $vconsoles_manage){ - $buttons['visual_console_template'] = array( +if ($is_enterprise && $vconsoles_manage) { + $buttons['visual_console_template'] = [ 'active' => false, - 'text' => '' . - html_print_image ("images/templates.png", true, array ("title" => __('Visual Console Template'))) .'' - ); + 'text' => ''.html_print_image('images/templates.png', true, ['title' => __('Visual Console Template')]).'', + ]; - $buttons['visual_console_template_wizard'] = array( + $buttons['visual_console_template_wizard'] = [ 'active' => false, - 'text' => '' . - html_print_image ("images/wand.png", true, array ("title" => __('Visual Console Template Wizard'))) .'' - ); + 'text' => ''.html_print_image('images/wand.png', true, ['title' => __('Visual Console Template Wizard')]).'', + ]; + + if ($is_metaconsole) { + $buttons['visual_console_manager'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/builder.png', true, ['title' => __('Visual Console Manager')]).'', + ]; + } } if (!$is_metaconsole) { - ui_print_page_header( - __('Reporting') .' » ' . __('Visual Favourite Console'), - "images/op_reporting.png", false, "map_builder", false, $buttons); -} -else{ + ui_print_page_header( + __('Reporting').' » '.__('Visual Favourite Console'), + 'images/op_reporting.png', + false, + 'map_builder', + false, + $buttons + ); +} else { ui_meta_print_header( - __('Visual console') . " » " . $visualConsoleName, "", - $buttons); + __('Visual console').' » '.$visualConsoleName, + '', + $buttons + ); } -$search = (string) get_parameter("search",""); -$ag_group = (int) get_parameter("ag_group",0); -$recursion = (int) get_parameter("recursion",0); +$search = (string) get_parameter('search', ''); +$ag_group = (int) get_parameter('ag_group', 0); +$recursion = (int) get_parameter('recursion', 0); -if(!is_metaconsole()){ - echo "
    "; } else { - echo ""; } + echo "
    • "; - echo "
      • "; - echo __('Search') . ' '; - html_print_input_text ("search", $search, '', 50); - echo "
      • "; - echo __('Group') . ' '; + echo '
        • '; + echo __('Search').' '; + html_print_input_text('search', $search, '', 50); + echo '
        • '; + echo __('Group').' '; $own_info = get_user_info($config['id_user']); - if (!$own_info['is_admin'] && !check_acl ($config['id_user'], 0, "AW")) - $return_all_group = false; - else - $return_all_group = true; - html_print_select_groups(false, "AR", $return_all_group, "ag_group", - $ag_group, 'this.form.submit();', '', 0, false, - false, true, '', false - ); - echo "
        • "; +if (!$own_info['is_admin'] && !check_acl($config['id_user'], 0, 'AW')) { + $return_all_group = false; +} else { + $return_all_group = true; +} + + html_print_select_groups( + false, + 'AR', + $return_all_group, + 'ag_group', + $ag_group, + 'this.form.submit();', + '', + 0, + false, + false, + true, + '', + false + ); + echo "
        • "; echo __('Group Recursion'); - html_print_checkbox ("recursion", 1, $recursion, false, false, 'this.form.submit()'); - echo "
        • "; + html_print_checkbox('recursion', 1, $recursion, false, false, 'this.form.submit()'); + echo '
        • '; echo ""; - echo "
      "; -echo "
    • "; + echo '
    '; + echo ''; -$returnAllGroups = 0; -$filters = array(); -if(!empty($search)){ - $filters['name'] = io_safe_input($search); -} - -if ($ag_group > 0) { - $ag_groups = array(); - $ag_groups = (array)$ag_group; - if ($recursion) { - $ag_groups = groups_get_id_recursive($ag_group, true); - } -} -elseif($own_info['is_admin']){ - $returnAllGroups = 1; -} - -if($ag_group){ - $filters['group'] = array_flip($ag_groups); -} - -$favorite_array = visual_map_get_user_layouts ($config['id_user'],false,$filters,$returnAllGroups,true); - -echo "
    "; - if($favorite_array == false){ - ui_print_info_message(__('No favourite consoles defined')); - } - else{ - echo ""; - } -echo "
    "; -?> + + if ($ag_group > 0) { + $ag_groups = []; + $ag_groups = (array) $ag_group; + if ($recursion) { + $ag_groups = groups_get_id_recursive($ag_group, true); + } + } else if ($own_info['is_admin']) { + $returnAllGroups = 1; + } + + if ($ag_group) { + $filters['group'] = array_flip($ag_groups); + } + + $favorite_array = visual_map_get_user_layouts($config['id_user'], false, $filters, $returnAllGroups, true); + + echo "
    "; + if ($favorite_array == false) { + ui_print_info_message(__('No favourite consoles defined')); + } else { + echo "'; + } + + echo '
    '; diff --git a/pandora_console/godmode/servers/manage_recontask.php b/pandora_console/godmode/servers/manage_recontask.php index 1d5dc69c89..a76571d54a 100644 --- a/pandora_console/godmode/servers/manage_recontask.php +++ b/pandora_console/godmode/servers/manage_recontask.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2012 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,24 +11,24 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Recon Task Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Recon Task Management' + ); + include 'general/noaccess.php'; + exit; } -require_once($config['homedir'] . "/include/functions_network_profiles.php"); +require_once $config['homedir'].'/include/functions_network_profiles.php'; -if (check_acl ($config['id_user'], 0, "AW")) { - $options[]['text'] = "" . html_print_image ("images/operation.png", true, array ("title" =>__('View'))) . ""; +if (check_acl($config['id_user'], 0, 'AW')) { + $options[]['text'] = "".html_print_image('images/operation.png', true, ['title' => __('View')]).''; } $user_groups_w = users_get_groups(false, 'PM', true, false, null, 'id_grupo'); @@ -39,432 +38,434 @@ $user_groups_r = users_get_groups(false, 'AW', true, false, null, 'id_grupo'); $user_groups_r = array_keys($user_groups_r); // Headers -//ui_print_page_header (__('Manage recontask'), "images/gm_servers.png", false, "", true); -ui_print_page_header (__('Manage recontask'), "images/gm_servers.png", false, "", true, $options); +// ui_print_page_header (__('Manage recontask'), "images/gm_servers.png", false, "", true); +ui_print_page_header(__('Manage recontask'), 'images/gm_servers.png', false, '', true, $options); // -------------------------------- // DELETE A RECON TASKs // -------------------------------- -if (isset ($_GET["delete"])) { - $id = get_parameter_get ("delete"); - - $result = db_process_sql_delete('trecon_task', array('id_rt' => $id)); - - if ($result !== false) { - ui_print_success_message(__('Successfully deleted recon task')); - } - else { - ui_print_error_message(__('Error deleting recon task')); - } -} -else if(isset($_GET["disabled"])) { - $id = get_parameter_get ("id"); - $disabled = get_parameter_get ("disabled"); - - $result = db_process_sql_update('trecon_task', array('disabled' => $disabled), array('id_rt' => $id)); - - if ($result !== false) { - ui_print_success_message(__('Successfully updated recon task')); - // If the action is enabled, we force recon_task to be queued asap - if($disabled == 0) { - servers_force_recon_task($id); - } - } - else { - ui_print_error_message(__('Error updating recon task')); - } +if (isset($_GET['delete'])) { + $id = get_parameter_get('delete'); + + $result = db_process_sql_delete('trecon_task', ['id_rt' => $id]); + + if ($result !== false) { + ui_print_success_message(__('Successfully deleted recon task')); + } else { + ui_print_error_message(__('Error deleting recon task')); + } +} else if (isset($_GET['disabled'])) { + $id = get_parameter_get('id'); + $disabled = get_parameter_get('disabled'); + + $result = db_process_sql_update('trecon_task', ['disabled' => $disabled], ['id_rt' => $id]); + + if ($result !== false) { + ui_print_success_message(__('Successfully updated recon task')); + // If the action is enabled, we force recon_task to be queued asap + if ($disabled == 0) { + servers_force_recon_task($id); + } + } else { + ui_print_error_message(__('Error updating recon task')); + } } // -------------------------------- // GET PARAMETERS IF UPDATE OR CREATE // -------------------------------- -if ((isset ($_GET["update"])) OR ((isset ($_GET["create"])))) { - $name = get_parameter_post ("name"); - $network = get_parameter_post ("network"); - $description = get_parameter_post ("description"); - $id_recon_server = get_parameter_post ("id_recon_server"); - $interval = get_parameter_post ("interval"); - $id_group = get_parameter_post ("id_group"); - $create_incident = get_parameter_post ("create_incident"); - $id_network_profile = get_parameter_post ("id_network_profile"); - $recon_ports = get_parameter_post ("recon_ports", ""); - $id_os = get_parameter_post ("id_os", 10); - $snmp_community = get_parameter_post ("snmp_community", "public"); - $id_recon_script = get_parameter ("id_recon_script", 0); - $mode = get_parameter ("mode", ""); - $field1 = get_parameter ("_field1_", ""); - $field2 = get_parameter ("_field2_", ""); - $field3 = get_parameter ("_field3_", ""); - $field4 = get_parameter ("_field4_", ""); - $snmp_version = get_parameter_post ("snmp_version"); - $snmp3_auth_user = get_parameter_post ("snmp_auth_user"); - $snmp3_auth_pass = get_parameter_post ("snmp_auth_pass"); - $snmp3_privacy_method = get_parameter_post ("snmp_privacy_method"); - $snmp3_privacy_pass = get_parameter_post ("snmp_privacy_pass"); - $snmp3_auth_method = get_parameter_post ("snmp_auth_method"); - $snmp3_security_level = get_parameter_post ("snmp_security_level"); +if ((isset($_GET['update'])) or ((isset($_GET['create'])))) { + $name = get_parameter_post('name'); + $network = get_parameter_post('network'); + $description = get_parameter_post('description'); + $id_recon_server = get_parameter_post('id_recon_server'); + $interval = get_parameter_post('interval'); + $id_group = get_parameter_post('id_group'); + $create_incident = get_parameter_post('create_incident'); + $id_network_profile = get_parameter_post('id_network_profile'); + $recon_ports = get_parameter_post('recon_ports', ''); + $id_os = get_parameter_post('id_os', 10); + $snmp_community = get_parameter_post('snmp_community', 'public'); + $id_recon_script = get_parameter('id_recon_script', 0); + $mode = get_parameter('mode', ''); + $field1 = get_parameter('_field1_', ''); + $field2 = get_parameter('_field2_', ''); + $field3 = get_parameter('_field3_', ''); + $field4 = get_parameter('_field4_', ''); + $snmp_version = get_parameter_post('snmp_version'); + $snmp3_auth_user = get_parameter_post('snmp_auth_user'); + $snmp3_auth_pass = get_parameter_post('snmp_auth_pass'); + $snmp3_privacy_method = get_parameter_post('snmp_privacy_method'); + $snmp3_privacy_pass = get_parameter_post('snmp_privacy_pass'); + $snmp3_auth_method = get_parameter_post('snmp_auth_method'); + $snmp3_security_level = get_parameter_post('snmp_security_level'); - if ($mode == "network_sweep") - $id_recon_script = 0; - else - $id_network_profile = 0; - - $os_detect = (int) get_parameter ("os_detect", 0); - $resolve_names = (int) get_parameter ("resolve_names", 0); - $parent_detection = (int) get_parameter ("parent_detection", 0); - $parent_recursion = (int) get_parameter ("parent_recursion", 1); - $alias_as_name = (int) get_parameter ("alias_as_name", 0); - $snmp_enabled = (int) get_parameter ('snmp_enabled', 0); - $vlan_enabled = (int) get_parameter ('vlan_enabled', 0); - // Get macros - $macros = (string) get_parameter ('macros'); - - if (!empty($macros)) { - $macros = json_decode(base64_decode($macros), true); - - foreach($macros as $k => $m) { - $macros[$k]['value'] = get_parameter($m['macro'], ''); - } - } - - $macros = io_json_mb_encode($macros); + if ($mode == 'network_sweep') { + $id_recon_script = 0; + } else { + $id_network_profile = 0; + } + + $os_detect = (int) get_parameter('os_detect', 0); + $resolve_names = (int) get_parameter('resolve_names', 0); + $parent_detection = (int) get_parameter('parent_detection', 0); + $parent_recursion = (int) get_parameter('parent_recursion', 1); + $alias_as_name = (int) get_parameter('alias_as_name', 0); + $snmp_enabled = (int) get_parameter('snmp_enabled', 0); + $vlan_enabled = (int) get_parameter('vlan_enabled', 0); + // Get macros + $macros = (string) get_parameter('macros'); + + if (!empty($macros)) { + $macros = json_decode(base64_decode($macros), true); + + foreach ($macros as $k => $m) { + $macros[$k]['value'] = get_parameter($m['macro'], ''); + } + } + + $macros = io_json_mb_encode($macros); } // -------------------------------- // UPDATE A RECON TASK // -------------------------------- -if (isset($_GET["update"])) { - $id = get_parameter_get ("update"); - - $values = array( - 'snmp_community' => $snmp_community, - 'id_os' => $id_os, - 'name' => $name, - 'subnet' => $network, - 'description' => $description, - 'id_recon_server' => $id_recon_server, - 'create_incident' => $create_incident, - 'id_group' => $id_group, - 'interval_sweep' => $interval, - 'id_network_profile' => $id_network_profile, - 'recon_ports' => $recon_ports, - 'id_recon_script' => $id_recon_script, - 'field1' => $field1, - 'field2' => $field2, - 'field3' => $field3, - 'field4' => $field4, - 'os_detect' => $os_detect, - 'resolve_names' => $resolve_names, - 'parent_detection' => $parent_detection, - 'parent_recursion' => $parent_recursion, - 'macros' => $macros, - 'alias_as_name' => $alias_as_name, - 'snmp_enabled' => $snmp_enabled, - 'vlan_enabled' => $vlan_enabled, - 'snmp_version' => $snmp_version - ); +if (isset($_GET['update'])) { + $id = get_parameter_get('update'); - $values_v3 = array( - 'snmp_auth_user' => $snmp3_auth_user, - 'snmp_auth_pass' => $snmp3_auth_pass, - 'snmp_privacy_method' => $snmp3_privacy_method, - 'snmp_privacy_pass' => $snmp3_privacy_pass, - 'snmp_auth_method' => $snmp3_auth_method, - 'snmp_security_level' => $snmp3_security_level - ); - if($values['snmp_version'] == '1' || $values['snmp_version'] == '2' || $values['snmp_version'] == '2c'){ - $values_v3 = array( - 'snmp_auth_user' => '', - 'snmp_auth_pass' => '', - 'snmp_privacy_method' => '', - 'snmp_privacy_pass' => '', - 'snmp_auth_method' => '', - 'snmp_security_level' => '' - ); - } + $values = [ + 'snmp_community' => $snmp_community, + 'id_os' => $id_os, + 'name' => $name, + 'subnet' => $network, + 'description' => $description, + 'id_recon_server' => $id_recon_server, + 'create_incident' => $create_incident, + 'id_group' => $id_group, + 'interval_sweep' => $interval, + 'id_network_profile' => $id_network_profile, + 'recon_ports' => $recon_ports, + 'id_recon_script' => $id_recon_script, + 'field1' => $field1, + 'field2' => $field2, + 'field3' => $field3, + 'field4' => $field4, + 'os_detect' => $os_detect, + 'resolve_names' => $resolve_names, + 'parent_detection' => $parent_detection, + 'parent_recursion' => $parent_recursion, + 'macros' => $macros, + 'alias_as_name' => $alias_as_name, + 'snmp_enabled' => $snmp_enabled, + 'vlan_enabled' => $vlan_enabled, + 'snmp_version' => $snmp_version, + ]; - $values = array_merge($values, $values_v3); - - $where = array('id_rt' => $id); - - $reason = ''; - if ($name != "") { - if (empty($id_recon_script)) { - if (!preg_match("/[0-9]+.+[0-9]+.+[0-9]+.+[0-9]+\/+[0-9]/", $network)){ - $reason = __('Wrong format in Subnet field'); - $result = false; - } - else{ - $result = db_process_sql_update('trecon_task', $values, $where); - } - } - else { - $result = db_process_sql_update('trecon_task', $values, $where); - } - } - else { - $result = false; - } + $values_v3 = [ + 'snmp_auth_user' => $snmp3_auth_user, + 'snmp_auth_pass' => $snmp3_auth_pass, + 'snmp_privacy_method' => $snmp3_privacy_method, + 'snmp_privacy_pass' => $snmp3_privacy_pass, + 'snmp_auth_method' => $snmp3_auth_method, + 'snmp_security_level' => $snmp3_security_level, + ]; + if ($values['snmp_version'] == '1' || $values['snmp_version'] == '2' || $values['snmp_version'] == '2c') { + $values_v3 = [ + 'snmp_auth_user' => '', + 'snmp_auth_pass' => '', + 'snmp_privacy_method' => '', + 'snmp_privacy_pass' => '', + 'snmp_auth_method' => '', + 'snmp_security_level' => '', + ]; + } - if ($result !== false) { - ui_print_success_message(__('Successfully updated recon task')); - } - else { - ui_print_error_message(__('Error updating recon task')); - echo $reason; - include('manage_recontask_form.php'); - return; - } + $values = array_merge($values, $values_v3); + + $where = ['id_rt' => $id]; + + $reason = ''; + if ($name != '') { + if (empty($id_recon_script)) { + if (!preg_match('/[0-9]+.+[0-9]+.+[0-9]+.+[0-9]+\/+[0-9]/', $network)) { + $reason = __('Wrong format in Subnet field'); + $result = false; + } else { + $result = db_process_sql_update('trecon_task', $values, $where); + } + } else { + $result = db_process_sql_update('trecon_task', $values, $where); + } + } else { + $result = false; + } + + if ($result !== false) { + ui_print_success_message(__('Successfully updated recon task')); + } else { + ui_print_error_message(__('Error updating recon task')); + echo $reason; + include 'manage_recontask_form.php'; + return; + } } // -------------------------------- // CREATE A RECON TASK // -------------------------------- -if (isset($_GET["create"])) { - $values = array( - 'name' => $name, - 'subnet' => $network, - 'description' => $description, - 'id_recon_server' => $id_recon_server, - 'create_incident' => $create_incident, - 'id_group' => $id_group, - 'id_network_profile' => $id_network_profile, - 'interval_sweep' => $interval, - 'id_os' => $id_os, - 'recon_ports' => $recon_ports, - 'snmp_community' => $snmp_community, - 'id_recon_script' => $id_recon_script, - 'field1' => $field1, - 'field2' => $field2, - 'field3' => $field3, - 'field4' => $field4, - 'os_detect' => $os_detect, - 'resolve_names' => $resolve_names, - 'parent_detection' => $parent_detection, - 'parent_recursion' => $parent_recursion, - 'macros' => $macros, - 'alias_as_name' => $alias_as_name, - 'snmp_enabled' => $snmp_enabled, - 'vlan_enabled' => $vlan_enabled, - 'snmp_version' => $snmp_version - ); +if (isset($_GET['create'])) { + $values = [ + 'name' => $name, + 'subnet' => $network, + 'description' => $description, + 'id_recon_server' => $id_recon_server, + 'create_incident' => $create_incident, + 'id_group' => $id_group, + 'id_network_profile' => $id_network_profile, + 'interval_sweep' => $interval, + 'id_os' => $id_os, + 'recon_ports' => $recon_ports, + 'snmp_community' => $snmp_community, + 'id_recon_script' => $id_recon_script, + 'field1' => $field1, + 'field2' => $field2, + 'field3' => $field3, + 'field4' => $field4, + 'os_detect' => $os_detect, + 'resolve_names' => $resolve_names, + 'parent_detection' => $parent_detection, + 'parent_recursion' => $parent_recursion, + 'macros' => $macros, + 'alias_as_name' => $alias_as_name, + 'snmp_enabled' => $snmp_enabled, + 'vlan_enabled' => $vlan_enabled, + 'snmp_version' => $snmp_version, + ]; - $values_v3 = array( - 'snmp_auth_user' => $snmp3_auth_user, - 'snmp_auth_pass' => $snmp3_auth_pass, - 'snmp_privacy_method' => $snmp3_privacy_method, - 'snmp_privacy_pass' => $snmp3_privacy_pass, - 'snmp_auth_method' => $snmp3_auth_method, - 'snmp_security_level' => $snmp3_security_level - ); - if($values['snmp_version'] == '1' || $values['snmp_version'] == '2' || $values['snmp_version'] == '2c'){ - $values_v3 = array( - 'snmp_auth_user' => '', - 'snmp_auth_pass' => '', - 'snmp_privacy_method' => '', - 'snmp_privacy_pass' => '', - 'snmp_auth_method' => '', - 'snmp_security_level' => '' - ); - } - if ($values['snmp_version'] == '3'){ - $values['vlan_enabled'] = 0; - } + $values_v3 = [ + 'snmp_auth_user' => $snmp3_auth_user, + 'snmp_auth_pass' => $snmp3_auth_pass, + 'snmp_privacy_method' => $snmp3_privacy_method, + 'snmp_privacy_pass' => $snmp3_privacy_pass, + 'snmp_auth_method' => $snmp3_auth_method, + 'snmp_security_level' => $snmp3_security_level, + ]; + if ($values['snmp_version'] == '1' || $values['snmp_version'] == '2' || $values['snmp_version'] == '2c') { + $values_v3 = [ + 'snmp_auth_user' => '', + 'snmp_auth_pass' => '', + 'snmp_privacy_method' => '', + 'snmp_privacy_pass' => '', + 'snmp_auth_method' => '', + 'snmp_security_level' => '', + ]; + } - $values = array_merge($values, $values_v3); + if ($values['snmp_version'] == '3') { + $values['vlan_enabled'] = 0; + } - $name = io_safe_output($name); - $name = trim($name, ' '); - $name = io_safe_input($name); - $reason = ""; + $values = array_merge($values, $values_v3); - if ($name != "") { + $name = io_safe_output($name); + $name = trim($name, ' '); + $name = io_safe_input($name); + $reason = ''; - $name_exists = (bool) db_get_value ('name', 'trecon_task', 'name', $name); + if ($name != '') { + $name_exists = (bool) db_get_value('name', 'trecon_task', 'name', $name); - if (empty($id_recon_script)) { - if ($name_exists && (!preg_match("/[0-9]+.+[0-9]+.+[0-9]+.+[0-9]+\/+[0-9]/", $network))){ - $reason = __('Recon-task name already exists and incorrect format in Subnet field'); - $result = false; - } - else if (!preg_match("/[0-9]+.+[0-9]+.+[0-9]+.+[0-9]+\/+[0-9]/", $network)){ - $reason = __('Wrong format in Subnet field'); - $result = false; - } - else if ($name_exists){ - $reason = __('Recon-task name already exists'); - $result = false; - } - else{ - $result = db_process_sql_insert('trecon_task', $values); - } - } - else { - if ($name_exists){ - $reason = __('Recon-task name already exists'); - $result = false; - } - else{ - $result = db_process_sql_insert('trecon_task', $values); - } - } - } - else { - $reason = 'The field "Task name" is empty'; - $result = false; - } + if (empty($id_recon_script)) { + if ($name_exists && (!preg_match('/[0-9]+.+[0-9]+.+[0-9]+.+[0-9]+\/+[0-9]/', $network))) { + $reason = __('Recon-task name already exists and incorrect format in Subnet field'); + $result = false; + } else if (!preg_match('/[0-9]+.+[0-9]+.+[0-9]+.+[0-9]+\/+[0-9]/', $network)) { + $reason = __('Wrong format in Subnet field'); + $result = false; + } else if ($name_exists) { + $reason = __('Recon-task name already exists'); + $result = false; + } else { + $result = db_process_sql_insert('trecon_task', $values); + } + } else { + if ($name_exists) { + $reason = __('Recon-task name already exists'); + $result = false; + } else { + $result = db_process_sql_insert('trecon_task', $values); + } + } + } else { + $reason = 'The field "Task name" is empty'; + $result = false; + } - if ($result !== false) { - ui_print_success_message(__('Successfully created recon task')); - } - else { - ui_print_error_message(__('Error creating recon task')); - echo $reason; - include('manage_recontask_form.php'); - return; - } + if ($result !== false) { + ui_print_success_message(__('Successfully created recon task')); + } else { + ui_print_error_message(__('Error creating recon task')); + echo $reason; + include 'manage_recontask_form.php'; + return; + } } // -------------------------------- // SHOW TABLE WITH ALL RECON TASKs // -------------------------------- -//Pandora Admin must see all columns -if (! check_acl ($config['id_user'], 0, "PM")) { - - $sql = sprintf('SELECT * +// Pandora Admin must see all columns +if (! check_acl($config['id_user'], 0, 'PM')) { + $sql = sprintf( + 'SELECT * FROM trecon_task RT, tusuario_perfil UP WHERE - UP.id_usuario = "%s" AND UP.id_grupo = RT.id_group', - $config['id_user']); - - $result = db_get_all_rows_sql ($sql); + UP.id_usuario = "%s" AND UP.id_grupo = RT.id_group', + $config['id_user'] + ); + + $result = db_get_all_rows_sql($sql); +} else { + $result = db_get_all_rows_in_table('trecon_task'); } -else { - $result = db_get_all_rows_in_table('trecon_task'); -} -$color=1; + +$color = 1; if ($result !== false) { - $table = new StdClass(); - $table->head = array (__('Name'), __('Network'), __('Mode'), __('Group'), __('SNMP Version'), __('Incident'), __('OS'), __('Interval'), __('Ports'), __('Action')); - $table->align = array ("left","left","left","left","left","left","left","left"); - $table->width = "100%"; - $table->cellpadding = 4; - $table->cellspacing = 4; - $table->class = "databox data"; - $table->data = array (); - - $table->style[8] = 'text-align: left;'; - $table->size[8] = '15%'; - - foreach ($result as $row) { - if (in_array($row["id_group"], $user_groups_r)){ - $data = array(); - $data[0] = $row["name"]; - if ($row["id_recon_script"] == 0) - $data[1] = $row["subnet"]; - else - $data[1] = "-"; - - - if ($row["id_recon_script"] == 0) { - // Network recon task - $data[2] = html_print_image ("images/network.png", true, array ("title" => __('Network recon task')))."  "; - $data[2] .= network_profiles_get_name ($row["id_network_profile"]); - $mode_name = ''; - } - else { - // APP recon task - $data[2] = html_print_image ("images/plugin.png", true). "  "; - $mode_name = db_get_sql (sprintf("SELECT name FROM trecon_script WHERE id_recon_script = %d", $row["id_recon_script"])); - $data[2] .= $mode_name; - } - - - // GROUP - if ($row["id_recon_script"] == 0) { - $data[3] = ui_print_group_icon ($row["id_group"], true); - } - else { - $data[3] = "-"; - } - - //SNMP VERSION - if ($row["snmp_version"] == '1'){ - $data[4] = "v. 1"; - } - elseif($row["snmp_version"] == '2'){ - $data[4] = "v. 2"; - } - elseif($row["snmp_version"] == '2c'){ - $data[4] = "v. 2c"; - } - elseif($row["snmp_version"] == '3'){ - $data[4] = "v. 3"; - } - - + $table = new StdClass(); + $table->head = [ + __('Name'), + __('Network'), + __('Mode'), + __('Group'), + __('SNMP Version'), + __('Incident'), + __('OS'), + __('Interval'), + __('Ports'), + __('Action'), + ]; + $table->align = [ + 'left', + 'left', + 'left', + 'left', + 'left', + 'left', + 'left', + 'left', + ]; + $table->width = '100%'; + $table->cellpadding = 4; + $table->cellspacing = 4; + $table->class = 'databox data'; + $table->data = []; - // INCIDENT - $data[5] = (($row["create_incident"] == 1) ? __('Yes') : __('No')); - - // OS - if ($row["id_recon_script"] == 0) { - $data[6] =(($row["id_os"] > 0) ? ui_print_os_icon ($row["id_os"], false, true) : __('Any')); - } - else { - $data[6] = "-"; - } - // INTERVAL - if ($row["interval_sweep"]==0) - $data[7] = __("Manual"); - else - $data[7] =human_time_description_raw($row["interval_sweep"]); - - // PORTS - if ($row["id_recon_script"] == 0) { - $data[8] = substr($row["recon_ports"],0,15); - } - else { - $data[8] = "-"; - } - - // ACTION - $task_group = $row["id_group"]; + $table->style[8] = 'text-align: left;'; + $table->size[8] = '15%'; - if (in_array($task_group, $user_groups_w)){ - $data[9] = '' . html_print_image("images/eye.png", true) . ''; - $data[9] .= '' . html_print_image("images/cross.png", true, array("border" => '0')) . ''; - if($mode_name != 'IPAM Recon'){ - $data[9] .= '' .html_print_image("images/config.png", true) . ''; - } else { - $sql_ipam = 'select id from tipam_network where id_recon_task =' . $row["id_rt"]; - $id_recon_ipam = db_get_sql($sql_ipam); - $data[9] .= '' . html_print_image("images/config.png", true) . ''; - } - if($row["disabled"] == 0) { - $data[9] .= '' .html_print_image("images/lightbulb.png", true) . ''; - } - else { - $data[9] .= '' .html_print_image("images/lightbulb_off.png", true) . ''; - } - } - - $table->data[] = $data; - } - } - - html_print_table ($table); - unset ($table); -} -else { - echo '
    '.__('There are no recon task configured').'
    '; + foreach ($result as $row) { + if (in_array($row['id_group'], $user_groups_r)) { + $data = []; + $data[0] = $row['name']; + if ($row['id_recon_script'] == 0) { + $data[1] = $row['subnet']; + } else { + $data[1] = '-'; + } + + + if ($row['id_recon_script'] == 0) { + // Network recon task + $data[2] = html_print_image('images/network.png', true, ['title' => __('Network recon task')]).'  '; + $data[2] .= network_profiles_get_name($row['id_network_profile']); + $mode_name = ''; + } else { + // APP recon task + $data[2] = html_print_image('images/plugin.png', true).'  '; + $mode_name = db_get_sql(sprintf('SELECT name FROM trecon_script WHERE id_recon_script = %d', $row['id_recon_script'])); + $data[2] .= $mode_name; + } + + + // GROUP + if ($row['id_recon_script'] == 0) { + $data[3] = ui_print_group_icon($row['id_group'], true); + } else { + $data[3] = '-'; + } + + // SNMP VERSION + if ($row['snmp_version'] == '1') { + $data[4] = 'v. 1'; + } else if ($row['snmp_version'] == '2') { + $data[4] = 'v. 2'; + } else if ($row['snmp_version'] == '2c') { + $data[4] = 'v. 2c'; + } else if ($row['snmp_version'] == '3') { + $data[4] = 'v. 3'; + } + + + + // INCIDENT + $data[5] = (($row['create_incident'] == 1) ? __('Yes') : __('No')); + + // OS + if ($row['id_recon_script'] == 0) { + $data[6] = (($row['id_os'] > 0) ? ui_print_os_icon($row['id_os'], false, true) : __('Any')); + } else { + $data[6] = '-'; + } + + // INTERVAL + if ($row['interval_sweep'] == 0) { + $data[7] = __('Manual'); + } else { + $data[7] = human_time_description_raw($row['interval_sweep']); + } + + // PORTS + if ($row['id_recon_script'] == 0) { + $data[8] = substr($row['recon_ports'], 0, 15); + } else { + $data[8] = '-'; + } + + // ACTION + $task_group = $row['id_group']; + + if (in_array($task_group, $user_groups_w)) { + $data[9] = ''.html_print_image('images/eye.png', true).''; + $data[9] .= ''.html_print_image('images/cross.png', true, ['border' => '0']).''; + if ($mode_name != 'IPAM Recon') { + $data[9] .= ''.html_print_image('images/config.png', true).''; + } else { + $sql_ipam = 'select id from tipam_network where id_recon_task ='.$row['id_rt']; + $id_recon_ipam = db_get_sql($sql_ipam); + $data[9] .= ''.html_print_image('images/config.png', true).''; + } + + if ($row['disabled'] == 0) { + $data[9] .= ''.html_print_image('images/lightbulb.png', true).''; + } else { + $data[9] .= ''.html_print_image('images/lightbulb_off.png', true).''; + } + } + + $table->data[] = $data; + } + } + + html_print_table($table); + unset($table); +} else { + echo '
    '.__('There are no recon task configured').'
    '; } echo '
    '; echo '
    '; -echo html_print_submit_button (__('Create'),"crt",false,'class="sub next"',true); +echo html_print_submit_button(__('Create'), 'crt', false, 'class="sub next"', true); echo '
    '; -echo "
    "; -?> +echo '
    '; diff --git a/pandora_console/godmode/servers/manage_recontask_form.php b/pandora_console/godmode/servers/manage_recontask_form.php index f5865d1470..c47416afd7 100644 --- a/pandora_console/godmode/servers/manage_recontask_form.php +++ b/pandora_console/godmode/servers/manage_recontask_form.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,199 +11,204 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Management' + ); + include 'general/noaccess.php'; + return; } -require_once ($config['homedir'].'/include/functions_users.php'); +require_once $config['homedir'].'/include/functions_users.php'; $user_groups = users_get_groups(false, 'AW', true, false, null, 'id_grupo'); $user_groups = array_keys($user_groups); -if (is_ajax ()) { - $get_explanation = (bool) get_parameter('get_explanation', 0); - - if ($get_explanation) { - $id = (int) get_parameter('id', 0); - - $explanation = db_get_value('description', 'trecon_script', 'id_recon_script', $id); - - echo io_safe_output($explanation); - - return; - } - - $get_recon_script_macros = get_parameter('get_recon_script_macros'); - if ($get_recon_script_macros) { - $id_recon_script = (int) get_parameter('id'); - $id_recon_task = (int) get_parameter('id_rt'); - - if (!empty($id_recon_task) && empty($id_recon_script)) { - $recon_script_macros = db_get_value('macros', 'trecon_task', 'id_rt', $id_recon_task); - } - else if (!empty($id_recon_task)) { - $recon_task_id_rs = (int) db_get_value('id_recon_script', 'trecon_task', 'id_rt', $id_recon_task); - - if ($id_recon_script == $recon_task_id_rs) { - $recon_script_macros = db_get_value('macros', 'trecon_task', 'id_rt', $id_recon_task); - } - else { - $recon_script_macros = db_get_value('macros', 'trecon_script', 'id_recon_script', $id_recon_script); - } - } - else if (!empty($id_recon_script)) { - $recon_script_macros = db_get_value('macros', 'trecon_script', 'id_recon_script', $id_recon_script); - } - else { - $recon_script_macros = array(); - } - - $macros = array(); - $macros['base64'] = base64_encode($recon_script_macros); - $macros['array'] = json_decode($recon_script_macros,true); - - echo io_json_mb_encode($macros); - return; - } - - return; +if (is_ajax()) { + $get_explanation = (bool) get_parameter('get_explanation', 0); + + if ($get_explanation) { + $id = (int) get_parameter('id', 0); + + $explanation = db_get_value('description', 'trecon_script', 'id_recon_script', $id); + + echo io_safe_output($explanation); + + return; + } + + $get_recon_script_macros = get_parameter('get_recon_script_macros'); + if ($get_recon_script_macros) { + $id_recon_script = (int) get_parameter('id'); + $id_recon_task = (int) get_parameter('id_rt'); + + if (!empty($id_recon_task) && empty($id_recon_script)) { + $recon_script_macros = db_get_value('macros', 'trecon_task', 'id_rt', $id_recon_task); + } else if (!empty($id_recon_task)) { + $recon_task_id_rs = (int) db_get_value('id_recon_script', 'trecon_task', 'id_rt', $id_recon_task); + + if ($id_recon_script == $recon_task_id_rs) { + $recon_script_macros = db_get_value('macros', 'trecon_task', 'id_rt', $id_recon_task); + } else { + $recon_script_macros = db_get_value('macros', 'trecon_script', 'id_recon_script', $id_recon_script); + } + } else if (!empty($id_recon_script)) { + $recon_script_macros = db_get_value('macros', 'trecon_script', 'id_recon_script', $id_recon_script); + } else { + $recon_script_macros = []; + } + + $macros = []; + $macros['base64'] = base64_encode($recon_script_macros); + $macros['array'] = json_decode($recon_script_macros, true); + + echo io_json_mb_encode($macros); + return; + } + + return; } // Edit mode -if (isset($_GET["update"]) || (isset($_GET["upd"]))) { - - $update_recon = true; - if (isset($_GET["upd"])) { - if ($_GET["upd"] != "update") { - $update_recon = false; - } - else { - $id_rt = get_parameter("upd"); - } - } - - if ($update_recon) { - if (!isset($id_rt)) { - $id_rt = (int) get_parameter_get ("update"); - } - $row = db_get_row ("trecon_task", "id_rt", $id_rt); - $name = $row["name"]; - $network = $row["subnet"]; - $id_recon_server = $row["id_recon_server"]; - $description = $row["description"]; - $interval = $row["interval_sweep"]; - $id_group = $row["id_group"]; - $create_incident = $row["create_incident"]; - $id_network_profile = $row["id_network_profile"]; - $id_os = $row["id_os"]; - $recon_ports = $row["recon_ports"]; - $snmp_community = $row["snmp_community"]; - $snmp_version = $row["snmp_version"]; - $snmp3_auth_user = $row["snmp_auth_user"]; - $snmp3_auth_pass = $row["snmp_auth_pass"]; - $snmp3_privacy_method = $row["snmp_privacy_method"]; - $snmp3_privacy_pass = $row["snmp_privacy_pass"]; - $snmp3_auth_method = $row["snmp_auth_method"]; - $snmp3_security_level = $row["snmp_security_level"]; - $id_recon_script = $row["id_recon_script"]; - $field1 = $row["field1"]; - $field2 = $row["field2"]; - $field3 = $row["field3"]; - $field4 = $row["field4"]; - if ($id_recon_script == 0) - $mode = "network_sweep"; - else - $mode = "recon_script"; - $os_detect = $row["os_detect"]; - $resolve_names = $row["resolve_names"]; - $os_detect = $row["os_detect"]; - $parent_detection = $row["parent_detection"]; - $parent_recursion = $row["parent_recursion"]; - $macros = $row["macros"]; - $alias_as_name = $row["alias_as_name"]; - $snmp_enabled = $row["snmp_enabled"]; - $vlan_enabled = $row["vlan_enabled"]; - - $name_script = db_get_value('name', - 'trecon_script', 'id_recon_script', $id_recon_script); +if (isset($_GET['update']) || (isset($_GET['upd']))) { + $update_recon = true; + if (isset($_GET['upd'])) { + if ($_GET['upd'] != 'update') { + $update_recon = false; + } else { + $id_rt = get_parameter('upd'); + } + } - if (! in_array($id_group, $user_groups)){ - db_pandora_audit("ACL Violation", - "Trying to access Recon Task Management"); - require ("general/noaccess.php"); - return; - } - } -} -elseif (isset($_GET["create"]) || isset($_GET["crt"])) { - $create_recon = true; - if (isset ($_GET["crt"])) { - if ($_GET["crt"] != "Create") { - $create_recon = false; - } - } - - if ($create_recon) { - $id_rt = -1; - $name = get_parameter('name'); - $network = get_parameter('network'); - $description = get_parameter('description'); - $id_recon_server = 0; - $interval = 0; - $id_group = 0; - $create_incident = 1; - $snmp_community = "public"; - $snmp3_auth_user = ''; - $snmp3_auth_pass = ''; - $snmp_version = 1; - $snmp3_privacy_method = ''; - $snmp3_privacy_pass = ''; - $snmp3_auth_method = ''; - $snmp3_security_level = ''; - $id_network_profile = 0; - $id_os = -1; // Any - $recon_ports = ""; // Any - $field1 = ""; - $field2 = ""; - $field3 = ""; - $field4 = ""; - $id_recon_script = 0; - $mode = "network_sweep"; - $os_detect = 0; - $resolve_names = 0; - $parent_detection = 1; - $parent_recursion = 5; - $macros = ''; - $alias_as_name = 0; - $snmp_enabled = 0; - $vlan_enabled = 0; - } + if ($update_recon) { + if (!isset($id_rt)) { + $id_rt = (int) get_parameter_get('update'); + } - $modify = false; - if (($name != '') || ($network != '')){ - $modify = true; - } + $row = db_get_row('trecon_task', 'id_rt', $id_rt); + $name = $row['name']; + $network = $row['subnet']; + $id_recon_server = $row['id_recon_server']; + $description = $row['description']; + $interval = $row['interval_sweep']; + $id_group = $row['id_group']; + $create_incident = $row['create_incident']; + $id_network_profile = $row['id_network_profile']; + $id_os = $row['id_os']; + $recon_ports = $row['recon_ports']; + $snmp_community = $row['snmp_community']; + $snmp_version = $row['snmp_version']; + $snmp3_auth_user = $row['snmp_auth_user']; + $snmp3_auth_pass = $row['snmp_auth_pass']; + $snmp3_privacy_method = $row['snmp_privacy_method']; + $snmp3_privacy_pass = $row['snmp_privacy_pass']; + $snmp3_auth_method = $row['snmp_auth_method']; + $snmp3_security_level = $row['snmp_security_level']; + $id_recon_script = $row['id_recon_script']; + $field1 = $row['field1']; + $field2 = $row['field2']; + $field3 = $row['field3']; + $field4 = $row['field4']; + if ($id_recon_script == 0) { + $mode = 'network_sweep'; + } else { + $mode = 'recon_script'; + } + + $os_detect = $row['os_detect']; + $resolve_names = $row['resolve_names']; + $os_detect = $row['os_detect']; + $parent_detection = $row['parent_detection']; + $parent_recursion = $row['parent_recursion']; + $macros = $row['macros']; + $alias_as_name = $row['alias_as_name']; + $snmp_enabled = $row['snmp_enabled']; + $vlan_enabled = $row['vlan_enabled']; + + $name_script = db_get_value( + 'name', + 'trecon_script', + 'id_recon_script', + $id_recon_script + ); + + if (! in_array($id_group, $user_groups)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Recon Task Management' + ); + include 'general/noaccess.php'; + return; + } + } +} else if (isset($_GET['create']) || isset($_GET['crt'])) { + $create_recon = true; + if (isset($_GET['crt'])) { + if ($_GET['crt'] != 'Create') { + $create_recon = false; + } + } + + if ($create_recon) { + $id_rt = -1; + $name = get_parameter('name'); + $network = get_parameter('network'); + $description = get_parameter('description'); + $id_recon_server = 0; + $interval = 0; + $id_group = 0; + $create_incident = 1; + $snmp_community = 'public'; + $snmp3_auth_user = ''; + $snmp3_auth_pass = ''; + $snmp_version = 1; + $snmp3_privacy_method = ''; + $snmp3_privacy_pass = ''; + $snmp3_auth_method = ''; + $snmp3_security_level = ''; + $id_network_profile = 0; + $id_os = -1; + // Any + $recon_ports = ''; + // Any + $field1 = ''; + $field2 = ''; + $field3 = ''; + $field4 = ''; + $id_recon_script = 0; + $mode = 'network_sweep'; + $os_detect = 0; + $resolve_names = 0; + $parent_detection = 1; + $parent_recursion = 5; + $macros = ''; + $alias_as_name = 0; + $snmp_enabled = 0; + $vlan_enabled = 0; + } + + $modify = false; + if (($name != '') || ($network != '')) { + $modify = true; + } } -if (!$modify){ - // Headers - ui_print_page_header (__('Manage recontask'), "", false, "recontask", true); +if (!$modify) { + // Headers + ui_print_page_header(__('Manage recontask'), '', false, 'recontask', true); } $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; if ($is_windows) { - echo '
    '; - echo __('Warning') . ": " . __("By default, in Windows, %s only support Standard network sweep, not custom scripts", get_product_name()); - echo '
    '; + echo '
    '; + echo __('Warning').': '.__('By default, in Windows, %s only support Standard network sweep, not custom scripts', get_product_name()); + echo '
    '; } $table = new stdClass(); @@ -212,401 +216,457 @@ $table->id = 'table_recon'; $table->width = '100%'; $table->cellspacing = 4; $table->cellpadding = 4; -$table->class = "databox filters"; +$table->class = 'databox filters'; -$table->rowclass[3] = "network_sweep"; -$table->rowclass[5] = "network_sweep"; -$table->rowclass[7] = "network_sweep"; -$table->rowclass[8] = "network_sweep"; -$table->rowclass[11] = "network_sweep"; -$table->rowclass[12] = "network_sweep"; -$table->rowclass[18] = "network_sweep"; -$table->rowclass[19] = "network_sweep"; -$table->rowclass[20] = "network_sweep"; -$table->rowclass[21] = "network_sweep"; -$table->rowclass[22] = "network_sweep"; -$table->rowclass[23] = "network_sweep"; -$table->rowclass[24] = "network_sweep"; -$table->rowclass[25] = "network_sweep recon_v3"; -$table->rowclass[26] = "network_sweep recon_v3"; -$table->rowclass[27] = "network_sweep recon_v3"; -$table->rowclass[28] = "network_sweep recon_v3"; -$table->rowclass[29] = "network_sweep recon_v3"; -$table->rowclass[30] = "network_sweep recon_v3"; +$table->rowclass[3] = 'network_sweep'; +$table->rowclass[5] = 'network_sweep'; +$table->rowclass[7] = 'network_sweep'; +$table->rowclass[8] = 'network_sweep'; +$table->rowclass[11] = 'network_sweep'; +$table->rowclass[12] = 'network_sweep'; +$table->rowclass[18] = 'network_sweep'; +$table->rowclass[19] = 'network_sweep'; +$table->rowclass[20] = 'network_sweep'; +$table->rowclass[21] = 'network_sweep'; +$table->rowclass[22] = 'network_sweep'; +$table->rowclass[23] = 'network_sweep'; +$table->rowclass[24] = 'network_sweep'; +$table->rowclass[25] = 'network_sweep recon_v3'; +$table->rowclass[26] = 'network_sweep recon_v3'; +$table->rowclass[27] = 'network_sweep recon_v3'; +$table->rowclass[28] = 'network_sweep recon_v3'; +$table->rowclass[29] = 'network_sweep recon_v3'; +$table->rowclass[30] = 'network_sweep recon_v3'; -$table->rowclass[6] = "recon_script"; -$table->rowclass[13] = "recon_script"; -$table->rowclass[14] = "recon_script"; -$table->rowclass[15] = "recon_script"; -$table->rowclass[16] = "recon_script"; -$table->rowclass[17] = "recon_script"; +$table->rowclass[6] = 'recon_script'; +$table->rowclass[13] = 'recon_script'; +$table->rowclass[14] = 'recon_script'; +$table->rowclass[15] = 'recon_script'; +$table->rowclass[16] = 'recon_script'; +$table->rowclass[17] = 'recon_script'; // Name -$table->data[0][0] = "" . __('Task name') . ""; -$table->data[0][1] = html_print_input_text ('name', $name, '', 25, 0, true); +$table->data[0][0] = ''.__('Task name').''; +$table->data[0][1] = html_print_input_text('name', $name, '', 25, 0, true); // Recon server -$table->data[1][0] = "" . __('Recon server') . - ui_print_help_tip( - __('You must select a Recon Server for the Task, otherwise the Recon Task will never run'), true); +$table->data[1][0] = ''.__('Recon server').ui_print_help_tip( + __('You must select a Recon Server for the Task, otherwise the Recon Task will never run'), + true +); $sql = 'SELECT id_server, name FROM tserver WHERE server_type = 3 ORDER BY name'; -$table->data[1][1] = html_print_select_from_sql ($sql, "id_recon_server", $id_recon_server, '', '', '', true); +$table->data[1][1] = html_print_select_from_sql($sql, 'id_recon_server', $id_recon_server, '', '', '', true); -$fields['network_sweep'] = __("Network sweep"); -if (!$is_windows) - $fields['recon_script'] = __("Custom script"); - - -$table->data[2][0] = "".__('Mode').""; -$table->data[2][1] = html_print_select ($fields, "mode", $mode, '', '', 0, true); - - -// Network -$table->data[3][0] = "" . __('Network') . ""; -$table->data[3][0] .= ui_print_help_tip (__('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'), true); -$table->data[3][1] = html_print_input_text ('network', $network, '', 25, 0, true); - -// Interval - -$interv_manual = 0; -if ((int)$interval == 0) { - $interv_manual = 1; +$fields['network_sweep'] = __('Network sweep'); +if (!$is_windows) { + $fields['recon_script'] = __('Custom script'); } -$table->data[4][0] = "".__('Interval'); -$table->data[4][0] .= ui_print_help_tip (__('Manual interval means that it will be executed only On-demand'), true); -$values = array (0 => __('Defined'), 1 => __('Manual')); -$table->data[4][1] = html_print_select ($values, "interval_manual_defined", $interv_manual, '','','',true); +$table->data[2][0] = ''.__('Mode').''; +$table->data[2][1] = html_print_select($fields, 'mode', $mode, '', '', 0, true); + + +// Network +$table->data[3][0] = ''.__('Network').''; +$table->data[3][0] .= ui_print_help_tip(__('You can specify several networks, separated by commas, for example: 192.168.50.0/24,192.168.60.0/24'), true); +$table->data[3][1] = html_print_input_text('network', $network, '', 25, 0, true); + +// Interval +$interv_manual = 0; +if ((int) $interval == 0) { + $interv_manual = 1; +} + +$table->data[4][0] = ''.__('Interval'); +$table->data[4][0] .= ui_print_help_tip(__('Manual interval means that it will be executed only On-demand'), true); + +$values = [ + 0 => __('Defined'), + 1 => __('Manual'), +]; +$table->data[4][1] = html_print_select($values, 'interval_manual_defined', $interv_manual, '', '', '', true); $table->data[4][1] .= ''; -$table->data[4][1] .= html_print_extended_select_for_time ('interval' , $interval, '', '', '0', false, true, false, false); -$table->data[4][1] .= ui_print_help_tip (__('The minimum recomended interval for Recon Task is 5 minutes'), true); +$table->data[4][1] .= html_print_extended_select_for_time('interval', $interval, '', '', '0', false, true, false, false); +$table->data[4][1] .= ui_print_help_tip(__('The minimum recomended interval for Recon Task is 5 minutes'), true); $table->data[4][1] .= ''; // Module template -$table->data[5][0] = "" . __('Module template') . ""; +$table->data[5][0] = ''.__('Module template').''; $sql = 'SELECT id_np, name FROM tnetwork_profile ORDER BY name'; -$table->data[5][1] = html_print_select_from_sql ($sql, "id_network_profile", $id_network_profile, '', __('None'), 0, true); +$table->data[5][1] = html_print_select_from_sql($sql, 'id_network_profile', $id_network_profile, '', __('None'), 0, true); // Recon script $data[1] = ''; -$table->data[6][0] = "" . __('Recon script') . ""; +$table->data[6][0] = ''.__('Recon script').''; $sql = "SELECT id_recon_script, name FROM trecon_script WHERE name <> 'IPAM Recon' ORDER BY name"; -if ($name_script != "IPAM Recon") { - $table->data[6][1] = html_print_select_from_sql ($sql, "id_recon_script", $id_recon_script, '', '', '', true); - $table->data[6][1] .= ""; - $table->data[6][1] .= $data[1] .= html_print_input_hidden('macros', base64_encode($macros),true); -} -else { - $table->data[6][1] = "IPAM Recon"; +if ($name_script != 'IPAM Recon') { + $table->data[6][1] = html_print_select_from_sql($sql, 'id_recon_script', $id_recon_script, '', '', '', true); + $table->data[6][1] .= "'; + $table->data[6][1] .= $data[1] .= html_print_input_hidden('macros', base64_encode($macros), true); +} else { + $table->data[6][1] = 'IPAM Recon'; } // OS -$table->data[7][0] = "" . __('OS') . ""; +$table->data[7][0] = ''.__('OS').''; $sql = 'SELECT id_os, name FROM tconfig_os ORDER BY name'; -$table->data[7][1] = html_print_select_from_sql ($sql, "id_os", $id_os, '', __('Any'), -1, true); +$table->data[7][1] = html_print_select_from_sql($sql, 'id_os', $id_os, '', __('Any'), -1, true); // Recon ports -$table->data[8][0] = "" . __('Ports') . ""; -$table->data[8][1] = html_print_input_text ('recon_ports', $recon_ports, '', 25, 0, true); +$table->data[8][0] = ''.__('Ports').''; +$table->data[8][1] = html_print_input_text('recon_ports', $recon_ports, '', 25, 0, true); $table->data[8][1] .= ui_print_help_tip( - __('Ports defined like: 80 or 80,443,512 or even 0-1024 (Like Nmap command line format). If dont want to do a sweep using portscan, left it in blank'), true); + __('Ports defined like: 80 or 80,443,512 or even 0-1024 (Like Nmap command line format). If dont want to do a sweep using portscan, left it in blank'), + true +); // Group -$table->data[9][0] = "".__('Group'); -$groups = users_get_groups (false, "PM", false); -$table->data[9][1] = html_print_select_groups(false, "PM", false, 'id_group', $id_group, '', '', 0, true); +$table->data[9][0] = ''.__('Group'); +$groups = users_get_groups(false, 'PM', false); +$table->data[9][1] = html_print_select_groups(false, 'PM', false, 'id_group', $id_group, '', '', 0, true); // Incident -$values = array (0 => __('No'), 1 => __('Yes')); -$table->data[10][0] = "".__('Incident'); -$table->data[10][1] = html_print_select ($values, "create_incident", $create_incident, - '','','',true) . ' ' . ui_print_help_tip (__('Choose if the discovery of a new system creates an incident or not.'), true); +$values = [ + 0 => __('No'), + 1 => __('Yes'), +]; +$table->data[10][0] = ''.__('Incident'); +$table->data[10][1] = html_print_select( + $values, + 'create_incident', + $create_incident, + '', + '', + '', + true +).' '.ui_print_help_tip(__('Choose if the discovery of a new system creates an incident or not.'), true); -//snmp_enabled -$table->data[11][0] = "".__('SNMP enabled'); -$table->data[11][1] = html_print_checkbox ('snmp_enabled', 1, $snmp_enabled, true); +// snmp_enabled +$table->data[11][0] = ''.__('SNMP enabled'); +$table->data[11][1] = html_print_checkbox('snmp_enabled', 1, $snmp_enabled, true); // SNMP default community -$table->data[12][0] = "".__('SNMP Default community'); -$table->data[12][0] .= ui_print_help_tip (__('You can specify several values, separated by commas, for example: public,mysecret,1234'), true); -$table->data[12][1] = html_print_input_text ('snmp_community', $snmp_community, '', 35, 0, true); - -//SNMP version +$table->data[12][0] = ''.__('SNMP Default community'); +$table->data[12][0] .= ui_print_help_tip(__('You can specify several values, separated by commas, for example: public,mysecret,1234'), true); +$table->data[12][1] = html_print_input_text('snmp_community', $snmp_community, '', 35, 0, true); +// SNMP version $snmp_versions['1'] = 'v. 1'; $snmp_versions['2'] = 'v. 2'; $snmp_versions['2c'] = 'v. 2c'; $snmp_versions['3'] = 'v. 3'; -$table->data[24][0] ="". _('SNMP version'); -$table->data[24][1] = html_print_select ($snmp_versions, 'snmp_version', $snmp_version, '', '', 0, true); +$table->data[24][0] = ''._('SNMP version'); +$table->data[24][1] = html_print_select($snmp_versions, 'snmp_version', $snmp_version, '', '', 0, true); -$table->data[25][0] ="".__('Auth user'); -$table->data[25][1] = html_print_input_text ('snmp_auth_user', $snmp3_auth_user, '', 15, 60, true, '', - false, '', ''); -$table->data[26][0] ="". __('Auth password') . ui_print_help_tip(__("The pass length must be eight character minimum."), true); -$table->data[26][1] = html_print_input_password ('snmp_auth_pass', $snmp3_auth_pass, '', 15, 60, true, '', - false, ''); +$table->data[25][0] = ''.__('Auth user'); +$table->data[25][1] = html_print_input_text( + 'snmp_auth_user', + $snmp3_auth_user, + '', + 15, + 60, + true, + '', + false, + '', + '' +); +$table->data[26][0] = ''.__('Auth password').ui_print_help_tip(__('The pass length must be eight character minimum.'), true); +$table->data[26][1] = html_print_input_password( + 'snmp_auth_pass', + $snmp3_auth_pass, + '', + 15, + 60, + true, + '', + false, + '' +); $table->data[26][1] .= html_print_input_hidden_extended('active_snmp_v3', 0, 'active_snmp_v3_mmen', true); -$table->data[27][0] ="". __('Privacy method'); -$table->data[27][1] = html_print_select(array('DES' => __('DES'), 'AES' => __('AES')), 'snmp_privacy_method', $snmp3_privacy_method, '', '', '', true, false, false, '', ''); -$table->data[28][0] ="". __('Privacy pass') . ui_print_help_tip(__("The pass length must be eight character minimum."), true); -$table->data[28][1] = html_print_input_password ('snmp_privacy_pass', $snmp3_privacy_pass, '', 15, 60, true, '', - false, ''); -$table->data[29][0] ="". __('Auth method'); -$table->data[29][1] = html_print_select(array('MD5' => __('MD5'), 'SHA' => __('SHA')), 'snmp_auth_method', $snmp3_auth_method, '', '', '', true, false, false, '', ''); -$table->data[30][0] ="". __('Security level'); -$table->data[30][1] = html_print_select(array('noAuthNoPriv' => __('Not auth and not privacy method'), - 'authNoPriv' => __('Auth and not privacy method'), 'authPriv' => __('Auth and privacy method')), 'snmp_security_level', $snmp3_security_level, '', '', '', true, false, false, '', ''); +$table->data[27][0] = ''.__('Privacy method'); +$table->data[27][1] = html_print_select(['DES' => __('DES'), 'AES' => __('AES')], 'snmp_privacy_method', $snmp3_privacy_method, '', '', '', true, false, false, '', ''); +$table->data[28][0] = ''.__('Privacy pass').ui_print_help_tip(__('The pass length must be eight character minimum.'), true); +$table->data[28][1] = html_print_input_password( + 'snmp_privacy_pass', + $snmp3_privacy_pass, + '', + 15, + 60, + true, + '', + false, + '' +); +$table->data[29][0] = ''.__('Auth method'); +$table->data[29][1] = html_print_select(['MD5' => __('MD5'), 'SHA' => __('SHA')], 'snmp_auth_method', $snmp3_auth_method, '', '', '', true, false, false, '', ''); +$table->data[30][0] = ''.__('Security level'); +$table->data[30][1] = html_print_select( + [ + 'noAuthNoPriv' => __('Not auth and not privacy method'), + 'authNoPriv' => __('Auth and not privacy method'), + 'authPriv' => __('Auth and privacy method'), + ], + 'snmp_security_level', + $snmp3_security_level, + '', + '', + '', + true, + false, + false, + '', + '' +); // Explanation $explanation = db_get_value('description', 'trecon_script', 'id_recon_script', $id_recon_script); -$table->data[13][0] = "" . __('Explanation') . ""; -$table->data[13][1] = "" . html_print_textarea('explanation', 4, 60, $explanation, 'style="width: 388px;"', true); +$table->data[13][0] = ''.__('Explanation').''; +$table->data[13][1] = "'.html_print_textarea('explanation', 4, 60, $explanation, 'style="width: 388px;"', true); // A hidden "model row" to clone it from javascript to add fields dynamicaly -$data = array (); +$data = []; $data[0] = 'macro_desc'; -$data[0] .= ui_print_help_tip ('macro_help', true); -$data[1] = html_print_input_text ('macro_name', 'macro_value', '', 100, 255, true); +$data[0] .= ui_print_help_tip('macro_help', true); +$data[1] = html_print_input_text('macro_name', 'macro_value', '', 100, 255, true); $table->colspan['macro_field'][1] = 3; $table->rowstyle['macro_field'] = 'display:none'; $table->data['macro_field'] = $data; // If there are $macros, we create the form fields if (!empty($macros)) { - $macros = json_decode($macros, true); - - foreach ($macros as $k => $m) { - $data = array (); - $data[0] = "" . $m['desc'] . ""; - if (!empty($m['help'])) { - $data[0] .= ui_print_help_tip ($m['help'], true); - } - if($m['hide']) { - $data[1] = html_print_input_password($m['macro'], $m['value'], '', 100, 255, true); - } - else { - $data[1] = html_print_input_text($m['macro'], $m['value'], '', 100, 255, true); - } - $table->colspan['macro'.$m['macro']][1] = 3; - $table->rowclass['macro'.$m['macro']] = 'macro_field'; - - $table->data['macro'.$m['macro']] = $data; - } + $macros = json_decode($macros, true); + + foreach ($macros as $k => $m) { + $data = []; + $data[0] = ''.$m['desc'].''; + if (!empty($m['help'])) { + $data[0] .= ui_print_help_tip($m['help'], true); + } + + if ($m['hide']) { + $data[1] = html_print_input_password($m['macro'], $m['value'], '', 100, 255, true); + } else { + $data[1] = html_print_input_text($m['macro'], $m['value'], '', 100, 255, true); + } + + $table->colspan['macro'.$m['macro']][1] = 3; + $table->rowclass['macro'.$m['macro']] = 'macro_field'; + + $table->data['macro'.$m['macro']] = $data; + } } // Comments -$table->data[18][0] = "".__('Comments'); -$table->data[18][1] = html_print_input_text ('description', $description, '', 45, 0, true); +$table->data[18][0] = ''.__('Comments'); +$table->data[18][1] = html_print_input_text('description', $description, '', 45, 0, true); // OS detection -$table->data[19][0] = "".__('OS detection'); -$table->data[19][1] = html_print_checkbox ('os_detect', 1, $os_detect, true); +$table->data[19][0] = ''.__('OS detection'); +$table->data[19][1] = html_print_checkbox('os_detect', 1, $os_detect, true); // Name resolution -$table->data[20][0] = "".__('Name resolution'); -$table->data[20][1] = html_print_checkbox ('resolve_names', 1, $resolve_names, true); +$table->data[20][0] = ''.__('Name resolution'); +$table->data[20][1] = html_print_checkbox('resolve_names', 1, $resolve_names, true); // Parent detection -$table->data[21][0] = "".__('Parent detection'); -$table->data[21][1] = html_print_checkbox ('parent_detection', 1, $parent_detection, true); +$table->data[21][0] = ''.__('Parent detection'); +$table->data[21][1] = html_print_checkbox('parent_detection', 1, $parent_detection, true); // Parent recursion -$table->data[22][0] = "".__('Parent recursion'); -$table->data[22][1] = html_print_input_text ('parent_recursion', $parent_recursion, '', 5, 0, true) . ui_print_help_tip (__('Maximum number of parent hosts that will be created if parent detection is enabled.'), true); +$table->data[22][0] = ''.__('Parent recursion'); +$table->data[22][1] = html_print_input_text('parent_recursion', $parent_recursion, '', 5, 0, true).ui_print_help_tip(__('Maximum number of parent hosts that will be created if parent detection is enabled.'), true); -//vlan_enabled -$table->data[23][0] = "".__('Vlan enabled'); -$table->data[23][1] = html_print_checkbox ('vlan_enabled', 1, $vlan_enabled, true); +// vlan_enabled +$table->data[23][0] = ''.__('Vlan enabled'); +$table->data[23][1] = html_print_checkbox('vlan_enabled', 1, $vlan_enabled, true); // Alias as name // NOTE: The 7.0NG Recon Server will not generate random names, since IP // address collisions could have other consequences. -//$table->data[22][0] = "".__('Alias as Name'); -//$table->data[22][1] = html_print_checkbox ('alias_as_name', 1, $alias_as_name, true); - +// $table->data[22][0] = "".__('Alias as Name'); +// $table->data[22][1] = html_print_checkbox ('alias_as_name', 1, $alias_as_name, true); // Different Form url if it's a create or if it's a update form echo '
    '; -html_print_table ($table); +html_print_table($table); echo '
    '; if ($id_rt != -1) { - if ($name_script != "IPAM Recon") { - html_print_submit_button (__('Update'), "crt", false, 'class="sub upd"'); - } + if ($name_script != 'IPAM Recon') { + html_print_submit_button(__('Update'), 'crt', false, 'class="sub upd"'); + } +} else { + html_print_submit_button(__('Add'), 'crt', false, 'class="sub wand"'); } -else { - html_print_submit_button (__('Add'), "crt", false, 'class="sub wand"'); -} -echo "
    "; -echo "
    "; +echo '
    '; -ui_require_javascript_file ('pandora_modules'); +echo ''; + +ui_require_javascript_file('pandora_modules'); ?> diff --git a/pandora_console/godmode/servers/modificar_server.php b/pandora_console/godmode/servers/modificar_server.php index aab4a3f918..66c14ee89f 100644 --- a/pandora_console/godmode/servers/modificar_server.php +++ b/pandora_console/godmode/servers/modificar_server.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,187 +11,202 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -require_once ("include/functions_servers.php"); -require_once ("include/functions_graph.php"); +require_once 'include/functions_servers.php'; +require_once 'include/functions_graph.php'; check_login(); -if (! check_acl ($config["id_user"], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access Server Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Server Management' + ); + include 'general/noaccess.php'; + exit; } -if (isset($_GET["server"])) { - - $id_server= get_parameter_get ("server"); - // Headers - ui_print_page_header (__('Update Server'), "images/gm_servers.png", false, "servers", true); - $sql = sprintf("SELECT name, ip_address, description, server_type, exec_proxy FROM tserver WHERE id_server = %d",$id_server); - $row = db_get_row_sql ($sql); - echo '
    '; - html_print_input_hidden ("server",$id_server); +if (isset($_GET['server'])) { + $id_server = get_parameter_get('server'); + // Headers + ui_print_page_header(__('Update Server'), 'images/gm_servers.png', false, 'servers', true); + $sql = sprintf('SELECT name, ip_address, description, server_type, exec_proxy FROM tserver WHERE id_server = %d', $id_server); + $row = db_get_row_sql($sql); + echo ''; + html_print_input_hidden('server', $id_server); - $server_type = __('Standard'); - if ($row["server_type"] == 13) { - $server_type = __('Satellite'); - } - $exec_server_enable = __("No"); - if ($row["exec_proxy"] == 1) { - $exec_server_enable = __('Yes'); - } - - $table->cellpadding=4; - $table->cellspacing=4; - $table->width='100%'; - $table->class="databox filters"; - - $table->data[] = array (__('Name'), $row["name"]); - $table->data[] = array (__('IP Address'), html_print_input_text ('address',$row["ip_address"],'',50,0,true)); - $table->data[] = array (__('Description'), html_print_input_text ('description',$row["description"],'',50,0,true)); - - if (enterprise_installed()) { - $table->data[] = array (__('Type'), $server_type); - if ($row["server_type"] == 13 || $row["server_type"] == 1) { - $table->data[] = array (__('Exec Server'), html_print_checkbox ("exec_proxy", 1, $row["exec_proxy"], true)); - if ($row["exec_proxy"]) { - $table->data[] = array (__('Check Exec Server'), '' . html_print_image ("images/dot_red.disabled.png", true) . '' . '
    '); - } - } - } - - html_print_table ($table); - - echo '
    '; - echo ''; - echo "
    "; + $server_type = __('Standard'); + if ($row['server_type'] == 13) { + $server_type = __('Satellite'); + } -} -elseif (isset($_GET["server_remote"])) { - // Headers - $id_server= get_parameter_get ("server_remote"); - $ext = get_parameter ("ext", ''); - ui_print_page_header (__('Remote Configuration'), "images/gm_servers.png", false, "servers", true); - enterprise_include("godmode/servers/server_disk_conf_editor.php"); -} -else { - // Header - ui_print_page_header (__('%s servers', get_product_name()), "images/gm_servers.png", false, "servers", true); + $exec_server_enable = __('No'); + if ($row['exec_proxy'] == 1) { + $exec_server_enable = __('Yes'); + } - // Move SNMP modules back to the enterprise server - if (isset($_GET["server_reset_snmp_enterprise"])) { - $result = db_process_sql ("UPDATE tagente_estado SET last_error=0"); - - if($result === false) { - ui_print_error_message(__('Unsuccessfull action')); - } - else { - ui_print_success_message(__('Successfully action')); - } - } - - // Reset module count - if (isset($_GET["server_reset_counts"])) { - $reslt = db_process_sql ("UPDATE tagente SET update_module_count=1, update_alert_count=1"); - - if($result === false) { - ui_print_error_message(__('Unsuccessfull action')); - } - else { - ui_print_success_message(__('Successfully action')); - } - } + $table->cellpadding = 4; + $table->cellspacing = 4; + $table->width = '100%'; + $table->class = 'databox filters'; - if (isset ($_GET["delete"])) { - $id_server = get_parameter_get ("server_del"); - - $result = db_process_sql_delete('tserver', array('id_server' => $id_server)); - - if ($result !== false) { - ui_print_success_message(__('Server deleted successfully')); - } - else { - ui_print_error_message(__('There was a problem deleting the server')); - } - } - elseif (isset($_GET["update"])) { - $address = get_parameter_post ("address"); - $description = get_parameter_post ("description"); - $id_server = get_parameter_post ("server"); - $exec_proxy = get_parameter_post ("exec_proxy"); - - $values = array('ip_address' => $address, 'description' => $description, 'exec_proxy' => $exec_proxy); - $result = db_process_sql_update('tserver', $values, array('id_server' => $id_server)); - if ($result !== false) { - ui_print_success_message(__('Server updated successfully')); - } - else { - ui_print_error_message(__('There was a problem updating the server')); - } - } - elseif (isset($_GET["delete_conf_file"])) { - - $correct = false; - $id_server = get_parameter ("id_server"); - $ext = get_parameter ("ext", ''); - $server_md5 = md5(io_safe_output(servers_get_name ($id_server,'none') . $ext), FALSE); - - if (file_exists ($config["remote_config"] . "/md5/" . $server_md5 . ".srv.md5")) { - // Server remote configuration editor - $file_name = $config["remote_config"] . "/conf/" . $server_md5 . ".srv.conf"; - $correct = @unlink ($file_name); - - $file_name = $config["remote_config"] . "/md5/" . $server_md5 . ".srv.md5"; - $correct = @unlink ($file_name); - } - - ui_print_result_message ($correct, - __('Conf file deleted successfully'), - __('Could not delete conf file')); - } - - - $tiny = false; - require($config['homedir'] . '/godmode/servers/servers.build_table.php'); + $table->data[] = [ + __('Name'), + $row['name'], + ]; + $table->data[] = [ + __('IP Address'), + html_print_input_text('address', $row['ip_address'], '', 50, 0, true), + ]; + $table->data[] = [ + __('Description'), + html_print_input_text('description', $row['description'], '', 50, 0, true), + ]; + + if (enterprise_installed()) { + $table->data[] = [ + __('Type'), + $server_type, + ]; + if ($row['server_type'] == 13 || $row['server_type'] == 1) { + $table->data[] = [ + __('Exec Server'), + html_print_checkbox('exec_proxy', 1, $row['exec_proxy'], true), + ]; + if ($row['exec_proxy']) { + $table->data[] = [ + __('Check Exec Server'), + ''.html_print_image('images/dot_red.disabled.png', true).''.'
    ', + ]; + } + } + } + + html_print_table($table); + + echo '
    '; + echo ''; + echo '
    '; +} else if (isset($_GET['server_remote'])) { + // Headers + $id_server = get_parameter_get('server_remote'); + $ext = get_parameter('ext', ''); + ui_print_page_header(__('Remote Configuration'), 'images/gm_servers.png', false, 'servers', true); + enterprise_include('godmode/servers/server_disk_conf_editor.php'); +} else { + // Header + ui_print_page_header(__('%s servers', get_product_name()), 'images/gm_servers.png', false, 'servers', true); + + // Move SNMP modules back to the enterprise server + if (isset($_GET['server_reset_snmp_enterprise'])) { + $result = db_process_sql('UPDATE tagente_estado SET last_error=0'); + + if ($result === false) { + ui_print_error_message(__('Unsuccessfull action')); + } else { + ui_print_success_message(__('Successfully action')); + } + } + + // Reset module count + if (isset($_GET['server_reset_counts'])) { + $reslt = db_process_sql('UPDATE tagente SET update_module_count=1, update_alert_count=1'); + + if ($result === false) { + ui_print_error_message(__('Unsuccessfull action')); + } else { + ui_print_success_message(__('Successfully action')); + } + } + + if (isset($_GET['delete'])) { + $id_server = get_parameter_get('server_del'); + + $result = db_process_sql_delete('tserver', ['id_server' => $id_server]); + + if ($result !== false) { + ui_print_success_message(__('Server deleted successfully')); + } else { + ui_print_error_message(__('There was a problem deleting the server')); + } + } else if (isset($_GET['update'])) { + $address = get_parameter_post('address'); + $description = get_parameter_post('description'); + $id_server = get_parameter_post('server'); + $exec_proxy = get_parameter_post('exec_proxy'); + + $values = [ + 'ip_address' => $address, + 'description' => $description, + 'exec_proxy' => $exec_proxy, + ]; + $result = db_process_sql_update('tserver', $values, ['id_server' => $id_server]); + if ($result !== false) { + ui_print_success_message(__('Server updated successfully')); + } else { + ui_print_error_message(__('There was a problem updating the server')); + } + } else if (isset($_GET['delete_conf_file'])) { + $correct = false; + $id_server = get_parameter('id_server'); + $ext = get_parameter('ext', ''); + $server_md5 = md5(io_safe_output(servers_get_name($id_server, 'none').$ext), false); + + if (file_exists($config['remote_config'].'/md5/'.$server_md5.'.srv.md5')) { + // Server remote configuration editor + $file_name = $config['remote_config'].'/conf/'.$server_md5.'.srv.conf'; + $correct = @unlink($file_name); + + $file_name = $config['remote_config'].'/md5/'.$server_md5.'.srv.md5'; + $correct = @unlink($file_name); + } + + ui_print_result_message( + $correct, + __('Conf file deleted successfully'), + __('Could not delete conf file') + ); + } + + + $tiny = false; + include $config['homedir'].'/godmode/servers/servers.build_table.php'; } ?> diff --git a/pandora_console/godmode/servers/plugin.php b/pandora_console/godmode/servers/plugin.php index 1440c13344..ff370a5c48 100644 --- a/pandora_console/godmode/servers/plugin.php +++ b/pandora_console/godmode/servers/plugin.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,797 +11,820 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -if (is_ajax ()) { - $get_plugin_description = get_parameter('get_plugin_description'); - $get_list_modules_and_component_locked_plugin = (bool) - get_parameter('get_list_modules_and_component_locked_plugin', 0); - - if ($get_plugin_description) { - $id_plugin = get_parameter('id_plugin'); - - $description = db_get_value_filter('description', 'tplugin', array('id' => $id_plugin)); - $preload = io_safe_output($description); - $preload = str_replace ("\n", "
    ", $preload); - - echo $preload; - return; - } - - if ($get_list_modules_and_component_locked_plugin) { - $id_plugin = (int)get_parameter('id_plugin', 0); - - $network_components = db_get_all_rows_filter( - 'tnetwork_component', - array('id_plugin' => $id_plugin)); - if (empty($network_components)) { - $network_components = array(); - } - $modules = db_get_all_rows_filter( - 'tagente_modulo', - array('delete_pending' => 0, 'id_plugin' => $id_plugin)); - if (empty($modules)) { - $modules = array(); - } - - $table = null; - $table->width = "100%"; - $table->head[0] = __('Network Components'); - $table->data = array(); - foreach ($network_components as $net_comp) { - $table->data[] = array($net_comp['name']); - } - if (!empty($table->data)) { - html_print_table($table); - - echo "
    "; - } - - $table = null; - $table->width = "100%"; - $table->head[0] = __('Agent'); - $table->head[1] = __('Module'); - foreach ($modules as $mod) { - $agent_name = '' . - modules_get_agentmodule_agent_name( - $mod['id_agente_modulo']) . - ''; - - - $table->data[] = array( - $agent_name, - $mod['nombre'] - ); - } - if (!empty($table->data)) { - html_print_table($table); - } - - return; - } +if (is_ajax()) { + $get_plugin_description = get_parameter('get_plugin_description'); + $get_list_modules_and_component_locked_plugin = (bool) get_parameter('get_list_modules_and_component_locked_plugin', 0); + + if ($get_plugin_description) { + $id_plugin = get_parameter('id_plugin'); + + $description = db_get_value_filter('description', 'tplugin', ['id' => $id_plugin]); + $preload = io_safe_output($description); + $preload = str_replace("\n", '
    ', $preload); + + echo $preload; + return; + } + + if ($get_list_modules_and_component_locked_plugin) { + $id_plugin = (int) get_parameter('id_plugin', 0); + + $network_components = db_get_all_rows_filter( + 'tnetwork_component', + ['id_plugin' => $id_plugin] + ); + if (empty($network_components)) { + $network_components = []; + } + + $modules = db_get_all_rows_filter( + 'tagente_modulo', + [ + 'delete_pending' => 0, + 'id_plugin' => $id_plugin, + ] + ); + if (empty($modules)) { + $modules = []; + } + + $table = null; + $table->width = '100%'; + $table->head[0] = __('Network Components'); + $table->data = []; + foreach ($network_components as $net_comp) { + $table->data[] = [$net_comp['name']]; + } + + if (!empty($table->data)) { + html_print_table($table); + + echo '
    '; + } + + $table = null; + $table->width = '100%'; + $table->head[0] = __('Agent'); + $table->head[1] = __('Module'); + foreach ($modules as $mod) { + $agent_name = ''.modules_get_agentmodule_agent_name( + $mod['id_agente_modulo'] + ).''; + + + $table->data[] = [ + $agent_name, + $mod['nombre'], + ]; + } + + if (!empty($table->data)) { + html_print_table($table); + } + + return; + } } -require_once ($config['homedir'] . "/include/functions_filemanager.php"); +require_once $config['homedir'].'/include/functions_filemanager.php'; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Plugin Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Plugin Management' + ); + include 'general/noaccess.php'; + return; } -enterprise_include_once ('meta/include/functions_components_meta.php'); +enterprise_include_once('meta/include/functions_components_meta.php'); -$view = get_parameter ("view", ""); -$create = get_parameter ("create", ""); -$filemanager = (bool)get_parameter("filemanager", false); -$edit_file = get_parameter("edit_file",false); -$update_file = get_parameter("update_file",false); +$view = get_parameter('view', ''); +$create = get_parameter('create', ''); +$filemanager = (bool) get_parameter('filemanager', false); +$edit_file = get_parameter('edit_file', false); +$update_file = get_parameter('update_file', false); $plugin_command = get_parameter('plugin_command', ''); $tab = get_parameter('tab', ''); -if ($view != "") { - $form_id = $view; - $plugin = db_get_row ("tplugin", "id", $form_id); - $form_name = $plugin["name"]; - $form_description = $plugin["description"]; - $form_max_timeout = $plugin ["max_timeout"]; - $form_max_retries = $plugin ["max_retries"]; - if (empty($plugin_command)) - $form_execute = $plugin ["execute"]; - else - $form_execute = $plugin_command; - $form_plugin_type = $plugin ["plugin_type"]; - $macros = $plugin ["macros"]; - $parameters = $plugin ["parameters"]; +if ($view != '') { + $form_id = $view; + $plugin = db_get_row('tplugin', 'id', $form_id); + $form_name = $plugin['name']; + $form_description = $plugin['description']; + $form_max_timeout = $plugin['max_timeout']; + $form_max_retries = $plugin['max_retries']; + if (empty($plugin_command)) { + $form_execute = $plugin['execute']; + } else { + $form_execute = $plugin_command; + } + + $form_plugin_type = $plugin['plugin_type']; + $macros = $plugin['macros']; + $parameters = $plugin['parameters']; } -if ($create != "") { - $form_id = 0; - $form_name = ""; - $form_description = ""; - $form_max_timeout = 15; - $form_max_retries = 1; - $form_execute = $plugin_command; - $form_plugin_type = 0; - $form_parameters = ""; - $macros = ""; - $parameters = ""; +if ($create != '') { + $form_id = 0; + $form_name = ''; + $form_description = ''; + $form_max_timeout = 15; + $form_max_retries = 1; + $form_execute = $plugin_command; + $form_plugin_type = 0; + $form_parameters = ''; + $macros = ''; + $parameters = ''; } -//END LOAD VALUES +// END LOAD VALUES // ===================================================================== // INIT FILEMANAGER // ===================================================================== if ($filemanager) { - if($edit_file) { - $location_file = get_parameter("location_file",''); - $filename = array_pop(explode("/",$location_file)); - $file = file_get_contents($location_file); - echo "

    " . __("Edit file") ." ".$filename. "

    "; - //echo "" . __('Back to file explorer') . ""; - echo ""; - //html_print_input_hidden('location_file', $locationFile); - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo "'; + echo ''; + echo '
    " . __('Edit') . "
    "; - echo ""; - echo "
    "; - html_print_input_hidden('location_file', $location_file); + if ($edit_file) { + $location_file = get_parameter('location_file', ''); + $filename = array_pop(explode('/', $location_file)); + $file = file_get_contents($location_file); + echo '

    '.__('Edit file').' '.$filename.'

    '; + // echo "" . __('Back to file explorer') . ""; + echo ""; + // html_print_input_hidden('location_file', $locationFile); + echo ""; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ""; + echo '"; - echo ""; - echo "
    '.__('Edit').'
    '; + echo "'; + echo '
    '; + html_print_input_hidden('location_file', $location_file); - echo __('Compatibility mode').":"; - $options = array('unix' => 'Unix', 'windows' => 'Windows'); - html_print_select($options, 'compatibility', $compatibility); - echo " "; - echo "
    "; - echo ""; - }else { + echo __('Compatibility mode').':'; + $options = [ + 'unix' => 'Unix', + 'windows' => 'Windows', + ]; + html_print_select($options, 'compatibility', $compatibility); + echo " "; + echo '
    '; + echo ''; + } else { + if ($update_file) { + $location_file = get_parameter('location_file', ''); + $contentFile = io_safe_output(get_parameter('content_file', '')); + $compatibility = get_parameter('compatibility', 'unix'); + $is_win_compatible = strpos($contentFile, "\r\n"); + // If is win compatible and the compatibility must be unix + if ($is_win_compatible !== false && $compatibility == 'unix') { + $contentFile = str_replace("\r\n", "\n", $contentFile); + } + // If is unix compatible and the compatibility must be win + else if ($is_win_compatible === false && $compatibility == 'windows') { + $contentFile = str_replace("\n", "\r\n", $contentFile); + } - if($update_file){ - $location_file = get_parameter("location_file",''); - $contentFile = io_safe_output(get_parameter('content_file', '')); - $compatibility = get_parameter('compatibility', 'unix'); - $is_win_compatible = strpos($contentFile, "\r\n"); - // If is win compatible and the compatibility must be unix - if ($is_win_compatible !== false && $compatibility == 'unix') { - $contentFile = str_replace("\r\n", "\n", $contentFile); - } - // If is unix compatible and the compatibility must be win - else if ($is_win_compatible === false && $compatibility == 'windows') { - $contentFile = str_replace("\n", "\r\n", $contentFile); - } - $result = file_put_contents($location_file, $contentFile); + $result = file_put_contents($location_file, $contentFile); + } - } - $id_plugin = (int)get_parameter('id_plugin', 0); + $id_plugin = (int) get_parameter('id_plugin', 0); - /* Add custom directories here */ - $fallback_directory = "attachment/plugin"; + // Add custom directories here + $fallback_directory = 'attachment/plugin'; - $directory = (string) get_parameter ('directory', $fallback_directory); - $directory = str_replace("\\", "/", $directory); + $directory = (string) get_parameter('directory', $fallback_directory); + $directory = str_replace('\\', '/', $directory); - // A miminal security check to avoid directory traversal - if (preg_match ("/\.\./", $directory)) - $directory = $fallback_directory; - if (preg_match ("/^\//", $directory)) - $directory = $fallback_directory; - if (preg_match ("/^manager/", $directory)) - $directory = $fallback_directory; + // A miminal security check to avoid directory traversal + if (preg_match('/\.\./', $directory)) { + $directory = $fallback_directory; + } - $banned_directories['include'] = true; - $banned_directories['godmode'] = true; - $banned_directories['operation'] = true; - $banned_directories['reporting'] = true; - $banned_directories['general'] = true; - $banned_directories[ENTERPRISE_DIR] = true; + if (preg_match('/^\//', $directory)) { + $directory = $fallback_directory; + } - if (isset ($banned_directories[$directory])) - $directory = $fallback_directory; + if (preg_match('/^manager/', $directory)) { + $directory = $fallback_directory; + } - $real_directory = realpath ($config['homedir'] . '/' . $directory); + $banned_directories['include'] = true; + $banned_directories['godmode'] = true; + $banned_directories['operation'] = true; + $banned_directories['reporting'] = true; + $banned_directories['general'] = true; + $banned_directories[ENTERPRISE_DIR] = true; - echo '

    ' . __('Index of %s', $directory) . '

    '; + if (isset($banned_directories[$directory])) { + $directory = $fallback_directory; + } - $chunck_url = '&view=' . $id_plugin; - if ($id_plugin == 0) { - $chunck_url = '&create=1'; - } + $real_directory = realpath($config['homedir'].'/'.$directory); - $homedir_filemanager = isset ($config['homedir_filemanager']) ? $config['homedir_filemanager'] : false; - filemanager_file_explorer($real_directory, - $directory, - 'index.php?sec=gservers&sec2=godmode/servers/plugin&filemanager=1&id_plugin=' . $id_plugin, - $fallback_directory, - true, - false, - 'index.php?sec=gservers&sec2=godmode/servers/plugin' . $chunck_url . '&plugin_command=[FILE_FULLPATH]&id_plugin=' . $id_plugin, - true, - 0775, - $homedir_filemanager); - } - return; + echo '

    '.__('Index of %s', $directory).'

    '; + + $chunck_url = '&view='.$id_plugin; + if ($id_plugin == 0) { + $chunck_url = '&create=1'; + } + + $homedir_filemanager = isset($config['homedir_filemanager']) ? $config['homedir_filemanager'] : false; + filemanager_file_explorer( + $real_directory, + $directory, + 'index.php?sec=gservers&sec2=godmode/servers/plugin&filemanager=1&id_plugin='.$id_plugin, + $fallback_directory, + true, + false, + 'index.php?sec=gservers&sec2=godmode/servers/plugin'.$chunck_url.'&plugin_command=[FILE_FULLPATH]&id_plugin='.$id_plugin, + true, + 0775, + $homedir_filemanager + ); + } + + return; } // ===================================================================== // END FILEMANAGER // ===================================================================== - - // ===================================================================== // SHOW THE FORM // ===================================================================== - $sec = 'gservers'; -if (($create != "") OR ($view != "")) { - enterprise_hook('open_meta_frame'); - - if (defined('METACONSOLE')) { - components_meta_print_header(); - $sec = 'advanced'; - } - else { - if ($create != "") - ui_print_page_header(__('Plugin creation'), - "images/gm_servers.png", false, "plugin_definition", true); - else { - ui_print_page_header(__('Plugin update'), - "images/gm_servers.png", false, "plugin_definition", true); - } - } - - - if ($create == "") { - $plugin_id = get_parameter ("view", ""); - echo "
    "; - } - else { - echo ""; - } - - $table = new stdClass(); - $table->width = '100%'; - $table->id = 'table-form'; - $table->class = 'databox filters'; - $table->style = array (); - $table->style[0] = 'font-weight: bold'; - $table->style[2] = 'font-weight: bold'; - $table->data = array (); - - $data = array(); - $data[0] = __('Name'); - $data[1] = ''; - $table->colspan['plugin_name'][1] = 3; - $table->data['plugin_name'] = $data; - - $data = array(); - $data[0] = __('Plugin type'); - $fields[0]= __("Standard"); - $fields[1]= __("Nagios"); - $data[1] = html_print_select ($fields, "form_plugin_type", $form_plugin_type, '', '', 0, true); - $table->data['plugin_type'] = $data; - $table->colspan['plugin_type'][1] = 3; - - $data[0] = __('Max. timeout').ui_print_help_tip (__('This value only will be applied if is minor than the server general configuration plugin timeout').'.

    '.__('If you set a 0 seconds timeout, the server plugin timeout will be used'), true); - $data[1] = html_print_extended_select_for_time ('form_max_timeout', $form_max_timeout, '', '', '0', false, true); +if (($create != '') or ($view != '')) { + enterprise_hook('open_meta_frame'); - $table->data['plugin_timeout'] = $data; - - $data = array(); - $data[0] = __('Description'); - $data[1] = ''; - $table->colspan['plugin_desc'][1] = 3; - $table->data['plugin_desc'] = $data; - - //if (!defined("METACONSOLE")) { - //echo '
    '; - //echo ''; - - enterprise_hook('close_meta_frame'); -} -else { - - enterprise_hook('open_meta_frame'); - - if(defined('METACONSOLE')) { - components_meta_print_header(); - $sec = 'advanced'; - } - else { - ui_print_page_header (__('Plug-ins registered on %s', get_product_name()), "images/gm_servers.png", false, "", true); + $table = new stdClass(); + $table->width = '100%'; + $table->id = 'table-form'; + $table->class = 'databox filters'; + $table->style = []; + $table->style[0] = 'font-weight: bold'; + $table->style[2] = 'font-weight: bold'; + $table->data = []; - $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; - if ($is_windows) { - echo '
    '; - echo __("You need to create your own plugins with Windows compatibility"); - echo '
    '; - } - } + $data = []; + $data[0] = __('Name'); + $data[1] = ''; + $table->colspan['plugin_name'][1] = 3; + $table->data['plugin_name'] = $data; - - // Update plugin - if (isset($_GET["update_plugin"])) { // if modified any parameter - $plugin_id = get_parameter ("update_plugin", 0); - $plugin_name = get_parameter ("form_name", ""); - $plugin_description = get_parameter ("form_description", ""); - $plugin_max_timeout = get_parameter ("form_max_timeout", ""); - $plugin_execute = get_parameter ("form_execute", ""); - $plugin_plugin_type = get_parameter ("form_plugin_type", "0"); - $parameters = get_parameter ("form_parameters", ""); - - // Get macros - $i = 1; - $macros = array(); - while (1) { - $macro = (string)get_parameter ('field'.$i.'_macro'); - if($macro == '') { - break; - } - - $desc = (string)get_parameter ('field'.$i.'_desc'); - $help = (string)get_parameter ('field'.$i.'_help'); - $value = (string)get_parameter ('field'.$i.'_value'); - $hide = get_parameter ('field'.$i.'_hide'); - - $macros[$i]['macro'] = $macro; - $macros[$i]['desc'] = $desc; - $macros[$i]['help'] = $help; - if ($hide == 1) { - $macros[$i]['value'] = io_input_password($value); - } else { - $macros[$i]['value'] = $value; - } - $macros[$i]['hide'] = $hide; + $data = []; + $data[0] = __('Plugin type'); + $fields[0] = __('Standard'); + $fields[1] = __('Nagios'); + $data[1] = html_print_select($fields, 'form_plugin_type', $form_plugin_type, '', '', 0, true); + $table->data['plugin_type'] = $data; + $table->colspan['plugin_type'][1] = 3; - $i++; - } - - $macros = io_json_mb_encode($macros); - - $values = array( - 'name' => $plugin_name, - 'description' => $plugin_description, - 'max_timeout' => $plugin_max_timeout, - 'execute' => $plugin_execute, - 'plugin_type' => $plugin_plugin_type, - 'parameters' => $parameters, - 'macros' => $macros); - - $result = false; - if ($values['name'] != '' && $values['execute'] != '') - $result = db_process_sql_update('tplugin', $values, - array('id' => $plugin_id)); - - if (! $result) { - ui_print_error_message(__('Problem updating plugin')); - } - else { - ui_print_success_message(__('Plugin updated successfully')); - } - } - - // Create plugin - if (isset($_GET["create_plugin"])) { - $plugin_name = get_parameter ("form_name", ""); - $plugin_description = get_parameter ("form_description", ""); - $plugin_max_timeout = get_parameter ("form_max_timeout", ""); - $plugin_execute = get_parameter ("form_execute", ""); - $plugin_plugin_type = get_parameter ("form_plugin_type", "0"); - $plugin_parameters = get_parameter ("form_parameters", ""); - - // Get macros - $i = 1; - $macros = array(); - while (1) { - $macro = (string)get_parameter ('field'.$i.'_macro'); - if($macro == '') { - break; - } - - $desc = (string)get_parameter ('field'.$i.'_desc'); - $help = (string)get_parameter ('field'.$i.'_help'); - $value = (string)get_parameter ('field'.$i.'_value'); - $hide = get_parameter ('field'.$i.'_hide'); - - $macros[$i]['macro'] = $macro; - $macros[$i]['desc'] = $desc; - $macros[$i]['help'] = $help; - if ($hide == 1) { - $macros[$i]['value'] = io_input_password($value); - } else { - $macros[$i]['value'] = $value; - } - $macros[$i]['hide'] = $hide; - $i++; - } - - $macros = io_json_mb_encode($macros); - - $values = array( - 'name' => $plugin_name, - 'description' => $plugin_description, - 'max_timeout' => $plugin_max_timeout, - 'execute' => $plugin_execute, - 'plugin_type' => $plugin_plugin_type, - 'parameters' => $plugin_parameters, - 'macros' => $macros); - - $result = false; - if ($values['name'] != '' && $values['execute'] != '') - $result = db_process_sql_insert('tplugin', $values); - - if (! $result) { - ui_print_error_message(__('Problem creating plugin')); - } - else { - ui_print_success_message(__('Plugin created successfully')); - } - } - - if (isset($_GET["kill_plugin"])) { // if delete alert - $plugin_id = get_parameter ("kill_plugin", 0); - - $result = db_process_sql_delete('tplugin', array('id' => $plugin_id)); - - if (! $result) { - ui_print_error_message(__('Problem deleting plugin')); - } - else { - ui_print_success_message(__('Plugin deleted successfully')); - } - if ($plugin_id != 0) { - // Delete all the modules with this plugin - $plugin_modules = db_get_all_rows_filter( - 'tagente_modulo', array('id_plugin' => $plugin_id)); - - if (empty($plugin_modules)) - $plugin_modules = array(); - - foreach ($plugin_modules as $pm) { - modules_delete_agent_module ($pm['id_agente_modulo']); - } - if (enterprise_installed()) { - enterprise_include_once('include/functions_policies.php'); - $policies_ids = db_get_all_rows_filter('tpolicy_modules', array('id_plugin' => $plugin_id)); - foreach($policies_ids as $policies_id) { - policies_change_delete_pending_module ($policies_id['id']); - } - } - } - } - - // If not edition or insert, then list available plugins - $rows = db_get_all_rows_sql('SELECT * FROM tplugin ORDER BY name'); - - if ($rows !== false) { - if(defined('METACONSOLE')) - echo '
    '; - //} - - $table->width = '100%'; - $table->class = 'databox filters'; - - if (defined("METACONSOLE")) { - $table->head[0] = __('General'); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; - html_print_table($table); - } - else { - echo '
    ' . __('General') . ''; - html_print_table($table); - echo '
    '; - } - - $table->data = array(); - - $plugin_id = get_parameter ("view", 0); - - $locked = true; - - // If we have plugin id (update mode) and this plugin used by any module or component - // The command configuration will be locked - if ($plugin_id > 0) { - $modules_using_plugin = db_get_value_filter('count(*)','tagente_modulo', array('delete_pending' => 0, 'id_plugin' => $plugin_id)); - $components_using_plugin = db_get_value_filter('count(*)','tnetwork_component', array('id_plugin' => $plugin_id)); - if(($components_using_plugin + $modules_using_plugin) == 0) { - $locked = false; - } - } - else { - $locked = false; - } - - $disabled = ''; - if ($locked) { - $disabled = 'readonly="readonly"'; - } - - $data = array(); - $data[0] = __('Plugin command'); - $data[1] = ''; - if ($locked) { - $data[1] .= html_print_image('images/lock.png', true, array('class' => 'command_advanced_conf lock')); - } - $data[1] .= ' '; - $data[1] .= html_print_image('images/file.png', true); - $data[1] .= ''; - $table->data['plugin_command'] = $data; - - $data = array(); - $data[0] = __('Plug-in parameters').ui_print_help_icon ('plugin_parameters', true); - $data[1] = ''; - if ($locked) { - $data[1] .= html_print_image('images/lock.png', true, array('class' => 'command_advanced_conf lock')); - } - $table->data['plugin_parameters'] = $data; - - $data = array(); - $data[0] = __('Command preview'); - $data[1] = '
    '; - $table->data['plugin_preview'] = $data; - - $table->width = '100%'; - $table->class = 'databox filters'; - if (defined("METACONSOLE")) { - $table->head[0] = __('Command'); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; - html_print_table($table); - } - else { - echo '
    ' . __('Command') . ''; - html_print_table($table); - echo '
    '; - } - - $data = array(); - - $table->data = array (); - - $macros = json_decode($macros,true); - - // The next row number is plugin_9 - $next_name_number = 9; - $i = 1; - while (1) { - // Always print at least one macro - if ((!isset($macros[$i]) || $macros[$i]['desc'] == '') && $i > 1) { - break; - } - $macro_desc_name = 'field'.$i.'_desc'; - $macro_desc_value = ''; - $macro_help_name = 'field'.$i.'_help'; - $macro_help_value = ''; - $macro_value_name = 'field'.$i.'_value'; - $macro_value_value = ''; - $macro_name_name = 'field'.$i.'_macro'; - $macro_name = '_field'.$i.'_'; - $macro_hide_value_name = 'field'.$i.'_hide'; - $macro_hide_value_value = 0; - - if (isset($macros[$i]['desc'])) { - $macro_desc_value = $macros[$i]['desc']; - } - - if (isset($macros[$i]['help'])) { - $macro_help_value = $macros[$i]['help']; - } - - if (isset($macros[$i]['value'])) { - $macro_value_value = $macros[$i]['value']; - } - - if (isset($macros[$i]['hide'])) { - $macro_hide_value_value = $macros[$i]['hide']; + if (defined('METACONSOLE')) { + components_meta_print_header(); + $sec = 'advanced'; + } else { + if ($create != '') { + ui_print_page_header( + __('Plugin creation'), + 'images/gm_servers.png', + false, + 'plugin_definition', + true + ); + } else { + ui_print_page_header( + __('Plugin update'), + 'images/gm_servers.png', + false, + 'plugin_definition', + true + ); + } + } - // Decrypt hidden macros. - $macro_value_value = io_output_password($macro_value_value); - } - - $datam = array (); - $datam[0] = __('Description')." ($macro_name)"; - $datam[0] .= html_print_input_hidden($macro_name_name, $macro_name, true); - $datam[1] = html_print_input_text_extended ($macro_desc_name, $macro_desc_value, 'text-'.$macro_desc_name, '', 30, 255, $locked, '', "class='command_macro'", true); - if ($locked) { - $datam[1] .= html_print_image('images/lock.png', true, array('class' => 'command_macro lock')); - } - - $datam[2] = __('Default value')." ($macro_name)"; - $datam[3] = html_print_input_text_extended ($macro_value_name, $macro_value_value, 'text-'.$macro_value_name, '', 30, 255, $locked, '', "class='command_component command_macro'", true); - if ($locked) { - $datam[3] .= html_print_image('images/lock.png', true, array('class' => 'command_macro lock')); - } - - $table->data['plugin_'.$next_name_number] = $datam; - - $next_name_number++; - - $table->colspan['plugin_'.$next_name_number][1] = 3; - - $datam = array (); - $datam[0] = __('Hide value') . ui_print_help_tip(__('This field will show up as dots like a password'), true); - $datam[1] = html_print_checkbox_extended ($macro_hide_value_name, 1, $macro_hide_value_value, 0, '', array('class' => 'command_macro'), true, 'checkbox-'.$macro_hide_value_name); - $table->data['plugin_'.$next_name_number] = $datam; - $next_name_number++; - - $table->colspan['plugin_'.$next_name_number][1] = 3; + if ($create == '') { + $plugin_id = get_parameter('view', ''); + echo ""; + } else { + echo ""; + } - $datam = array (); - $datam[0] = __('Help')." ($macro_name)


    "; - $tadisabled = $locked === true ? ' disabled' : ''; - $datam[1] = html_print_textarea ($macro_help_name, 6, 100, $macro_help_value, 'class="command_macro" style="width: 97%;"' . $tadisabled, true); - - if ($locked) { - $datam[1] .= html_print_image('images/lock.png', true, array('class' => 'command_macro lock')); - } - $datam[1] .= "


    "; - - $table->data['plugin_'.$next_name_number] = $datam; - $next_name_number++; - $i++; - } - - // Add/Delete buttons - $datam = array (); - $datam[0] = '' . - '' . - __('Add macro') . - '' . ' ' . - html_print_image('images/add.png',true) . - ''; - $datam[0] .= ''; - $datam[0] .= ''; - - if (!$locked) { - $delete_macro_style = ''; - if ($i <= 2) { - $delete_macro_style = 'display:none;'; - } - $datam[2] = ''; - - $table->colspan['plugin_action'][0] = 2; - $table->colspan['plugin_action'][2] = 2; - } - else { - $table->colspan['plugin_action'][0] = 4; - } - - $table->rowstyle['plugin_action'] = 'text-align:center'; - $table->data['plugin_action'] = $datam; - - - if (defined("METACONSOLE")) { - $table->head[0] = __('Parameters macros'); - $table->head_colspan[0] = 4; - $table->headstyle[0] = 'text-align: center'; - html_print_table($table); - } - else { - echo '
    ' . - '' . __('Parameters macros') .ui_print_help_icon ('macros', true) . ''; - html_print_table($table); - echo '
    '; - } - - echo ''; - - echo '
    '; - - if ($create != "") { - echo ""; - } - else { - echo ""; - } - echo '
    '; - - if (defined("METACONSOLE")) - echo '
    '; - else - echo '
    '; - - echo ""; - echo ""; - echo ""; - echo ""; - $color = 0; - - foreach ($rows as $row) { - if ($color == 1) { - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - } - echo "
    " . __('Name') . "" . __('Type') . "" . __('Command') . "" . - '' . __('Op.') . '' . - "
    "; - echo ""; - echo $row["name"]; - echo ""; - if ($row["plugin_type"] == 0) - echo __('Standard'); - else - echo __('Nagios'); - echo ""; - echo $row["execute"]; - echo ""; - - //Show it is locket - $modules_using_plugin = db_get_value_filter( - 'count(*)', - 'tagente_modulo', - array('delete_pending' => 0, 'id_plugin' => $row["id"])); - $components_using_plugin = db_get_value_filter( - 'count(*)', - 'tnetwork_component', - array('id_plugin' => $row["id"])); - if (($components_using_plugin + $modules_using_plugin) > 0) { - echo ''; - html_print_image('images/lock.png'); - echo ""; - } - echo "" . html_print_image('images/config.png', true, array("title" => __("Edit"))) . "  "; - echo "" . html_print_image("images/cross.png", true, array("border" => '0')) . ""; - echo "
    "; - } - else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no plugins in the system') ) ); - } - - echo ""; + $data[0] = __('Max. timeout').ui_print_help_tip(__('This value only will be applied if is minor than the server general configuration plugin timeout').'.

    '.__('If you set a 0 seconds timeout, the server plugin timeout will be used'), true); + $data[1] = html_print_extended_select_for_time('form_max_timeout', $form_max_timeout, '', '', '0', false, true); - echo "
    "; - echo "
    "; - echo ""; - echo "
    "; - - // The '%s' will be replaced in the javascript code of the function 'show_locked_dialog' - echo ""; - - enterprise_hook('close_meta_frame'); + $table->data['plugin_timeout'] = $data; + + $data = []; + $data[0] = __('Description'); + $data[1] = ''; + $table->colspan['plugin_desc'][1] = 3; + $table->data['plugin_desc'] = $data; + + // if (!defined("METACONSOLE")) { + // echo '
    '; + // echo ''; + } + + enterprise_hook('close_meta_frame'); +} else { + enterprise_hook('open_meta_frame'); + + if (defined('METACONSOLE')) { + components_meta_print_header(); + $sec = 'advanced'; + } else { + ui_print_page_header(__('Plug-ins registered on %s', get_product_name()), 'images/gm_servers.png', false, '', true); + + $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; + if ($is_windows) { + echo '
    '; + echo __('You need to create your own plugins with Windows compatibility'); + echo '
    '; + } + } + + + // Update plugin + if (isset($_GET['update_plugin'])) { + // if modified any parameter + $plugin_id = get_parameter('update_plugin', 0); + $plugin_name = get_parameter('form_name', ''); + $plugin_description = get_parameter('form_description', ''); + $plugin_max_timeout = get_parameter('form_max_timeout', ''); + $plugin_execute = get_parameter('form_execute', ''); + $plugin_plugin_type = get_parameter('form_plugin_type', '0'); + $parameters = get_parameter('form_parameters', ''); + + // Get macros + $i = 1; + $macros = []; + while (1) { + $macro = (string) get_parameter('field'.$i.'_macro'); + if ($macro == '') { + break; + } + + $desc = (string) get_parameter('field'.$i.'_desc'); + $help = (string) get_parameter('field'.$i.'_help'); + $value = (string) get_parameter('field'.$i.'_value'); + $hide = get_parameter('field'.$i.'_hide'); + + $macros[$i]['macro'] = $macro; + $macros[$i]['desc'] = $desc; + $macros[$i]['help'] = $help; + if ($hide == 1) { + $macros[$i]['value'] = io_input_password($value); + } else { + $macros[$i]['value'] = $value; + } + + $macros[$i]['hide'] = $hide; + + $i++; + } + + $macros = io_json_mb_encode($macros); + + $values = [ + 'name' => $plugin_name, + 'description' => $plugin_description, + 'max_timeout' => $plugin_max_timeout, + 'execute' => $plugin_execute, + 'plugin_type' => $plugin_plugin_type, + 'parameters' => $parameters, + 'macros' => $macros, + ]; + + $result = false; + if ($values['name'] != '' && $values['execute'] != '') { + $result = db_process_sql_update( + 'tplugin', + $values, + ['id' => $plugin_id] + ); + } + + if (! $result) { + ui_print_error_message(__('Problem updating plugin')); + } else { + ui_print_success_message(__('Plugin updated successfully')); + } + } + + // Create plugin + if (isset($_GET['create_plugin'])) { + $plugin_name = get_parameter('form_name', ''); + $plugin_description = get_parameter('form_description', ''); + $plugin_max_timeout = get_parameter('form_max_timeout', ''); + $plugin_execute = get_parameter('form_execute', ''); + $plugin_plugin_type = get_parameter('form_plugin_type', '0'); + $plugin_parameters = get_parameter('form_parameters', ''); + + // Get macros + $i = 1; + $macros = []; + while (1) { + $macro = (string) get_parameter('field'.$i.'_macro'); + if ($macro == '') { + break; + } + + $desc = (string) get_parameter('field'.$i.'_desc'); + $help = (string) get_parameter('field'.$i.'_help'); + $value = (string) get_parameter('field'.$i.'_value'); + $hide = get_parameter('field'.$i.'_hide'); + + $macros[$i]['macro'] = $macro; + $macros[$i]['desc'] = $desc; + $macros[$i]['help'] = $help; + if ($hide == 1) { + $macros[$i]['value'] = io_input_password($value); + } else { + $macros[$i]['value'] = $value; + } + + $macros[$i]['hide'] = $hide; + $i++; + } + + $macros = io_json_mb_encode($macros); + + $values = [ + 'name' => $plugin_name, + 'description' => $plugin_description, + 'max_timeout' => $plugin_max_timeout, + 'execute' => $plugin_execute, + 'plugin_type' => $plugin_plugin_type, + 'parameters' => $plugin_parameters, + 'macros' => $macros, + ]; + + $result = false; + if ($values['name'] != '' && $values['execute'] != '') { + $result = db_process_sql_insert('tplugin', $values); + } + + if (! $result) { + ui_print_error_message(__('Problem creating plugin')); + } else { + ui_print_success_message(__('Plugin created successfully')); + } + } + + if (isset($_GET['kill_plugin'])) { + // if delete alert + $plugin_id = get_parameter('kill_plugin', 0); + + $result = db_process_sql_delete('tplugin', ['id' => $plugin_id]); + + if (! $result) { + ui_print_error_message(__('Problem deleting plugin')); + } else { + ui_print_success_message(__('Plugin deleted successfully')); + } + + if ($plugin_id != 0) { + // Delete all the modules with this plugin + $plugin_modules = db_get_all_rows_filter( + 'tagente_modulo', + ['id_plugin' => $plugin_id] + ); + + if (empty($plugin_modules)) { + $plugin_modules = []; + } + + foreach ($plugin_modules as $pm) { + modules_delete_agent_module($pm['id_agente_modulo']); + } + + if (enterprise_installed()) { + enterprise_include_once('include/functions_policies.php'); + $policies_ids = db_get_all_rows_filter('tpolicy_modules', ['id_plugin' => $plugin_id]); + foreach ($policies_ids as $policies_id) { + policies_change_delete_pending_module($policies_id['id']); + } + } + } + } + + // If not edition or insert, then list available plugins + $rows = db_get_all_rows_sql('SELECT * FROM tplugin ORDER BY name'); + + if ($rows !== false) { + if (defined('METACONSOLE')) { + echo '
    '; + // } + $table->width = '100%'; + $table->class = 'databox filters'; + + if (defined('METACONSOLE')) { + $table->head[0] = __('General'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; + html_print_table($table); + } else { + echo '
    '.__('General').''; + html_print_table($table); + echo '
    '; + } + + $table->data = []; + + $plugin_id = get_parameter('view', 0); + + $locked = true; + + // If we have plugin id (update mode) and this plugin used by any module or component + // The command configuration will be locked + if ($plugin_id > 0) { + $modules_using_plugin = db_get_value_filter('count(*)', 'tagente_modulo', ['delete_pending' => 0, 'id_plugin' => $plugin_id]); + $components_using_plugin = db_get_value_filter('count(*)', 'tnetwork_component', ['id_plugin' => $plugin_id]); + if (($components_using_plugin + $modules_using_plugin) == 0) { + $locked = false; + } + } else { + $locked = false; + } + + $disabled = ''; + if ($locked) { + $disabled = 'readonly="readonly"'; + } + + $data = []; + $data[0] = __('Plugin command'); + $data[1] = ''; + if ($locked) { + $data[1] .= html_print_image('images/lock.png', true, ['class' => 'command_advanced_conf lock']); + } + + $data[1] .= ' '; + $data[1] .= html_print_image('images/file.png', true); + $data[1] .= ''; + $table->data['plugin_command'] = $data; + + $data = []; + $data[0] = __('Plug-in parameters').ui_print_help_icon('plugin_parameters', true); + $data[1] = ''; + if ($locked) { + $data[1] .= html_print_image('images/lock.png', true, ['class' => 'command_advanced_conf lock']); + } + + $table->data['plugin_parameters'] = $data; + + $data = []; + $data[0] = __('Command preview'); + $data[1] = '
    '; + $table->data['plugin_preview'] = $data; + + $table->width = '100%'; + $table->class = 'databox filters'; + if (defined('METACONSOLE')) { + $table->head[0] = __('Command'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; + html_print_table($table); + } else { + echo '
    '.__('Command').''; + html_print_table($table); + echo '
    '; + } + + $data = []; + + $table->data = []; + + $macros = json_decode($macros, true); + + // The next row number is plugin_9 + $next_name_number = 9; + $i = 1; + while (1) { + // Always print at least one macro + if ((!isset($macros[$i]) || $macros[$i]['desc'] == '') && $i > 1) { + break; + } + + $macro_desc_name = 'field'.$i.'_desc'; + $macro_desc_value = ''; + $macro_help_name = 'field'.$i.'_help'; + $macro_help_value = ''; + $macro_value_name = 'field'.$i.'_value'; + $macro_value_value = ''; + $macro_name_name = 'field'.$i.'_macro'; + $macro_name = '_field'.$i.'_'; + $macro_hide_value_name = 'field'.$i.'_hide'; + $macro_hide_value_value = 0; + + if (isset($macros[$i]['desc'])) { + $macro_desc_value = $macros[$i]['desc']; + } + + if (isset($macros[$i]['help'])) { + $macro_help_value = $macros[$i]['help']; + } + + if (isset($macros[$i]['value'])) { + $macro_value_value = $macros[$i]['value']; + } + + if (isset($macros[$i]['hide'])) { + $macro_hide_value_value = $macros[$i]['hide']; + + // Decrypt hidden macros. + $macro_value_value = io_output_password($macro_value_value); + } + + $datam = []; + $datam[0] = __('Description')." ($macro_name)"; + $datam[0] .= html_print_input_hidden($macro_name_name, $macro_name, true); + $datam[1] = html_print_input_text_extended($macro_desc_name, $macro_desc_value, 'text-'.$macro_desc_name, '', 30, 255, $locked, '', "class='command_macro'", true); + if ($locked) { + $datam[1] .= html_print_image('images/lock.png', true, ['class' => 'command_macro lock']); + } + + $datam[2] = __('Default value')." ($macro_name)"; + $datam[3] = html_print_input_text_extended($macro_value_name, $macro_value_value, 'text-'.$macro_value_name, '', 30, 255, $locked, '', "class='command_component command_macro'", true); + if ($locked) { + $datam[3] .= html_print_image('images/lock.png', true, ['class' => 'command_macro lock']); + } + + $table->data['plugin_'.$next_name_number] = $datam; + + $next_name_number++; + + $table->colspan['plugin_'.$next_name_number][1] = 3; + + $datam = []; + $datam[0] = __('Hide value').ui_print_help_tip(__('This field will show up as dots like a password'), true); + $datam[1] = html_print_checkbox_extended($macro_hide_value_name, 1, $macro_hide_value_value, 0, '', ['class' => 'command_macro'], true, 'checkbox-'.$macro_hide_value_name); + + $table->data['plugin_'.$next_name_number] = $datam; + $next_name_number++; + + $table->colspan['plugin_'.$next_name_number][1] = 3; + + $datam = []; + $datam[0] = __('Help')." ($macro_name)


    "; + $tadisabled = $locked === true ? ' disabled' : ''; + $datam[1] = html_print_textarea($macro_help_name, 6, 100, $macro_help_value, 'class="command_macro" style="width: 97%;"'.$tadisabled, true); + + if ($locked) { + $datam[1] .= html_print_image('images/lock.png', true, ['class' => 'command_macro lock']); + } + + $datam[1] .= '


    '; + + $table->data['plugin_'.$next_name_number] = $datam; + $next_name_number++; + $i++; + } + + // Add/Delete buttons + $datam = []; + $datam[0] = ''.''.__('Add macro').''.' '.html_print_image('images/add.png', true).''; + $datam[0] .= ''; + $datam[0] .= ''; + + if (!$locked) { + $delete_macro_style = ''; + if ($i <= 2) { + $delete_macro_style = 'display:none;'; + } + + $datam[2] = ''; + + $table->colspan['plugin_action'][0] = 2; + $table->colspan['plugin_action'][2] = 2; + } else { + $table->colspan['plugin_action'][0] = 4; + } + + $table->rowstyle['plugin_action'] = 'text-align:center'; + $table->data['plugin_action'] = $datam; + + + if (defined('METACONSOLE')) { + $table->head[0] = __('Parameters macros'); + $table->head_colspan[0] = 4; + $table->headstyle[0] = 'text-align: center'; + html_print_table($table); + } else { + echo '
    '.''.__('Parameters macros').ui_print_help_icon('macros', true).''; + html_print_table($table); + echo '
    '; + } + + echo ''; + + echo '
    '; + + if ($create != '') { + echo ""; + } else { + echo ""; + } + + echo '
    '; + + if (defined('METACONSOLE')) { + echo '
    '; + } else { + echo '
    '; + } + + echo ''; + echo ''; + echo ''; + echo "'; + $color = 0; + + foreach ($rows as $row) { + if ($color == 1) { + $tdcolor = 'datos'; + $color = 0; + } else { + $tdcolor = 'datos2'; + $color = 1; + } + + echo ''; + echo "'; + echo "'; + echo "'; + echo ''; + } + + echo '
    '.__('Name').''.__('Type').''.__('Command').'".''.__('Op.').''.'
    "; + echo ""; + echo $row['name']; + echo '"; + if ($row['plugin_type'] == 0) { + echo __('Standard'); + } else { + echo __('Nagios'); + } + + echo ""; + echo $row['execute']; + echo '"; + + // Show it is locket + $modules_using_plugin = db_get_value_filter( + 'count(*)', + 'tagente_modulo', + [ + 'delete_pending' => 0, + 'id_plugin' => $row['id'], + ] + ); + $components_using_plugin = db_get_value_filter( + 'count(*)', + 'tnetwork_component', + ['id_plugin' => $row['id']] + ); + if (($components_using_plugin + $modules_using_plugin) > 0) { + echo ''; + html_print_image('images/lock.png'); + echo ''; + } + + echo "".html_print_image('images/config.png', true, ['title' => __('Edit')]).'  '; + echo "".html_print_image('images/cross.png', true, ['border' => '0']).''; + echo '
    '; + } else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no plugins in the system') ]); + } + + echo ""; + + echo '
    '; + echo "
    "; + echo ""; + echo '
    '; + + // The '%s' will be replaced in the javascript code of the function 'show_locked_dialog' + echo "'; + + enterprise_hook('close_meta_frame'); } ui_require_javascript_file('pandora_modules'); @@ -810,152 +832,152 @@ ui_require_javascript_file('pandora_modules'); ?> diff --git a/pandora_console/godmode/servers/recon_script.php b/pandora_console/godmode/servers/recon_script.php index be8af68434..b24c2a59e2 100644 --- a/pandora_console/godmode/servers/recon_script.php +++ b/pandora_console/godmode/servers/recon_script.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,379 +11,391 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +if (is_ajax()) { + $get_reconscript_description = get_parameter('get_reconscript_description'); + $id_reconscript = get_parameter('id_reconscript'); + $description = db_get_value_filter( + 'description', + 'trecon_script', + ['id_recon_script' => $id_reconscript] + ); -if (is_ajax ()) { - $get_reconscript_description = get_parameter('get_reconscript_description'); - $id_reconscript = get_parameter('id_reconscript'); - - $description = db_get_value_filter('description', 'trecon_script', - array('id_recon_script' => $id_reconscript)); - - echo htmlentities (io_safe_output($description), ENT_QUOTES, "UTF-8", true); - return; + echo htmlentities(io_safe_output($description), ENT_QUOTES, 'UTF-8', true); + return; } // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "LM")) { - db_pandora_audit("ACL Violation", - "Trying to access recon script Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'LM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access recon script Management' + ); + include 'general/noaccess.php'; + return; } /* * Disabled at the moment. -if (!check_referer()) { - require ("general/noaccess.php"); - - return; + if (!check_referer()) { + require ("general/noaccess.php"); + + return; + } + */ + +$view = get_parameter('view', ''); +$create = get_parameter('create', ''); + +if ($view != '') { + $form_id = $view; + $reconscript = db_get_row('trecon_script', 'id_recon_script', $form_id); + $form_name = $reconscript['name']; + $form_description = $reconscript['description']; + $form_script = $reconscript['script']; + $macros = $reconscript['macros']; } -*/ -$view = get_parameter ("view", ""); -$create = get_parameter ("create", ""); - -if ($view != "") { - $form_id = $view; - $reconscript = db_get_row ("trecon_script", "id_recon_script", $form_id); - $form_name = $reconscript["name"]; - $form_description = $reconscript["description"]; - $form_script = $reconscript ["script"]; - $macros = $reconscript ["macros"]; -} -if ($create != "") { - $form_name = ""; - $form_description = ""; - $form_script = ""; - $macros = ""; +if ($create != '') { + $form_name = ''; + $form_description = ''; + $form_script = ''; + $macros = ''; } // SHOW THE FORM // ================================================================= +if (($create != '') or ($view != '')) { + if ($create != '') { + ui_print_page_header(__('Recon script creation'), 'images/gm_servers.png', false, 'reconscript_definition', true); + } else { + ui_print_page_header(__('Recon script update'), 'images/gm_servers.png', false, 'reconscript_definition', true); + $id_recon_script = get_parameter('view', ''); + } -if (($create != "") OR ($view != "")) { - - if ($create != "") - ui_print_page_header (__('Recon script creation'), "images/gm_servers.png", false, "reconscript_definition", true); - else { - ui_print_page_header (__('Recon script update'), "images/gm_servers.png", false, "reconscript_definition", true); - $id_recon_script = get_parameter ("view",""); - } - - - if ($create == "") - echo ""; - else - echo ""; - - $table = new stdClass(); - $table->width = '100%'; - $table->id = 'table-form'; - $table->class = 'databox filters'; - $table->style = array (); - $table->style[0] = 'font-weight: bold'; - $table->style[2] = 'font-weight: bold'; - $table->data = array (); - - $data = array(); - $data[0] = __('Name'); - $data[1] = ''; - $table->data['recon_name'] = $data; - $table->colspan['recon_name'][1] = 3; - - $data = array(); - $data[0] = __('Script fullpath'); - $data[1] = ''; - $table->data['recon_fullpath'] = $data; - $table->colspan['recon_fullpath'][1] = 3; - $data = array(); - $data[0] = __('Description'); - $data[1] = ''; - $table->data['recon_description'] = $data; - $table->colspan['recon_description'][1] = 3; + if ($create == '') { + echo ""; + } else { + echo ""; + } - $macros = json_decode($macros,true); - - // This code is ready to add locked feature as plugins - $locked = false; - - // The next row number is recon_3 - $next_name_number = 3; - $i = 1; - while (1) { - // Always print at least one macro - if((!isset($macros[$i]) || $macros[$i]['desc'] == '') && $i > 1) { - break; - } - $macro_desc_name = 'field'.$i.'_desc'; - $macro_desc_value = ''; - $macro_help_name = 'field'.$i.'_help'; - $macro_help_value = ''; - $macro_value_name = 'field'.$i.'_value'; - $macro_value_value = ''; - $macro_name_name = 'field'.$i.'_macro'; - $macro_name = '_field'.$i.'_'; - $macro_hide_value_name = 'field'.$i.'_hide'; - $macro_hide_value_value = 0; - - if(isset($macros[$i]['desc'])) { - $macro_desc_value = $macros[$i]['desc']; - } - - if(isset($macros[$i]['help'])) { - $macro_help_value = $macros[$i]['help']; - } - - if(isset($macros[$i]['value'])) { - $macro_value_value = $macros[$i]['value']; - } - if(isset($macros[$i]['hide'])) { - $macro_hide_value_value = $macros[$i]['hide']; - } - - $datam = array (); - $datam[0] = __('Description')." ($macro_name)"; - $datam[0] .= html_print_input_hidden($macro_name_name, $macro_name, true); - $datam[1] = html_print_input_text_extended ($macro_desc_name, $macro_desc_value, 'text-'.$macro_desc_name, '', 30, 255, $locked, '', "class='command_advanced_conf'", true); - if($locked) { - $datam[1] .= html_print_image('images/lock.png', true, array('class' => 'command_advanced_conf')); - } - - $datam[2] = __('Default value')." ($macro_name)"; - $datam[3] = html_print_input_text_extended ($macro_value_name, $macro_value_value, 'text-'.$macro_value_name, '', 30, 255, $locked, '', "class='command_component command_advanced_conf'", true); - if($locked) { - $datam[3] .= html_print_image('images/lock.png', true, array('class' => 'command_advanced_conf')); - } - - $table->data['recon_'.$next_name_number] = $datam; - - $next_name_number++; - - $table->colspan['recon_'.$next_name_number][1] = 3; - - $datam = array (); - $datam[0] = __('Hide value') . ui_print_help_tip(__('This field will show up as dots like a password'), true); - $datam[1] = html_print_checkbox_extended ($macro_hide_value_name, 1, $macro_hide_value_value, 0, '', array('class' => 'command_advanced_conf'), true, 'checkbox-'.$macro_hide_value_name); + $table = new stdClass(); + $table->width = '100%'; + $table->id = 'table-form'; + $table->class = 'databox filters'; + $table->style = []; + $table->style[0] = 'font-weight: bold'; + $table->style[2] = 'font-weight: bold'; + $table->data = []; - $table->data['recon_'.$next_name_number] = $datam; - $next_name_number++; - - $table->colspan['recon_'.$next_name_number][1] = 3; + $data = []; + $data[0] = __('Name'); + $data[1] = ''; + $table->data['recon_name'] = $data; + $table->colspan['recon_name'][1] = 3; - $datam = array (); - $datam[0] = __('Help')." ($macro_name)


    "; - $tadisabled = $locked === true ? ' disabled' : ''; - $datam[1] = html_print_textarea ($macro_help_name, 6, 100, $macro_help_value, 'class="command_advanced_conf" style="width: 97%;"' . $tadisabled, true); - - if($locked) { - $datam[1] .= html_print_image('images/lock.png', true, array('class' => 'command_advanced_conf')); - } - $datam[1] .= "


    "; - - $table->data['recon_'.$next_name_number] = $datam; - $next_name_number++; - $i++; - } - - if (!$locked) { - $datam = array (); - $datam[0] = ''.__('Add macro').' '.html_print_image('images/add.png',true).''; - $datam[0] .= ''; - $datam[0] .= ''; - $delete_macro_style = ''; - if($i <= 2) { - $delete_macro_style = 'display:none;'; - } - $datam[2] = ''; - - $table->colspan['recon_action'][0] = 2; - $table->rowstyle['recon_action'] = 'text-align:center'; - $table->colspan['recon_action'][2] = 2; - $table->data['recon_action'] = $datam; - } - - html_print_table($table); - - echo ''; - echo '
    '; - - if ($create != "") { - echo ""; - } - else { - echo ""; - } - echo '
    '; -} -else { - ui_print_page_header (__('Recon scripts registered on %s', get_product_name()), "images/gm_servers.png", false, "", true); - - // Update reconscript - if (isset($_GET["update_reconscript"])) { // if modified any parameter - $id_recon_script = get_parameter ("update_reconscript", 0); - $reconscript_name = get_parameter ("form_name", ""); - $reconscript_description = get_parameter ("form_description", ""); - $reconscript_script = get_parameter ("form_script", ""); - - // Get macros - $i = 1; - $macros = array(); - while (1) { - $macro = (string)get_parameter ('field'.$i.'_macro'); - if($macro == '') { - break; - } - - $desc = (string)get_parameter ('field'.$i.'_desc'); - $help = (string)get_parameter ('field'.$i.'_help'); - $value = (string)get_parameter ('field'.$i.'_value'); - $hide = get_parameter ('field'.$i.'_hide'); - - $macros[$i]['macro'] = $macro; - $macros[$i]['desc'] = $desc; - $macros[$i]['help'] = $help; - $macros[$i]['value'] = $value; - $macros[$i]['hide'] = $hide; - $i++; - } - - $macros = io_json_mb_encode($macros); - - $sql_update ="UPDATE trecon_script SET + $data = []; + $data[0] = __('Script fullpath'); + $data[1] = ''; + $table->data['recon_fullpath'] = $data; + $table->colspan['recon_fullpath'][1] = 3; + + $data = []; + $data[0] = __('Description'); + $data[1] = ''; + $table->data['recon_description'] = $data; + $table->colspan['recon_description'][1] = 3; + + $macros = json_decode($macros, true); + + // This code is ready to add locked feature as plugins + $locked = false; + + // The next row number is recon_3 + $next_name_number = 3; + $i = 1; + while (1) { + // Always print at least one macro + if ((!isset($macros[$i]) || $macros[$i]['desc'] == '') && $i > 1) { + break; + } + + $macro_desc_name = 'field'.$i.'_desc'; + $macro_desc_value = ''; + $macro_help_name = 'field'.$i.'_help'; + $macro_help_value = ''; + $macro_value_name = 'field'.$i.'_value'; + $macro_value_value = ''; + $macro_name_name = 'field'.$i.'_macro'; + $macro_name = '_field'.$i.'_'; + $macro_hide_value_name = 'field'.$i.'_hide'; + $macro_hide_value_value = 0; + + if (isset($macros[$i]['desc'])) { + $macro_desc_value = $macros[$i]['desc']; + } + + if (isset($macros[$i]['help'])) { + $macro_help_value = $macros[$i]['help']; + } + + if (isset($macros[$i]['value'])) { + $macro_value_value = $macros[$i]['value']; + } + + if (isset($macros[$i]['hide'])) { + $macro_hide_value_value = $macros[$i]['hide']; + } + + $datam = []; + $datam[0] = __('Description')." ($macro_name)"; + $datam[0] .= html_print_input_hidden($macro_name_name, $macro_name, true); + $datam[1] = html_print_input_text_extended($macro_desc_name, $macro_desc_value, 'text-'.$macro_desc_name, '', 30, 255, $locked, '', "class='command_advanced_conf'", true); + if ($locked) { + $datam[1] .= html_print_image('images/lock.png', true, ['class' => 'command_advanced_conf']); + } + + $datam[2] = __('Default value')." ($macro_name)"; + $datam[3] = html_print_input_text_extended($macro_value_name, $macro_value_value, 'text-'.$macro_value_name, '', 30, 255, $locked, '', "class='command_component command_advanced_conf'", true); + if ($locked) { + $datam[3] .= html_print_image('images/lock.png', true, ['class' => 'command_advanced_conf']); + } + + $table->data['recon_'.$next_name_number] = $datam; + + $next_name_number++; + + $table->colspan['recon_'.$next_name_number][1] = 3; + + $datam = []; + $datam[0] = __('Hide value').ui_print_help_tip(__('This field will show up as dots like a password'), true); + $datam[1] = html_print_checkbox_extended($macro_hide_value_name, 1, $macro_hide_value_value, 0, '', ['class' => 'command_advanced_conf'], true, 'checkbox-'.$macro_hide_value_name); + + $table->data['recon_'.$next_name_number] = $datam; + $next_name_number++; + + $table->colspan['recon_'.$next_name_number][1] = 3; + + $datam = []; + $datam[0] = __('Help')." ($macro_name)


    "; + $tadisabled = $locked === true ? ' disabled' : ''; + $datam[1] = html_print_textarea($macro_help_name, 6, 100, $macro_help_value, 'class="command_advanced_conf" style="width: 97%;"'.$tadisabled, true); + + if ($locked) { + $datam[1] .= html_print_image('images/lock.png', true, ['class' => 'command_advanced_conf']); + } + + $datam[1] .= '


    '; + + $table->data['recon_'.$next_name_number] = $datam; + $next_name_number++; + $i++; + } + + if (!$locked) { + $datam = []; + $datam[0] = ''.__('Add macro').' '.html_print_image('images/add.png', true).''; + $datam[0] .= ''; + $datam[0] .= ''; + $delete_macro_style = ''; + if ($i <= 2) { + $delete_macro_style = 'display:none;'; + } + + $datam[2] = ''; + + $table->colspan['recon_action'][0] = 2; + $table->rowstyle['recon_action'] = 'text-align:center'; + $table->colspan['recon_action'][2] = 2; + $table->data['recon_action'] = $datam; + } + + html_print_table($table); + + echo ''; + echo '
    '; + + if ($create != '') { + echo ""; + } else { + echo ""; + } + + echo '
    '; +} else { + ui_print_page_header(__('Recon scripts registered on %s', get_product_name()), 'images/gm_servers.png', false, '', true); + + // Update reconscript + if (isset($_GET['update_reconscript'])) { + // if modified any parameter + $id_recon_script = get_parameter('update_reconscript', 0); + $reconscript_name = get_parameter('form_name', ''); + $reconscript_description = get_parameter('form_description', ''); + $reconscript_script = get_parameter('form_script', ''); + + // Get macros + $i = 1; + $macros = []; + while (1) { + $macro = (string) get_parameter('field'.$i.'_macro'); + if ($macro == '') { + break; + } + + $desc = (string) get_parameter('field'.$i.'_desc'); + $help = (string) get_parameter('field'.$i.'_help'); + $value = (string) get_parameter('field'.$i.'_value'); + $hide = get_parameter('field'.$i.'_hide'); + + $macros[$i]['macro'] = $macro; + $macros[$i]['desc'] = $desc; + $macros[$i]['help'] = $help; + $macros[$i]['value'] = $value; + $macros[$i]['hide'] = $hide; + $i++; + } + + $macros = io_json_mb_encode($macros); + + $sql_update = "UPDATE trecon_script SET name = '$reconscript_name', description = '$reconscript_description', script = '$reconscript_script', macros = '$macros' WHERE id_recon_script = $id_recon_script"; - $result = false; - if ($reconscript_name != '' && $reconscript_script != '') - $result = db_process_sql ($sql_update); - if (! $result) { - ui_print_error_message(__('Problem updating')); - } - else { - ui_print_success_message(__('Updated successfully')); - } - } - - // Create reconscript - if (isset($_GET["create_reconscript"])) { - $reconscript_name = get_parameter ("form_name", ""); - $reconscript_description = get_parameter ("form_description", ""); - $reconscript_script = get_parameter ("form_script", ""); - - // Get macros - $i = 1; - $macros = array(); - while (1) { - $macro = (string)get_parameter ('field'.$i.'_macro'); - if($macro == '') { - break; - } - - $desc = (string)get_parameter ('field'.$i.'_desc'); - $help = (string)get_parameter ('field'.$i.'_help'); - $value = (string)get_parameter ('field'.$i.'_value'); - $hide = get_parameter ('field'.$i.'_hide'); - - $macros[$i]['macro'] = $macro; - $macros[$i]['desc'] = $desc; - $macros[$i]['help'] = $help; - $macros[$i]['value'] = $value; - $macros[$i]['hide'] = $hide; - $i++; - } - - $macros = io_json_mb_encode($macros); - - $values = array( - 'name' => $reconscript_name, - 'description' => $reconscript_description, - 'script' => $reconscript_script, - 'macros' => $macros); - $result = false; - if ($values['name'] != '' && $values['script'] != '') - $result = db_process_sql_insert('trecon_script', $values); - if (! $result) { - ui_print_error_message(__('Problem creating')); - } - else { - ui_print_success_message(__('Created successfully')); - } - } - - if (isset($_GET["kill_reconscript"])) { // if delete alert - $reconscript_id = get_parameter ("kill_reconscript", 0); - - $result = db_process_sql_delete('trecon_script', - array('id_recon_script' => $reconscript_id)); - - if (! $result) { - ui_print_error_message(__('Problem deleting reconscript')); - } - else { - ui_print_success_message(__('reconscript deleted successfully')); - } - if ($reconscript_id != 0) { - $result = db_process_sql_delete('trecon_task', - array('id_recon_script' => $reconscript_id)); - } - } - - // If not edition or insert, then list available reconscripts - - $rows = db_get_all_rows_in_table('trecon_script'); - - if ($rows !== false) { - echo ''; - echo ""; - echo ""; - echo ""; - $color = 0; - foreach ($rows as $row) { - if ($color == 1) { - $tdcolor = "datos"; - $color = 0; - } - else { - $tdcolor = "datos2"; - $color = 1; - } - echo ""; - echo ""; - echo ""; - } - echo "
    " . __('Name') . "" . __('Description') . "" . __('Delete') . "
    "; - echo ""; - echo $row["name"]; - echo ""; - $desc = io_safe_output($row["description"]); - $desc = str_replace("\n", "
    ", $desc); - echo $desc . '

    '; - echo '' . __('Command') . ': ' . $row["script"] . ''; - echo "
    "; - echo "" . html_print_image("images/cross.png", true, array("border" => '0')) . ""; - echo "
    "; - } - else { - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no recon scripts in the system') ) ); - } - echo ""; - echo "
    "; - echo "
    "; - echo ""; - echo "
    "; + $result = false; + if ($reconscript_name != '' && $reconscript_script != '') { + $result = db_process_sql($sql_update); + } + + if (! $result) { + ui_print_error_message(__('Problem updating')); + } else { + ui_print_success_message(__('Updated successfully')); + } + } + + // Create reconscript + if (isset($_GET['create_reconscript'])) { + $reconscript_name = get_parameter('form_name', ''); + $reconscript_description = get_parameter('form_description', ''); + $reconscript_script = get_parameter('form_script', ''); + + // Get macros + $i = 1; + $macros = []; + while (1) { + $macro = (string) get_parameter('field'.$i.'_macro'); + if ($macro == '') { + break; + } + + $desc = (string) get_parameter('field'.$i.'_desc'); + $help = (string) get_parameter('field'.$i.'_help'); + $value = (string) get_parameter('field'.$i.'_value'); + $hide = get_parameter('field'.$i.'_hide'); + + $macros[$i]['macro'] = $macro; + $macros[$i]['desc'] = $desc; + $macros[$i]['help'] = $help; + $macros[$i]['value'] = $value; + $macros[$i]['hide'] = $hide; + $i++; + } + + $macros = io_json_mb_encode($macros); + + $values = [ + 'name' => $reconscript_name, + 'description' => $reconscript_description, + 'script' => $reconscript_script, + 'macros' => $macros, + ]; + $result = false; + if ($values['name'] != '' && $values['script'] != '') { + $result = db_process_sql_insert('trecon_script', $values); + } + + if (! $result) { + ui_print_error_message(__('Problem creating')); + } else { + ui_print_success_message(__('Created successfully')); + } + } + + if (isset($_GET['kill_reconscript'])) { + // if delete alert + $reconscript_id = get_parameter('kill_reconscript', 0); + + $result = db_process_sql_delete( + 'trecon_script', + ['id_recon_script' => $reconscript_id] + ); + + if (! $result) { + ui_print_error_message(__('Problem deleting reconscript')); + } else { + ui_print_success_message(__('reconscript deleted successfully')); + } + + if ($reconscript_id != 0) { + $result = db_process_sql_delete( + 'trecon_task', + ['id_recon_script' => $reconscript_id] + ); + } + } + + // If not edition or insert, then list available reconscripts + $rows = db_get_all_rows_in_table('trecon_script'); + + if ($rows !== false) { + echo ''; + echo ''; + echo ''; + echo ''; + $color = 0; + foreach ($rows as $row) { + if ($color == 1) { + $tdcolor = 'datos'; + $color = 0; + } else { + $tdcolor = 'datos2'; + $color = 1; + } + + echo ''; + echo "'; + echo "'; + } + + echo '
    '.__('Name').''.__('Description').''.__('Delete').'
    "; + echo ""; + echo $row['name']; + echo '"; + $desc = io_safe_output($row['description']); + $desc = str_replace("\n", '
    ', $desc); + echo $desc.'

    '; + echo ''.__('Command').': '.$row['script'].''; + echo "
    "; + echo "".html_print_image('images/cross.png', true, ['border' => '0']).''; + echo '
    '; + } else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no recon scripts in the system') ]); + } + + echo ''; + echo '
    '; + echo ""; + echo ""; + echo '
    '; } ui_require_javascript_file('pandora_modules'); - -?> - diff --git a/pandora_console/godmode/servers/servers.build_table.php b/pandora_console/godmode/servers/servers.build_table.php index 1090f76490..2bb4f6ab00 100644 --- a/pandora_console/godmode/servers/servers.build_table.php +++ b/pandora_console/godmode/servers/servers.build_table.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2012 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,20 +11,20 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars - -require_once ('include/functions_clippy.php'); +require_once 'include/functions_clippy.php'; global $config; check_login(); -if (! check_acl ($config["id_user"], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access Server Management"); - require ("general/noaccess.php"); - exit; +if (! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Server Management' + ); + include 'general/noaccess.php'; + exit; } global $tiny; @@ -34,20 +33,20 @@ $date = time(); $servers = servers_get_info(); if ($servers === false) { - $server_clippy = clippy_context_help("servers_down"); - echo "
    ".__('There are no servers configured into the database').$server_clippy."
    "; - return; + $server_clippy = clippy_context_help('servers_down'); + echo "
    ".__('There are no servers configured into the database').$server_clippy.'
    '; + return; } $table = new StdClass(); $table->width = '100%'; $table->class = 'databox data'; -$table->size = array (); +$table->size = []; -$table->style = array (); +$table->style = []; $table->style[0] = 'font-weight: bold'; -$table->align = array (); +$table->align = []; $table->align[1] = 'center'; $table->align[3] = 'center'; $table->align[8] = 'center'; @@ -56,154 +55,177 @@ $table->headstyle[1] = 'text-align:center'; $table->headstyle[3] = 'text-align:center'; $table->headstyle[8] = 'text-align:center'; -//$table->title = __('Tactical server information'); +// $table->title = __('Tactical server information'); $table->titleclass = 'tabletitle'; $table->titlestyle = 'text-transform:uppercase;'; -$table->head = array (); +$table->head = []; $table->head[0] = __('Name'); $table->head[1] = __('Status'); $table->head[2] = __('Type'); $table->head[3] = __('Version'); $table->head[4] = __('Modules'); -$table->head[5] = __('Lag') . ui_print_help_tip (__("Avg. Delay(sec)/Modules delayed"), true); -$table->head[6] = __('T/Q') . ui_print_help_tip (__("Threads / Queued modules currently"), true); +$table->head[5] = __('Lag').ui_print_help_tip(__('Avg. Delay(sec)/Modules delayed'), true); +$table->head[6] = __('T/Q').ui_print_help_tip(__('Threads / Queued modules currently'), true); // This will have a column of data such as "6 hours" $table->head[7] = __('Updated'); -//Only Pandora Administrator can delete servers -if (check_acl ($config["id_user"], 0, "PM")) { - $table->head[8] = '' . __('Op.') . ''; +// Only Pandora Administrator can delete servers +if (check_acl($config['id_user'], 0, 'PM')) { + $table->head[8] = ''.__('Op.').''; } -$table->data = array (); -$names_servers = array (); +$table->data = []; +$names_servers = []; foreach ($servers as $server) { - $data = array (); - $table->cellclass[][3] = "progress_bar"; - $data[0] = '' . - strip_tags($server['name']) . ''; - - //Status - $data[1] = ui_print_status_image (STATUS_SERVER_OK, '', true); - if (($server['status'] == 0) || (($date - time_w_fixed_tz($server['keepalive'])) > ($server['server_keepalive'])*2)) { - $data[1] = ui_print_status_image (STATUS_SERVER_DOWN, '', true); - } - - // Type - $data[2] = '' . $server["img"]; - if ($server["master"] == 1) { - $data[2] .= ui_print_help_tip (__("This is a master server"), true); - } - //$data[2] .= ' v' .. ''; - - switch ($server['type']) { - case "snmp": - case "event": - case "autoprovision": - case "migration": - $data[3] = $server["version"]; - $data[4] = __('N/A'); - $data[5] = __('N/A'); - break; - case "export": - $data[3] = $server["version"]; - $data[4] = $server["modules"] . " ".__('of')." ". $server["modules_total"]; - $data[5] = __('N/A'); - break; - default: - $data[3] = $server["version"]; - $data[4] = $server["modules"] . " ".__('of')." ". $server["modules_total"]; - $data[5] = '' . - $server["lag_txt"] . ''; - break; - } - - $data[6] = $server['threads'].' : '.$server['queued_modules']; - if ($server['queued_modules'] > 200) { - $data[6] .= clippy_context_help("server_queued_modules"); - } - $data[7] = ui_print_timestamp ($server['keepalive'], true); - - - $ext = '_server'; - if ($server['type'] != 'data') - $ext = ''; - - $safe_server_name = servers_get_name($server["id_server"]); - if (($server['type'] == 'data' || $server['type'] == 'enterprise satellite')) { - if (servers_check_remote_config ($safe_server_name . $ext) && enterprise_installed()) { - $names_servers[$safe_server_name] = true; - } else { - $names_servers[$safe_server_name] = false; - } - } - - //Only Pandora Administrator can delete servers - if (check_acl ($config["id_user"], 0, "PM")) { - $data[8] = ''; - - if ($server['type'] == 'recon') { - $data[8] .= ''; - $data[8] .= html_print_image ('images/firts_task/icono_grande_reconserver.png', true, - array('title' => __('Manage recon tasks'),'style' => 'width:21px;height:21px;')); - $data[8] .= '  '; - } - - if ($server['type'] == 'data') { - $data[8] .= ''; - $data[8] .= html_print_image ('images/target.png', true, - array('title' => __('Reset module status and fired alert counts'))); - $data[8] .= '  '; - } - else if ($server['type'] == 'enterprise snmp') { - $data[8] .= ''; - $data[8] .= html_print_image ('images/target.png', true, - array('title' => __('Claim back SNMP modules'))); - $data[8] .= '  '; - } - - $data[8] .= ''; - $data[8] .= html_print_image ('images/config.png', true, - array('title' => __('Edit'))); - $data[8] .= ''; - - if (($names_servers[$safe_server_name] === true) && ($server['type'] == 'data' || $server['type'] == 'enterprise satellite')) { - $data[8] .= ''; - $data[8] .= html_print_image ('images/remote_configuration.png', true, - array('title' => __('Remote configuration'))); - $data[8] .= ''; - $names_servers[$safe_server_name] = false; - } - - $data[8] .= '  '; - $data[8] .= html_print_image ('images/cross.png', true, - array('title' => __('Delete'), - 'onclick' => "if (! confirm ('" . __('Modules run by this server will stop working. Do you want to continue?') ."')) return false")); - $data[8] .= ''; - } - - if ($tiny) { - unset($data[4]); - unset($data[6]); - unset($data[7]); - unset($data[8]); - } - array_push ($table->data, $data); - + $data = []; + $table->cellclass[][3] = 'progress_bar'; + $data[0] = ''.strip_tags($server['name']).''; + + // Status + $data[1] = ui_print_status_image(STATUS_SERVER_OK, '', true); + if (($server['status'] == 0) || (($date - time_w_fixed_tz($server['keepalive'])) > ($server['server_keepalive']) * 2)) { + $data[1] = ui_print_status_image(STATUS_SERVER_DOWN, '', true); + } + + // Type + $data[2] = ''.$server['img']; + if ($server['master'] == 1) { + $data[2] .= ui_print_help_tip(__('This is a master server'), true); + } + + // $data[2] .= ' v' .. ''; + switch ($server['type']) { + case 'snmp': + case 'event': + case 'autoprovision': + case 'migration': + $data[3] = $server['version']; + $data[4] = __('N/A'); + $data[5] = __('N/A'); + break; + + case 'export': + $data[3] = $server['version']; + $data[4] = $server['modules'].' '.__('of').' '.$server['modules_total']; + $data[5] = __('N/A'); + break; + + default: + $data[3] = $server['version']; + $data[4] = $server['modules'].' '.__('of').' '.$server['modules_total']; + $data[5] = ''.$server['lag_txt'].''; + break; + } + + $data[6] = $server['threads'].' : '.$server['queued_modules']; + if ($server['queued_modules'] > 200) { + $data[6] .= clippy_context_help('server_queued_modules'); + } + + $data[7] = ui_print_timestamp($server['keepalive'], true); + + + $ext = '_server'; + if ($server['type'] != 'data') { + $ext = ''; + } + + $safe_server_name = servers_get_name($server['id_server']); + if (($server['type'] == 'data' || $server['type'] == 'enterprise satellite')) { + if (servers_check_remote_config($safe_server_name.$ext) && enterprise_installed()) { + $names_servers[$safe_server_name] = true; + } else { + $names_servers[$safe_server_name] = false; + } + } + + // Only Pandora Administrator can delete servers + if (check_acl($config['id_user'], 0, 'PM')) { + $data[8] = ''; + + if ($server['type'] == 'recon') { + $data[8] .= ''; + $data[8] .= html_print_image( + 'images/firts_task/icono_grande_reconserver.png', + true, + [ + 'title' => __('Manage recon tasks'), + 'style' => 'width:21px;height:21px;', + ] + ); + $data[8] .= '  '; + } + + if ($server['type'] == 'data') { + $data[8] .= ''; + $data[8] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Reset module status and fired alert counts')] + ); + $data[8] .= '  '; + } else if ($server['type'] == 'enterprise snmp') { + $data[8] .= ''; + $data[8] .= html_print_image( + 'images/target.png', + true, + ['title' => __('Claim back SNMP modules')] + ); + $data[8] .= '  '; + } + + $data[8] .= ''; + $data[8] .= html_print_image( + 'images/config.png', + true, + ['title' => __('Edit')] + ); + $data[8] .= ''; + + if (($names_servers[$safe_server_name] === true) && ($server['type'] == 'data' || $server['type'] == 'enterprise satellite')) { + $data[8] .= ''; + $data[8] .= html_print_image( + 'images/remote_configuration.png', + true, + ['title' => __('Remote configuration')] + ); + $data[8] .= ''; + $names_servers[$safe_server_name] = false; + } + + $data[8] .= '  '; + $data[8] .= html_print_image( + 'images/cross.png', + true, + [ + 'title' => __('Delete'), + 'onclick' => "if (! confirm ('".__('Modules run by this server will stop working. Do you want to continue?')."')) return false", + ] + ); + $data[8] .= ''; + } + + if ($tiny) { + unset($data[4]); + unset($data[6]); + unset($data[7]); + unset($data[8]); + } + + array_push($table->data, $data); } if ($tiny) { - unset($table->head[4]); - unset($table->head[6]); - unset($table->head[7]); - unset($table->head[8]); + unset($table->head[4]); + unset($table->head[6]); + unset($table->head[7]); + unset($table->head[8]); } + if ($tiny) { - ui_toggle(html_print_table ($table,true), __('Tactical server information'),false,$hidden_toggle); + ui_toggle(html_print_table($table, true), __('Tactical server information'), false, $hidden_toggle); +} else { + html_print_table($table); } -else { - html_print_table ($table); -} -?> diff --git a/pandora_console/godmode/setup/file_manager.php b/pandora_console/godmode/setup/file_manager.php index 3ffcc3768d..27f3e232c8 100644 --- a/pandora_console/godmode/setup/file_manager.php +++ b/pandora_console/godmode/setup/file_manager.php @@ -1,10 +1,9 @@ -' . __('Index of %s', $directory) . ''; +echo '

    '.__('Index of %s', $directory).'

    '; -$homedir_filemanager = isset ($config['homedir_filemanager']) ? $config['homedir_filemanager'] : false; +$homedir_filemanager = isset($config['homedir_filemanager']) ? $config['homedir_filemanager'] : false; -filemanager_file_explorer($real_directory, - $directory, - 'index.php?sec=gsetup&sec2=godmode/setup/file_manager', - '', - false, - false, - '', - false, - '', - $homedir_filemanager); -?> +filemanager_file_explorer( + $real_directory, + $directory, + 'index.php?sec=gsetup&sec2=godmode/setup/file_manager', + '', + false, + false, + '', + false, + '', + $homedir_filemanager +); diff --git a/pandora_console/godmode/setup/gis.php b/pandora_console/godmode/setup/gis.php index 6288b3b751..946d0526ea 100755 --- a/pandora_console/godmode/setup/gis.php +++ b/pandora_console/godmode/setup/gis.php @@ -3,7 +3,7 @@ * Pandora FMS- http://pandorafms.com * ================================================== * Copyright (c) 2005-2010 Artica Soluciones Tecnologicas - * + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation for version 2. @@ -16,46 +16,51 @@ // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Visual Setup Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Visual Setup Management'); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_gis.php'); +require_once 'include/functions_gis.php'; ui_require_javascript_file('openlayers.pandora'); // Header -ui_print_page_header (__('Map conections GIS'), "", false, "setup_gis_index", true); +ui_print_page_header(__('Map conections GIS'), '', false, 'setup_gis_index', true); $action = get_parameter('action'); switch ($action) { - case 'save_edit_map_connection': - if(!$errorfill) - ui_print_success_message(__('Successfully updated')); - else - ui_print_error_message(__('Could not be updated')); - break; - case 'save_map_connection': - if(!$errorfill) - ui_print_success_message(__('Successfully created')); - else - ui_print_error_message(__('Could not be created')); - break; - case 'delete_connection': - $idConnectionMap = get_parameter('id_connection_map'); - - $result = gis_delete_map_connection($idConnectionMap); - - if($result === false) - ui_print_error_message(__('Could not be deleted')); - else - ui_print_success_message(__('Successfully deleted')); - break; + case 'save_edit_map_connection': + if (!$errorfill) { + ui_print_success_message(__('Successfully updated')); + } else { + ui_print_error_message(__('Could not be updated')); + } + break; + + case 'save_map_connection': + if (!$errorfill) { + ui_print_success_message(__('Successfully created')); + } else { + ui_print_error_message(__('Could not be created')); + } + break; + + case 'delete_connection': + $idConnectionMap = get_parameter('id_connection_map'); + + $result = gis_delete_map_connection($idConnectionMap); + + if ($result === false) { + ui_print_error_message(__('Could not be deleted')); + } else { + ui_print_success_message(__('Successfully deleted')); + } + break; } $table->width = '98%'; @@ -67,30 +72,26 @@ $table->align[1] = 'center'; $table->align[2] = 'center'; $table->align[3] = 'center'; -$mapsConnections = db_get_all_rows_in_table ('tgis_map_connection','conection_name'); +$mapsConnections = db_get_all_rows_in_table('tgis_map_connection', 'conection_name'); -$table->data = array(); +$table->data = []; if ($mapsConnections !== false) { - foreach ($mapsConnections as $mapsConnection) { - $table->data[] = array('' - . $mapsConnection['conection_name'] . '', - ui_print_group_icon ($mapsConnection['group_id'], true), - '' . - html_print_image ("images/cross.png", true).''); - } + foreach ($mapsConnections as $mapsConnection) { + $table->data[] = [ + ''.$mapsConnection['conection_name'].'', + ui_print_group_icon($mapsConnection['group_id'], true), + ''.html_print_image('images/cross.png', true).'', + ]; + } } html_print_table($table); echo '
    '; echo ''; -html_print_input_hidden ('action','create_connection_map'); -html_print_submit_button (__('Create'), '', false, 'class="sub next"'); +html_print_input_hidden('action', 'create_connection_map'); +html_print_submit_button(__('Create'), '', false, 'class="sub next"'); echo ''; echo '
    '; -?> diff --git a/pandora_console/godmode/setup/gis_step_2.php b/pandora_console/godmode/setup/gis_step_2.php index 3de03185f2..5203bdef23 100644 --- a/pandora_console/godmode/setup/gis_step_2.php +++ b/pandora_console/godmode/setup/gis_step_2.php @@ -3,7 +3,7 @@ * Pandora FMS- http://pandorafms.com * ================================================== * Copyright (c) 2005-2010 Artica Soluciones Tecnologicas - * + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation for version 2. @@ -16,178 +16,197 @@ // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Visual Setup Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Visual Setup Management'); + include 'general/noaccess.php'; + return; } -require_once ('include/functions_gis.php'); +require_once 'include/functions_gis.php'; $action = get_parameter('action', 'create_connection_map'); -if (is_ajax ()) { +if (is_ajax()) { } echo '
    '; switch ($action) { - case 'create_connection_map': - // Header - ui_print_page_header (__('Create new map connection'), "", false, "gis_setup_map_connection", true); - - $mapConnection_name = ''; - $mapConnection_group = ''; - $mapConnection_numLevelsZoom = '19'; - $mapConnection_defaultZoom = '16'; - $mapConnection_type = 0; - $mapConnection_defaultLatitude = '40.42056'; - $mapConnection_defaultLongitude = '-3.708187'; - $mapConnection_defaultAltitude = '0'; - $mapConnection_centerLatitude = '40.42056'; - $mapConnection_centerLongitude = '-3.708187'; - $mapConnection_centerAltitude = '0'; - $mapConnectionData = null; - - html_print_input_hidden('action', 'save_map_connection'); - break; - case 'edit_connection_map': - // Header - ui_print_page_header (__('Edit map connection'), "", false, "gis_setup_map_connection", true); - - $idConnectionMap = get_parameter('id_connection_map'); - $mapConnection = db_get_row_sql('SELECT * FROM tgis_map_connection WHERE id_tmap_connection = ' . $idConnectionMap); - - $mapConnection_name = $mapConnection['conection_name']; - $mapConnection_group = $mapConnection['group_id']; - $mapConnection_numLevelsZoom = $mapConnection['num_zoom_levels']; - $mapConnection_defaultZoom = $mapConnection['default_zoom_level']; - $mapConnection_type = $mapConnection['connection_type']; - $mapConnection_defaultLatitude = $mapConnection['default_latitude']; - $mapConnection_defaultLongitude = $mapConnection['default_longitude']; - $mapConnection_defaultAltitude = $mapConnection['default_altitude']; - $mapConnection_centerLatitude = $mapConnection['initial_latitude']; - $mapConnection_centerLongitude = $mapConnection['initial_longitude']; - $mapConnection_centerAltitude = $mapConnection['initial_altitude']; - $mapConnectionData = json_decode($mapConnection['conection_data'], true); - - html_print_input_hidden('id_connection_map', $idConnectionMap); - html_print_input_hidden('action', 'save_edit_map_connection'); - break; - case 'save_map_connection': - case 'save_edit_map_connection': - $mapConnection_name = get_parameter('name'); - $mapConnection_group = get_parameter('group'); - $mapConnection_numLevelsZoom = get_parameter('num_levels_zoom'); - $mapConnection_defaultZoom = get_parameter('initial_zoom'); - $mapConnection_type = get_parameter('type'); - $mapConnection_defaultLatitude = get_parameter('default_latitude'); - $mapConnection_defaultLongitude = get_parameter('default_longitude'); - $mapConnection_defaultAltitude = get_parameter('default_altitude'); - $mapConnection_centerLatitude = get_parameter('center_latitude'); - $mapConnection_centerLongitude = get_parameter('center_longitude'); - $mapConnection_centerAltitude = get_parameter('center_altitude'); - - $idConnectionMap = get_parameter('id_connection_map', null); - - switch ($mapConnection_type) { - case 'OSM': - $mapConnection_OSM_url = get_parameter('url'); - $mapConnectionData = array('type' => 'OSM', - 'url' => $mapConnection_OSM_url); - break; - case 'Gmap': - $gmap_type= get_parameter('gmap_type'); - $gmap_key= get_parameter('gmap_key'); - $mapConnectionData = array('type' => 'Gmap', - 'gmap_type' => $gmap_type, - 'gmap_key' => $gmap_key); - break; - case 'Static_Image': - $mapConnection_Image_url= get_parameter('url'); - $bb_left= get_parameter('bb_left'); - $bb_right= get_parameter('bb_right'); - $bb_top= get_parameter('bb_top'); - $bb_bottom= get_parameter('bb_bottom'); - $image_height= get_parameter('image_height'); - $image_width= get_parameter('image_width'); - $mapConnectionData = array('type' => 'Static_Image', - 'url' => $mapConnection_Image_url, - 'bb_left' => $bb_left, - 'bb_right' => $bb_right, - 'bb_top' => $bb_top, - 'bb_bottom' => $bb_bottom, - 'image_width' => $image_width, - 'image_height' => $image_height - ); - break; - case 'WMS': - $url = get_parameter('url'); - $layers = get_parameter('layers'); - $mapConnectionData = array( - 'type' => 'WMS', - 'url' => $url, - 'layers' => $layers - ); - break; - } - - //TODO VALIDATE PARAMETERS - if ($mapConnection_name != "" && $mapConnection_type != "") { - gis_save_map_connection($mapConnection_name, $mapConnection_group, - $mapConnection_numLevelsZoom, $mapConnection_defaultZoom, - $mapConnection_defaultLatitude, $mapConnection_defaultLongitude, - $mapConnection_defaultAltitude, $mapConnection_centerLatitude, - $mapConnection_centerLongitude, $mapConnection_centerAltitude, - $mapConnectionData, $idConnectionMap); - - $errorfill = false; - } - else - $errorfill = true; - - require_once('gis.php'); - return; - break; + case 'create_connection_map': + // Header + ui_print_page_header(__('Create new map connection'), '', false, 'gis_setup_map_connection', true); + + $mapConnection_name = ''; + $mapConnection_group = ''; + $mapConnection_numLevelsZoom = '19'; + $mapConnection_defaultZoom = '16'; + $mapConnection_type = 0; + $mapConnection_defaultLatitude = '40.42056'; + $mapConnection_defaultLongitude = '-3.708187'; + $mapConnection_defaultAltitude = '0'; + $mapConnection_centerLatitude = '40.42056'; + $mapConnection_centerLongitude = '-3.708187'; + $mapConnection_centerAltitude = '0'; + $mapConnectionData = null; + + html_print_input_hidden('action', 'save_map_connection'); + break; + + case 'edit_connection_map': + // Header + ui_print_page_header(__('Edit map connection'), '', false, 'gis_setup_map_connection', true); + + $idConnectionMap = get_parameter('id_connection_map'); + $mapConnection = db_get_row_sql('SELECT * FROM tgis_map_connection WHERE id_tmap_connection = '.$idConnectionMap); + + $mapConnection_name = $mapConnection['conection_name']; + $mapConnection_group = $mapConnection['group_id']; + $mapConnection_numLevelsZoom = $mapConnection['num_zoom_levels']; + $mapConnection_defaultZoom = $mapConnection['default_zoom_level']; + $mapConnection_type = $mapConnection['connection_type']; + $mapConnection_defaultLatitude = $mapConnection['default_latitude']; + $mapConnection_defaultLongitude = $mapConnection['default_longitude']; + $mapConnection_defaultAltitude = $mapConnection['default_altitude']; + $mapConnection_centerLatitude = $mapConnection['initial_latitude']; + $mapConnection_centerLongitude = $mapConnection['initial_longitude']; + $mapConnection_centerAltitude = $mapConnection['initial_altitude']; + $mapConnectionData = json_decode($mapConnection['conection_data'], true); + + html_print_input_hidden('id_connection_map', $idConnectionMap); + html_print_input_hidden('action', 'save_edit_map_connection'); + break; + + case 'save_map_connection': + case 'save_edit_map_connection': + $mapConnection_name = get_parameter('name'); + $mapConnection_group = get_parameter('group'); + $mapConnection_numLevelsZoom = get_parameter('num_levels_zoom'); + $mapConnection_defaultZoom = get_parameter('initial_zoom'); + $mapConnection_type = get_parameter('type'); + $mapConnection_defaultLatitude = get_parameter('default_latitude'); + $mapConnection_defaultLongitude = get_parameter('default_longitude'); + $mapConnection_defaultAltitude = get_parameter('default_altitude'); + $mapConnection_centerLatitude = get_parameter('center_latitude'); + $mapConnection_centerLongitude = get_parameter('center_longitude'); + $mapConnection_centerAltitude = get_parameter('center_altitude'); + + $idConnectionMap = get_parameter('id_connection_map', null); + + switch ($mapConnection_type) { + case 'OSM': + $mapConnection_OSM_url = get_parameter('url'); + $mapConnectionData = [ + 'type' => 'OSM', + 'url' => $mapConnection_OSM_url, + ]; + break; + + case 'Gmap': + $gmap_type = get_parameter('gmap_type'); + $gmap_key = get_parameter('gmap_key'); + $mapConnectionData = [ + 'type' => 'Gmap', + 'gmap_type' => $gmap_type, + 'gmap_key' => $gmap_key, + ]; + break; + + case 'Static_Image': + $mapConnection_Image_url = get_parameter('url'); + $bb_left = get_parameter('bb_left'); + $bb_right = get_parameter('bb_right'); + $bb_top = get_parameter('bb_top'); + $bb_bottom = get_parameter('bb_bottom'); + $image_height = get_parameter('image_height'); + $image_width = get_parameter('image_width'); + $mapConnectionData = [ + 'type' => 'Static_Image', + 'url' => $mapConnection_Image_url, + 'bb_left' => $bb_left, + 'bb_right' => $bb_right, + 'bb_top' => $bb_top, + 'bb_bottom' => $bb_bottom, + 'image_width' => $image_width, + 'image_height' => $image_height, + ]; + break; + + case 'WMS': + $url = get_parameter('url'); + $layers = get_parameter('layers'); + $mapConnectionData = [ + 'type' => 'WMS', + 'url' => $url, + 'layers' => $layers, + ]; + break; + } + + // TODO VALIDATE PARAMETERS + if ($mapConnection_name != '' && $mapConnection_type != '') { + gis_save_map_connection( + $mapConnection_name, + $mapConnection_group, + $mapConnection_numLevelsZoom, + $mapConnection_defaultZoom, + $mapConnection_defaultLatitude, + $mapConnection_defaultLongitude, + $mapConnection_defaultAltitude, + $mapConnection_centerLatitude, + $mapConnection_centerLongitude, + $mapConnection_centerAltitude, + $mapConnectionData, + $idConnectionMap + ); + + $errorfill = false; + } else { + $errorfill = true; + } + + include_once 'gis.php'; + return; + + break; } $table->width = '90%'; -$table->data = array(); -$table->data[0][0] = __('Connection Name') . ui_print_help_tip (__('Descriptive name for the connection'), true). ":"; -$table->data[0][1] = html_print_input_text ('name', $mapConnection_name, '', 30, 60, true); +$table->data = []; +$table->data[0][0] = __('Connection Name').ui_print_help_tip(__('Descriptive name for the connection'), true).':'; +$table->data[0][1] = html_print_input_text('name', $mapConnection_name, '', 30, 60, true); -$table->data[1][0] = __("Group") . ui_print_help_tip (__('Group that owns the connection'), true) . ":"; +$table->data[1][0] = __('Group').ui_print_help_tip(__('Group that owns the connection'), true).':'; $table->data[1][1] = html_print_select_groups(false, false, false, 'group', $mapConnection_group, '', __('All'), '0', true); -$table->data[2][0] = __('Number of zoom levels') . ":"; -$table->data[2][1] = html_print_input_text ('num_levels_zoom', $mapConnection_numLevelsZoom, '', 4, 10, true); +$table->data[2][0] = __('Number of zoom levels').':'; +$table->data[2][1] = html_print_input_text('num_levels_zoom', $mapConnection_numLevelsZoom, '', 4, 10, true); -$table->data[3][0] = __('Default zoom level') . ui_print_help_tip (__('Zoom level used when the map is opened'), true). ":"; -$table->data[3][1] = html_print_input_text ('initial_zoom', $mapConnection_defaultZoom, '', 4, 10, true); +$table->data[3][0] = __('Default zoom level').ui_print_help_tip(__('Zoom level used when the map is opened'), true).':'; +$table->data[3][1] = html_print_input_text('initial_zoom', $mapConnection_defaultZoom, '', 4, 10, true); -echo "

    " . __('Basic configuration') . "

    "; +echo '

    '.__('Basic configuration').'

    '; html_print_table($table); $table->width = '60%'; -$table->data = array(); -$types["OSM"] = __('Open Street Maps'); -$types["Gmap"] = __('Google Maps'); -$types["Static_Image"] = __('Static Image'); -$types["WMS"] = __('WMS Server'); -$table->data[0][0] = __('Type') . ":"; -$table->data[0][1] = html_print_select($types, 'sel_type', $mapConnection_type, "selMapConnectionType();", __('Please select the connection type'), 0, true); +$table->data = []; +$types['OSM'] = __('Open Street Maps'); +$types['Gmap'] = __('Google Maps'); +$types['Static_Image'] = __('Static Image'); +$types['WMS'] = __('WMS Server'); +$table->data[0][0] = __('Type').':'; +$table->data[0][1] = html_print_select($types, 'sel_type', $mapConnection_type, 'selMapConnectionType();', __('Please select the connection type'), 0, true); -echo "

    " . __('Map connection type') . "

    "; -html_print_table ($table); +echo '

    '.__('Map connection type').'

    '; +html_print_table($table); $optionsConnectionTypeTable = ''; $mapConnectionDataUrl = ''; $gmap_type = ''; -$gmap_key= ''; +$gmap_key = ''; $bb_left = ''; $bb_right = ''; $bb_bottom = ''; @@ -196,159 +215,104 @@ $image_width = ''; $image_height = ''; $layers = ''; if ($mapConnectionData != null) { - switch ($mapConnection_type) { - case 'OSM': - $mapConnectionDataUrl = $mapConnectionData['url']; - break; - case 'Gmap': - $gmap_type = $mapConnectionData['gmap_type']; - $gmap_key = $mapConnectionData['gmap_key']; - break; - case 'Static_Image': - $mapConnectionDataUrl = $mapConnectionData['url']; - $bb_left= $mapConnectionData['bb_left']; - $bb_right= $mapConnectionData['bb_right']; - $bb_bottom= $mapConnectionData['bb_bottom']; - $bb_top= $mapConnectionData['bb_top']; - $image_width= $mapConnectionData['image_width']; - $image_height= $mapConnectionData['image_height']; - break; - case 'WMS': - $mapConnectionDataUrl = $mapConnectionData['url']; - $layers = $mapConnectionData['layers']; - break; - } + switch ($mapConnection_type) { + case 'OSM': + $mapConnectionDataUrl = $mapConnectionData['url']; + break; + + case 'Gmap': + $gmap_type = $mapConnectionData['gmap_type']; + $gmap_key = $mapConnectionData['gmap_key']; + break; + + case 'Static_Image': + $mapConnectionDataUrl = $mapConnectionData['url']; + $bb_left = $mapConnectionData['bb_left']; + $bb_right = $mapConnectionData['bb_right']; + $bb_bottom = $mapConnectionData['bb_bottom']; + $bb_top = $mapConnectionData['bb_top']; + $image_width = $mapConnectionData['image_width']; + $image_height = $mapConnectionData['image_height']; + break; + + case 'WMS': + $mapConnectionDataUrl = $mapConnectionData['url']; + $layers = $mapConnectionData['layers']; + break; + } } + // Open Street Map Connection -$optionsConnectionOSMTable = '' . - '' . - '' . - '' . - '' . - '
    ' . htmlentities(__("Tile Server URL"), ENT_QUOTES, "UTF-8") . ':' . html_print_input_text ('url', $mapConnectionDataUrl, '', 45, 90, true) . '
    '; +$optionsConnectionOSMTable = ''.''.''.''.''.'
    '.htmlentities(__('Tile Server URL'), ENT_QUOTES, 'UTF-8').':'.html_print_input_text('url', $mapConnectionDataUrl, '', 45, 90, true).'
    '; // Google Maps Connection -$gmaps_types["G_PHYSICAL_MAP"] = __('Google Physical'); -$gmaps_types["G_HYBRID_MAP"] = __('Google Hybrid'); -$gmaps_types["G_SATELITE_MAP"] = __('Google Satelite'); +$gmaps_types['G_PHYSICAL_MAP'] = __('Google Physical'); +$gmaps_types['G_HYBRID_MAP'] = __('Google Hybrid'); +$gmaps_types['G_SATELITE_MAP'] = __('Google Satelite'); // TODO: Use label tags for the forms. -$optionsConnectionGmapTable = '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '
    ' . __("Google Map Type") . ':'.trim(html_print_select($gmaps_types,'gmap_type', $gmap_type, "", '', 0, true)) . '
    ' . __("Google Maps Key") . ':
    ' . html_print_input_text ('gmap_key', $gmap_key, '', 90, 128, true) . '
    '; +$optionsConnectionGmapTable = ''.''.''.''.''.''.''.''.''.''.''.'
    '.__('Google Map Type').':'.trim(html_print_select($gmaps_types, 'gmap_type', $gmap_type, '', '', 0, true)).'
    '.__('Google Maps Key').':
    '.html_print_input_text('gmap_key', $gmap_key, '', 90, 128, true).'
    '; // Image Map Connection -$optionsConnectionImageTable = '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '
    ' . __("Image URL") . ':' . html_print_input_text ('url', $mapConnectionDataUrl, '', 45, 90, true) . '
    ' . __("Corners of the area of the image") . ':
    ' . __("Left") . ':'. html_print_input_text ('bb_left', $bb_left, '', 25, 25, true) . '' . __("Bottom") . ':'. html_print_input_text ('bb_bottom', $bb_bottom, '',25 , 25, true) . '
    ' . __("Right") . ':'. html_print_input_text ('bb_right', $bb_right, '', 25, 25, true) . '' . __("Top") . ':'. html_print_input_text ('bb_top', $bb_top, '', 25, 25, true) . '
    ' . __("Image Size") . ':
    ' . __("Width") . ':'. html_print_input_text ('image_width', $image_width, '', 25, 25, true) . '' . __("Height") . ':'. html_print_input_text ('image_height', $image_height, '', 25, 25, true) . '
    '; +$optionsConnectionImageTable = ''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.''.'
    '.__('Image URL').':'.html_print_input_text('url', $mapConnectionDataUrl, '', 45, 90, true).'
    '.__('Corners of the area of the image').':
    '.__('Left').':'.html_print_input_text('bb_left', $bb_left, '', 25, 25, true).''.__('Bottom').':'.html_print_input_text('bb_bottom', $bb_bottom, '', 25, 25, true).'
    '.__('Right').':'.html_print_input_text('bb_right', $bb_right, '', 25, 25, true).''.__('Top').':'.html_print_input_text('bb_top', $bb_top, '', 25, 25, true).'
    '.__('Image Size').':
    '.__('Width').':'.html_print_input_text('image_width', $image_width, '', 25, 25, true).''.__('Height').':'.html_print_input_text('image_height', $image_height, '', 25, 25, true).'
    '; // WMS Server Connection -$optionsConnectionWMSTable = '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '' . - '
    ' . __("WMS Server URL") . '' . - '' . - html_print_input_text('url', $mapConnectionDataUrl, '', 90, 255, true) . - '
    ' . - __("Layers") . - ui_print_help_tip (__('Enter a single element or a comma separated list'), true) . - '' . - html_print_input_text('layers', $layers, '', 90, 255, true) . - '
    '; +$optionsConnectionWMSTable = ''.''.''.''.''.''.''.''.''.'
    '.__('WMS Server URL').''.''.html_print_input_text('url', $mapConnectionDataUrl, '', 90, 255, true).'
    '.__('Layers').ui_print_help_tip(__('Enter a single element or a comma separated list'), true).''.html_print_input_text('layers', $layers, '', 90, 255, true).'
    '; if ($mapConnectionData != null) { - switch ($mapConnection_type) { - case 'OSM': - $optionsConnectionTypeTable = $optionsConnectionOSMTable; - break; - case 'Gmap': - $optionsConnectionTypeTable = $optionsConnectionGmapTable; - break; - case 'Static_Image': - $optionsConnectionTypeTable = $optionsConnectionImageTable; - break; - case 'WMS': - $optionsConnectionTypeTable = $optionsConnectionWMSTable; - break; - } + switch ($mapConnection_type) { + case 'OSM': + $optionsConnectionTypeTable = $optionsConnectionOSMTable; + break; + + case 'Gmap': + $optionsConnectionTypeTable = $optionsConnectionGmapTable; + break; + + case 'Static_Image': + $optionsConnectionTypeTable = $optionsConnectionImageTable; + break; + + case 'WMS': + $optionsConnectionTypeTable = $optionsConnectionWMSTable; + break; + } } -echo "
    " . $optionsConnectionTypeTable . "
    "; +echo "
    ".$optionsConnectionTypeTable.'
    '; -echo "

    " . __('Preview to select the center of the map and the default position of an agent without gis data') . "


    "; -html_print_button(__("Load preview map"),'button_refresh', false, 'refreshMapView();', 'class="sub"'); -echo "

    "; +echo '

    '.__('Preview to select the center of the map and the default position of an agent without gis data').'


    '; +html_print_button(__('Load preview map'), 'button_refresh', false, 'refreshMapView();', 'class="sub"'); +echo '

    '; echo "
    "; $table->width = '60%'; -$table->data = array(); +$table->data = []; -//$table->colspan[0][3] = 3; +// $table->colspan[0][3] = 3; $table->data[0][0] = ''; -$table->data[0][1] = __('Map Center') . ui_print_help_tip (__('Position to center the map when the map is opened'), true) ; -$table->data[0][2] = __("Default position for agents without GIS data"); +$table->data[0][1] = __('Map Center').ui_print_help_tip(__('Position to center the map when the map is opened'), true); +$table->data[0][2] = __('Default position for agents without GIS data'); -$table->data[1][0] = __('Change in the map'). ui_print_help_tip (__('This selects what to change by clicking on the map'), true); -$table->data[1][1] = html_print_radio_button_extended('radio_button', 1, '', 1, false, "changeSetManualPosition(true, false)", '', true); -$table->data[1][2] = html_print_radio_button_extended('radio_button', 2, '', 0, false, "changeSetManualPosition(false, true)", '', true); +$table->data[1][0] = __('Change in the map').ui_print_help_tip(__('This selects what to change by clicking on the map'), true); +$table->data[1][1] = html_print_radio_button_extended('radio_button', 1, '', 1, false, 'changeSetManualPosition(true, false)', '', true); +$table->data[1][2] = html_print_radio_button_extended('radio_button', 2, '', 0, false, 'changeSetManualPosition(false, true)', '', true); -$table->data[2][0] = __('Latitude') . ":"; -$table->data[2][1] = html_print_input_text ('center_latitude', $mapConnection_centerLatitude, '', 10, 10, true); -$table->data[2][2] = html_print_input_text ('default_latitude', $mapConnection_defaultLatitude, '', 10, 10, true); +$table->data[2][0] = __('Latitude').':'; +$table->data[2][1] = html_print_input_text('center_latitude', $mapConnection_centerLatitude, '', 10, 10, true); +$table->data[2][2] = html_print_input_text('default_latitude', $mapConnection_defaultLatitude, '', 10, 10, true); -$table->data[3][0] = __('Longitude') . ":"; -$table->data[3][1] = html_print_input_text ('center_longitude', $mapConnection_centerLongitude, '', 10, 10, true); -$table->data[3][2] = html_print_input_text ('default_longitude', $mapConnection_defaultLongitude, '', 10, 10, true); +$table->data[3][0] = __('Longitude').':'; +$table->data[3][1] = html_print_input_text('center_longitude', $mapConnection_centerLongitude, '', 10, 10, true); +$table->data[3][2] = html_print_input_text('default_longitude', $mapConnection_defaultLongitude, '', 10, 10, true); -$table->data[4][0] = __('Altitude') . ":"; -$table->data[4][1] = html_print_input_text ('center_altitude', $mapConnection_centerAltitude, '', 10, 10, true); -$table->data[4][2] = html_print_input_text ('default_altitude', $mapConnection_defaultAltitude, '', 10, 10, true); +$table->data[4][0] = __('Altitude').':'; +$table->data[4][1] = html_print_input_text('center_altitude', $mapConnection_centerAltitude, '', 10, 10, true); +$table->data[4][2] = html_print_input_text('default_altitude', $mapConnection_defaultAltitude, '', 10, 10, true); html_print_table($table); echo '
    '; -html_print_submit_button (__('Save'), '', false, 'class="sub save wand"'); +html_print_submit_button(__('Save'), '', false, 'class="sub save wand"'); echo '
    '; -echo "
    "; +echo ''; ui_require_javascript_file('OpenLayers/OpenLayers'); ui_require_javascript_file('openlayers.pandora'); @@ -368,8 +332,8 @@ var GISDefaultPositionPoint = null; * @return None */ function changeSetManualPosition(stCenter, stGISDefault) { - setCenter = stCenter; - setGISDefaultPosition = stGISDefault; + setCenter = stCenter; + setGISDefaultPosition = stGISDefault; } /** @@ -380,36 +344,36 @@ function changeSetManualPosition(stCenter, stGISDefault) { * @return None */ function changePoints(e) { - var lonlat = map.getLonLatFromViewPortPx(e.xy); - lonlat.transform(map.getProjectionObject(), map.displayProjection); //transform the lonlat in object proyection to "standar proyection" - - if (setCenter) { - //Change the fields - center_latitude = $('input[name=center_latitude]').val(lonlat.lat); - center_longitude = $('input[name=center_longitude]').val(lonlat.lon); - - if (centerPoint == null) { - centerPoint = js_addPointExtent('temp_layer', '', lonlat.lon, lonlat.lat, 'images/dot_green.png', 11, 11, 'center', ''); - } - else { - //return to no-standar the proyection for to move - centerPoint.move(lonlat.transform(map.displayProjection, map.getProjectionObject())); - } - } - - if (setGISDefaultPosition) { - //Change the fields - center_latitude = $('input[name=default_latitude]').val(lonlat.lat); - center_longitude = $('input[name=default_longitude]').val(lonlat.lon); - - if (GISDefaultPositionPoint == null) { - GISDefaultPositionPoint = js_addPointExtent('temp_layer', '', lonlat.lon, lonlat.lat, 'images/dot_red.png', 11, 11, 'default', ''); - } - else { - //return to no-standar the proyection for to move - GISDefaultPositionPoint.move(lonlat.transform(map.displayProjection, map.getProjectionObject())); - } - } + var lonlat = map.getLonLatFromViewPortPx(e.xy); + lonlat.transform(map.getProjectionObject(), map.displayProjection); //transform the lonlat in object proyection to "standar proyection" + + if (setCenter) { + //Change the fields + center_latitude = $('input[name=center_latitude]').val(lonlat.lat); + center_longitude = $('input[name=center_longitude]').val(lonlat.lon); + + if (centerPoint == null) { + centerPoint = js_addPointExtent('temp_layer', '', lonlat.lon, lonlat.lat, 'images/dot_green.png', 11, 11, 'center', ''); + } + else { + //return to no-standar the proyection for to move + centerPoint.move(lonlat.transform(map.displayProjection, map.getProjectionObject())); + } + } + + if (setGISDefaultPosition) { + //Change the fields + center_latitude = $('input[name=default_latitude]').val(lonlat.lat); + center_longitude = $('input[name=default_longitude]').val(lonlat.lon); + + if (GISDefaultPositionPoint == null) { + GISDefaultPositionPoint = js_addPointExtent('temp_layer', '', lonlat.lon, lonlat.lat, 'images/dot_red.png', 11, 11, 'default', ''); + } + else { + //return to no-standar the proyection for to move + GISDefaultPositionPoint.move(lonlat.transform(map.displayProjection, map.getProjectionObject())); + } + } } /** @@ -417,22 +381,22 @@ function changePoints(e) { * fields. And make two points, center and default. */ function refreshMapView() { - switch ($('#sel_type :selected').val()) { - case 'Gmap': - //TODO: Validate there is a key, and use it - gmap_key = $('input[name=gmap_key]').val(); - var script = document.createElement("script"); - script.type = "text/javascript"; - script.src = 'http://www.google.com/jsapi?key='+gmap_key+'&callback=loadGoogleMap'; - //script.src = 'http://www.google.com/jsapi?key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTS6gjckBmeABOGXIUiOiZObZESPg&callback=loadGoogleMap'; - document.getElementsByTagName("head")[0].appendChild(script); - - //TODO: paint the gif clock for waiting the request. - break; - default: - refreshMapViewSecondStep(); - break; - } + switch ($('#sel_type :selected').val()) { + case 'Gmap': + //TODO: Validate there is a key, and use it + gmap_key = $('input[name=gmap_key]').val(); + var script = document.createElement("script"); + script.type = "text/javascript"; + script.src = 'http://www.google.com/jsapi?key='+gmap_key+'&callback=loadGoogleMap'; + //script.src = 'http://www.google.com/jsapi?key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTS6gjckBmeABOGXIUiOiZObZESPg&callback=loadGoogleMap'; + document.getElementsByTagName("head")[0].appendChild(script); + + //TODO: paint the gif clock for waiting the request. + break; + default: + refreshMapViewSecondStep(); + break; + } } @@ -441,100 +405,100 @@ function refreshMapView() { * fields. And make two points, center and default. */ function refreshMapViewSecondStep() { - //Clear the previous map. - map = null; - $("#map").html(''); - //Clear the points. - centerPoint = null; - GISDefaultPositionPoint = null; - - //Change the text to button. - $("input[name=button_refresh]").val(''); - - //Obtain data of map of fields. - inital_zoom = $('input[name=initial_zoom]').val(); - num_levels_zoom =$('input[name=num_levels_zoom]').val(); - center_latitude = $('input[name=center_latitude]').val(); - center_longitude = $('input[name=center_longitude]').val(); - center_altitude = $('input[name=center_altitude]').val(); - - var objBaseLayers = Array(); - objBaseLayers[0] = {}; - objBaseLayers[0]['type'] = $('select[name=sel_type] :selected').val(); - objBaseLayers[0]['name'] = $('input[name=name]').val(); - objBaseLayers[0]['url'] = $('input[name=url]').val(); - // type Gmap - objBaseLayers[0]['gmap_type'] = $('select[name=gmap_type] option:selected').val(); - objBaseLayers[0]['gmap_key'] = $('input[name=gmap_key]').val(); - // type Static Image - objBaseLayers[0]['bb_left'] = $('input[name=bb_left]').val(); - objBaseLayers[0]['bb_right'] = $('input[name=bb_right]').val(); - objBaseLayers[0]['bb_bottom'] = $('input[name=bb_bottom]').val(); - objBaseLayers[0]['bb_top'] = $('input[name=bb_top]').val(); - objBaseLayers[0]['image_width'] = $('input[name=image_width]').val(); - objBaseLayers[0]['image_height'] = $('input[name=image_height]').val(); - // type WMS - objBaseLayers[0]['layers'] = $('input[name=layers]').val(); - - arrayControls = null; - arrayControls = Array('Navigation', 'PanZoom', 'MousePosition'); - - js_printMap('map', inital_zoom, center_latitude, center_longitude, objBaseLayers, arrayControls); - - layer = js_makeLayer('temp_layer', true, null); - - centerPoint = js_addPointExtent('temp_layer', - '', - $('input[name=center_longitude]').val(), - $('input[name=center_latitude]').val(), - 'images/gis_map/icons/circle.default.png', 11, 11, 'center', ''); - GISDefaultPositionPoint = js_addPointExtent('temp_layer', - '', - $('input[name=default_longitude]').val(), - $('input[name=default_latitude]').val(), - 'images/gis_map/icons/cross.default.png', 11, 11, 'default', ''); - - js_activateEvents(changePoints); + //Clear the previous map. + map = null; + $("#map").html(''); + //Clear the points. + centerPoint = null; + GISDefaultPositionPoint = null; + + //Change the text to button. + $("input[name=button_refresh]").val(''); + + //Obtain data of map of fields. + inital_zoom = $('input[name=initial_zoom]').val(); + num_levels_zoom =$('input[name=num_levels_zoom]').val(); + center_latitude = $('input[name=center_latitude]').val(); + center_longitude = $('input[name=center_longitude]').val(); + center_altitude = $('input[name=center_altitude]').val(); + + var objBaseLayers = Array(); + objBaseLayers[0] = {}; + objBaseLayers[0]['type'] = $('select[name=sel_type] :selected').val(); + objBaseLayers[0]['name'] = $('input[name=name]').val(); + objBaseLayers[0]['url'] = $('input[name=url]').val(); + // type Gmap + objBaseLayers[0]['gmap_type'] = $('select[name=gmap_type] option:selected').val(); + objBaseLayers[0]['gmap_key'] = $('input[name=gmap_key]').val(); + // type Static Image + objBaseLayers[0]['bb_left'] = $('input[name=bb_left]').val(); + objBaseLayers[0]['bb_right'] = $('input[name=bb_right]').val(); + objBaseLayers[0]['bb_bottom'] = $('input[name=bb_bottom]').val(); + objBaseLayers[0]['bb_top'] = $('input[name=bb_top]').val(); + objBaseLayers[0]['image_width'] = $('input[name=image_width]').val(); + objBaseLayers[0]['image_height'] = $('input[name=image_height]').val(); + // type WMS + objBaseLayers[0]['layers'] = $('input[name=layers]').val(); + + arrayControls = null; + arrayControls = Array('Navigation', 'PanZoom', 'MousePosition'); + + js_printMap('map', inital_zoom, center_latitude, center_longitude, objBaseLayers, arrayControls); + + layer = js_makeLayer('temp_layer', true, null); + + centerPoint = js_addPointExtent('temp_layer', + '', + $('input[name=center_longitude]').val(), + $('input[name=center_latitude]').val(), + 'images/gis_map/icons/circle.default.png', 11, 11, 'center', ''); + GISDefaultPositionPoint = js_addPointExtent('temp_layer', + '', + $('input[name=default_longitude]').val(), + $('input[name=default_latitude]').val(), + 'images/gis_map/icons/cross.default.png', 11, 11, 'default', ''); + + js_activateEvents(changePoints); } function validateGmapsParamtres () { - gmap_key = $('input[name=gmap_key]').val(); - if (gmap_key == "") { - $('input[name=gmap_key]').css('background-color', 'red'); - } - else { - refreshMapViewSecondStep(); - } + gmap_key = $('input[name=gmap_key]').val(); + if (gmap_key == "") { + $('input[name=gmap_key]').css('background-color', 'red'); + } + else { + refreshMapViewSecondStep(); + } } function loadGoogleMap() { - google.load("maps", "2", {"callback" : validateGmapsParamtres}); + google.load("maps", "2", {"callback" : validateGmapsParamtres}); } /** * Dinamic write the fields in form when select a type of connection. */ function selMapConnectionType() { - $('#form_map_connection_type').fadeOut("normal"); - - switch ($('#sel_type :selected').val()) { - case 'OSM': - $('#form_map_connection_type').html('').hide(); - break; - case 'Gmap': - // TODO: Validate there is a key, and use it - $('#form_map_connection_type').html('').hide(); - break; - case 'Static_Image': - $('#form_map_connection_type').html('').hide(); - break; - case 'WMS': - $('#form_map_connection_type').html('').hide(); - break; - default: - $('#form_map_connection_type').html('').hide(); - break; - } - $('#form_map_connection_type').fadeIn("normal"); + $('#form_map_connection_type').fadeOut("normal"); + + switch ($('#sel_type :selected').val()) { + case 'OSM': + $('#form_map_connection_type').html('').hide(); + break; + case 'Gmap': + // TODO: Validate there is a key, and use it + $('#form_map_connection_type').html('').hide(); + break; + case 'Static_Image': + $('#form_map_connection_type').html('').hide(); + break; + case 'WMS': + $('#form_map_connection_type').html('').hide(); + break; + default: + $('#form_map_connection_type').html('').hide(); + break; + } + $('#form_map_connection_type').fadeIn("normal"); } diff --git a/pandora_console/godmode/setup/license.php b/pandora_console/godmode/setup/license.php index 6cbcb4f68c..413b1d7fe1 100644 --- a/pandora_console/godmode/setup/license.php +++ b/pandora_console/godmode/setup/license.php @@ -1,8 +1,7 @@ $value) { - db_process_sql_update( - 'tupdate_settings', - array(db_escape_key_identifier('value') => $value), - array(db_escape_key_identifier('key') => $key)); - } - - ui_print_success_message(__('License updated')); + foreach ($_POST['keys'] as $key => $value) { + db_process_sql_update( + 'tupdate_settings', + [db_escape_key_identifier('value') => $value], + [db_escape_key_identifier('key') => $key] + ); + } + + ui_print_success_message(__('License updated')); } ui_require_javascript_file_enterprise('load_enterprise'); @@ -45,12 +44,14 @@ $rows = db_get_all_rows_in_table('tupdate_settings'); $settings = new StdClass; foreach ($rows as $row) { - $settings->{$row['key']} = $row['value']; + $settings->{$row['key']} = $row['value']; } echo ''; echo '
    '; @@ -59,25 +60,25 @@ $table = new stdClass(); $table->width = '100%'; $table->class = 'databox filters'; -$table->data = array (); +$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[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][1] = html_print_input_text('expires', $license['expiry_date'], '', 10, 255, true, true); $table->data[2][0] = ''.__('Platform Limit').''; -$table->data[2][1] = html_print_input_text('expires', $license['limit'], '', 10, 255, true, true) . ' ' . ($license['limit_mode'] == 0 ? __('agents') : __('modules')); +$table->data[2][1] = html_print_input_text('expires', $license['limit'], '', 10, 255, true, true).' '.($license['limit_mode'] == 0 ? __('agents') : __('modules')); $table->data[3][0] = ''.__('Current Platform Count').''; -$table->data[3][1] = html_print_input_text('expires', $license['count'], '', 10, 255, true, true) . ' ' . ($license['limit_mode'] == 0 ? __('agents') : __('modules')); +$table->data[3][1] = html_print_input_text('expires', $license['count'], '', 10, 255, true, true).' '.($license['limit_mode'] == 0 ? __('agents') : __('modules')); $table->data[4][0] = ''.__('Current Platform Count (enabled: items)').''; -$table->data[4][1] = html_print_input_text('expires', $license['count_enabled'], '', 10, 255, true, true) . ' ' . ($license['limit_mode'] == 0 ? __('agents') : __('modules')); +$table->data[4][1] = html_print_input_text('expires', $license['count_enabled'], '', 10, 255, true, true).' '.($license['limit_mode'] == 0 ? __('agents') : __('modules')); $table->data[5][0] = ''.__('Current Platform Count (disabled: items)').''; -$table->data[5][1] = html_print_input_text('expires', $license['count_disabled'], '', 10, 255, true, true) . ' ' . ($license['limit_mode'] == 0 ? __('agents') : __('modules')); +$table->data[5][1] = html_print_input_text('expires', $license['count_disabled'], '', 10, 255, true, true).' '.($license['limit_mode'] == 0 ? __('agents') : __('modules')); $table->data[6][0] = ''.__('License Mode').''; $table->data[6][1] = html_print_input_text('expires', $license['license_mode'], '', 10, 255, true, true); @@ -91,41 +92,40 @@ $table->data[8][1] = html_print_input_text('expires', ($license['dhpm'] == 1 ? _ $table->data[9][0] = ''.__('Licensed to').''; $table->data[9][1] = html_print_input_text('licensed_to', $license['licensed_to'], '', 64, 255, true, true); -html_print_table ($table); +html_print_table($table); if (enterprise_installed()) { - echo '
    '; - html_print_input_hidden ('update_settings', 1); - html_print_submit_button (__('Validate'), 'update_button', false, 'class="sub upd"'); - echo "  "; - html_print_button(__('Request new license'), '', false, 'generate_request_code()', 'class="ui-button-dialog ui-widget ui-state-default ui-corner-all ui-button-text-only sub next"'); - echo '
    '; + echo '
    '; + html_print_input_hidden('update_settings', 1); + html_print_submit_button(__('Validate'), 'update_button', false, 'class="sub upd"'); + echo '  '; + html_print_button(__('Request new license'), '', false, 'generate_request_code()', 'class="ui-button-dialog ui-widget ui-state-default ui-corner-all ui-button-text-only sub next"'); + echo '
    '; } + echo '
    '; -echo ''; -enterprise_hook('close_meta_frame'); + echo ""; + echo ''; + if ($action == 'update') { + echo "'; + echo ''; + } -?> + if ($action == 'new') { + echo ''; + echo ''; + } + + echo ''; + echo '
    "; + html_print_input_hidden('update_tag', 1); + echo ''; + html_print_submit_button(__('Update'), 'update_button', false, 'class="sub next"'); + echo ''; + html_print_input_hidden('create_tag', 1); + echo ''; + html_print_submit_button(__('Create'), 'create_button', false, 'class="sub next"'); + echo '
    '; + + echo ''; + + enterprise_hook('close_meta_frame'); diff --git a/pandora_console/godmode/tag/tag.php b/pandora_console/godmode/tag/tag.php index 222979461e..d717a9095e 100644 --- a/pandora_console/godmode/tag/tag.php +++ b/pandora_console/godmode/tag/tag.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,135 +11,144 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; // Check login and ACLs -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Tag Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Tag Management'); + include 'general/noaccess.php'; + return; } -//Include functions code -require_once ($config['homedir'].'/include/functions_tags.php'); +// Include functions code +require_once $config['homedir'].'/include/functions_tags.php'; // Get parameters -$delete = (int) get_parameter ("delete_tag", 0); -$tag_name = (string) get_parameter ("tag_name",""); -$tab = (string) get_parameter ("tab", "list"); +$delete = (int) get_parameter('delete_tag', 0); +$tag_name = (string) get_parameter('tag_name', ''); +$tab = (string) get_parameter('tab', 'list'); // Metaconsole nodes $servers = false; if (is_metaconsole()) { - enterprise_include_once('include/functions_metaconsole.php'); - $servers = metaconsole_get_servers(); + enterprise_include_once('include/functions_metaconsole.php'); + $servers = metaconsole_get_servers(); } -//Ajax tooltip to deploy module's count info of a tag. -if (is_ajax ()) { - ob_clean(); - - $get_tag_tooltip = (bool) get_parameter ('get_tag_tooltip', 0); - - if ($get_tag_tooltip) { - $id_tag = (int) get_parameter ('id_tag'); - $tag = tags_search_tag_id ($id_tag); - if ($tag === false) - return; - - $local_modules_count = 0; - if (is_metaconsole() && !empty($servers)) { - $local_modules_count = array_reduce($servers, function($counter, $server) use ($id_tag) { - if (metaconsole_connect($server) === NOERR) - $counter += tags_get_local_modules_count($id_tag); - return $counter; - }, 0); - } - else { - $local_modules_count = tags_get_local_modules_count($id_tag); - } - - $policy_modules_count = 0; - if (is_metaconsole() && !empty($servers)) { - $policy_modules_count = array_reduce($servers, function($counter, $server) use ($id_tag) { - if (metaconsole_connect($server) === NOERR) - $counter += tags_get_policy_modules_count($id_tag); - return $counter; - }, 0); - } - else { - $policy_modules_count = tags_get_policy_modules_count($id_tag); - } - - echo '

    '.$tag['name'].'

    '; - echo ''.__('Number of modules').': ' . $local_modules_count; - echo '
    '; - echo ''.__('Number of policy modules').': ' . $policy_modules_count; - - return; - } - return; +// Ajax tooltip to deploy module's count info of a tag. +if (is_ajax()) { + ob_clean(); + + $get_tag_tooltip = (bool) get_parameter('get_tag_tooltip', 0); + + if ($get_tag_tooltip) { + $id_tag = (int) get_parameter('id_tag'); + $tag = tags_search_tag_id($id_tag); + if ($tag === false) { + return; + } + + $local_modules_count = 0; + if (is_metaconsole() && !empty($servers)) { + $local_modules_count = array_reduce( + $servers, + function ($counter, $server) use ($id_tag) { + if (metaconsole_connect($server) === NOERR) { + $counter += tags_get_local_modules_count($id_tag); + } + + return $counter; + }, + 0 + ); + } else { + $local_modules_count = tags_get_local_modules_count($id_tag); + } + + $policy_modules_count = 0; + if (is_metaconsole() && !empty($servers)) { + $policy_modules_count = array_reduce( + $servers, + function ($counter, $server) use ($id_tag) { + if (metaconsole_connect($server) === NOERR) { + $counter += tags_get_policy_modules_count($id_tag); + } + + return $counter; + }, + 0 + ); + } else { + $policy_modules_count = tags_get_policy_modules_count($id_tag); + } + + echo '

    '.$tag['name'].'

    '; + echo ''.__('Number of modules').': '.$local_modules_count; + echo '
    '; + echo ''.__('Number of policy modules').': '.$policy_modules_count; + + return; + } + + return; } -//~ enterprise_hook('open_meta_frame'); +// ~ enterprise_hook('open_meta_frame'); +if (is_metaconsole()) { + $sec = 'advanced'; +} else { + $sec = 'gmodules'; +} -if (is_metaconsole()) - $sec = 'advanced'; -else - $sec = 'gmodules'; - -$buttons = array( - 'list' => array( - 'active' => false, - 'text' => '' . - html_print_image ("images/list.png", true, array ("title" => __('List tags'))) .'')); +$buttons = [ + 'list' => [ + 'active' => false, + 'text' => ''.html_print_image('images/list.png', true, ['title' => __('List tags')]).'', + ], +]; $buttons[$tab]['active'] = true; if (is_metaconsole()) { - // Print header - //ui_meta_print_header(__('Tags'), "", $buttons); -} -else { - // Header - ui_print_page_header (__('Tags configuration'), "images/tag.png", false, "tags_config", true, $buttons); + // Print header + // ui_meta_print_header(__('Tags'), "", $buttons); +} else { + // Header + ui_print_page_header(__('Tags configuration'), 'images/tag.png', false, 'tags_config', true, $buttons); } // Two actions can performed in this page: search and delete tags - // Delete action: This will delete a tag if ($delete != 0) { - $return_delete = tags_delete_tag ($delete); - - if ($return_delete === false) { - db_pandora_audit("Tag management", "Fail try to delete tag #$delete"); - ui_print_error_message(__('Error deleting tag')); - } - else { - db_pandora_audit("Tag management", "Delete tag #$delete"); - ui_print_success_message(__('Successfully deleted tag')); - } + $return_delete = tags_delete_tag($delete); + + if ($return_delete === false) { + db_pandora_audit('Tag management', "Fail try to delete tag #$delete"); + ui_print_error_message(__('Error deleting tag')); + } else { + db_pandora_audit('Tag management', "Delete tag #$delete"); + ui_print_success_message(__('Successfully deleted tag')); + } } // Search action: This will filter the display tag view -$filter = array(); -// Filtered view? +$filter = []; +// Filtered view? if (!empty($tag_name)) { - $filter['name'] = $tag_name; + $filter['name'] = $tag_name; } // If the user has filtered the view $filter_performed = !empty($filter); -$filter['offset'] = (int) get_parameter ('offset'); +$filter['offset'] = (int) get_parameter('offset'); $filter['limit'] = (int) $config['block_size']; // statements for pagination -$url = ui_get_url_refresh (); +$url = ui_get_url_refresh(); $total_tags = tags_get_tag_count($filter); $result = tags_search_tag(false, $filter); @@ -149,210 +157,207 @@ $result = tags_search_tag(false, $filter); $table = new StdClass(); $table->class = 'databox filters'; $table->width = '100%'; -$table->data = array(); +$table->data = []; -$row = array(); +$row = []; -$name_input = __("Name") . " / " . __("Description"); -$name_input .= "  "; -$name_input .= html_print_input_text ('tag_name', $tag_name, '', 30, 255, true); +$name_input = __('Name').' / '.__('Description'); +$name_input .= '  '; +$name_input .= html_print_input_text('tag_name', $tag_name, '', 30, 255, true); $row[] = $name_input; -$filter_button = html_print_submit_button (__('Filter'), 'filter_button', false, 'class="sub search"',true); +$filter_button = html_print_submit_button(__('Filter'), 'filter_button', false, 'class="sub search"', true); $row[] = $filter_button; $table->data[] = $row; $filter_form = '
    '; $filter_form .= html_print_table($table, true); -$filter_form .= "
    "; +$filter_form .= ''; // End of filter form - if (!empty($result)) { - if (!is_metaconsole()) { - echo $filter_form; - } - else { - ui_toggle($filter_form, __("Show Options")); - } + if (!is_metaconsole()) { + echo $filter_form; + } else { + ui_toggle($filter_form, __('Show Options')); + } - // Prepare pagination - ui_pagination ($total_tags, $url); + // Prepare pagination + ui_pagination($total_tags, $url); - // Display tags previously filtered or not - $rowPair = true; - $iterator = 0; - - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox data'; - - $table->data = array (); - $table->head = array (); - $table->align = array (); - $table->style = array (); - $table->size = array("15%","30%","15%","15%","","","8%"); - - $table->style[0] = 'font-weight: bold;'; - $table->style[3] = 'text-align:left'; - $table->style[6] = 'text-align:left'; - $table->head[0] = __('Tag name'); - $table->head[1] = __('Description'); - $table->head[2] = __('Detail information'); - $table->head[3] = __('Number of modules affected'); - $table->head[4] = __('Email'); - $table->head[5] = __('Phone'); - $table->head[6] = __('Actions'); - - foreach ($result as $tag) { - if ($rowPair) - $table->rowclass[$iterator] = 'rowPair'; - else - $table->rowclass[$iterator] = 'rowOdd'; - $rowPair = !$rowPair; - $iterator++; - - $data = array (); - - $data[0] = "" . $tag["name"] . ""; - $data[1] = ui_print_truncate_text($tag["description"], 'description', false); - $data[2] = '' . $tag["url"] . ''; - - // The tooltip needs a title on the item, don't delete the title - $data[3] = '' . - html_print_image("images/zoom.png", true) . ' '; - - $modules_count = 0; - if (is_metaconsole() && !empty($servers)) { - $tag_id = $tag['id_tag']; - $modules_count = array_reduce($servers, function($counter, $server) use ($tag_id) { - if (metaconsole_connect($server) === NOERR) - $counter += tags_get_modules_count($tag_id); - - return $counter; - }, 0); - } - else { - $modules_count = tags_get_modules_count($tag["id_tag"]); - } - - $data[3] .= $modules_count; - - $email_large = io_safe_output($tag["email"]); - $email_small = substr($email_large,0, 24); - if ($email_large == $email_small) { - $output = $email_large; - } - else { - $output = - "" . - '' . - $email_small . ' ' . - "" . html_print_image("images/rosette.png", true) . "" . ""; - } - $data[4] = $output; + // Display tags previously filtered or not + $rowPair = true; + $iterator = 0; - $phone_large = io_safe_output($tag["phone"]); - $phone_small = substr($phone_large,0, 24); - if ($phone_large == $phone_small) { - $output = $phone_large; - } - else { - $output = - "" . - '' . - $phone_small . ' ' . - "" . html_print_image("images/rosette.png", true) . "" . ""; - } - $data[5] = $output; - - $data[6] = "" . html_print_image("images/config.png", true, array("title" => "Edit")) . "  "; - $data[6] .= '' . html_print_image("images/cross.png", true, array("title" => "Delete")) . ''; - array_push ($table->data, $data); - } - - html_print_table ($table); -} -else { - if (is_metaconsole()) { - ui_toggle($filter_form, __("Show Options")); - ui_print_info_message(array("no_close" => true, "message" => __("No tags defined"))); - } - else if ($filter_performed) { - echo $filter_form; - } - else { - require ($config['homedir'] . "/general/firts_task/tags.php"); - return; - } + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox data'; + + $table->data = []; + $table->head = []; + $table->align = []; + $table->style = []; + $table->size = [ + '15%', + '30%', + '15%', + '15%', + '', + '', + '8%', + ]; + + $table->style[0] = 'font-weight: bold;'; + $table->style[3] = 'text-align:left'; + $table->style[6] = 'text-align:left'; + $table->head[0] = __('Tag name'); + $table->head[1] = __('Description'); + $table->head[2] = __('Detail information'); + $table->head[3] = __('Number of modules affected'); + $table->head[4] = __('Email'); + $table->head[5] = __('Phone'); + $table->head[6] = __('Actions'); + + foreach ($result as $tag) { + if ($rowPair) { + $table->rowclass[$iterator] = 'rowPair'; + } else { + $table->rowclass[$iterator] = 'rowOdd'; + } + + $rowPair = !$rowPair; + $iterator++; + + $data = []; + + $data[0] = "".$tag['name'].''; + $data[1] = ui_print_truncate_text($tag['description'], 'description', false); + $data[2] = ''.$tag['url'].''; + + // The tooltip needs a title on the item, don't delete the title + $data[3] = ''.html_print_image('images/zoom.png', true).' '; + + $modules_count = 0; + if (is_metaconsole() && !empty($servers)) { + $tag_id = $tag['id_tag']; + $modules_count = array_reduce( + $servers, + function ($counter, $server) use ($tag_id) { + if (metaconsole_connect($server) === NOERR) { + $counter += tags_get_modules_count($tag_id); + } + + return $counter; + }, + 0 + ); + } else { + $modules_count = tags_get_modules_count($tag['id_tag']); + } + + $data[3] .= $modules_count; + + $email_large = io_safe_output($tag['email']); + $email_small = substr($email_large, 0, 24); + if ($email_large == $email_small) { + $output = $email_large; + } else { + $output = "'.''.$email_small.' '."".html_print_image('images/rosette.png', true).''.''; + } + + $data[4] = $output; + + $phone_large = io_safe_output($tag['phone']); + $phone_small = substr($phone_large, 0, 24); + if ($phone_large == $phone_small) { + $output = $phone_large; + } else { + $output = "'.''.$phone_small.' '."".html_print_image('images/rosette.png', true).''.''; + } + + $data[5] = $output; + + $data[6] = "".html_print_image('images/config.png', true, ['title' => 'Edit']).'  '; + $data[6] .= ''.html_print_image('images/cross.png', true, ['title' => 'Delete']).''; + array_push($table->data, $data); + } + + html_print_table($table); +} else { + if (is_metaconsole()) { + ui_toggle($filter_form, __('Show Options')); + ui_print_info_message(['no_close' => true, 'message' => __('No tags defined')]); + } else if ($filter_performed) { + echo $filter_form; + } else { + include $config['homedir'].'/general/firts_task/tags.php'; + return; + } } -echo ""; - echo ""; - echo ""; - echo ""; -echo "
    "; - echo '
    '; - html_print_input_hidden ("create_tag", "1", true); - html_print_submit_button (__('Create tag'), 'create_button', false, 'class="sub next"'); - echo "
    "; - echo "
    "; +echo ''; + echo ''; + echo ''; + echo ''; +echo '
    '; + echo '
    '; + html_print_input_hidden('create_tag', '1', true); + html_print_submit_button(__('Create tag'), 'create_button', false, 'class="sub next"'); + echo '
    '; + echo '
    '; -//~ enterprise_hook('close_meta_frame'); - +// ~ enterprise_hook('close_meta_frame'); ?> diff --git a/pandora_console/godmode/update_manager/update_manager.css b/pandora_console/godmode/update_manager/update_manager.css index 7b276e6b9b..f68c92ea94 100644 --- a/pandora_console/godmode/update_manager/update_manager.css +++ b/pandora_console/godmode/update_manager/update_manager.css @@ -1,141 +1,145 @@ .fileupload_form { - background-color: #373A3D; - background-image: -moz-linear-gradient(center top , #373A3D, #313437); - border-radius: 3px; - font-family: 'PT Sans Narrow',sans-serif; - margin: 0px; - padding: 30px; + background-color: #373a3d; + background-image: -moz-linear-gradient(center top, #373a3d, #313437); + border-radius: 3px; + font-family: "PT Sans Narrow", sans-serif; + margin: 0px; + padding: 30px; } #drop_file { - background-color: #E6E6E6; - border: 20px solid rgba(0, 0, 0, 0); - border-radius: 3px; - color: #707070; - font-size: 16px; - font-weight: bold; - margin-bottom: 30px; - padding: 40px 50px; - text-align: center; - text-transform: uppercase; + background-color: #e6e6e6; + border: 20px solid rgba(0, 0, 0, 0); + border-radius: 3px; + color: #707070; + font-size: 16px; + font-weight: bold; + margin-bottom: 30px; + padding: 40px 50px; + text-align: center; + text-transform: uppercase; } #drop_file table { - vertical-align: middle; + vertical-align: middle; } -#drop_file table td, #drop_file table label { - color: #707070; - font-family: 'PT Sans Narrow',sans-serif; - font-size: 16px; - font-weight: bold; - margin-top: 0; - vertical-align: middle; +#drop_file table td, +#drop_file table label { + color: #707070; + font-family: "PT Sans Narrow", sans-serif; + font-size: 16px; + font-weight: bold; + margin-top: 0; + vertical-align: middle; } #drop_file table select { - float: none; + float: none; } #drop_file a { - background-color: #80BA27; - border-radius: 2px; - color: #FFFFFF; - cursor: pointer; - display: inline-block; - font-size: 14px; - line-height: 1; - padding: 12px 26px; + background-color: #80ba27; + border-radius: 2px; + color: #ffffff; + cursor: pointer; + display: inline-block; + font-size: 14px; + line-height: 1; + padding: 12px 26px; } #drop_file a:hover { - background-color: #A6CE67; - text-decoration: none; + background-color: #a6ce67; + text-decoration: none; } #drop_file input { - display: none; + display: none; } .fileupload_form ul { - border-bottom: 1px solid #3D4043; - border-top: 1px solid #2B2E31; - list-style: none outside none; - margin: 0 -30px; - padding: 0; + border-bottom: 1px solid #3d4043; + border-top: 1px solid #2b2e31; + list-style: none outside none; + margin: 0 -30px; + padding: 0; } .fileupload_form ul li { - background-color: #333639; - background-image: -moz-linear-gradient(center top , #333639, #303335); - border-bottom: 1px solid #2B2E31; - border-top: 1px solid #3D4043; - padding: 15px; - position: relative; + background-color: #333639; + background-image: -moz-linear-gradient(center top, #333639, #303335); + border-bottom: 1px solid #2b2e31; + border-top: 1px solid #3d4043; + padding: 15px; + position: relative; } .fileupload_form ul li #input-progress { - left: 68px; - position: absolute; + left: 68px; + position: absolute; } .fileupload_form ul li p { - color: #EEEEEE; - font-size: 12px; - font-weight: bold; - left: 95px; - overflow: hidden; - position: absolute; - top: 12px; - white-space: nowrap; + color: #eeeeee; + font-size: 12px; + font-weight: bold; + left: 95px; + overflow: hidden; + position: absolute; + top: 12px; + white-space: nowrap; } .fileupload_form ul li i { - color: #7F7F7F; - display: block; - font-style: normal; - font-weight: normal; + color: #7f7f7f; + display: block; + font-style: normal; + font-weight: normal; } .fileupload_form ul li canvas { - left: 13px; - position: absolute; - top: 15px; + left: 13px; + position: absolute; + top: 15px; } .fileupload_form ul li span { - background: url("../../images/check-cross.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0); - cursor: pointer; - height: 12px; - position: absolute; - right: 13px; - top: 34px; - width: 15px; + background: url("../../images/check-cross.png") no-repeat scroll 0 0 + rgba(0, 0, 0, 0); + cursor: pointer; + height: 12px; + position: absolute; + right: 13px; + top: 34px; + width: 15px; } .fileupload_form ul li div { - display: block !important; + display: block !important; } .fileupload_form ul li.working span { - background-position: 0 -12px; - height: 16px; + background-position: 0 -12px; + height: 16px; } .fileupload_form ul li.loading span { - background: url("../../images/spinner.gif") no-repeat scroll 0 0 rgba(0, 0, 0, 0); - height: 16px; + background: url("../../images/spinner.gif") no-repeat scroll 0 0 + rgba(0, 0, 0, 0); + height: 16px; } .fileupload_form ul li.suc span { - background: url("../../images/check-cross.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0); - height: 12px; + background: url("../../images/check-cross.png") no-repeat scroll 0 0 + rgba(0, 0, 0, 0); + height: 12px; } .fileupload_form ul li.suc p { - color: #5A8629; + color: #5a8629; } .fileupload_form ul li.error span { - background: url("../../images/check-cross.png") no-repeat scroll 0 -12px rgba(0, 0, 0, 0); - height: 16px; + background: url("../../images/check-cross.png") no-repeat scroll 0 -12px rgba(0, 0, 0, 0); + height: 16px; } .fileupload_form ul li.error p { - color: #FF3333; + color: #ff3333; } #log_zone { - background-color: #E6E6E6; - border: 20px solid rgba(0, 0, 0, 0); - border-radius: 3px; - color: #707070; - font-size: 12px; - margin-bottom: 30px; - padding: 10px; - text-align: left; + background-color: #e6e6e6; + border: 20px solid rgba(0, 0, 0, 0); + border-radius: 3px; + color: #707070; + font-size: 12px; + margin-bottom: 30px; + padding: 10px; + text-align: left; } #box_online { - background-color: #E6E6E6; - padding: 10px; -} \ No newline at end of file + background-color: #e6e6e6; + padding: 10px; +} diff --git a/pandora_console/godmode/update_manager/update_manager.messages.php b/pandora_console/godmode/update_manager/update_manager.messages.php index 06646fd931..31f9866b01 100644 --- a/pandora_console/godmode/update_manager/update_manager.messages.php +++ b/pandora_console/godmode/update_manager/update_manager.messages.php @@ -4,327 +4,337 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -include_once ("include/functions_update_manager.php"); -check_login (); +require_once 'include/functions_update_manager.php'; +check_login(); -if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; } if (is_ajax()) { + $not_read_single = get_parameter('not_read_single', 0); - $not_read_single = get_parameter ('not_read_single', 0); - - if ($not_read_single) { - $message_id = get_parameter ('message_id', 0); - update_manger_set_read_message ($message_id, 1); - update_manager_remote_read_messages ($message_id); - } - - return; + if ($not_read_single) { + $message_id = get_parameter('message_id', 0); + update_manger_set_read_message($message_id, 1); + update_manager_remote_read_messages($message_id); + } + + return; } $not_read_action = get_parameter('not_read_button', false); $read_action = get_parameter('read_button', false); -$delete_action = get_parameter ('delete_button', false); +$delete_action = get_parameter('delete_button', false); if ($not_read_action !== false) { - - $selected = get_parameter ('select_multiple', false); - foreach ($selected as $k => $message_id) { - - update_manger_set_read_message ($message_id, 0); - } + $selected = get_parameter('select_multiple', false); + foreach ($selected as $k => $message_id) { + update_manger_set_read_message($message_id, 0); + } } if ($read_action !== false) { - - $selected = get_parameter ('select_multiple', false); - foreach ($selected as $k => $message_id) { - - update_manger_set_read_message ($message_id, 1); - } + $selected = get_parameter('select_multiple', false); + foreach ($selected as $k => $message_id) { + update_manger_set_read_message($message_id, 1); + } } if ($delete_action !== false) { - - $selected = get_parameter ('select_multiple', false); - foreach ($selected as $k => $message_id) { - - update_manger_set_deleted_message ($message_id); - } - + $selected = get_parameter('select_multiple', false); + foreach ($selected as $k => $message_id) { + update_manger_set_deleted_message($message_id); + } } -$offset = (int) get_parameter ('offset', 0); +$offset = (int) get_parameter('offset', 0); -$total_messages = update_manager_get_not_deleted_messages (); -if ($total_messages){ +$total_messages = update_manager_get_not_deleted_messages(); +if ($total_messages) { + // Get all messages + $sql = 'SELECT data, svn_version, filename, data_rollback, db_field_value FROM tupdate '; + $sql .= 'WHERE description NOT LIKE \'%"'.$config['id_user'].'":1%\' '; + $sql .= 'OR description IS NULL '; + $sql .= 'ORDER BY svn_version DESC '; + $sql .= 'LIMIT '.$offset.','.$config['block_size'].' '; + $um_messages = []; + $um_messages = db_get_all_rows_sql($sql); - // Get all messages - $sql = 'SELECT data, svn_version, filename, data_rollback, db_field_value FROM tupdate '; - $sql .= 'WHERE description NOT LIKE \'%"' . $config['id_user'] . '":1%\' '; - $sql .= 'OR description IS NULL '; - $sql .= 'ORDER BY svn_version DESC '; - $sql .= 'LIMIT ' . $offset . ',' . $config['block_size'] . ' '; - $um_messages = array (); - $um_messages = db_get_all_rows_sql ($sql); + echo '
    '; - echo ''; + html_print_input_hidden('tab', 'messages'); + html_print_input_hidden('offset', $offset); + echo '
    '; + html_print_submit_button( + __('Delete'), + 'delete_button', + false, + 'class="sub delete"' + ); + echo '
    '; - html_print_input_hidden ('tab', 'messages'); - html_print_input_hidden ('offset', $offset); - echo '
    '; - html_print_submit_button (__('Delete'), 'delete_button', false, - 'class="sub delete"'); - echo '
    '; + echo '
    '; + html_print_submit_button( + __('Mark as not read'), + 'not_read_button', + false, + 'class="sub wand"' + ); + echo '
    '; - echo '
    '; - html_print_submit_button (__('Mark as not read'), 'not_read_button', false, - 'class="sub wand"'); - echo '
    '; + echo '
    '; + html_print_submit_button( + __('Mark as read'), + 'read_button', + false, + 'class="sub upd"' + ); + echo '
    '; - echo '
    '; - html_print_submit_button (__('Mark as read'), 'read_button', false, - 'class="sub upd"'); - echo '
    '; - - // Pagination - if ($total_messages > $config['block_size']) { - ui_pagination (update_manager_get_total_messages (), false, 0); - } + // Pagination + if ($total_messages > $config['block_size']) { + ui_pagination(update_manager_get_total_messages(), false, 0); + } - $table = new stdClass(); - $table->width = '100%'; - $table->class = 'databox data'; - $table->cellpadding = 4; - $table->cellspacing = 4; - $table->head = array (); - $table->data = array (); - $table->align = array (); - $table->size = array (); - $table->id = 'um_messages_table'; - - $table->align[0] = "left"; - $table->align[1] = "left"; - $table->align[2] = "left"; - $table->align[3] = "left"; - $table->align[4] = "left"; - - $table->size[0] = "30px"; - $table->size[1] = "100px"; - $table->size[3] = "80px"; - $table->size[4] = "60px"; - - $table->style[0] = "padding-left: 20px"; - $table->style[1] = "display: none"; - - $table->head[0] = html_print_checkbox_extended('all_selection[]', 0, false, false, '', '', true); - $table->head[2] = __('Subject'); - + $table = new stdClass(); + $table->width = '100%'; + $table->class = 'databox data'; + $table->cellpadding = 4; + $table->cellspacing = 4; + $table->head = []; + $table->data = []; + $table->align = []; + $table->size = []; + $table->id = 'um_messages_table'; - $i = 0; - foreach ($um_messages as $message) { - $data[0] = html_print_checkbox_extended('select_multiple[]', $message['svn_version'], false, false, '', 'class="check_selection"', true); - $table->cellclass[count($table->data)][0] = 'um_individual_check'; - - $data[1] = $message['svn_version']; - $table->cellclass[count($table->data)][1] = 'um_individual_info'; - - $data[2] = io_safe_output($message['db_field_value']); - $table->cellclass[count($table->data)][2] = 'um_individual_subject'; - - - // Change row class if message is read or not by this user - if (update_manger_get_read_message ($message['svn_version'], $message['data_rollback'])) { - $table->rowclass[count($table->data)] = "um_read_message"; - - } else { - $table->rowclass[count($table->data)] = "um_not_read_message"; - - } - array_push ($table->data, $data); - - } - html_print_table($table); + $table->align[0] = 'left'; + $table->align[1] = 'left'; + $table->align[2] = 'left'; + $table->align[3] = 'left'; + $table->align[4] = 'left'; - echo '
    '; - html_print_submit_button (__('Delete'), 'delete_button', false, - 'class="sub delete"'); - echo '
    '; + $table->size[0] = '30px'; + $table->size[1] = '100px'; + $table->size[3] = '80px'; + $table->size[4] = '60px'; - echo '
    '; - html_print_submit_button (__('Mark as not read'), 'not_read_button', false, - 'class="sub wand"'); - echo '
    '; + $table->style[0] = 'padding-left: 20px'; + $table->style[1] = 'display: none'; - echo '
    '; - html_print_submit_button (__('Mark as read'), 'read_button', false, - 'class="sub upd"'); - echo '
    '; - echo '
    '; - - // Get unread messages to update the notification ball. - // Clean the cache because the unread messages can be different. - db_clean_cache(); - $total_unread_messages = update_manager_get_unread_messages(); - + $table->head[0] = html_print_checkbox_extended('all_selection[]', 0, false, false, '', '', true); + $table->head[2] = __('Subject'); + + + $i = 0; + foreach ($um_messages as $message) { + $data[0] = html_print_checkbox_extended('select_multiple[]', $message['svn_version'], false, false, '', 'class="check_selection"', true); + $table->cellclass[count($table->data)][0] = 'um_individual_check'; + + $data[1] = $message['svn_version']; + $table->cellclass[count($table->data)][1] = 'um_individual_info'; + + $data[2] = io_safe_output($message['db_field_value']); + $table->cellclass[count($table->data)][2] = 'um_individual_subject'; + + + // Change row class if message is read or not by this user + if (update_manger_get_read_message($message['svn_version'], $message['data_rollback'])) { + $table->rowclass[count($table->data)] = 'um_read_message'; + } else { + $table->rowclass[count($table->data)] = 'um_not_read_message'; + } + + array_push($table->data, $data); + } + + html_print_table($table); + + echo '
    '; + html_print_submit_button( + __('Delete'), + 'delete_button', + false, + 'class="sub delete"' + ); + echo '
    '; + + echo '
    '; + html_print_submit_button( + __('Mark as not read'), + 'not_read_button', + false, + 'class="sub wand"' + ); + echo '
    '; + + echo '
    '; + html_print_submit_button( + __('Mark as read'), + 'read_button', + false, + 'class="sub upd"' + ); + echo '
    '; + echo ''; + + // Get unread messages to update the notification ball. + // Clean the cache because the unread messages can be different. + db_clean_cache(); + $total_unread_messages = update_manager_get_unread_messages(); } else { - ui_print_info_message ( array ( 'no_close' => true, 'message' => __('There is not any update manager messages.') ) ); + ui_print_info_message([ 'no_close' => true, 'message' => __('There is not any update manager messages.') ]); } ?> diff --git a/pandora_console/godmode/update_manager/update_manager.offline.php b/pandora_console/godmode/update_manager/update_manager.offline.php index fccdab6b0b..79f9a72d2e 100644 --- a/pandora_console/godmode/update_manager/update_manager.offline.php +++ b/pandora_console/godmode/update_manager/update_manager.offline.php @@ -4,28 +4,25 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; // ui_require_css_file('update_manager', 'godmode/update_manager/'); - -check_login (); +check_login(); // ui_require_css_file('update_manager', 'godmode/update_manager/'); -if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; } + $baseurl = ui_get_full_url(false, false, false, false); ?> @@ -34,50 +31,53 @@ $baseurl = ui_get_full_url(false, false, false, false);
    -
    -
      +
      +
        @@ -87,5 +87,5 @@ $baseurl = ui_get_full_url(false, false, false, false); \ No newline at end of file + form_upload(""); + diff --git a/pandora_console/godmode/update_manager/update_manager.online.php b/pandora_console/godmode/update_manager/update_manager.online.php index 117c020515..3e807367bd 100644 --- a/pandora_console/godmode/update_manager/update_manager.online.php +++ b/pandora_console/godmode/update_manager/update_manager.online.php @@ -4,161 +4,159 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { + db_pandora_audit('ACL Violation', 'Trying to access Setup Management'); + include 'general/noaccess.php'; + return; } ui_require_css_file('update_manager', 'godmode/update_manager/'); if (!is_metaconsole()) { - require_once("include/functions_update_manager.php"); -} -else { - require_once("../../include/functions_update_manager.php"); + include_once 'include/functions_update_manager.php'; +} else { + include_once '../../include/functions_update_manager.php'; } -enterprise_include_once("include/functions_update_manager.php"); +enterprise_include_once('include/functions_update_manager.php'); $current_package = update_manager_get_current_package(); -if(!enterprise_installed()){ - $open=true; +if (!enterprise_installed()) { + $open = true; } -$memory_limit = ini_get("memory_limit"); -$memory_limit = str_replace("M", "", $memory_limit); -$memory_limit = (int)$memory_limit; +$memory_limit = ini_get('memory_limit'); +$memory_limit = str_replace('M', '', $memory_limit); +$memory_limit = (int) $memory_limit; if ($memory_limit < 500) { - ui_print_error_message( - sprintf(__('Your PHP has set memory limit in %s. For avoid problems with big updates please set to 500M'), ini_get("memory_limit")) - ); -} -$post_max_size = ini_get("post_max_size"); -$post_max_size = str_replace("M", "", $post_max_size); -if ($memory_limit < 100) { - ui_print_error_message( - sprintf(__('Your PHP has set post parameter max size limit in %s. For avoid problems with big updates please set to 100M'), ini_get("post_max_size")) - ); -} -$upload_max_filesize = ini_get("upload_max_filesize"); -$upload_max_filesize = str_replace("M", "", $upload_max_filesize); -if ($memory_limit < 100) { - ui_print_error_message( - sprintf(__('Your PHP has set maximum allowed size for uploaded files limit in %s. For avoid problems with big updates please set to 100M'), ini_get("upload_max_filesize")) - ); + ui_print_error_message( + sprintf(__('Your PHP has set memory limit in %s. For avoid problems with big updates please set to 500M'), ini_get('memory_limit')) + ); } -/* Translators: Do not translade Update Manager, it's the name of the program */ +$post_max_size = ini_get('post_max_size'); +$post_max_size = str_replace('M', '', $post_max_size); +if ($memory_limit < 100) { + ui_print_error_message( + sprintf(__('Your PHP has set post parameter max size limit in %s. For avoid problems with big updates please set to 100M'), ini_get('post_max_size')) + ); +} +$upload_max_filesize = ini_get('upload_max_filesize'); +$upload_max_filesize = str_replace('M', '', $upload_max_filesize); +if ($memory_limit < 100) { + ui_print_error_message( + sprintf(__('Your PHP has set maximum allowed size for uploaded files limit in %s. For avoid problems with big updates please set to 100M'), ini_get('upload_max_filesize')) + ); +} + +// Translators: Do not translade Update Manager, it's the name of the program if (is_metaconsole()) { - echo ""; } if (is_metaconsole()) { - echo " -'); +' + ); } -include_once($config['homedir'] . "/include/functions_profile.php"); -enterprise_include ('include/auth/mysql.php'); +require_once $config['homedir'].'/include/functions_profile.php'; +enterprise_include('include/auth/mysql.php'); + +$config['user_can_update_info'] = true; +$config['user_can_update_password'] = true; +$config['admin_can_add_user'] = true; +$config['admin_can_delete_user'] = true; +$config['admin_can_disable_user'] = false; +// currently not implemented +$config['admin_can_make_admin'] = true; -$config["user_can_update_info"] = true; -$config["user_can_update_password"] = true; -$config["admin_can_add_user"] = true; -$config["admin_can_delete_user"] = true; -$config["admin_can_disable_user"] = false; //currently not implemented -$config["admin_can_make_admin"] = true; /** * process_user_login accepts $login and $pass and handles it according to current authentication scheme * - * @param string $login - * @param string $pass + * @param string $login + * @param string $pass * @param boolean $api * * @return mixed False in case of error or invalid credentials, the username in case it's correct. */ -function process_user_login ($login, $pass, $api = false) { - global $config, $mysql_cache; - - // Always authenticate admins against the local database - if (strtolower ($config["auth"]) == 'mysql' || is_user_admin ($login)) { - return process_user_login_local ($login, $pass, $api); - } - else { - $login_remote = process_user_login_remote ($login, io_safe_output($pass), $api); - if ($login_remote == false && $config['fallback_local_auth'] == '1') { - return process_user_login_local ($login, $pass, $api); - } - else { - return $login_remote; - } - } +function process_user_login($login, $pass, $api=false) +{ + global $config, $mysql_cache; - return false; + // Always authenticate admins against the local database + if (strtolower($config['auth']) == 'mysql' || is_user_admin($login)) { + return process_user_login_local($login, $pass, $api); + } else { + $login_remote = process_user_login_remote($login, io_safe_output($pass), $api); + if ($login_remote == false && $config['fallback_local_auth'] == '1') { + return process_user_login_local($login, $pass, $api); + } else { + return $login_remote; + } + } + + return false; } -function process_user_login_local ($login, $pass, $api = false) { - global $config, $mysql_cache; - // Connect to Database - switch ($config["dbtype"]) { - case "mysql": - if (!$api) { - $sql = sprintf ("SELECT `id_user`, `password` +function process_user_login_local($login, $pass, $api=false) +{ + global $config, $mysql_cache; + + // Connect to Database + switch ($config['dbtype']) { + case 'mysql': + if (!$api) { + $sql = sprintf( + "SELECT `id_user`, `password` FROM `tusuario` WHERE `id_user` = '%s' AND `not_login` = 0 - AND `disabled` = 0", $login); - } - else { - $sql = sprintf ("SELECT `id_user`, `password` + AND `disabled` = 0", + $login + ); + } else { + $sql = sprintf( + "SELECT `id_user`, `password` FROM `tusuario` WHERE `id_user` = '%s' - AND `disabled` = 0", $login); - } - break; - case "postgresql": - if (!$api) { - $sql = sprintf ('SELECT "id_user", "password" + AND `disabled` = 0", + $login + ); + } + break; + + case 'postgresql': + if (!$api) { + $sql = sprintf( + 'SELECT "id_user", "password" FROM "tusuario" WHERE "id_user" = \'%s\' AND "not_login" = 0 - AND "disabled" = 0', $login); - } - else { - $sql = sprintf ('SELECT "id_user", "password" + AND "disabled" = 0', + $login + ); + } else { + $sql = sprintf( + 'SELECT "id_user", "password" FROM "tusuario" WHERE "id_user" = \'%s\' - AND "disabled" = 0', $login); - } - break; - case "oracle": - if (!$api) { - $sql = sprintf ('SELECT id_user, password + AND "disabled" = 0', + $login + ); + } + break; + + case 'oracle': + if (!$api) { + $sql = sprintf( + 'SELECT id_user, password FROM tusuario WHERE id_user = \'%s\' AND not_login = 0 - AND disabled = 0', $login); - } - else { - $sql = sprintf ('SELECT id_user, password + AND disabled = 0', + $login + ); + } else { + $sql = sprintf( + 'SELECT id_user, password FROM tusuario WHERE id_user = \'%s\' - AND disabled = 0', $login); - } - break; - } - $row = db_get_row_sql ($sql); - - //Check that row exists, that password is not empty and that password is the same hash - if ($row !== false && $row["password"] !== md5 ("") - && $row["password"] == md5 ($pass)) { - // Login OK - // Nick could be uppercase or lowercase (select in MySQL - // is not case sensitive) - // We get DB nick to put in PHP Session variable, - // to avoid problems with case-sensitive usernames. - // Thanks to David Muñiz for Bug discovery :) - - $filter = array("id_usuario" => $login); - $user_profile = db_get_row_filter ("tusuario_perfil", $filter); - if(!users_is_admin($login) && !$user_profile){ - $mysql_cache["auth_error"] = "User does not have any profile"; - $config["auth_error"] = "User does not have any profile"; - return false; - } - - return $row["id_user"]; - } - else { - if (!user_can_login($login)) { - $mysql_cache["auth_error"] = "User only can use the API."; - $config["auth_error"] = "User only can use the API."; - } - else { - $mysql_cache["auth_error"] = "User not found in database or incorrect password"; - $config["auth_error"] = "User not found in database or incorrect password"; - } - } - - return false; + AND disabled = 0', + $login + ); + } + break; + } + + $row = db_get_row_sql($sql); + + // Check that row exists, that password is not empty and that password is the same hash + if ($row !== false && $row['password'] !== md5('') + && $row['password'] == md5($pass) + ) { + // Login OK + // Nick could be uppercase or lowercase (select in MySQL + // is not case sensitive) + // We get DB nick to put in PHP Session variable, + // to avoid problems with case-sensitive usernames. + // Thanks to David Muñiz for Bug discovery :) + $filter = ['id_usuario' => $login]; + $user_profile = db_get_row_filter('tusuario_perfil', $filter); + if (!users_is_admin($login) && !$user_profile) { + $mysql_cache['auth_error'] = 'User does not have any profile'; + $config['auth_error'] = 'User does not have any profile'; + return false; + } + + return $row['id_user']; + } else { + if (!user_can_login($login)) { + $mysql_cache['auth_error'] = 'User only can use the API.'; + $config['auth_error'] = 'User only can use the API.'; + } else { + $mysql_cache['auth_error'] = 'User not found in database or incorrect password'; + $config['auth_error'] = 'User not found in database or incorrect password'; + } + } + + return false; } -function process_user_login_remote ($login, $pass, $api = false) { - global $config, $mysql_cache; - - // Remote authentication - switch ($config["auth"]) { - // LDAP - case 'ldap': - $sr = ldap_process_user_login ($login, $pass); - - if(!$sr) { - return false; - } - break; - - // Active Directory - case 'ad': - if (enterprise_hook ('ad_process_user_login', array ($login, $pass)) === false) { - $config["auth_error"] = "User not found in database or incorrect password"; - return false; - } - break; - - // Remote Pandora FMS - case 'pandora': - if (enterprise_hook ('remote_pandora_process_user_login', array ($login, $pass)) === false) { - $config["auth_error"] = "User not found in database or incorrect password"; - return false; - } - break; - - // Remote Integria - case 'integria': - if (enterprise_hook ('remote_integria_process_user_login', array ($login, $pass)) === false) { - $config["auth_error"] = "User not found in database or incorrect password"; - return false; - } - break; - - // Unknown authentication method - default: - $config["auth_error"] = "User not found in database - or incorrect password"; - return false; - break; - } - - if ($config["auth"] === 'ldap') { - $login_user_attribute = $login; - if ($config['ldap_login_user_attr'] == 'mail') { - $login = $sr["mail"][0]; - } - } - - // Authentication ok, check if the user exists in the local database - if (is_user ($login)) { - if (!user_can_login($login)) { - return false; - } - - if (($config["auth"] === 'ad') && - (isset($config['ad_advanced_config']) && $config['ad_advanced_config'])) { - - $return = enterprise_hook ('prepare_permissions_groups_of_user_ad', - array ($login, $pass, false, true, defined('METACONSOLE'))); - if ($return === "error_permissions") { - $config["auth_error"] = - __("Problems with configuration permissions. Please contact with Administrator"); - return false; - } - else { - if ($return === "permissions_changed") { - $config["auth_error"] = - __("Your permissions have changed. Please, login again."); - return false; - } - } - } - elseif ($config["auth"] === 'ldap') { - if ($config['ldap_save_password']) { - $update_credentials = change_local_user_pass_ldap ($login, $pass); +function process_user_login_remote($login, $pass, $api=false) +{ + global $config, $mysql_cache; - if ($update_credentials) { - $config["auth_error"] = - __("Your permissions have changed. Please, login again."); - return false; - } - } - else { - delete_user_pass_ldap ($login); - } - - $permissions = array(); - if($config['ldap_advanced_config']){ - $i = 0; - - $ldap_adv_perms = json_decode(io_safe_output($config['ldap_adv_perms']), true); - foreach ($ldap_adv_perms as $ldap_adv_perm) { - $attributes = $ldap_adv_perm['groups_ldap']; - - foreach ($attributes as $attr) { - $attr = explode('=', $attr, 2); - foreach ($sr[$attr[0]] as $s_attr) { - if(preg_match('/' . $attr[1] . '/', $s_attr)){ - $permissions[$i]["profile"] = $ldap_adv_perm['profile']; - $permissions[$i]["groups"] = $ldap_adv_perm['group']; - $permissions[$i]["tags"] = implode(",",$ldap_adv_perm['tags']); - $i++; - } - } - } - } - } else { - $permissions[0]["profile"] = $config['default_remote_profile']; - $permissions[0]["groups"][] = $config['default_remote_group']; - $permissions[0]["tags"] = $config['default_assign_tags']; - } - if(empty($permissions)) { - $config["auth_error"] = __("User not found in database or incorrect password"); - return false; - - } else { - // check permissions - $result = check_permission_ad ($login, $pass, false, - $permissions, defined('METACONSOLE')); - - if ($return === "error_permissions") { - $config["auth_error"] = - __("Problems with configuration permissions. Please contact with Administrator"); - return false; - } - else { - if ($return === "permissions_changed") { - $config["auth_error"] = - __("Your permissions have changed. Please, login again."); - return false; - } - } - - - } - } + // Remote authentication + switch ($config['auth']) { + // LDAP + case 'ldap': + $sr = ldap_process_user_login($login, $pass); - return $login; - } - - // The user does not exist and can not be created - if ($config['autocreate_remote_users'] == 0 || is_user_blacklisted ($login)) { - $config["auth_error"] = __("Ooops User not found in - database or incorrect password"); - - return false; - } - - if ($config["auth"] === 'ad' && - (isset($config['ad_advanced_config']) && - $config['ad_advanced_config'])) { - - - if ( defined('METACONSOLE') ) { - enterprise_include_once('include/functions_metaconsole.php'); - enterprise_include_once ('meta/include/functions_groups_meta.php'); - - $return = groups_meta_synchronizing(); - - if ($return["group_create_err"] > 0 || $return["group_update_err"] > 0) { - $config["auth_error"] = __('Fail the group synchronizing'); - return false; - } - - $return = meta_tags_synchronizing(); - if ($return['tag_create_err'] > 0 || $return['tag_update_err'] > 0) { - $config["auth_error"] = __('Fail the tag synchronizing'); - return false; - } - } - - // Create the user - if (enterprise_hook ('prepare_permissions_groups_of_user_ad', - array($login, - $pass, - array ('fullname' => $login, - 'comments' => 'Imported from ' . $config['auth']), - false, defined('METACONSOLE'))) === false) { - - $config["auth_error"] = __("User not found in database - or incorrect password"); - - return false; - } - } - elseif ($config["auth"] === 'ldap') { - if ( defined('METACONSOLE') ) { - enterprise_include_once('include/functions_metaconsole.php'); - enterprise_include_once ('meta/include/functions_groups_meta.php'); - - $return = groups_meta_synchronizing(); - - if ($return["group_create_err"] > 0 || $return["group_update_err"] > 0) { - $config["auth_error"] = __('Fail the group synchronizing'); - return false; - } - - $return = meta_tags_synchronizing(); - if ($return['tag_create_err'] > 0 || $return['tag_update_err'] > 0) { - $config["auth_error"] = __('Fail the tag synchronizing'); - return false; - } - } - - $permissions = array(); - if($config['ldap_advanced_config']){ - $i = 0; - - $ldap_adv_perms = json_decode(io_safe_output($config['ldap_adv_perms']), true); - - foreach ($ldap_adv_perms as $ldap_adv_perm) { - $attributes = $ldap_adv_perm['groups_ldap']; - - foreach ($attributes as $attr) { - $attr = explode('=', $attr, 2); - foreach ($sr[$attr[0]] as $s_attr) { - if(preg_match('/' . $attr[1] . '/', $s_attr)){ - $permissions[$i]["profile"] = $ldap_adv_perm['profile']; - $permissions[$i]["groups"] = $ldap_adv_perm['group']; - $permissions[$i]["tags"] = implode(",",$ldap_adv_perm['tags']); - $i++; - } - } - } - } - } else { - $permissions[0]["profile"] = $config['default_remote_profile']; - $permissions[0]["groups"][] = $config['default_remote_group']; - $permissions[0]["tags"] = $config['default_assign_tags']; - } - - if(empty($permissions)) { - $config["auth_error"] = __("User not found in database or incorrect password"); - return false; - - } else { - $user_info['fullname'] = $sr['cn'][0]; - $user_info['email'] = $sr['mail'][0]; - - // Create the user - $create_user = create_user_and_permisions_ldap($login, $pass, $user_info, $permissions, defined('METACONSOLE')); - } + if (!$sr) { + return false; + } + break; - } - else { - - $user_info = array ('fullname' => $login, - 'comments' => 'Imported from ' . $config['auth']); - if ( is_metaconsole() && $config["auth"] === 'ad') - $user_info['metaconsole_access_node'] = $config['ad_adv_user_node']; - - // Create the user in the local database - if (create_user ($login, $pass, $user_info ) === false) { - $config["auth_error"] = __("User not found in database or incorrect password"); - return false; - } - - profile_create_user_profile ($login, $config['default_remote_profile'], - $config['default_remote_group'], false, $config['default_assign_tags']); - //TODO: Check the creation in the nodes - if ( is_metaconsole() ) { - enterprise_include_once('include/functions_metaconsole.php'); - enterprise_include_once ('meta/include/functions_groups_meta.php'); - - $return = groups_meta_synchronizing(); - - if ($return["group_create_err"] > 0 || $return["group_update_err"] > 0) { - $config["auth_error"] = __('Fail the group synchronizing'); - return false; - } - - $return = meta_tags_synchronizing(); - if ($return['tag_create_err'] > 0 || $return['tag_update_err'] > 0) { - $config["auth_error"] = __('Fail the tag synchronizing'); - return false; - } - - $servers = metaconsole_get_servers(); - foreach ($servers as $server) { - $perfil_maestro = db_get_row('tperfil', - 'id_perfil', $config['default_remote_profile']); - - if (metaconsole_connect($server) == NOERR ) { - - if (!profile_exist($perfil_maestro['name'])) { - unset($perfil_maestro['id_perfil']); - $id_profile = db_process_sql_insert('tperfil', $perfil_maestro); - } - else { - $id_profile = db_get_value('id_perfil', 'tperfil', 'name', $perfil_maestro['name']); - } - - if ($config["auth"] === 'ad') { - unset($user_info['metaconsole_access_node']); - $user_info['not_login'] = (int) !$config['ad_adv_user_node']; - } - - if (create_user ($login, $pass, $user_info) === false) - continue; - profile_create_user_profile ($login, $id_profile, - $config['default_remote_group'], false, $config['default_assign_tags']); - } - - metaconsole_restore_db(); - } - } - } - - return $login; + // Active Directory + case 'ad': + if (enterprise_hook('ad_process_user_login', [$login, $pass]) === false) { + $config['auth_error'] = 'User not found in database or incorrect password'; + return false; + } + break; + + // Remote Pandora FMS + case 'pandora': + if (enterprise_hook('remote_pandora_process_user_login', [$login, $pass]) === false) { + $config['auth_error'] = 'User not found in database or incorrect password'; + return false; + } + break; + + // Remote Integria + case 'integria': + if (enterprise_hook('remote_integria_process_user_login', [$login, $pass]) === false) { + $config['auth_error'] = 'User not found in database or incorrect password'; + return false; + } + break; + + // Unknown authentication method + default: + $config['auth_error'] = 'User not found in database + or incorrect password'; + return false; + break; + } + + if ($config['auth'] === 'ldap') { + $login_user_attribute = $login; + if ($config['ldap_login_user_attr'] == 'mail') { + $login = $sr['mail'][0]; + } + } + + // Authentication ok, check if the user exists in the local database + if (is_user($login)) { + if (!user_can_login($login)) { + return false; + } + + if (($config['auth'] === 'ad') + && (isset($config['ad_advanced_config']) && $config['ad_advanced_config']) + ) { + $return = enterprise_hook( + 'prepare_permissions_groups_of_user_ad', + [ + $login, + $pass, + false, + true, + defined('METACONSOLE'), + ] + ); + + if ($return === 'error_permissions') { + $config['auth_error'] = __('Problems with configuration permissions. Please contact with Administrator'); + return false; + } else { + if ($return === 'permissions_changed') { + $config['auth_error'] = __('Your permissions have changed. Please, login again.'); + return false; + } + } + } else if ($config['auth'] === 'ldap') { + if ($config['ldap_save_password']) { + $update_credentials = change_local_user_pass_ldap($login, $pass); + + if ($update_credentials) { + $config['auth_error'] = __('Your permissions have changed. Please, login again.'); + return false; + } + } else { + delete_user_pass_ldap($login); + } + + $permissions = fill_permissions_ldap($sr); + if (empty($permissions)) { + $config['auth_error'] = __('User not found in database or incorrect password'); + return false; + } else { + // check permissions + $result = check_permission_ad( + $login, + $pass, + false, + $permissions, + defined('METACONSOLE') + ); + + if ($return === 'error_permissions') { + $config['auth_error'] = __('Problems with configuration permissions. Please contact with Administrator'); + return false; + } else { + if ($return === 'permissions_changed') { + $config['auth_error'] = __('Your permissions have changed. Please, login again.'); + return false; + } + } + } + } + + return $login; + } + + // The user does not exist and can not be created + if ($config['autocreate_remote_users'] == 0 || is_user_blacklisted($login)) { + $config['auth_error'] = __( + 'Ooops User not found in + database or incorrect password' + ); + + return false; + } + + if ($config['auth'] === 'ad' + && (isset($config['ad_advanced_config']) + && $config['ad_advanced_config']) + ) { + if (defined('METACONSOLE')) { + enterprise_include_once('include/functions_metaconsole.php'); + enterprise_include_once('meta/include/functions_groups_meta.php'); + + $return = groups_meta_synchronizing(); + + if ($return['group_create_err'] > 0 || $return['group_update_err'] > 0) { + $config['auth_error'] = __('Fail the group synchronizing'); + return false; + } + + $return = meta_tags_synchronizing(); + if ($return['tag_create_err'] > 0 || $return['tag_update_err'] > 0) { + $config['auth_error'] = __('Fail the tag synchronizing'); + return false; + } + } + + // Create the user + if (enterprise_hook( + 'prepare_permissions_groups_of_user_ad', + [ + $login, + $pass, + [ + 'fullname' => $login, + 'comments' => 'Imported from '.$config['auth'], + ], + false, + defined('METACONSOLE'), + ] + ) === false + ) { + $config['auth_error'] = __( + 'User not found in database + or incorrect password' + ); + + return false; + } + } else if ($config['auth'] === 'ldap') { + if (defined('METACONSOLE')) { + enterprise_include_once('include/functions_metaconsole.php'); + enterprise_include_once('meta/include/functions_groups_meta.php'); + + $return = groups_meta_synchronizing(); + + if ($return['group_create_err'] > 0 || $return['group_update_err'] > 0) { + $config['auth_error'] = __('Fail the group synchronizing'); + return false; + } + + $return = meta_tags_synchronizing(); + if ($return['tag_create_err'] > 0 || $return['tag_update_err'] > 0) { + $config['auth_error'] = __('Fail the tag synchronizing'); + return false; + } + } + + $permissions = fill_permissions_ldap($sr); + if (empty($permissions)) { + $config['auth_error'] = __('User not found in database or incorrect password'); + return false; + } else { + $user_info['fullname'] = $sr['cn'][0]; + $user_info['email'] = $sr['mail'][0]; + + // Create the user + $create_user = create_user_and_permisions_ldap($login, $pass, $user_info, $permissions, defined('METACONSOLE')); + } + } else { + $user_info = [ + 'fullname' => $login, + 'comments' => 'Imported from '.$config['auth'], + ]; + if (is_metaconsole() && $config['auth'] === 'ad') { + $user_info['metaconsole_access_node'] = $config['ad_adv_user_node']; + } + + // Create the user in the local database + if (create_user($login, $pass, $user_info) === false) { + $config['auth_error'] = __('User not found in database or incorrect password'); + return false; + } + + profile_create_user_profile( + $login, + $config['default_remote_profile'], + $config['default_remote_group'], + false, + $config['default_assign_tags'] + ); + // TODO: Check the creation in the nodes + if (is_metaconsole()) { + enterprise_include_once('include/functions_metaconsole.php'); + enterprise_include_once('meta/include/functions_groups_meta.php'); + + $return = groups_meta_synchronizing(); + + if ($return['group_create_err'] > 0 || $return['group_update_err'] > 0) { + $config['auth_error'] = __('Fail the group synchronizing'); + return false; + } + + $return = meta_tags_synchronizing(); + if ($return['tag_create_err'] > 0 || $return['tag_update_err'] > 0) { + $config['auth_error'] = __('Fail the tag synchronizing'); + return false; + } + + $servers = metaconsole_get_servers(); + foreach ($servers as $server) { + $perfil_maestro = db_get_row( + 'tperfil', + 'id_perfil', + $config['default_remote_profile'] + ); + + if (metaconsole_connect($server) == NOERR) { + if (!profile_exist($perfil_maestro['name'])) { + unset($perfil_maestro['id_perfil']); + $id_profile = db_process_sql_insert('tperfil', $perfil_maestro); + } else { + $id_profile = db_get_value('id_perfil', 'tperfil', 'name', $perfil_maestro['name']); + } + + if ($config['auth'] === 'ad') { + unset($user_info['metaconsole_access_node']); + $user_info['not_login'] = (int) !$config['ad_adv_user_node']; + } + + if (create_user($login, $pass, $user_info) === false) { + continue; + } + + profile_create_user_profile( + $login, + $id_profile, + $config['default_remote_group'], + false, + $config['default_assign_tags'] + ); + } + + metaconsole_restore_db(); + } + } + } + + return $login; } -/** + +/** * Checks if a user is administrator. - * + * * @param string User id. - * - * @return bool True is the user is admin + * + * @return boolean True is the user is admin */ -function is_user_admin ($id_user) { - require_once(__DIR__ . "/../functions_users.php"); - return users_is_admin($id_user); +function is_user_admin($id_user) +{ + include_once __DIR__.'/../functions_users.php'; + return users_is_admin($id_user); } @@ -516,89 +511,101 @@ function is_user_admin ($id_user) { * @param mixed User structure to get id. It might be a row returned from * tusuario or tusuario_perfil. If it's not a row, the int value is returned. * - * @return int User id of the mixed parameter. + * @return integer User id of the mixed parameter. */ -function get_user_id ($user) { - if (is_array ($user)) { - if (isset ($user['id_user'])) - return $user['id_user']; - elseif (isset ($user['id_usuario'])) - return $user['id_usuario']; - else - return false; - } - else { - return $user; - } +function get_user_id($user) +{ + if (is_array($user)) { + if (isset($user['id_user'])) { + return $user['id_user']; + } else if (isset($user['id_usuario'])) { + return $user['id_usuario']; + } else { + return false; + } + } else { + return $user; + } } -/** + +/** * Check is a user exists in the system - * + * * @param mixed User id. - * - * @return bool True if the user exists. + * + * @return boolean True if the user exists. */ -function is_user ($user) { - $user = db_get_row('tusuario', 'id_user', get_user_id ($user)); - - if (! $user) - return false; - - return true; +function is_user($user) +{ + $user = db_get_row('tusuario', 'id_user', get_user_id($user)); + + if (! $user) { + return false; + } + + return true; } -function user_can_login($user) { - $not_login = db_get_value('not_login', 'tusuario', 'id_user', $user); - - if ($not_login != 0) { - return false; - } - - return true; + +function user_can_login($user) +{ + $not_login = db_get_value('not_login', 'tusuario', 'id_user', $user); + + if ($not_login != 0) { + return false; + } + + return true; } -/** + +/** * Gets the users real name - * + * * @param mixed User id. - * + * * @return string The users full name */ -function get_user_fullname ($user) { - return (string) db_get_value ('fullname', 'tusuario', 'id_user', get_user_id ($user)); +function get_user_fullname($user) +{ + return (string) db_get_value('fullname', 'tusuario', 'id_user', get_user_id($user)); } -/** + +/** * Gets the users email - * + * * @param mixed User id. - * + * * @return string The users email address */ -function get_user_email ($user) { - return (string) db_get_value ('email', 'tusuario', 'id_user', get_user_id ($user)); +function get_user_email($user) +{ + return (string) db_get_value('email', 'tusuario', 'id_user', get_user_id($user)); } + /** * Gets a Users info - * + * * @param mixed User id * * @return mixed An array of users */ -function get_user_info ($user) { - static $cache_user_info = array(); - if (array_key_exists($user, $cache_user_info)){ - return $cache_user_info[$user]; - } - else{ - $return = db_get_row ("tusuario", "id_user", get_user_id ($user)); - $cache_user_info[$user] = $return; - return $return; - } +function get_user_info($user) +{ + static $cache_user_info = []; + if (array_key_exists($user, $cache_user_info)) { + return $cache_user_info[$user]; + } else { + $return = db_get_row('tusuario', 'id_user', get_user_id($user)); + $cache_user_info[$user] = $return; + return $return; + } } + /** * Get a list of all users in an array [username] => array (userinfo) * We can't simplify this because some auth schemes (like LDAP) automatically (or it's at least cheaper to) return all the information @@ -608,269 +615,309 @@ function get_user_info ($user) { * * @return array An array of user information */ -function get_users ($order = "fullname", $filter = false, $fields = false) { - if (is_array($order)) { - $filter['order'] = $order['field'] . ' ' . $order['order']; - } - else { - switch ($order) { - case "registered": - case "last_connect": - case "fullname": - break; - default: - $order = "fullname"; - break; - } - - $filter['order'] = $order." ASC"; - } - - - $output = array(); - - $result = db_get_all_rows_filter ("tusuario", $filter, $fields); - if ($result !== false) { - foreach ($result as $row) { - $output[$row["id_user"]] = $row; - } - } - - return $output; +function get_users($order='fullname', $filter=false, $fields=false) +{ + if (is_array($order)) { + $filter['order'] = $order['field'].' '.$order['order']; + } else { + switch ($order) { + case 'registered': + case 'last_connect': + case 'fullname': + break; + + default: + $order = 'fullname'; + break; + } + + $filter['order'] = $order.' ASC'; + } + + $output = []; + + $result = db_get_all_rows_filter('tusuario', $filter, $fields); + if ($result !== false) { + foreach ($result as $row) { + $output[$row['id_user']] = $row; + } + } + + return $output; } + /** * Sets the last login for a user * * @param string User id */ -function process_user_contact ($id_user) { - return db_process_sql_update ("tusuario", - array ("last_connect" => get_system_time ()), - array ("id_user" => $id_user)); +function process_user_contact($id_user) +{ + return db_process_sql_update( + 'tusuario', + ['last_connect' => get_system_time()], + ['id_user' => $id_user] + ); } + /** * Create a new user * - * @return bool false + * @return boolean false */ -function create_user ($id_user, $password, $user_info) { - $values = $user_info; - $values["id_user"] = $id_user; - $values["password"] = md5 ($password); - $values["last_connect"] = 0; - $values["registered"] = get_system_time (); - - return (@db_process_sql_insert ("tusuario", $values)) !== false; +function create_user($id_user, $password, $user_info) +{ + $values = $user_info; + $values['id_user'] = $id_user; + $values['password'] = md5($password); + $values['last_connect'] = 0; + $values['registered'] = get_system_time(); + + return (@db_process_sql_insert('tusuario', $values)) !== false; } + /** * Save password history * - * @return bool false + * @return boolean false */ -function save_pass_history ($id_user, $password) { - $values["id_user"] = $id_user; - $values["password"] = md5 ($password); - $values["date_begin"] = date ("Y/m/d H:i:s", get_system_time()); - - return (@db_process_sql_insert ("tpassword_history", $values)) !== false; +function save_pass_history($id_user, $password) +{ + $values['id_user'] = $id_user; + $values['password'] = md5($password); + $values['date_begin'] = date('Y/m/d H:i:s', get_system_time()); + + return (@db_process_sql_insert('tpassword_history', $values)) !== false; } + /** * Deletes the user * * @param string User id */ -function delete_user ($id_user) { - $result = db_process_sql_delete('tusuario_perfil', - array('id_usuario' => $id_user)); - if ($result === false) { - return false; - } - - $result = db_process_sql_delete('tusuario', - array('id_user' => $id_user)); - if ($result === false) { - return false; - } - return true; +function delete_user($id_user) +{ + $result = db_process_sql_delete( + 'tusuario_perfil', + ['id_usuario' => $id_user] + ); + if ($result === false) { + return false; + } + + $result = db_process_sql_delete( + 'tusuario', + ['id_user' => $id_user] + ); + if ($result === false) { + return false; + } + + return true; } + /** * Update the password in MD5 for user pass as id_user with * password in plain text. - * + * * @param string user User ID * @param string password Password in plain text. - * + * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function update_user_password ($user, $password_new) { - global $config; - if (isset($config['auth']) && $config['auth'] == 'pandora') { - $sql = sprintf("UPDATE tusuario SET password = '" . md5($password_new) . - "', last_pass_change = '" . date("Y-m-d H:i:s", get_system_time()) . - "' WHERE id_user = '" . $user . "'"); +function update_user_password($user, $password_new) +{ + global $config; + if (isset($config['auth']) && $config['auth'] == 'pandora') { + $sql = sprintf( + "UPDATE tusuario SET password = '".md5($password_new)."', last_pass_change = '".date('Y-m-d H:i:s', get_system_time())."' WHERE id_user = '".$user."'" + ); - $connection = mysql_connect_db($config['rpandora_server'], - $config['rpandora_dbname'], $config['rpandora_user'], - $config['rpandora_pass']); - $remote_pass_update = db_process_sql ($sql, 'affected_rows', $connection); + $connection = mysql_connect_db( + $config['rpandora_server'], + $config['rpandora_dbname'], + $config['rpandora_user'], + $config['rpandora_pass'] + ); + $remote_pass_update = db_process_sql($sql, 'affected_rows', $connection); - if (!$remote_pass_update) { - $config["auth_error"] = __('Could not changes password on remote pandora'); - return false; - } - } - return db_process_sql_update ('tusuario', - array ('password' => md5 ($password_new), 'last_pass_change' => date ("Y/m/d H:i:s", get_system_time())), - array ('id_user' => $user)); + if (!$remote_pass_update) { + $config['auth_error'] = __('Could not changes password on remote pandora'); + return false; + } + } + + return db_process_sql_update( + 'tusuario', + [ + 'password' => md5($password_new), + 'last_pass_change' => date('Y/m/d H:i:s', get_system_time()), + ], + ['id_user' => $user] + ); } + /** * Update the data of a user that user is choose with * id_user. - * + * * @param string user User ID * @param array values Associative array with index as name of field and content. - * + * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function update_user ($id_user, $values) { - if (! is_array ($values)) - return false; - - return db_process_sql_update ("tusuario", $values, array ("id_user" => $id_user)); +function update_user($id_user, $values) +{ + if (! is_array($values)) { + return false; + } + + return db_process_sql_update('tusuario', $values, ['id_user' => $id_user]); } + /** * Authenticate against an LDAP server. * * @param string User login * @param string User password (plain text) * - * @return bool True if the login is correct, false in other case + * @return boolean True if the login is correct, false in other case */ -function ldap_process_user_login ($login, $password) { - global $config; - - if (! function_exists ("ldap_connect")) { - $config["auth_error"] = __('Your installation of PHP does not support LDAP'); - - return false; - } - - // Connect to the LDAP server - $ds = @ldap_connect ($config["ldap_server"], $config["ldap_port"]); - - if (!$ds) { - $config["auth_error"] = 'Error connecting to LDAP server'; - - return false; - } - - // Set the LDAP version - ldap_set_option ($ds, LDAP_OPT_PROTOCOL_VERSION, $config["ldap_version"]); - - if ($config["ldap_start_tls"]) { - if (!@ldap_start_tls ($ds)) { - $config["auth_error"] = 'Could not start TLS for LDAP connection'; - @ldap_close ($ds); - - return false; - } - } +function ldap_process_user_login($login, $password) +{ + global $config; + + if (! function_exists('ldap_connect')) { + $config['auth_error'] = __('Your installation of PHP does not support LDAP'); + + return false; + } + + // Connect to the LDAP server + $ds = @ldap_connect($config['ldap_server'], $config['ldap_port']); + + if (!$ds) { + $config['auth_error'] = 'Error connecting to LDAP server'; + + return false; + } + + // Set the LDAP version + ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $config['ldap_version']); + + if ($config['ldap_start_tls']) { + if (!@ldap_start_tls($ds)) { + $config['auth_error'] = 'Could not start TLS for LDAP connection'; + @ldap_close($ds); + + return false; + } + } + + if ($config['ldap_function'] == 'local') { + $sr = local_ldap_search( + $config['ldap_server'], + $config['ldap_port'], + $config['ldap_version'], + io_safe_output($config['ldap_base_dn']), + $config['ldap_login_attr'], + io_safe_output($config['ldap_admin_login']), + $config['ldap_admin_pass'], + io_safe_output($login) + ); + + if ($sr) { + $user_dn = $sr['dn'][0]; + + $ldap_base_dn = !empty($config['ldap_base_dn']) ? ','.io_safe_output($config['ldap_base_dn']) : ''; + + if (!empty($ldap_base_dn)) { + if (strlen($password) != 0 && @ldap_bind($ds, io_safe_output($user_dn), $password)) { + @ldap_close($ds); + return $sr; + } + } else { + if (strlen($password) != 0 && @ldap_bind($ds, io_safe_output($login), $password)) { + @ldap_close($ds); + return $sr; + } + } + } + } else { + // PHP LDAP function + if ($config['ldap_admin_login'] != '' && $config['ldap_admin_pass'] != '') { + if (!@ldap_bind($ds, io_safe_output($config['ldap_admin_login']), $config['ldap_admin_pass'])) { + $config['auth_error'] = 'Admin ldap connection fail'; + @ldap_close($ds); + return false; + } + } + + $filter = '('.$config['ldap_login_attr'].'='.io_safe_output($login).')'; + + $sr = ldap_search($ds, io_safe_output($config['ldap_base_dn']), $filter); + + $memberof = ldap_get_entries($ds, $sr); + + if ($memberof['count'] == 0 && !isset($memberof[0]['memberof'])) { + @ldap_close($ds); + return false; + } else { + $memberof = $memberof[0]; + } + + unset($memberof['count']); + $ldap_base_dn = !empty($config['ldap_base_dn']) ? ','.io_safe_output($config['ldap_base_dn']) : ''; + + if (!empty($ldap_base_dn)) { + if (strlen($password) != 0 && @ldap_bind($ds, io_safe_output($memberof['dn']), $password)) { + @ldap_close($ds); + return $memberof; + } + } else { + if (strlen($password) != 0 && @ldap_bind($ds, io_safe_output($login), $password)) { + @ldap_close($ds); + return $memberof; + } + } + } + + @ldap_close($ds); + $config['auth_error'] = 'User not found in database or incorrect password'; + return false; - if($config['ldap_function'] == 'local'){ - $sr = local_ldap_search($config["ldap_server"], $config["ldap_port"], $config["ldap_version"], - io_safe_output($config["ldap_base_dn"]), $config['ldap_login_attr'], - io_safe_output($config['ldap_admin_login']), $config['ldap_admin_pass'], io_safe_output($login)); - - if($sr) { - $user_dn = $sr["dn"][0]; - - $ldap_base_dn = !empty($config["ldap_base_dn"]) ? "," . io_safe_output($config["ldap_base_dn"]) : ''; - - if(!empty($ldap_base_dn)) { - if (strlen($password) != 0 && @ldap_bind($ds, io_safe_output($user_dn), $password) ) { - @ldap_close ($ds); - return $sr; - } - } else { - if (strlen($password) != 0 && @ldap_bind($ds, io_safe_output($login), $password) ) { - @ldap_close ($ds); - return $sr; - } - } - } - - } else { - // PHP LDAP function - if ($config['ldap_admin_login'] != "" && $config['ldap_admin_pass'] != "") { - if (!@ldap_bind($ds, io_safe_output($config['ldap_admin_login']), $config['ldap_admin_pass'])) { - $config["auth_error"] = 'Admin ldap connection fail'; - @ldap_close ($ds); - return false; - } - } - - $filter="(" . $config['ldap_login_attr'] . "=" . io_safe_output($login) . ")"; - - $sr = ldap_search($ds, io_safe_output($config["ldap_base_dn"]), $filter); - - $memberof = ldap_get_entries($ds, $sr); - - if ($memberof["count"] == 0 && !isset($memberof[0]["memberof"])) { - @ldap_close ($ds); - return false; - } else { - $memberof = $memberof[0]; - } - - unset($memberof["count"]); - $ldap_base_dn = !empty($config["ldap_base_dn"]) ? "," . io_safe_output($config["ldap_base_dn"]) : ''; - - if(!empty($ldap_base_dn)) { - if (strlen($password) != 0 && @ldap_bind($ds, io_safe_output($memberof['dn']), $password) ) { - @ldap_close ($ds); - return $memberof; - } - } else { - if (strlen($password) != 0 && @ldap_bind($ds, io_safe_output($login), $password) ) { - @ldap_close ($ds); - return $memberof; - } - } - } - - @ldap_close ($ds); - $config["auth_error"] = 'User not found in database or incorrect password'; - return false; - } + /** * Checks if a user is in the autocreate blacklist. * * @param string User * - * @return bool True if the user is in the blacklist, false otherwise. + * @return boolean True if the user is in the blacklist, false otherwise. */ -function is_user_blacklisted ($user) { - global $config; - - $blisted_users = explode (',', $config['autocreate_blacklist']); - foreach ($blisted_users as $blisted_user) { - if ($user == $blisted_user) { - return true; - } - } - - return false; +function is_user_blacklisted($user) +{ + global $config; + + $blisted_users = explode(',', $config['autocreate_blacklist']); + foreach ($blisted_users as $blisted_user) { + if ($user == $blisted_user) { + return true; + } + } + + return false; } + /** * Create progile with data obtaint from AD * @@ -879,84 +926,113 @@ function is_user_blacklisted ($user) { * @param array user_info * @param array permiisons * - * @return bool + * @return boolean */ -function create_user_and_permisions_ldap ($id_user, $password, $user_info, - $permissions, $syncronize = false) { - global $config; - - $values = $user_info; - $values["id_user"] = $id_user; - - if ($config['ldap_save_password']) { - $values["password"] = md5 ($password); - } - $values["last_connect"] = 0; - $values["registered"] = get_system_time (); - if ( defined("METACONSOLE") && $syncronize ) - $values['metaconsole_access_node'] = $config['ldap_adv_user_node']; - $user = (@db_process_sql_insert ("tusuario", $values)) !== false; - - if ($user) { - if (!empty($permissions)) { - foreach ($permissions as $permission) { - - $id_profile = $permission["profile"]; - $id_groups = $permission["groups"]; - $tags = $permission["tags"]; - - foreach ($id_groups as $id_group) { - $profile = profile_create_user_profile( - $id_user, $id_profile, $id_group, false, $tags); - } - - if ( defined("METACONSOLE") && $syncronize ) { - enterprise_include_once('include/functions_metaconsole.php'); - - unset($values['metaconsole_access_node']); - $values['not_login'] = (int) !$config['ldap_adv_user_node']; - - $servers = metaconsole_get_servers(); - foreach ($servers as $server) { - $perfil_maestro = db_get_row('tperfil', - 'id_perfil', $permission["profile"]); +function create_user_and_permisions_ldap( + $id_user, + $password, + $user_info, + $permissions, + $syncronize=false +) { + global $config; - if (metaconsole_connect($server) == NOERR ) { - - if (!profile_exist($perfil_maestro['name'])) { - unset($perfil_maestro['id_perfil']); - $id_profile = db_process_sql_insert('tperfil', $perfil_maestro); - } - else { - $id_profile = db_get_value('id_perfil', 'tperfil', 'name', $perfil_maestro['name']); - } - - db_process_sql_insert ("tusuario", $values); - foreach ($id_groups as $id_group) { - $profile = profile_create_user_profile ($id_user, - $id_profile, $id_group, false, $tags); - } - } - - metaconsole_restore_db(); - } - } - - if (!$profile) - return false; - } - } - else { - $profile = profile_create_user_profile( - $id_user, $config['default_remote_profile'], $config['default_remote_group'], false, $config['default_assign_tags']); + $values = $user_info; + $values['id_user'] = $id_user; - if (!$profile) - return false; - } - } - return true; + if ($config['ldap_save_password']) { + $values['password'] = md5($password); + } + + $values['last_connect'] = 0; + $values['registered'] = get_system_time(); + if (defined('METACONSOLE') && $syncronize) { + $values['metaconsole_access_node'] = $config['ldap_adv_user_node']; + } + + $user = (@db_process_sql_insert('tusuario', $values)) !== false; + + if ($user) { + if (!empty($permissions)) { + foreach ($permissions as $permission) { + $id_profile = $permission['profile']; + $id_groups = $permission['groups']; + $tags = $permission['tags']; + $no_hierarchy = (bool) $permission['no_hierarchy'] ? 1 : 0; + + foreach ($id_groups as $id_group) { + $profile = profile_create_user_profile( + $id_user, + $id_profile, + $id_group, + false, + $tags, + $no_hierarchy + ); + } + + if (defined('METACONSOLE') && $syncronize) { + enterprise_include_once('include/functions_metaconsole.php'); + + unset($values['metaconsole_access_node']); + $values['not_login'] = (int) !$config['ldap_adv_user_node']; + + $servers = metaconsole_get_servers(); + foreach ($servers as $server) { + $perfil_maestro = db_get_row( + 'tperfil', + 'id_perfil', + $permission['profile'] + ); + + if (metaconsole_connect($server) == NOERR) { + if (!profile_exist($perfil_maestro['name'])) { + unset($perfil_maestro['id_perfil']); + $id_profile = db_process_sql_insert('tperfil', $perfil_maestro); + } else { + $id_profile = db_get_value('id_perfil', 'tperfil', 'name', $perfil_maestro['name']); + } + + db_process_sql_insert('tusuario', $values); + foreach ($id_groups as $id_group) { + $profile = profile_create_user_profile( + $id_user, + $id_profile, + $id_group, + false, + $tags, + $no_hierarchy + ); + } + } + + metaconsole_restore_db(); + } + } + + if (!$profile) { + return false; + } + } + } else { + $profile = profile_create_user_profile( + $id_user, + $config['default_remote_profile'], + $config['default_remote_group'], + false, + $config['default_assign_tags'] + ); + + if (!$profile) { + return false; + } + } + } + + return true; } + /** * Check if user have right permission in pandora. This * permission depend of ldap. @@ -966,270 +1042,373 @@ function create_user_and_permisions_ldap ($id_user, $password, $user_info, * * @return string */ -function check_permission_ldap ($id_user, $password, $user_info, - $permissions, $syncronize = false) { - - global $config; - include_once($config['homedir'] . "/enterprise/include/functions_metaconsole.php"); - - $result_user = users_get_user_by_id($id_user); - $filter = array("id_usuario" => $id_user); - $profiles_user = array(); - $user_profiles = - db_get_all_rows_filter ("tusuario_perfil", $filter); - - foreach ($user_profiles as $user_profile) { - $profiles_user[$user_profile["id_up"]] = - $user_profile["id_perfil"]; - } - - $profiles_user_nodes = array(); - $permissions_nodes = array(); - if ( is_metaconsole() && $syncronize ) { - $servers = metaconsole_get_servers(); - foreach ($servers as $server) { - if ( metaconsole_connect($server) == NOERR ) { - $user_profiles_nodes = - db_get_all_rows_filter ("tusuario_perfil", $filter); - foreach ($user_profiles_nodes as $user_profile_node) { - $profiles_user_nodes[$server['server_name']][$user_profile_node["id_up"]] = - $user_profile_node["id_perfil"]; - } - } - metaconsole_restore_db(); - } - - foreach ($permissions as $key => $permission) { - $perfil_maestro = db_get_row('tperfil', - 'id_perfil', $permission['profile']); - foreach ($servers as $server) { - if (metaconsole_connect($server) == NOERR ) { - if (profile_exist($perfil_maestro['name'])) { - $id_profile = db_get_value('id_perfil', 'tperfil', 'name', $perfil_maestro['name']); - $permissions_nodes[$server['server_name']][$key] = $permission; - $permissions_nodes[$server['server_name']][$key]['profile'] = $id_profile; - } - } - metaconsole_restore_db(); - } - } - } - - $no_found = array(); - if ($result_user) { - foreach ($permissions as $permission) { - $id_profile = $permission["profile"]; - $id_groups = $permission["groups"]; - $tags = $permission["tags"]; +function check_permission_ldap( + $id_user, + $password, + $user_info, + $permissions, + $syncronize=false +) { + global $config; + include_once $config['homedir'].'/enterprise/include/functions_metaconsole.php'; - foreach ($id_groups as $id_group) { - $filter = array("id_usuario" => $id_user, - "id_perfil"=>$id_profile, - "id_grupo" => $id_group); - //~ Find perfil with advance permissions in - //~ authentication menu. This data depends on - //~ groups where this user it belong. - $result_profiles = - db_get_row_filter ("tusuario_perfil", $filter); - if (!$result_profiles) { - #If not found save in array. - $no_found[] = array("id_perfil"=>$id_profile, - "id_grupo" => $id_group, "tags" =>$tags); - } - else { - #if profile is find, delete from array. - db_process_sql_update("tusuario_perfil", - array("tags" =>$tags), - array('id_usuario' => $id_user, - 'id_up' => $profiles_user[$id_profile])); - - unset($profiles_user[$result_profiles["id_up"]]); - } - } - } + $result_user = users_get_user_by_id($id_user); + $filter = ['id_usuario' => $id_user]; + $profiles_user = []; + $user_profiles = db_get_all_rows_filter('tusuario_perfil', $filter); - if (is_metaconsole() && $syncronize) { - $servers = metaconsole_get_servers(); - foreach ($servers as $server) { - foreach ($permissions_nodes[$server['server_name']] as $permission_node) { - - $id_profile = $permission_node["profile"]; - $id_groups = $permission_node["groups"]; - $tags = $permission_node["tags"]; - - foreach ($id_groups as $id_group) { + foreach ($user_profiles as $user_profile) { + $profiles_user[$user_profile['id_up']] = $user_profile['id_perfil']; + } - $filter = array("id_usuario" => $id_user, - "id_perfil"=>$id_profile, - "id_grupo" => $id_group); - - if (metaconsole_connect($server) == NOERR ) { - $result_profiles = - db_get_row_filter ("tusuario_perfil", $filter); - - if (!$result_profiles) { - #If not found save in array. - $no_found_server[$server['server_name']][] = array("id_perfil" => $id_profile, - "id_grupo" => $id_group, "tags" => $tags); - } - else { - #if profile is find, delete from array. - db_process_sql_update("tusuario_perfil", - array("tags" =>$tags), - array('id_usuario' => $id_user, - 'id_up' => $profiles_user_nodes[$server_name][$id_profile])); + $profiles_user_nodes = []; + $permissions_nodes = []; + if (is_metaconsole() && $syncronize) { + $servers = metaconsole_get_servers(); + foreach ($servers as $server) { + if (metaconsole_connect($server) == NOERR) { + $user_profiles_nodes = db_get_all_rows_filter('tusuario_perfil', $filter); + foreach ($user_profiles_nodes as $user_profile_node) { + $profiles_user_nodes[$server['server_name']][$user_profile_node['id_up']] = $user_profile_node['id_perfil']; + } + } - unset($profiles_user_nodes[$server_name][$result_profiles["id_up"]]); - } - } - } - } - metaconsole_restore_db(); - } - } - - if ( empty($profiles_user) && empty($no_found) ) { - #The permmisions of user not changed - return true; - } - else { - foreach ($profiles_user as $key => $profile_user) { - #The other profiles are deleted - profile_delete_user_profile ($id_user, $key); - } + metaconsole_restore_db(); + } - if ( is_metaconsole() && $syncronize ) { - foreach ($profiles_user_nodes as $server_name => $profile_users) { - $server = metaconsole_get_connection($server_name); - foreach ($profile_users as $key => $profile_user) { - if ( metaconsole_connect($server) == NOERR ) { - profile_delete_user_profile ($id_user, $key); - } - } - metaconsole_restore_db(); - } - } + foreach ($permissions as $key => $permission) { + $perfil_maestro = db_get_row( + 'tperfil', + 'id_perfil', + $permission['profile'] + ); + foreach ($servers as $server) { + if (metaconsole_connect($server) == NOERR) { + if (profile_exist($perfil_maestro['name'])) { + $id_profile = db_get_value('id_perfil', 'tperfil', 'name', $perfil_maestro['name']); + $permissions_nodes[$server['server_name']][$key] = $permission; + $permissions_nodes[$server['server_name']][$key]['profile'] = $id_profile; + } + } - foreach ($no_found as $new_profiles) { - //Add the missing permissions - profile_create_user_profile ($id_user, - $new_profiles["id_perfil"], - $new_profiles["id_grupo"], false, - $new_profiles["tags"]); - } - - if ( is_metaconsole() && $syncronize ) { - $servers = metaconsole_get_servers(); - foreach ($servers as $server) { - if ( metaconsole_connect($server) == NOERR ) { - foreach ($no_found_server[$server['server_name']] as $new_profiles) { - profile_create_user_profile ($id_user, - $new_profiles["id_perfil"], - $new_profiles["id_grupo"], false, - $new_profiles["tags"]); - } - } - metaconsole_restore_db(); - } - } + metaconsole_restore_db(); + } + } + } - return "permissions_changed"; - } - } - else { - return "error_permissions"; - } + $no_found = []; + if ($result_user) { + foreach ($permissions as $permission) { + $id_profile = $permission['profile']; + $id_groups = $permission['groups']; + $tags = $permission['tags']; + + foreach ($id_groups as $id_group) { + $filter = [ + 'id_usuario' => $id_user, + 'id_perfil' => $id_profile, + 'id_grupo' => $id_group, + ]; + // ~ Find perfil with advance permissions in + // ~ authentication menu. This data depends on + // ~ groups where this user it belong. + $result_profiles = db_get_row_filter('tusuario_perfil', $filter); + if (!$result_profiles) { + // If not found save in array. + $no_found[] = [ + 'id_perfil' => $id_profile, + 'id_grupo' => $id_group, + 'tags' => $tags, + ]; + } else { + // if profile is find, delete from array. + db_process_sql_update( + 'tusuario_perfil', + ['tags' => $tags], + [ + 'id_usuario' => $id_user, + 'id_up' => $profiles_user[$id_profile], + ] + ); + + unset($profiles_user[$result_profiles['id_up']]); + } + } + } + + if (is_metaconsole() && $syncronize) { + $servers = metaconsole_get_servers(); + foreach ($servers as $server) { + foreach ($permissions_nodes[$server['server_name']] as $permission_node) { + $id_profile = $permission_node['profile']; + $id_groups = $permission_node['groups']; + $tags = $permission_node['tags']; + + foreach ($id_groups as $id_group) { + $filter = [ + 'id_usuario' => $id_user, + 'id_perfil' => $id_profile, + 'id_grupo' => $id_group, + ]; + + if (metaconsole_connect($server) == NOERR) { + $result_profiles = db_get_row_filter('tusuario_perfil', $filter); + + if (!$result_profiles) { + // If not found save in array. + $no_found_server[$server['server_name']][] = [ + 'id_perfil' => $id_profile, + 'id_grupo' => $id_group, + 'tags' => $tags, + ]; + } else { + // if profile is find, delete from array. + db_process_sql_update( + 'tusuario_perfil', + ['tags' => $tags], + [ + 'id_usuario' => $id_user, + 'id_up' => $profiles_user_nodes[$server_name][$id_profile], + ] + ); + + unset($profiles_user_nodes[$server_name][$result_profiles['id_up']]); + } + } + } + } + + metaconsole_restore_db(); + } + } + + if (empty($profiles_user) && empty($no_found)) { + // The permmisions of user not changed + return true; + } else { + foreach ($profiles_user as $key => $profile_user) { + // The other profiles are deleted + profile_delete_user_profile($id_user, $key); + } + + if (is_metaconsole() && $syncronize) { + foreach ($profiles_user_nodes as $server_name => $profile_users) { + $server = metaconsole_get_connection($server_name); + foreach ($profile_users as $key => $profile_user) { + if (metaconsole_connect($server) == NOERR) { + profile_delete_user_profile($id_user, $key); + } + } + + metaconsole_restore_db(); + } + } + + foreach ($no_found as $new_profiles) { + // Add the missing permissions + profile_create_user_profile( + $id_user, + $new_profiles['id_perfil'], + $new_profiles['id_grupo'], + false, + $new_profiles['tags'] + ); + } + + if (is_metaconsole() && $syncronize) { + $servers = metaconsole_get_servers(); + foreach ($servers as $server) { + if (metaconsole_connect($server) == NOERR) { + foreach ($no_found_server[$server['server_name']] as $new_profiles) { + profile_create_user_profile( + $id_user, + $new_profiles['id_perfil'], + $new_profiles['id_grupo'], + false, + $new_profiles['tags'] + ); + } + } + + metaconsole_restore_db(); + } + } + + return 'permissions_changed'; + } + } else { + return 'error_permissions'; + } } + +/** + * Fill permissions array with setup values + * + * @param string sr return value from LDAP connection + * + * @return array with all permission on LDAP authentication + */ +function fill_permissions_ldap($sr) +{ + global $config; + + $permissions = []; + if (!$config['ldap_advanced_config']) { + $permissions[0]['profile'] = $config['default_remote_profile']; + $permissions[0]['groups'][] = $config['default_remote_group']; + $permissions[0]['tags'] = $config['default_assign_tags']; + $permissions[0]['no_hierarchy'] = $config['default_no_hierarchy']; + return $permissions; + } + + // Decode permissions in advanced mode + $ldap_adv_perms = json_decode(io_safe_output($config['ldap_adv_perms']), true); + foreach ($ldap_adv_perms as $ldap_adv_perm) { + $attributes = $ldap_adv_perm['groups_ldap']; + foreach ($attributes as $attr) { + $attr = explode('=', $attr, 2); + foreach ($sr[$attr[0]] as $s_attr) { + if (preg_match('/'.$attr[1].'/', $s_attr)) { + $permissions[] = [ + 'profile' => $ldap_adv_perm['profile'], + 'groups' => $ldap_adv_perm['group'], + 'tags' => implode(',', $ldap_adv_perm['tags']), + 'no_hierarchy' => (bool) $ldap_adv_perm['no_hierarchy'] ? 1 : 0, + ]; + } + } + } + } + + return $permissions; +} + + /** * Update local user pass from ldap user * * @param string Login * @param string Password * - * @return bool + * @return boolean */ -function change_local_user_pass_ldap ($id_user, $password) { - $local_user_pass = db_get_value_filter('password', 'tusuario', array('id_user' => $id_user)); +function change_local_user_pass_ldap($id_user, $password) +{ + $local_user_pass = db_get_value_filter('password', 'tusuario', ['id_user' => $id_user]); - $return = false; - if (md5($password) !== $local_user_pass) { - $values_update = array(); - $values_update['password'] = md5($password); + $return = false; + if (md5($password) !== $local_user_pass) { + $values_update = []; + $values_update['password'] = md5($password); - $return = db_process_sql_update('tusuario', $values_update, array('id_user' => $id_user)); - } + $return = db_process_sql_update('tusuario', $values_update, ['id_user' => $id_user]); + } - return $return; + return $return; } -function delete_user_pass_ldap ($id_user) { - $values_update = array(); - $values_update['password'] = null; - $return = db_process_sql_update('tusuario', $values_update, array('id_user' => $id_user)); +function delete_user_pass_ldap($id_user) +{ + $values_update = []; + $values_update['password'] = null; - return; + $return = db_process_sql_update('tusuario', $values_update, ['id_user' => $id_user]); + + return; } -function safe_output_accute($string) { - $no_allowed= array ("á","é","í","ó","ú","Á","É","Í","Ó","Ú","ñ","Ñ"); - $allowed= array ("a","e","i","o","u","A","E","I","O","U","n","N"); - $result = str_replace($no_allowed, $allowed ,$string); - return $result; + +function safe_output_accute($string) +{ + $no_allowed = [ + 'á', + 'é', + 'í', + 'ó', + 'ú', + 'Á', + 'É', + 'Í', + 'Ó', + 'Ú', + 'ñ', + 'Ñ', + ]; + $allowed = [ + 'a', + 'e', + 'i', + 'o', + 'u', + 'A', + 'E', + 'I', + 'O', + 'U', + 'n', + 'N', + ]; + $result = str_replace($no_allowed, $allowed, $string); + return $result; } -function local_ldap_search($ldap_host, $ldap_port=389, $ldap_version=3, $dn, $access_attr, $ldap_admin_user, $ldap_admin_pass, $user) { - global $config; - - $filter = ""; - if(!empty($access_attr) && !empty($user)){ - $filter = " -s sub '(" . $access_attr . "=" . $user . ")' "; - } - - $tls = ""; - if($config["ldap_start_tls"]) { - $tls = " -ZZ "; - } - - $ldap_host = " -h " . $ldap_host; - $ldap_port = " -p ". $ldap_port; - $ldap_version = " -P ". $ldap_version; - if(!empty($ldap_admin_user)){ - $ldap_admin_user = " -D '". $ldap_admin_user."'"; - } - if(!empty($ldap_admin_pass)){ - $ldap_admin_pass = " -w " . $ldap_admin_pass; - } - $dn = " -b '". $dn ."'"; - - $shell_ldap_search = explode("\n", shell_exec('ldapsearch -LLL -o ldif-wrap=no -x' . $ldap_host . $ldap_port . $ldap_version . ' -E pr=10000/noprompt ' . $ldap_admin_user . $ldap_admin_pass . $dn . $filter . $tls . ' | grep -v "^#\|^$" | sed "s/:\+ /=>/g"')); - foreach($shell_ldap_search as $line) { - $values = explode("=>", $line); - if(!empty($values[0]) && !empty($values[1])) { - $user_attr[$values[0]][] = $values[1]; - } - } - - if (empty($user_attr)) { - return false; - } - - $base64 = preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $user_attr["dn"][0]); - if($base64){ - $user_dn = safe_output_accute(base64_decode($user_attr["dn"][0])); - } else { - $user_dn = safe_output_accute($user_attr["dn"][0]); - } - - if(strlen($user_dn) > 0) { - $user_attr["dn"][0]=$user_dn; - } - - return $user_attr; - + +function local_ldap_search($ldap_host, $ldap_port=389, $ldap_version=3, $dn, $access_attr, $ldap_admin_user, $ldap_admin_pass, $user) +{ + global $config; + + $filter = ''; + if (!empty($access_attr) && !empty($user)) { + $filter = " -s sub '(".$access_attr.'='.$user.")' "; + } + + $tls = ''; + if ($config['ldap_start_tls']) { + $tls = ' -ZZ '; + } + + $ldap_host = ' -h '.$ldap_host; + $ldap_port = ' -p '.$ldap_port; + $ldap_version = ' -P '.$ldap_version; + if (!empty($ldap_admin_user)) { + $ldap_admin_user = " -D '".$ldap_admin_user."'"; + } + + if (!empty($ldap_admin_pass)) { + $ldap_admin_pass = ' -w '.$ldap_admin_pass; + } + + $dn = " -b '".$dn."'"; + + $shell_ldap_search = explode("\n", shell_exec('ldapsearch -LLL -o ldif-wrap=no -x'.$ldap_host.$ldap_port.$ldap_version.' -E pr=10000/noprompt '.$ldap_admin_user.$ldap_admin_pass.$dn.$filter.$tls.' | grep -v "^#\|^$" | sed "s/:\+ /=>/g"')); + foreach ($shell_ldap_search as $line) { + $values = explode('=>', $line); + if (!empty($values[0]) && !empty($values[1])) { + $user_attr[$values[0]][] = $values[1]; + } + } + + if (empty($user_attr)) { + return false; + } + + $base64 = preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $user_attr['dn'][0]); + if ($base64) { + $user_dn = safe_output_accute(base64_decode($user_attr['dn'][0])); + } else { + $user_dn = safe_output_accute($user_attr['dn'][0]); + } + + if (strlen($user_dn) > 0) { + $user_attr['dn'][0] = $user_dn; + } + + return $user_attr; + } -//Reference the global use authorization error to last auth error. -$config["auth_error"] = &$mysql_cache["auth_error"]; -?> \ No newline at end of file + +// Reference the global use authorization error to last auth error. +$config['auth_error'] = &$mysql_cache['auth_error']; diff --git a/pandora_console/include/chart_generator.php b/pandora_console/include/chart_generator.php index f73d146424..96124afa4c 100644 --- a/pandora_console/include/chart_generator.php +++ b/pandora_console/include/chart_generator.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2018 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,220 +10,226 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Global & session manageme +session_id($_REQUEST['session_id']); -session_id($_REQUEST["session_id"]); - -require_once ('config.php'); -require_once ($config['homedir'] . '/include/auth/mysql.php'); -require_once ($config['homedir'] . '/include/functions.php'); -require_once ($config['homedir'] . '/include/functions_db.php'); -require_once ($config['homedir'] . '/include/functions_reporting.php'); -require_once ($config['homedir'] . '/include/functions_graph.php'); -require_once ($config['homedir'] . '/include/functions_custom_graphs.php'); -require_once ($config['homedir'] . '/include/functions_modules.php'); -require_once ($config['homedir'] . '/include/functions_agents.php'); -require_once ($config['homedir'] . '/include/functions_tags.php'); +require_once 'config.php'; +require_once $config['homedir'].'/include/auth/mysql.php'; +require_once $config['homedir'].'/include/functions.php'; +require_once $config['homedir'].'/include/functions_db.php'; +require_once $config['homedir'].'/include/functions_reporting.php'; +require_once $config['homedir'].'/include/functions_graph.php'; +require_once $config['homedir'].'/include/functions_custom_graphs.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_tags.php'; check_login(); global $config; -//get_parameter(array)('data', ''); - +// get_parameter(array)('data', ''); $params = json_decode($_REQUEST['data'], true); // Metaconsole connection to the node $server_id = $params['server_id']; -if ($config["metaconsole"] && !empty($server_id)) { - $server = metaconsole_get_connection_by_id($server_id); - // Error connecting - if (metaconsole_connect($server) !== NOERR) { - echo ""; - echo ""; - ui_print_error_message(__('There was a problem connecting with the node')); - echo ""; - echo ""; - exit; - } +if ($config['metaconsole'] && !empty($server_id)) { + $server = metaconsole_get_connection_by_id($server_id); + // Error connecting + if (metaconsole_connect($server) !== NOERR) { + echo ''; + echo ''; + ui_print_error_message(__('There was a problem connecting with the node')); + echo ''; + echo ''; + exit; + } } $user_language = get_user_language($config['id_user']); -if (file_exists ('languages/'.$user_language.'.mo')) { - $l10n = new gettext_reader (new CachedFileReader ('languages/'.$user_language.'.mo')); - $l10n->load_tables(); +if (file_exists('languages/'.$user_language.'.mo')) { + $l10n = new gettext_reader(new CachedFileReader('languages/'.$user_language.'.mo')); + $l10n->load_tables(); } ?> - - - Pandora FMS Graph (<?php echo agents_get_alias($agent_id) . ' - ' . $interface_name; ?>) + + + Pandora FMS Graph (<?php echo agents_get_alias($agent_id).' - '.$interface_name; ?>) - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + '; + switch ($type_graph_pdf) { + case 'combined': + echo graphic_combined_module( + $module_list, + $params, + $params_combined + ); + break; - echo '
        '; - switch ($type_graph_pdf) { - case 'combined': - echo graphic_combined_module( - $module_list, - $params, - $params_combined - ); - break; - case 'sparse': - echo grafico_modulo_sparse($params); - break; - case 'pie_chart': - echo flot_pie_chart( - $params['values'], - $params['keys'], - $params['width'], - $params['height'], - $params['water_mark_url'], - $params['font'], - $config['font_size'], - $params['legend_position'], - $params['colors'], - $params['hide_labels'] - ); - break; - case 'vbar': - echo flot_vcolumn_chart( - $params['chart_data'], - $params['width'], - $params['height'], - $params['color'], - $params['legend'], - $params['long_index'], - $params['homeurl'], - $params['unit'], - $params['water_mark_url'], - $params['homedir'], - $params['font'], - $config['font_size'], - $params['from_ux'], - $params['from_wux'], - $params['backgroundColor'], - $params['tick_color'] - ); - break; - case 'hbar': - echo flot_hcolumn_chart( - $params['chart_data'], - $params['width'], - $params['height'], - $params['water_mark_url'], - $params['font'], - $config['font_size'], - $params['backgroundColor'], - $params['tick_color'], - $params['val_min'], - $params['val_max'] - ); - break; - case 'ring_graph': - echo flot_custom_pie_chart ( - $params['chart_data'], - $params['width'], - $params['height'], - $params['colors'], - $params['module_name_list'], - $params['long_index'], - $params['no_data'], - false, - '', - $params['water_mark'], - $params['font'], - $config['font_size'], - $params['unit'], - $params['ttl'], - $params['homeurl'], - $params['background_color'], - $params['legend_position'], - $params['background_color'] - ); - break; - case 'slicebar': - echo flot_slicesbar_graph ( - $params['graph_data'], - $params['period'], - $params['width'], - $params['height'], - $params['legend'], - $params['colors'], - $params['fontpath'], - $params['round_corner'], - $params['homeurl'], - $params['watermark'], - $params['adapt_key'], - $params['stat_winalse'], - $params['id_agent'], - $params['full_legend_daterray'], - $params['not_interactive'], - $params['ttl'], - $params['widgets'], - $params['show'] - ); - break; - default: - # code... - break; - } - echo '
        '; + case 'sparse': + echo grafico_modulo_sparse($params); + break; - $config['font_size'] = $aux_font_size; -?> + case 'pie_chart': + echo flot_pie_chart( + $params['values'], + $params['keys'], + $params['width'], + $params['height'], + $params['water_mark_url'], + $params['font'], + $config['font_size'], + $params['legend_position'], + $params['colors'], + $params['hide_labels'] + ); + break; - - + case 'vbar': + echo flot_vcolumn_chart( + $params['chart_data'], + $params['width'], + $params['height'], + $params['color'], + $params['legend'], + $params['long_index'], + $params['homeurl'], + $params['unit'], + $params['water_mark_url'], + $params['homedir'], + $params['font'], + $config['font_size'], + $params['from_ux'], + $params['from_wux'], + $params['backgroundColor'], + $params['tick_color'] + ); + break; + case 'hbar': + echo flot_hcolumn_chart( + $params['chart_data'], + $params['width'], + $params['height'], + $params['water_mark_url'], + $params['font'], + $config['font_size'], + $params['backgroundColor'], + $params['tick_color'], + $params['val_min'], + $params['val_max'] + ); + break; + + case 'ring_graph': + echo flot_custom_pie_chart( + $params['chart_data'], + $params['width'], + $params['height'], + $params['colors'], + $params['module_name_list'], + $params['long_index'], + $params['no_data'], + false, + '', + $params['water_mark'], + $params['font'], + $config['font_size'], + $params['unit'], + $params['ttl'], + $params['homeurl'], + $params['background_color'], + $params['legend_position'], + $params['background_color'] + ); + break; + + case 'slicebar': + echo flot_slicesbar_graph( + $params['graph_data'], + $params['period'], + $params['width'], + $params['height'], + $params['legend'], + $params['colors'], + $params['fontpath'], + $params['round_corner'], + $params['homeurl'], + $params['watermark'], + $params['adapt_key'], + $params['stat_winalse'], + $params['id_agent'], + $params['full_legend_daterray'], + $params['not_interactive'], + $params['ttl'], + $params['widgets'], + $params['show'] + ); + break; + + default: + // code... + break; + } + + echo '
        '; + + $config['font_size'] = $aux_font_size; + ?> + + + + diff --git a/pandora_console/include/class/Tree.class.php b/pandora_console/include/class/Tree.class.php index af7cb2daf3..eda92b48b5 100644 --- a/pandora_console/include/class/Tree.class.php +++ b/pandora_console/include/class/Tree.class.php @@ -1,760 +1,904 @@ type = $type; - $this->rootType = !empty($rootType) ? $rootType : $type; - $this->id = $id; - $this->rootID = !empty($rootID) ? $rootID : $id; - $this->serverID = $serverID; - if (is_metaconsole()) { - $this->serverName = metaconsole_get_server_by_id($serverID); - } - $this->childrenMethod = $childrenMethod; - $this->access = $access; + protected $childrenMethod = 'on_demand'; - $userGroupsACL = users_get_groups(false, $this->access); - $this->userGroupsACL = empty($userGroupsACL) ? false : $userGroupsACL; - $this->userGroups = $this->userGroupsACL; - $this->userGroupsArray = array_keys($this->userGroups); + protected $userGroupsACL; - global $config; - include_once($config['homedir']."/include/functions_servers.php"); - include_once($config['homedir']."/include/functions_modules.php"); - require_once($config['homedir']."/include/functions_tags.php"); - enterprise_include_once("include/functions_agents.php"); + protected $userGroups; - if (is_metaconsole()) enterprise_include_once("meta/include/functions_ui_meta.php"); - } + protected $userGroupsArray; - public function setFilter($filter) { - // There is not module filter in metaconsole. - if (is_metaconsole()) { - $filter['searchModule'] = ""; - $filter['statusModule'] = self::TV_DEFAULT_AGENT_STATUS; - } - $this->filter = $filter; - } + protected $access = false; - protected function getEmptyModuleFilterStatus() { - return ( - !isset($this->filter['statusModule']) || - $this->filter['statusModule'] == -1 - ); - } + protected $L1fieldName = ''; - protected function getModuleSearchFilter() { - if (empty($this->filter['searchModule'])) { - return ""; - } - return " AND tam.nombre LIKE '%%".$this->filter['searchModule']."%%' "; - } + protected $L1fieldNameSql = ''; - protected function getAgentSearchFilter() { - if (empty($this->filter['searchAgent'])) return ""; - return " AND LOWER(ta.alias) LIKE LOWER('%%".$this->filter['searchAgent']."%%')"; - } + protected $L1extraFields = []; + + protected $L1inner = ''; + + protected $L1innerInside = ''; + + protected $L1orderByFinal = ''; + + protected $L2condition = ''; + + protected $L2conditionInside = ''; + + protected $L2inner = ''; + + protected $L3forceTagCondition = false; + + const TV_DEFAULT_AGENT_STATUS = -1; - protected function getAgentStatusFilter ($status = self::TV_DEFAULT_AGENT_STATUS) { - if ($status == self::TV_DEFAULT_AGENT_STATUS) - $status = $this->filter['statusAgent']; + public function __construct($type, $rootType='', $id=-1, $rootID=-1, $serverID=false, $childrenMethod='on_demand', $access='AR') + { + $this->type = $type; + $this->rootType = !empty($rootType) ? $rootType : $type; + $this->id = $id; + $this->rootID = !empty($rootID) ? $rootID : $id; + $this->serverID = $serverID; + if (is_metaconsole()) { + $this->serverName = metaconsole_get_server_by_id($serverID); + } - $agent_status_filter = ""; - switch ($status) { - case AGENT_STATUS_ALL: - break; - case AGENT_STATUS_NOT_INIT: - $agent_status_filter = " AND (ta.total_count = 0 - OR ta.total_count = ta.notinit_count) "; - break; - case AGENT_STATUS_CRITICAL: - $agent_status_filter = " AND ta.critical_count > 0 "; - break; - case AGENT_STATUS_WARNING: - $agent_status_filter = " AND (ta.critical_count = 0 - AND ta.warning_count > 0) "; - break; - case AGENT_STATUS_UNKNOWN: - $agent_status_filter = " AND (ta.critical_count = 0 + $this->childrenMethod = $childrenMethod; + $this->access = $access; + + $userGroupsACL = users_get_groups(false, $this->access); + $this->userGroupsACL = empty($userGroupsACL) ? false : $userGroupsACL; + $this->userGroups = $this->userGroupsACL; + $this->userGroupsArray = array_keys($this->userGroups); + + global $config; + include_once $config['homedir'].'/include/functions_servers.php'; + include_once $config['homedir'].'/include/functions_modules.php'; + include_once $config['homedir'].'/include/functions_tags.php'; + enterprise_include_once('include/functions_agents.php'); + + if (is_metaconsole()) { + enterprise_include_once('meta/include/functions_ui_meta.php'); + } + } + + + public function setFilter($filter) + { + // There is not module filter in metaconsole. + if (is_metaconsole()) { + $filter['searchModule'] = ''; + $filter['statusModule'] = self::TV_DEFAULT_AGENT_STATUS; + } + + $this->filter = $filter; + } + + + protected function getEmptyModuleFilterStatus() + { + return ( + !isset($this->filter['statusModule']) || + $this->filter['statusModule'] == -1 + ); + } + + + protected function getModuleSearchFilter() + { + if (empty($this->filter['searchModule'])) { + return ''; + } + + return " AND tam.nombre LIKE '%%".$this->filter['searchModule']."%%' "; + } + + + protected function getAgentSearchFilter() + { + if (empty($this->filter['searchAgent'])) { + return ''; + } + + return " AND LOWER(ta.alias) LIKE LOWER('%%".$this->filter['searchAgent']."%%')"; + } + + + protected function getAgentStatusFilter($status=self::TV_DEFAULT_AGENT_STATUS) + { + if ($status == self::TV_DEFAULT_AGENT_STATUS) { + $status = $this->filter['statusAgent']; + } + + $agent_status_filter = ''; + switch ($status) { + case AGENT_STATUS_ALL: + break; + + case AGENT_STATUS_NOT_INIT: + $agent_status_filter = ' AND (ta.total_count = 0 + OR ta.total_count = ta.notinit_count) '; + break; + + case AGENT_STATUS_CRITICAL: + $agent_status_filter = ' AND ta.critical_count > 0 '; + break; + + case AGENT_STATUS_WARNING: + $agent_status_filter = ' AND (ta.critical_count = 0 + AND ta.warning_count > 0) '; + break; + + case AGENT_STATUS_UNKNOWN: + $agent_status_filter = ' AND (ta.critical_count = 0 AND ta.warning_count = 0 - AND ta.unknown_count > 0) "; - break; - case AGENT_STATUS_NORMAL: - $agent_status_filter = " AND (ta.critical_count = 0 + AND ta.unknown_count > 0) '; + break; + + case AGENT_STATUS_NORMAL: + $agent_status_filter = ' AND (ta.critical_count = 0 AND ta.warning_count = 0 AND ta.unknown_count = 0 - AND ta.normal_count > 0) "; - break; - } + AND ta.normal_count > 0) '; + break; + } - return $agent_status_filter; - } + return $agent_status_filter; + } - protected function getFirstLevelFields() { - $fields = array ( - "g AS " . $this->L1fieldName, - "SUM(x_critical) AS total_critical_count", - "SUM(x_warning) AS total_warning_count", - "SUM(x_normal) AS total_normal_count", - "SUM(x_unknown) AS total_unknown_count", - "SUM(x_not_init) AS total_not_init_count", - "SUM(x_alerts) AS total_alerts_count", - "SUM(x_total) AS total_count" - ); - return implode(",", array_merge($fields, $this->L1extraFields)); - } - protected function getFirstLevelFieldsInside() { - return array( - 'warning' => array( - 'header' => "0 AS x_critical, SUM(total) AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", - 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_WARNING, $this->filter['show_not_init_agents']) - ), - 'critical' => array( - 'header' => "SUM(total) AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", - 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_CRITICAL, $this->filter['show_not_init_agents']) - ), - 'normal' => array( - 'header' => "0 AS x_critical, 0 AS x_warning, SUM(total) AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", - 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_NORMAL, $this->filter['show_not_init_agents']) - ), - 'unknown' => array( - 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, SUM(total) AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", - 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_UNKNOWN, $this->filter['show_not_init_agents']) - ), - 'not_init' => array( - 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, SUM(total) AS x_not_init, 0 AS x_alerts, 0 AS x_total, g", - 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_NOT_INIT, $this->filter['show_not_init_agents']) - ), - 'alerts' => array( - 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, SUM(total) AS x_alerts, 0 AS x_total, g", - 'condition' => "AND ta.fired_count > 0" - ), - 'total' => array( - 'header' => "0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, SUM(total) AS x_total, g", - 'condition' => "AND " . agents_get_status_clause(AGENT_STATUS_ALL, $this->filter['show_not_init_agents']) - ) - ); - } + protected function getFirstLevelFields() + { + $fields = [ + 'g AS '.$this->L1fieldName, + 'SUM(x_critical) AS total_critical_count', + 'SUM(x_warning) AS total_warning_count', + 'SUM(x_normal) AS total_normal_count', + 'SUM(x_unknown) AS total_unknown_count', + 'SUM(x_not_init) AS total_not_init_count', + 'SUM(x_alerts) AS total_alerts_count', + 'SUM(x_total) AS total_count', + ]; + return implode(',', array_merge($fields, $this->L1extraFields)); + } - protected function getInnerOrLeftJoin () { - return $this->filter['show_not_init_agents'] - ? "LEFT" - : "INNER"; - } - protected function getModuleStatusFilter () { - $show_init_condition = ($this->filter['show_not_init_agents']) - ? "" - : " AND ta.notinit_count <> ta.total_count"; + protected function getFirstLevelFieldsInside() + { + return [ + 'warning' => [ + 'header' => '0 AS x_critical, SUM(total) AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', + 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_WARNING, $this->filter['show_not_init_agents']), + ], + 'critical' => [ + 'header' => 'SUM(total) AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', + 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_CRITICAL, $this->filter['show_not_init_agents']), + ], + 'normal' => [ + 'header' => '0 AS x_critical, 0 AS x_warning, SUM(total) AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', + 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_NORMAL, $this->filter['show_not_init_agents']), + ], + 'unknown' => [ + 'header' => '0 AS x_critical, 0 AS x_warning, 0 AS x_normal, SUM(total) AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', + 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_UNKNOWN, $this->filter['show_not_init_agents']), + ], + 'not_init' => [ + 'header' => '0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, SUM(total) AS x_not_init, 0 AS x_alerts, 0 AS x_total, g', + 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_NOT_INIT, $this->filter['show_not_init_agents']), + ], + 'alerts' => [ + 'header' => '0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, SUM(total) AS x_alerts, 0 AS x_total, g', + 'condition' => 'AND ta.fired_count > 0', + ], + 'total' => [ + 'header' => '0 AS x_critical, 0 AS x_warning, 0 AS x_normal, 0 AS x_unknown, 0 AS x_not_init, 0 AS x_alerts, SUM(total) AS x_total, g', + 'condition' => 'AND '.agents_get_status_clause(AGENT_STATUS_ALL, $this->filter['show_not_init_agents']), + ], + ]; + } - if ($this->getEmptyModuleFilterStatus()) { - return $show_init_condition; - } - $field_filter = modules_get_counter_by_states($this->filter['statusModule']); - if ($field_filter === false) return " AND 1=0"; + protected function getInnerOrLeftJoin() + { + return $this->filter['show_not_init_agents'] ? 'LEFT' : 'INNER'; + } - return "AND ta.$field_filter > 0" . $show_init_condition; - } - protected function getTagJoin () { - return 'INNER JOIN ttag_module ttm + protected function getModuleStatusFilter() + { + $show_init_condition = ($this->filter['show_not_init_agents']) ? '' : ' AND ta.notinit_count <> ta.total_count'; + + if ($this->getEmptyModuleFilterStatus()) { + return $show_init_condition; + } + + $field_filter = modules_get_counter_by_states($this->filter['statusModule']); + if ($field_filter === false) { + return ' AND 1=0'; + } + + return "AND ta.$field_filter > 0".$show_init_condition; + } + + + protected function getTagJoin() + { + return 'INNER JOIN ttag_module ttm ON tam.id_agente_modulo = ttm.id_agente_modulo'; - } + } - protected function getTagCondition () { - $tags = tags_get_user_applied_agent_tags($this->id, "AR"); - // All tags permision, returns no condition - if ($tags === true) return ""; - // No permision, do not show anything - if ($tags === false) return " AND 1=0"; - $tags_sql = implode(',', $tags); - return "AND ttm.id_tag IN ($tags_sql)";; - } - protected function getModuleStatusFilterFromTestado ($state = false, $without_ands = false) { - $selected_status = ($state !== false && $state !== self::TV_DEFAULT_AGENT_STATUS) - ? $state - : $this->filter['statusModule']; + protected function getTagCondition() + { + $tags = tags_get_user_applied_agent_tags($this->id, 'AR'); + // All tags permision, returns no condition + if ($tags === true) { + return ''; + } - $filter = array( - modules_get_state_condition($selected_status) - ); - if (!$this->filter['show_not_init_modules'] && $state === false) { - if (!empty($filter)) - $filter[] = "( - tae.estado <> ".AGENT_MODULE_STATUS_NO_DATA." - AND tae.estado <> ".AGENT_MODULE_STATUS_NOT_INIT." - )"; - } - $filter = implode(" AND ", $filter); - return ($without_ands) - ? $filter - : " AND $filter "; - } + // No permision, do not show anything + if ($tags === false) { + return ' AND 1=0'; + } - public function getGroupAclCondition() { - if (users_can_manage_group_all("AR")) return ""; + $tags_sql = implode(',', $tags); + return "AND ttm.id_tag IN ($tags_sql)"; + ; + } - $groups_str= implode(",", $this->userGroupsArray); - return " AND ( + + protected function getModuleStatusFilterFromTestado($state=false, $without_ands=false) + { + $selected_status = ($state !== false && $state !== self::TV_DEFAULT_AGENT_STATUS) ? $state : $this->filter['statusModule']; + + $filter = [modules_get_state_condition($selected_status)]; + if (!$this->filter['show_not_init_modules'] && $state === false) { + if (!empty($filter)) { + $filter[] = '( + tae.estado <> '.AGENT_MODULE_STATUS_NO_DATA.' + AND tae.estado <> '.AGENT_MODULE_STATUS_NOT_INIT.' + )'; + } + } + + $filter = implode(' AND ', $filter); + return ($without_ands) ? $filter : " AND $filter "; + } + + + public function getGroupAclCondition() + { + if (users_can_manage_group_all('AR')) { + return ''; + } + + $groups_str = implode(',', $this->userGroupsArray); + return " AND ( ta.id_grupo IN ($groups_str) OR tasg.id_group IN ($groups_str) )"; - } + } - protected function getGroupSearchInner() { - if (empty($this->filter['searchGroup'])) return ""; - return "INNER JOIN tgrupo tg + + protected function getGroupSearchInner() + { + if (empty($this->filter['searchGroup'])) { + return ''; + } + + return 'INNER JOIN tgrupo tg ON ta.id_grupo = tg.id_grupo - OR tasg.id_group = tg.id_grupo" - ; - } - - protected function getGroupSearchFilter() { - if (empty($this->filter['searchGroup'])) return ""; - return " AND tg.nombre LIKE '%%" . $this->filter['searchGroup'] . "%%'"; - } - - static function cmpSortNames($a, $b) { - return strcmp($a["name"], $b["name"]); - } - - protected function getProcessedItem ($item, $server = false) { - - if (isset($processed_item['is_processed']) && $processed_item['is_processed']) - return $item; - - $processed_item = array(); - $processed_item['id'] = $item['id']; - $processed_item['name'] = $item['name']; - $processed_item['rootID'] = $item['id']; - $processed_item['rootType'] = $this->rootType; - $processed_item['searchChildren'] = 1; - - if (isset($item['type'])) - $processed_item['type'] = $item['type']; - else - $processed_item['type'] = $this->type; - - if (isset($item['rootType'])) - $processed_item['rootType'] = $item['rootType']; - else - $processed_item['rootType'] = $this->rootType; - - if ($processed_item['type'] == 'group') { - $processed_item['parent'] = $item['parent']; - - $processed_item['icon'] = empty($item['icon']) - ? "without_group.png" - : $item['icon'].".png"; - } - if (isset($item['iconHTML'])) { - $processed_item['icon'] = $item['iconHTML']; - } - - if (is_metaconsole() && !empty($server)) { - $processed_item['serverID'] = $server['id']; - } - - $counters = array(); - if (isset($item['total_unknown_count'])) - $counters['unknown'] = $item['total_unknown_count']; - if (isset($item['total_critical_count'])) - $counters['critical'] = $item['total_critical_count']; - if (isset($item['total_warning_count'])) - $counters['warning'] = $item['total_warning_count']; - if (isset($item['total_not_init_count'])) - $counters['not_init'] = $item['total_not_init_count']; - if (isset($item['total_normal_count'])) - $counters['ok'] = $item['total_normal_count']; - if (isset($item['total_count'])) - $counters['total'] = $item['total_count']; - if (isset($item['total_fired_count'])) - $counters['alerts'] = $item['total_fired_count']; - - if (!empty($counters)) - $processed_item['counters'] = $counters; - - if (!empty($processed_item)) - $processed_item['is_processed'] = true; - - return $processed_item; - } - - // This function should be used only when retrieving the data of the metaconsole's nodes - protected function getMergedItems ($items) { - // This variable holds the result - $mergedItems = array(); - - foreach ($items as $key => $item) { - // Avoid the deleted items - if (!isset($items[$key]) || empty($item)) - continue; - - // Store the item in a temporary element - $resultItem = $item; - - // The 'id' parameter will be stored as 'server_id' => 'id' - $resultItem['id'] = array(); - $resultItem['id'][$item['serverID']] = $item['id']; - $resultItem['rootID'] = array(); - $resultItem['rootID'][$item['serverID']] = $item['rootID']; - $resultItem['serverID'] = array(); - $resultItem['serverID'][$item['serverID']] = $item['rootID']; - - // Initialize counters if any of it don't exist - if (!isset($resultItem['counters'])) - $resultItem['counters'] = array(); - if (!isset($resultItem['counters']['unknown'])) - $resultItem['counters']['unknown'] = 0; - if (!isset($resultItem['counters']['critical'])) - $resultItem['counters']['critical'] = 0; - if (!isset($resultItem['counters']['warning'])) - $resultItem['counters']['warning'] = 0; - if (!isset($resultItem['counters']['not_init'])) - $resultItem['counters']['not_init'] = 0; - if (!isset($resultItem['counters']['ok'])) - $resultItem['counters']['ok'] = 0; - if (!isset($resultItem['counters']['total'])) - $resultItem['counters']['total'] = 0; - if (!isset($resultItem['counters']['alerts'])) - $resultItem['counters']['alerts'] = 0; - - if ($item['type'] == 'group') { - // Add the children - if (!isset($resultItem['children'])) - $resultItem['children'] = array(); - } - - // Iterate over the list to search items that match the actual item - foreach ($items as $key2 => $item2) { - // Skip the actual or empty items - if ($key == $key2 || !isset($items[$key2])) - continue; - - // Match with the name and type - if ($item['name'] == $item2['name'] && $item['type'] == $item2['type']) { - // Add the matched ids - $resultItem['id'][$item2['serverID']] = $item2['id']; - $resultItem['rootID'][$item2['serverID']] = $item2['rootID']; - $resultItem['serverID'][$item2['serverID']] = $item2['rootID']; - - // Add the matched counters - if (isset($item2['counters']) && !empty($item2['counters'])) { - foreach ($item2['counters'] as $type => $value) { - if (isset($resultItem['counters'][$type])) - $resultItem['counters'][$type] += $value; - } - } - - if ($item['type'] == 'group') { - // Add the matched children - if (isset($item2['children'])) - $resultItem['children'] = array_merge($resultItem['children'], $item2['children']); - } - - // Remove the item - unset($items[$key2]); - } - } - - if ($item['type'] == 'group') { - // Get the merged children (recursion) - if (!empty($resultItem['children'])) - $resultItem['children'] = $this->getMergedItems($resultItem['children']); - - } - - // Add the resulting item - if (!empty($resultItem) && !empty($resultItem['counters']['total'])) - $mergedItems[] = $resultItem; - - // Remove the item - unset($items[$key]); - } - - usort($mergedItems, array("Tree", "cmpSortNames")); - - return $mergedItems; - } - - protected function processModule (&$module, $server = false, $all_groups) { - global $config; - - if (isset($module['children'])) { - foreach ($module['children'] as $i => $children) { - $this->processModule($module['children'][$i], $server, $all_groups); - } - } - - $module['type'] = 'module'; - $module['id'] = (int) $module['id']; - $module['name'] = io_safe_output($module['name']); - $module['id_module_type'] = (int) $module['id_tipo_modulo']; - $module['server_type'] = (int) $module['id_modulo']; - $module['status'] = $module['estado']; - $module['value'] = $module['datos']; - - if (is_metaconsole()) { - $module['serverID'] = $this->serverID; - $module['serverName'] = $this->serverName; - } - else { - $module['serverName'] = false; - $module['serverID'] = false; - } - - if (!isset($module['value'])) - $module['value'] = modules_get_last_value($module['id']); - - // Status - switch ($module['status']) { - case AGENT_MODULE_STATUS_CRITICAL_ALERT: - $module['alert'] = 1; - case AGENT_MODULE_STATUS_CRITICAL_BAD: - $statusType = STATUS_MODULE_CRITICAL_BALL; - $statusTitle = __('CRITICAL'); - $module['statusText'] = "critical"; - break; - case AGENT_MODULE_STATUS_WARNING_ALERT: - $module['alert'] = 1; - case AGENT_MODULE_STATUS_WARNING: - $statusType = STATUS_MODULE_WARNING_BALL; - $statusTitle = __('WARNING'); - $module['statusText'] = "warning"; - break; - case AGENT_MODULE_STATUS_UNKNOWN: - $statusType = STATUS_MODULE_UNKNOWN_BALL; - $statusTitle = __('UNKNOWN'); - $module['statusText'] = "unknown"; - break; - case AGENT_MODULE_STATUS_NO_DATA: - case AGENT_MODULE_STATUS_NOT_INIT: - $statusType = STATUS_MODULE_NO_DATA_BALL; - $statusTitle = __('NO DATA'); - $module['statusText'] = "not_init"; - break; - case AGENT_MODULE_STATUS_NORMAL_ALERT: - $module['alert'] = 1; - case AGENT_MODULE_STATUS_NORMAL: - default: - $statusType = STATUS_MODULE_OK_BALL; - $statusTitle = __('NORMAL'); - $module['statusText'] = "ok"; - break; - } - - if ($statusType !== STATUS_MODULE_UNKNOWN_BALL - && $statusType !== STATUS_MODULE_NO_DATA_BALL) { - if (is_numeric($module["value"])) { - $statusTitle .= " : " . format_for_graph($module["value"]); - } - else { - $statusTitle .= " : " . substr(io_safe_output($module["value"]),0,42); - } - } - - $module['statusImageHTML'] = ui_print_status_image($statusType, $statusTitle, true); - - // HTML of the server type image - $module['serverTypeHTML'] = servers_show_type($module['server_type']); - - // Link to the Module graph - - // ACL - $acl_graphs = false; - $module["showGraphs"] = 0; - - // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions - if (!empty($group_id) && !is_metaconsole()) { - $acl_graphs = check_acl_one_of_groups($config['id_user'], $all_groups, "RR"); - } - else if (!empty($all_groups)) { - $acl_graphs = true; - } - - if ($acl_graphs) { - $module["showGraphs"] = 1; - } - - if ($module["showGraphs"]) { - $graphType = return_graphtype($module['id_module_type']); - $url = ui_get_full_url("operation/agentes/stat_win.php", false, false, false); - $winHandle = dechex(crc32($module['id'].$module['name'])); - - $graph_params = array( - "type" => $graphType, - "period" => SECONDS_1DAY, - "id" => $module['id'], - "label" => base64_encode($module['name']), - "refresh" => SECONDS_10MINUTES - ); - - if (is_metaconsole()) { - // Set the server id - $graph_params["server"] = $module['serverID']; - } - - $graph_params_str = http_build_query($graph_params); - $moduleGraphURL = "$url?$graph_params_str"; - - $module['moduleGraph'] = array( - 'url' => $moduleGraphURL, - 'handle' => $winHandle - ); - - // Info to be able to open the snapshot image new page - $module['snapshot'] = ui_get_snapshot_link(array( - 'id_module' => $module['id'], - 'interval' => $module['current_interval'], - 'module_name' => $module['name'], - 'id_node' => $module['serverID'] ? $module['serverID'] : 0, - ), true); - } - - // Alerts fired image - if ((bool)$module['alerts']) { - $module['alertsImageHTML'] = html_print_image("images/bell.png", true, array("title" => __('Module alerts'))); - } - } - - protected function processModules (&$modules, $server = false) { - if (!empty($modules)) { - $all_groups = modules_get_agent_groups($modules[0]['id']); - } - foreach ($modules as $iterator => $module) { - $this->processModule($modules[$iterator], $server, $all_groups); - } - } - - protected function processAgent (&$agent, $server = false) { - global $config; - - $agent['type'] = 'agent'; - $agent['id'] = (int) $agent['id']; - $agent['name'] = $agent['name']; - - $agent['rootID'] = $this->rootID; - $agent['rootType'] = $this->rootType; - - if (is_metaconsole()) { - if (isset($agent['server_id'])) - $agent['serverID'] = $agent['server_id']; - else if (!empty($server)) - $agent['serverID'] = $server['id']; - } - // Counters - if (empty($agent['counters'])) { - $agent['counters'] = array(); - - $agent['counters']['unknown'] = isset($agent['unknown_count']) ? $agent['unknown_count'] : 0; - $agent['counters']['critical'] = isset($agent['critical_count']) ? $agent['critical_count'] : 0; - $agent['counters']['warning'] = isset($agent['warning_count']) ? $agent['warning_count'] : 0; - $agent['counters']['not_init'] = isset($agent['notinit_count']) ? $agent['notinit_count'] : 0; - $agent['counters']['ok'] = isset($agent['normal_count']) ? $agent['normal_count'] : 0; - $agent['counters']['total'] = isset($agent['total_count']) ? $agent['total_count'] : 0; - $agent['counters']['alerts'] = isset($agent['fired_count']) ? $agent['fired_count'] : 0; - } - - // Status image - $agent['statusImageHTML'] = agents_tree_view_status_img_ball( - $agent['counters']['critical'], - $agent['counters']['warning'], - $agent['counters']['unknown'], - $agent['counters']['total'], - $agent['counters']['not_init']); - - // Alerts fired image - $agent["alertImageHTML"] = agents_tree_view_alert_img_ball($agent['counters']['alerts']); - - // search module recalculate counters - if(array_key_exists('state_normal', $agent)){ - $agent['counters']['unknown'] = $agent['state_unknown']; - $agent['counters']['critical'] = $agent['state_critical']; - $agent['counters']['warning'] = $agent['state_warning']; - $agent['counters']['not_init'] = $agent['state_notinit']; - $agent['counters']['ok'] = $agent['state_normal']; - $agent['counters']['total'] = $agent['state_total']; - - $agent['critical_count'] = $agent['counters']['critical']; - $agent['warning_count'] = $agent['counters']['warning']; - $agent['unknown_count'] = $agent['counters']['unknown']; - $agent['notinit_count'] = $agent['counters']['not_init']; - $agent['normal_count'] = $agent['counters']['ok']; - $agent['total_count'] = $agent['counters']['total']; - } - - if (!$this->getEmptyModuleFilterStatus()) { - $agent['counters']['unknown'] = 0; - $agent['counters']['critical'] = 0; - $agent['counters']['warning'] = 0; - $agent['counters']['not_init'] = 0; - $agent['counters']['ok'] = 0; - $agent['counters']['total'] = 0; - switch($this->filter['statusModule']) { - case AGENT_MODULE_STATUS_CRITICAL_ALERT: - case AGENT_MODULE_STATUS_CRITICAL_BAD: - $agent['counters']['critical'] = $agent['critical_count']; - $agent['counters']['total'] = $agent['critical_count']; - break; - case AGENT_MODULE_STATUS_WARNING_ALERT: - case AGENT_MODULE_STATUS_WARNING: - $agent['counters']['warning'] = $agent['warning_count']; - $agent['counters']['total'] = $agent['warning_count']; - break; - case AGENT_MODULE_STATUS_UNKNOWN: - $agent['counters']['unknown'] = $agent['unknown_count']; - $agent['counters']['total'] = $agent['unknown_count']; - break; - case AGENT_MODULE_STATUS_NO_DATA: - case AGENT_MODULE_STATUS_NOT_INIT: - $agent['counters']['not_init'] = $agent['notinit_count']; - $agent['counters']['total'] = $agent['notinit_count']; - break; - case AGENT_MODULE_STATUS_NORMAL_ALERT: - case AGENT_MODULE_STATUS_NORMAL: - $agent['counters']['ok'] = $agent['normal_count']; - $agent['counters']['total'] = $agent['normal_count']; - break; - } - } - - if (!$this->filter['show_not_init_modules']) { - $agent['counters']['total'] -= $agent['counters']['not_init']; - $agent['counters']['not_init'] = 0; - } - - // Quiet image - if (isset($agent['quiet']) && $agent['quiet']) - $agent['quietImageHTML'] = html_print_image("/images/dot_blue.png", true, array("title" => __('Quiet'))); - - // Children - if (empty($agent['children'])) { - $agent['children'] = array(); - if ($agent['counters']['total'] > 0) { - switch ($this->childrenMethod) { - case 'on_demand': - $agent['searchChildren'] = 1; - break; - case 'live': - $agent['searchChildren'] = 0; - break; - } - } - else { - switch ($this->childrenMethod) { - case 'on_demand': - $agent['searchChildren'] = 0; - break; - case 'live': - $agent['searchChildren'] = 0; - break; - } - } - } - } - - protected function processAgents (&$agents, $server = false) { - if (!empty($agents)) { - foreach ($agents as $iterator => $agent) { - $this->processAgent($agents[$iterator], $server); - } - } - } - - protected function getData() { - - } - - protected function getFirstLevel() { - $sql = $this->getFirstLevelSql(); - $items = db_get_all_rows_sql($sql); - if ($items === false) $items = array(); - - $this->tree = $this->getProcessedItemsFirstLevel($items); - } - - protected function getProcessedItemsFirstLevel($items){ - $processed_items = array(); - foreach ($items as $key => $item) { - $processed_item = $this->getProcessedItem($item); - $processed_items[] = $processed_item; - } - return $processed_items; - } - - protected function getFirstLevelSql() { - - $fields = $this->getFirstLevelFields(); - $field_name_sql = $this->L1fieldNameSql; - $inside_fields = $this->getFirstLevelFieldsInside(); - $inner = $this->L1inner; - $inner_inside = $this->L1innerInside; - $order_by_final = $this->L1orderByFinal; - - $group_inner = $this->getGroupSearchInner(); - $group_acl = $this->getGroupAclCondition(); - $group_search_filter = $this->getGroupSearchFilter(); - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_search_filter = $this->getModuleSearchFilter(); - $module_status_inner = ""; - $module_status_filter = $this->getModuleStatusFilterFromTestado(); - if (!empty($module_status_filter)) { - $module_status_inner = " + OR tasg.id_group = tg.id_grupo'; + } + + + protected function getGroupSearchFilter() + { + if (empty($this->filter['searchGroup'])) { + return ''; + } + + return " AND tg.nombre LIKE '%%".$this->filter['searchGroup']."%%'"; + } + + + static function cmpSortNames($a, $b) + { + return strcmp($a['name'], $b['name']); + } + + + protected function getProcessedItem($item, $server=false) + { + if (isset($processed_item['is_processed']) && $processed_item['is_processed']) { + return $item; + } + + $processed_item = []; + $processed_item['id'] = $item['id']; + $processed_item['name'] = $item['name']; + $processed_item['rootID'] = $item['id']; + $processed_item['rootType'] = $this->rootType; + $processed_item['searchChildren'] = 1; + + if (isset($item['type'])) { + $processed_item['type'] = $item['type']; + } else { + $processed_item['type'] = $this->type; + } + + if (isset($item['rootType'])) { + $processed_item['rootType'] = $item['rootType']; + } else { + $processed_item['rootType'] = $this->rootType; + } + + if ($processed_item['type'] == 'group') { + $processed_item['parent'] = $item['parent']; + + $processed_item['icon'] = empty($item['icon']) ? 'without_group.png' : $item['icon'].'.png'; + } + + if (isset($item['iconHTML'])) { + $processed_item['icon'] = $item['iconHTML']; + } + + if (is_metaconsole() && !empty($server)) { + $processed_item['serverID'] = $server['id']; + } + + $counters = []; + if (isset($item['total_unknown_count'])) { + $counters['unknown'] = $item['total_unknown_count']; + } + + if (isset($item['total_critical_count'])) { + $counters['critical'] = $item['total_critical_count']; + } + + if (isset($item['total_warning_count'])) { + $counters['warning'] = $item['total_warning_count']; + } + + if (isset($item['total_not_init_count'])) { + $counters['not_init'] = $item['total_not_init_count']; + } + + if (isset($item['total_normal_count'])) { + $counters['ok'] = $item['total_normal_count']; + } + + if (isset($item['total_count'])) { + $counters['total'] = $item['total_count']; + } + + if (isset($item['total_fired_count'])) { + $counters['alerts'] = $item['total_fired_count']; + } + + if (!empty($counters)) { + $processed_item['counters'] = $counters; + } + + if (!empty($processed_item)) { + $processed_item['is_processed'] = true; + } + + return $processed_item; + } + + + // This function should be used only when retrieving the data of the metaconsole's nodes + protected function getMergedItems($items) + { + // This variable holds the result + $mergedItems = []; + + foreach ($items as $key => $item) { + // Avoid the deleted items + if (!isset($items[$key]) || empty($item)) { + continue; + } + + // Store the item in a temporary element + $resultItem = $item; + + // The 'id' parameter will be stored as 'server_id' => 'id' + $resultItem['id'] = []; + $resultItem['id'][$item['serverID']] = $item['id']; + $resultItem['rootID'] = []; + $resultItem['rootID'][$item['serverID']] = $item['rootID']; + $resultItem['serverID'] = []; + $resultItem['serverID'][$item['serverID']] = $item['rootID']; + + // Initialize counters if any of it don't exist + if (!isset($resultItem['counters'])) { + $resultItem['counters'] = []; + } + + if (!isset($resultItem['counters']['unknown'])) { + $resultItem['counters']['unknown'] = 0; + } + + if (!isset($resultItem['counters']['critical'])) { + $resultItem['counters']['critical'] = 0; + } + + if (!isset($resultItem['counters']['warning'])) { + $resultItem['counters']['warning'] = 0; + } + + if (!isset($resultItem['counters']['not_init'])) { + $resultItem['counters']['not_init'] = 0; + } + + if (!isset($resultItem['counters']['ok'])) { + $resultItem['counters']['ok'] = 0; + } + + if (!isset($resultItem['counters']['total'])) { + $resultItem['counters']['total'] = 0; + } + + if (!isset($resultItem['counters']['alerts'])) { + $resultItem['counters']['alerts'] = 0; + } + + if ($item['type'] == 'group') { + // Add the children + if (!isset($resultItem['children'])) { + $resultItem['children'] = []; + } + } + + // Iterate over the list to search items that match the actual item + foreach ($items as $key2 => $item2) { + // Skip the actual or empty items + if ($key == $key2 || !isset($items[$key2])) { + continue; + } + + // Match with the name and type + if ($item['name'] == $item2['name'] && $item['type'] == $item2['type']) { + // Add the matched ids + $resultItem['id'][$item2['serverID']] = $item2['id']; + $resultItem['rootID'][$item2['serverID']] = $item2['rootID']; + $resultItem['serverID'][$item2['serverID']] = $item2['rootID']; + + // Add the matched counters + if (isset($item2['counters']) && !empty($item2['counters'])) { + foreach ($item2['counters'] as $type => $value) { + if (isset($resultItem['counters'][$type])) { + $resultItem['counters'][$type] += $value; + } + } + } + + if ($item['type'] == 'group') { + // Add the matched children + if (isset($item2['children'])) { + $resultItem['children'] = array_merge($resultItem['children'], $item2['children']); + } + } + + // Remove the item + unset($items[$key2]); + } + } + + if ($item['type'] == 'group') { + // Get the merged children (recursion) + if (!empty($resultItem['children'])) { + $resultItem['children'] = $this->getMergedItems($resultItem['children']); + } + } + + // Add the resulting item + if (!empty($resultItem) && !empty($resultItem['counters']['total'])) { + $mergedItems[] = $resultItem; + } + + // Remove the item + unset($items[$key]); + } + + usort($mergedItems, ['Tree', 'cmpSortNames']); + + return $mergedItems; + } + + + protected function processModule(&$module, $server=false, $all_groups) + { + global $config; + + if (isset($module['children'])) { + foreach ($module['children'] as $i => $children) { + $this->processModule($module['children'][$i], $server, $all_groups); + } + } + + $module['type'] = 'module'; + $module['id'] = (int) $module['id']; + $module['name'] = io_safe_output($module['name']); + $module['id_module_type'] = (int) $module['id_tipo_modulo']; + $module['server_type'] = (int) $module['id_modulo']; + $module['status'] = $module['estado']; + $module['value'] = $module['datos']; + + if (is_metaconsole()) { + $module['serverID'] = $this->serverID; + $module['serverName'] = $this->serverName; + } else { + $module['serverName'] = false; + $module['serverID'] = false; + } + + if (!isset($module['value'])) { + $module['value'] = modules_get_last_value($module['id']); + } + + // Status + switch ($module['status']) { + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + $module['alert'] = 1; + case AGENT_MODULE_STATUS_CRITICAL_BAD: + $statusType = STATUS_MODULE_CRITICAL_BALL; + $statusTitle = __('CRITICAL'); + $module['statusText'] = 'critical'; + break; + + case AGENT_MODULE_STATUS_WARNING_ALERT: + $module['alert'] = 1; + case AGENT_MODULE_STATUS_WARNING: + $statusType = STATUS_MODULE_WARNING_BALL; + $statusTitle = __('WARNING'); + $module['statusText'] = 'warning'; + break; + + case AGENT_MODULE_STATUS_UNKNOWN: + $statusType = STATUS_MODULE_UNKNOWN_BALL; + $statusTitle = __('UNKNOWN'); + $module['statusText'] = 'unknown'; + break; + + case AGENT_MODULE_STATUS_NO_DATA: + case AGENT_MODULE_STATUS_NOT_INIT: + $statusType = STATUS_MODULE_NO_DATA_BALL; + $statusTitle = __('NO DATA'); + $module['statusText'] = 'not_init'; + break; + + case AGENT_MODULE_STATUS_NORMAL_ALERT: + $module['alert'] = 1; + case AGENT_MODULE_STATUS_NORMAL: + default: + $statusType = STATUS_MODULE_OK_BALL; + $statusTitle = __('NORMAL'); + $module['statusText'] = 'ok'; + break; + } + + if ($statusType !== STATUS_MODULE_UNKNOWN_BALL + && $statusType !== STATUS_MODULE_NO_DATA_BALL + ) { + if (is_numeric($module['value'])) { + $statusTitle .= ' : '.format_for_graph($module['value']); + } else { + $statusTitle .= ' : '.substr(io_safe_output($module['value']), 0, 42); + } + } + + $module['statusImageHTML'] = ui_print_status_image($statusType, $statusTitle, true); + + // HTML of the server type image + $module['serverTypeHTML'] = servers_show_type($module['server_type']); + + // Link to the Module graph + // ACL + $acl_graphs = false; + $module['showGraphs'] = 0; + + // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions + if (!empty($group_id) && !is_metaconsole()) { + $acl_graphs = check_acl_one_of_groups($config['id_user'], $all_groups, 'RR'); + } else if (!empty($all_groups)) { + $acl_graphs = true; + } + + if ($acl_graphs) { + $module['showGraphs'] = 1; + } + + if ($module['showGraphs']) { + $graphType = return_graphtype($module['id_module_type']); + $url = ui_get_full_url('operation/agentes/stat_win.php', false, false, false); + $winHandle = dechex(crc32($module['id'].$module['name'])); + + $graph_params = [ + 'type' => $graphType, + 'period' => SECONDS_1DAY, + 'id' => $module['id'], + 'label' => base64_encode($module['name']), + 'refresh' => SECONDS_10MINUTES, + ]; + + if (is_metaconsole()) { + // Set the server id + $graph_params['server'] = $module['serverID']; + } + + $graph_params_str = http_build_query($graph_params); + $moduleGraphURL = "$url?$graph_params_str"; + + $module['moduleGraph'] = [ + 'url' => $moduleGraphURL, + 'handle' => $winHandle, + ]; + + // Info to be able to open the snapshot image new page + $module['snapshot'] = ui_get_snapshot_link( + [ + 'id_module' => $module['id'], + 'interval' => $module['current_interval'], + 'module_name' => $module['name'], + 'id_node' => $module['serverID'] ? $module['serverID'] : 0, + ], + true + ); + } + + // Alerts fired image + if ((bool) $module['alerts']) { + $module['alertsImageHTML'] = html_print_image('images/bell.png', true, ['title' => __('Module alerts')]); + } + } + + + protected function processModules(&$modules, $server=false) + { + if (!empty($modules)) { + $all_groups = modules_get_agent_groups($modules[0]['id']); + } + + foreach ($modules as $iterator => $module) { + $this->processModule($modules[$iterator], $server, $all_groups); + } + } + + + protected function processAgent(&$agent, $server=false) + { + global $config; + + $agent['type'] = 'agent'; + $agent['id'] = (int) $agent['id']; + $agent['name'] = $agent['name']; + + $agent['rootID'] = $this->rootID; + $agent['rootType'] = $this->rootType; + + if (is_metaconsole()) { + if (isset($agent['server_id'])) { + $agent['serverID'] = $agent['server_id']; + } else if (!empty($server)) { + $agent['serverID'] = $server['id']; + } + } + + // Counters + if (empty($agent['counters'])) { + $agent['counters'] = []; + + $agent['counters']['unknown'] = isset($agent['unknown_count']) ? $agent['unknown_count'] : 0; + $agent['counters']['critical'] = isset($agent['critical_count']) ? $agent['critical_count'] : 0; + $agent['counters']['warning'] = isset($agent['warning_count']) ? $agent['warning_count'] : 0; + $agent['counters']['not_init'] = isset($agent['notinit_count']) ? $agent['notinit_count'] : 0; + $agent['counters']['ok'] = isset($agent['normal_count']) ? $agent['normal_count'] : 0; + $agent['counters']['total'] = isset($agent['total_count']) ? $agent['total_count'] : 0; + $agent['counters']['alerts'] = isset($agent['fired_count']) ? $agent['fired_count'] : 0; + } + + // Status image + $agent['statusImageHTML'] = agents_tree_view_status_img_ball( + $agent['counters']['critical'], + $agent['counters']['warning'], + $agent['counters']['unknown'], + $agent['counters']['total'], + $agent['counters']['not_init'] + ); + + // Alerts fired image + $agent['alertImageHTML'] = agents_tree_view_alert_img_ball($agent['counters']['alerts']); + + // search module recalculate counters + if (array_key_exists('state_normal', $agent)) { + $agent['counters']['unknown'] = $agent['state_unknown']; + $agent['counters']['critical'] = $agent['state_critical']; + $agent['counters']['warning'] = $agent['state_warning']; + $agent['counters']['not_init'] = $agent['state_notinit']; + $agent['counters']['ok'] = $agent['state_normal']; + $agent['counters']['total'] = $agent['state_total']; + + $agent['critical_count'] = $agent['counters']['critical']; + $agent['warning_count'] = $agent['counters']['warning']; + $agent['unknown_count'] = $agent['counters']['unknown']; + $agent['notinit_count'] = $agent['counters']['not_init']; + $agent['normal_count'] = $agent['counters']['ok']; + $agent['total_count'] = $agent['counters']['total']; + } + + if (!$this->getEmptyModuleFilterStatus()) { + $agent['counters']['unknown'] = 0; + $agent['counters']['critical'] = 0; + $agent['counters']['warning'] = 0; + $agent['counters']['not_init'] = 0; + $agent['counters']['ok'] = 0; + $agent['counters']['total'] = 0; + switch ($this->filter['statusModule']) { + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + case AGENT_MODULE_STATUS_CRITICAL_BAD: + $agent['counters']['critical'] = $agent['critical_count']; + $agent['counters']['total'] = $agent['critical_count']; + break; + + case AGENT_MODULE_STATUS_WARNING_ALERT: + case AGENT_MODULE_STATUS_WARNING: + $agent['counters']['warning'] = $agent['warning_count']; + $agent['counters']['total'] = $agent['warning_count']; + break; + + case AGENT_MODULE_STATUS_UNKNOWN: + $agent['counters']['unknown'] = $agent['unknown_count']; + $agent['counters']['total'] = $agent['unknown_count']; + break; + + case AGENT_MODULE_STATUS_NO_DATA: + case AGENT_MODULE_STATUS_NOT_INIT: + $agent['counters']['not_init'] = $agent['notinit_count']; + $agent['counters']['total'] = $agent['notinit_count']; + break; + + case AGENT_MODULE_STATUS_NORMAL_ALERT: + case AGENT_MODULE_STATUS_NORMAL: + $agent['counters']['ok'] = $agent['normal_count']; + $agent['counters']['total'] = $agent['normal_count']; + break; + } + } + + if (!$this->filter['show_not_init_modules']) { + $agent['counters']['total'] -= $agent['counters']['not_init']; + $agent['counters']['not_init'] = 0; + } + + // Quiet image + if (isset($agent['quiet']) && $agent['quiet']) { + $agent['quietImageHTML'] = html_print_image('/images/dot_blue.png', true, ['title' => __('Quiet')]); + } + + // Children + if (empty($agent['children'])) { + $agent['children'] = []; + if ($agent['counters']['total'] > 0) { + switch ($this->childrenMethod) { + case 'on_demand': + $agent['searchChildren'] = 1; + break; + + case 'live': + $agent['searchChildren'] = 0; + break; + } + } else { + switch ($this->childrenMethod) { + case 'on_demand': + $agent['searchChildren'] = 0; + break; + + case 'live': + $agent['searchChildren'] = 0; + break; + } + } + } + } + + + protected function processAgents(&$agents, $server=false) + { + if (!empty($agents)) { + foreach ($agents as $iterator => $agent) { + $this->processAgent($agents[$iterator], $server); + } + } + } + + + protected function getData() + { + + } + + + protected function getFirstLevel() + { + $sql = $this->getFirstLevelSql(); + $items = db_get_all_rows_sql($sql); + if ($items === false) { + $items = []; + } + + $this->tree = $this->getProcessedItemsFirstLevel($items); + } + + + protected function getProcessedItemsFirstLevel($items) + { + $processed_items = []; + foreach ($items as $key => $item) { + $processed_item = $this->getProcessedItem($item); + $processed_items[] = $processed_item; + } + + return $processed_items; + } + + + protected function getFirstLevelSql() + { + $fields = $this->getFirstLevelFields(); + $field_name_sql = $this->L1fieldNameSql; + $inside_fields = $this->getFirstLevelFieldsInside(); + $inner = $this->L1inner; + $inner_inside = $this->L1innerInside; + $order_by_final = $this->L1orderByFinal; + + $group_inner = $this->getGroupSearchInner(); + $group_acl = $this->getGroupAclCondition(); + $group_search_filter = $this->getGroupSearchFilter(); + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_search_filter = $this->getModuleSearchFilter(); + $module_status_inner = ''; + $module_status_filter = $this->getModuleStatusFilterFromTestado(); + if (!empty($module_status_filter)) { + $module_status_inner = ' INNER JOIN tagente_estado tae - ON tae.id_agente_modulo = tam.id_agente_modulo"; - } + ON tae.id_agente_modulo = tam.id_agente_modulo'; + } - $sql_model = "SELECT %s FROM + $sql_model = "SELECT %s FROM ( SELECT COUNT(DISTINCT(ta.id_agente)) AS total, $field_name_sql AS g FROM tagente ta @@ -776,35 +920,42 @@ class Tree { $group_acl GROUP BY $field_name_sql ) x GROUP BY g"; - $sql_array = array(); - foreach ($inside_fields as $inside_field) { - $sql_array[] = sprintf( - $sql_model, - $inside_field['header'], - $inside_field['condition'] - ); - } - $sql = "SELECT $fields FROM (" . implode(" UNION ALL ", $sql_array) . ") x2 + $sql_array = []; + foreach ($inside_fields as $inside_field) { + $sql_array[] = sprintf( + $sql_model, + $inside_field['header'], + $inside_field['condition'] + ); + } + + $sql = "SELECT $fields FROM (".implode(' UNION ALL ', $sql_array).") x2 $inner GROUP BY g ORDER BY $order_by_final"; - return $sql; - } + return $sql; + } - protected function getSecondLevel() { - $sql = $this->getSecondLevelSql(); - $data = db_process_sql($sql); - if (empty($data)) { - $this->tree = array(); - return; - } - $this->processAgents($data); - $this->tree = $data; - } + protected function getSecondLevel() + { + $sql = $this->getSecondLevelSql(); + $data = db_process_sql($sql); + if (empty($data)) { + $this->tree = []; + return; + } - protected function getSecondLevelSql() { - $columns = sprintf("ta.id_agente AS id, ta.nombre AS name, ta.alias, + $this->processAgents($data); + + $this->tree = $data; + } + + + protected function getSecondLevelSql() + { + $columns = sprintf( + 'ta.id_agente AS id, ta.nombre AS name, ta.alias, ta.fired_count, ta.normal_count, ta.warning_count, ta.critical_count, ta.unknown_count, ta.notinit_count, ta.total_count, ta.quiet, @@ -814,29 +965,29 @@ class Tree { SUM(if(%s, 1, 0)) as state_notinit, SUM(if(%s, 1, 0)) as state_normal, SUM(if(%s AND tae.estado IS NOT NULL, 1, 0)) as state_total - ", - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_CRITICAL_ALERT, true), - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_WARNING_ALERT, true), - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_UNKNOWN, true), - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NO_DATA, true), - $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NORMAL, true), - $this->getModuleStatusFilterFromTestado(self::TV_DEFAULT_AGENT_STATUS, true) - ); + ', + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_CRITICAL_ALERT, true), + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_WARNING_ALERT, true), + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_UNKNOWN, true), + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NO_DATA, true), + $this->getModuleStatusFilterFromTestado(AGENT_MODULE_STATUS_NORMAL, true), + $this->getModuleStatusFilterFromTestado(self::TV_DEFAULT_AGENT_STATUS, true) + ); - $inner_or_left = $this->getInnerOrLeftJoin(); - $group_inner = $this->getGroupSearchInner(); - $group_acl = $this->getGroupAclCondition(); - $group_search_filter = $this->getGroupSearchFilter(); - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_search_filter = $this->getModuleSearchFilter(); - $module_status_filter = $this->getModuleStatusFilter(); + $inner_or_left = $this->getInnerOrLeftJoin(); + $group_inner = $this->getGroupSearchInner(); + $group_acl = $this->getGroupAclCondition(); + $group_search_filter = $this->getGroupSearchFilter(); + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_search_filter = $this->getModuleSearchFilter(); + $module_status_filter = $this->getModuleStatusFilter(); - $condition = $this->L2condition; - $condition_inside = $this->L2conditionInside; - $inner = $this->L2inner; + $condition = $this->L2condition; + $condition_inside = $this->L2conditionInside; + $inner = $this->L2inner; - $sql = "SELECT $columns + $sql = "SELECT $columns FROM tagente ta $inner_or_left JOIN tagente_modulo tam ON ta.id_agente = tam.id_agente @@ -866,45 +1017,48 @@ class Tree { ORDER BY ta.alias ASC, ta.id_agente ASC "; - return $sql; - } + return $sql; + } - protected function getThirdLevel() { - $sql = $this->getThirdLevelSql(); - $data = db_process_sql($sql); - if (empty($data)) { - $this->tree = array(); - return; - } - $data = $this->getProcessedModules($data); - $this->processModules($data); - $this->tree = $data; - } + protected function getThirdLevel() + { + $sql = $this->getThirdLevelSql(); + $data = db_process_sql($sql); + if (empty($data)) { + $this->tree = []; + return; + } - protected function getThirdLevelSql() { - // Get the server id - $serverID = $this->serverID; + $data = $this->getProcessedModules($data); + $this->processModules($data); - $group_acl = $this->getGroupAclCondition(); - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_search_filter = $this->getModuleSearchFilter(); - $module_status_filter = $this->getModuleStatusFilterFromTestado(); - $agent_filter = "AND ta.id_agente = " . $this->id; - $tag_condition = $this->getTagCondition(); - $tag_join = empty($tag_condition) && (!$this->L3forceTagCondition) - ? '' - : $this->getTagJoin(); + $this->tree = $data; + } - $condition = $this->L2condition; - $inner = $this->L2inner; - $columns = 'DISTINCT(tam.id_agente_modulo) AS id, tam.nombre AS name, + protected function getThirdLevelSql() + { + // Get the server id + $serverID = $this->serverID; + + $group_acl = $this->getGroupAclCondition(); + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_search_filter = $this->getModuleSearchFilter(); + $module_status_filter = $this->getModuleStatusFilterFromTestado(); + $agent_filter = 'AND ta.id_agente = '.$this->id; + $tag_condition = $this->getTagCondition(); + $tag_join = empty($tag_condition) && (!$this->L3forceTagCondition) ? '' : $this->getTagJoin(); + + $condition = $this->L2condition; + $inner = $this->L2inner; + + $columns = 'DISTINCT(tam.id_agente_modulo) AS id, tam.nombre AS name, tam.id_tipo_modulo, tam.id_modulo, tae.estado, tae.datos, tam.parent_module_id AS parent, tatm.id AS alerts'; - $sql = "SELECT $columns + $sql = "SELECT $columns FROM tagente_modulo tam $tag_join INNER JOIN tagente_estado tae @@ -926,53 +1080,77 @@ class Tree { $module_search_filter $tag_condition ORDER BY tam.nombre ASC, tam.id_agente_modulo ASC"; - return $sql; - } + return $sql; + } - public function getJSON() { - $this->getData(); - return json_encode($this->tree); - } + public function getJSON() + { + $this->getData(); - public function getArray() { - $this->getData(); + return json_encode($this->tree); + } - return $this->tree; - } - static function name2symbol($name) { - return str_replace( - array(' ','#','/','.','(',')','¿','?','¡','!'), - array( - '_articapandora_'.ord(' ').'_pandoraartica_', - '_articapandora_'.ord('#').'_pandoraartica_', - '_articapandora_'.ord('/').'_pandoraartica_', - '_articapandora_'.ord('.').'_pandoraartica_', - '_articapandora_'.ord('(').'_pandoraartica_', - '_articapandora_'.ord(')').'_pandoraartica_', - '_articapandora_'.ord('¿').'_pandoraartica_', - '_articapandora_'.ord('?').'_pandoraartica_', - '_articapandora_'.ord('¡').'_pandoraartica_', - '_articapandora_'.ord('!').'_pandoraartica_' - ), - io_safe_output($name) - ); - } + public function getArray() + { + $this->getData(); - static function symbol2name($name) { - $symbols = ' !"#$%&\'()*+,./:;<=>?@[\\]^{|}~'; - for ($i = 0; $i < strlen($symbols); $i++) { - $name = str_replace('_articapandora_' . - ord(substr($symbols, $i, 1)) .'_pandoraartica_', - substr($symbols, $i, 1), $name); - } - return io_safe_input($name); - } + return $this->tree; + } + + + static function name2symbol($name) + { + return str_replace( + [ + ' ', + '#', + '/', + '.', + '(', + ')', + '¿', + '?', + '¡', + '!', + ], + [ + '_articapandora_'.ord(' ').'_pandoraartica_', + '_articapandora_'.ord('#').'_pandoraartica_', + '_articapandora_'.ord('/').'_pandoraartica_', + '_articapandora_'.ord('.').'_pandoraartica_', + '_articapandora_'.ord('(').'_pandoraartica_', + '_articapandora_'.ord(')').'_pandoraartica_', + '_articapandora_'.ord('¿').'_pandoraartica_', + '_articapandora_'.ord('?').'_pandoraartica_', + '_articapandora_'.ord('¡').'_pandoraartica_', + '_articapandora_'.ord('!').'_pandoraartica_', + ], + io_safe_output($name) + ); + } + + + static function symbol2name($name) + { + $symbols = ' !"#$%&\'()*+,./:;<=>?@[\\]^{|}~'; + for ($i = 0; $i < strlen($symbols); $i++) { + $name = str_replace( + '_articapandora_'.ord(substr($symbols, $i, 1)).'_pandoraartica_', + substr($symbols, $i, 1), + $name + ); + } + + return io_safe_input($name); + } + + + protected function getProcessedModules($modules_tree) + { + return $modules_tree; + } - protected function getProcessedModules($modules_tree) { - return $modules_tree; - } } -?> diff --git a/pandora_console/include/class/TreeGroup.class.php b/pandora_console/include/class/TreeGroup.class.php index ced6b8d442..bef4287c7d 100644 --- a/pandora_console/include/class/TreeGroup.class.php +++ b/pandora_console/include/class/TreeGroup.class.php @@ -1,189 +1,215 @@ L1fieldName = "id_group"; - $this->L1extraFields = array( - "tg.nombre AS `name`", - "tg.icon", - "tg.id_grupo AS gid" - ); + parent::__construct($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); - $this->L2conditionInside = "AND ( - ta.id_grupo = " . $this->id . " - OR tasg.id_group = " . $this->id . " - )"; - } + $this->L1fieldName = 'id_group'; + $this->L1extraFields = [ + 'tg.nombre AS `name`', + 'tg.icon', + 'tg.id_grupo AS gid', + ]; - public function setPropagateCounters($value) { - $this->propagateCounters = (bool)$value; - } + $this->L2conditionInside = 'AND ( + ta.id_grupo = '.$this->id.' + OR tasg.id_group = '.$this->id.' + )'; + } - public function setDisplayAllGroups($value) { - $this->displayAllGroups = (bool)$value; - } - protected function getData() { - if ($this->id == -1) { - $this->getFirstLevel(); - } elseif ($this->type == 'group') { - $this->getSecondLevel(); - } elseif ($this->type == 'agent') { - $this->getThirdLevel(); - } - } + public function setPropagateCounters($value) + { + $this->propagateCounters = (bool) $value; + } - protected function getGroupSearchFilter() { - return ""; - } - protected function getFirstLevel() { - $processed_items = $this->getProcessedGroups(); + public function setDisplayAllGroups($value) + { + $this->displayAllGroups = (bool) $value; + } - if (!empty($processed_items)) { - // Filter by group name. This should be done after rerieving the items cause we need the possible items descendants - if (!empty($this->filter['searchGroup'])) { - // Save the groups which intersect with the user groups - $groups = db_get_all_rows_filter('tgrupo', array('nombre' => '%' . $this->filter['searchGroup'] . '%')); - if ($groups == false) $groups = array(); - $userGroupsACL = $this->userGroupsACL; - $ids_hash = array_reduce($groups, function ($userGroups, $group) use ($userGroupsACL) { - $group_id = $group['id_grupo']; - if (isset($userGroupsACL[$group_id])) { - $userGroups[$group_id] = $userGroupsACL[$group_id]; - } - return $userGroups; - }, array()); + protected function getData() + { + if ($this->id == -1) { + $this->getFirstLevel(); + } else if ($this->type == 'group') { + $this->getSecondLevel(); + } else if ($this->type == 'agent') { + $this->getThirdLevel(); + } + } - $result = self::extractGroupsWithIDs($processed_items, $ids_hash); - $processed_items = ($result === false) ? array() : $result; - } + protected function getGroupSearchFilter() + { + return ''; + } - // groupID filter. To access the view from tactical views f.e. - if (!empty($this->filter['groupID'])) { - $result = self::extractItemWithID($processed_items, $this->filter['groupID'], "group", $this->strictACL); - $processed_items = ($result === false) ? array() : array($result); - } - } + protected function getFirstLevel() + { + $processed_items = $this->getProcessedGroups(); - $this->tree = $processed_items; - } + if (!empty($processed_items)) { + // Filter by group name. This should be done after rerieving the items cause we need the possible items descendants + if (!empty($this->filter['searchGroup'])) { + // Save the groups which intersect with the user groups + $groups = db_get_all_rows_filter('tgrupo', ['nombre' => '%'.$this->filter['searchGroup'].'%']); + if ($groups == false) { + $groups = []; + } - protected function getProcessedGroups () { - $processed_groups = array(); - // Index and process the groups - $groups = $this->getGroupCounters(); + $userGroupsACL = $this->userGroupsACL; + $ids_hash = array_reduce( + $groups, + function ($userGroups, $group) use ($userGroupsACL) { + $group_id = $group['id_grupo']; + if (isset($userGroupsACL[$group_id])) { + $userGroups[$group_id] = $userGroupsACL[$group_id]; + } - // If user have not permissions in parent, set parent node to 0 (all) - // Avoid to do foreach for admins - if (!users_can_manage_group_all("AR")) { - foreach ($groups as $id => $group) { - if (!isset($this->userGroups[$groups[$id]['parent']])) { - $groups[$id]['parent'] = 0; - } - } - } - // Build the group hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = array(); - } - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], array("Tree", "cmpSortNames")); - } - } - //Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter($groups, function ($group) { - return !$group['have_parent']; - }); - // Propagate child counters to her parents + return $userGroups; + }, + [] + ); - if ($this->propagateCounters) { - TreeGroup::processCounters($groups); - // Filter groups and eliminates the reference to empty groups - $groups = $this->deleteEmptyGroups($groups); - } else { - $groups = $this->deleteEmptyGroupsNotPropagate($groups); - } + $result = self::extractGroupsWithIDs($processed_items, $ids_hash); - usort($groups, array("Tree", "cmpSortNames")); - return $groups; - } + $processed_items = ($result === false) ? [] : $result; + } - protected function getGroupCounters() { - $fields = $this->getFirstLevelFields(); - $inside_fields = $this->getFirstLevelFieldsInside(); + // groupID filter. To access the view from tactical views f.e. + if (!empty($this->filter['groupID'])) { + $result = self::extractItemWithID($processed_items, $this->filter['groupID'], 'group', $this->strictACL); - $group_acl = ""; - $secondary_group_acl = ""; - if (!users_can_manage_group_all("AR")) { - $user_groups_str = implode(",", $this->userGroupsArray); - $group_acl = " AND ta.id_grupo IN ($user_groups_str)"; - $secondary_group_acl = " AND tasg.id_group IN ($user_groups_str)"; - } - $agent_search_filter = $this->getAgentSearchFilter(); - $agent_search_filter = preg_replace("/%/", "%%", $agent_search_filter); - $agent_status_filter = $this->getAgentStatusFilter(); - $module_status_filter = $this->getModuleStatusFilter(); + $processed_items = ($result === false) ? [] : [$result]; + } + } - $module_search_inner = ""; - $module_search_filter = ""; - if (!empty($this->filter['searchModule'])) { - $module_search_inner = " + $this->tree = $processed_items; + } + + + protected function getProcessedGroups() + { + $processed_groups = []; + // Index and process the groups + $groups = $this->getGroupCounters(); + + // If user have not permissions in parent, set parent node to 0 (all) + // Avoid to do foreach for admins + if (!users_can_manage_group_all('AR')) { + foreach ($groups as $id => $group) { + if (!isset($this->userGroups[$groups[$id]['parent']])) { + $groups[$id]['parent'] = 0; + } + } + } + + // Build the group hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = []; + } + + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } + + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); + } + } + + // Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter( + $groups, + function ($group) { + return !$group['have_parent']; + } + ); + // Propagate child counters to her parents + if ($this->propagateCounters) { + self::processCounters($groups); + // Filter groups and eliminates the reference to empty groups + $groups = $this->deleteEmptyGroups($groups); + } else { + $groups = $this->deleteEmptyGroupsNotPropagate($groups); + } + + usort($groups, ['Tree', 'cmpSortNames']); + return $groups; + } + + + protected function getGroupCounters() + { + $fields = $this->getFirstLevelFields(); + $inside_fields = $this->getFirstLevelFieldsInside(); + + $group_acl = ''; + $secondary_group_acl = ''; + if (!users_can_manage_group_all('AR')) { + $user_groups_str = implode(',', $this->userGroupsArray); + $group_acl = " AND ta.id_grupo IN ($user_groups_str)"; + $secondary_group_acl = " AND tasg.id_group IN ($user_groups_str)"; + } + + $agent_search_filter = $this->getAgentSearchFilter(); + $agent_search_filter = preg_replace('/%/', '%%', $agent_search_filter); + $agent_status_filter = $this->getAgentStatusFilter(); + $module_status_filter = $this->getModuleStatusFilter(); + + $module_search_inner = ''; + $module_search_filter = ''; + if (!empty($this->filter['searchModule'])) { + $module_search_inner = ' INNER JOIN tagente_modulo tam ON ta.id_agente = tam.id_agente INNER JOIN tagente_estado tae - ON tae.id_agente_modulo = tam.id_agente_modulo"; - $module_search_filter = "AND tam.disabled = 0 - AND tam.nombre LIKE '%%" . $this->filter['searchModule'] . "%%' " . - $this->getModuleStatusFilterFromTestado() - ; - } + ON tae.id_agente_modulo = tam.id_agente_modulo'; + $module_search_filter = "AND tam.disabled = 0 + AND tam.nombre LIKE '%%".$this->filter['searchModule']."%%' ".$this->getModuleStatusFilterFromTestado(); + } - $table = is_metaconsole() ? "tmetaconsole_agent" : "tagente"; - $table_sec = is_metaconsole() ? "tmetaconsole_agent_secondary_group" : "tagent_secondary_group"; + $table = is_metaconsole() ? 'tmetaconsole_agent' : 'tagente'; + $table_sec = is_metaconsole() ? 'tmetaconsole_agent_secondary_group' : 'tagent_secondary_group'; - $sql_model = "SELECT %s FROM + $sql_model = "SELECT %s FROM ( SELECT COUNT(DISTINCT(ta.id_agente)) AS total, id_grupo AS g FROM $table ta @@ -210,248 +236,294 @@ class TreeGroup extends Tree { $secondary_group_acl GROUP BY id_group ) x GROUP BY g"; - $sql_array = array(); - foreach ($inside_fields as $inside_field) { - $sql_array[] = sprintf( - $sql_model, - $inside_field['header'], - $inside_field['condition'], - $inside_field['condition'] - ); - } - $sql = "SELECT $fields FROM (" . implode(" UNION ALL ", $sql_array) . ") x2 + $sql_array = []; + foreach ($inside_fields as $inside_field) { + $sql_array[] = sprintf( + $sql_model, + $inside_field['header'], + $inside_field['condition'], + $inside_field['condition'] + ); + } + + $sql = "SELECT $fields FROM (".implode(' UNION ALL ', $sql_array).') x2 RIGHT JOIN tgrupo tg ON x2.g = tg.id_grupo - GROUP BY tg.id_grupo"; - $stats = db_get_all_rows_sql($sql); + GROUP BY tg.id_grupo'; + $stats = db_get_all_rows_sql($sql); - $group_stats = array(); - foreach ($stats as $group) { - $group_stats[$group['gid']]['total_count'] = (int)$group['total_count']; - $group_stats[$group['gid']]['total_critical_count'] = (int)$group['total_critical_count']; - $group_stats[$group['gid']]['total_unknown_count'] = (int)$group['total_unknown_count']; - $group_stats[$group['gid']]['total_warning_count'] = (int)$group['total_warning_count']; - $group_stats[$group['gid']]['total_not_init_count'] = (int)$group['total_not_init_count']; - $group_stats[$group['gid']]['total_normal_count'] = (int)$group['total_normal_count']; - $group_stats[$group['gid']]['total_fired_count'] = (int)$group['total_alerts_count']; - $group_stats[$group['gid']]['name'] = $group['name']; - $group_stats[$group['gid']]['parent'] = $group['parent']; - $group_stats[$group['gid']]['icon'] = $group['icon']; - $group_stats[$group['gid']]['id'] = $group['gid']; - $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); - } + $group_stats = []; + foreach ($stats as $group) { + $group_stats[$group['gid']]['total_count'] = (int) $group['total_count']; + $group_stats[$group['gid']]['total_critical_count'] = (int) $group['total_critical_count']; + $group_stats[$group['gid']]['total_unknown_count'] = (int) $group['total_unknown_count']; + $group_stats[$group['gid']]['total_warning_count'] = (int) $group['total_warning_count']; + $group_stats[$group['gid']]['total_not_init_count'] = (int) $group['total_not_init_count']; + $group_stats[$group['gid']]['total_normal_count'] = (int) $group['total_normal_count']; + $group_stats[$group['gid']]['total_fired_count'] = (int) $group['total_alerts_count']; + $group_stats[$group['gid']]['name'] = $group['name']; + $group_stats[$group['gid']]['parent'] = $group['parent']; + $group_stats[$group['gid']]['icon'] = $group['icon']; + $group_stats[$group['gid']]['id'] = $group['gid']; + $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); + } - return $group_stats; - } + return $group_stats; + } - protected function getFirstLevelFields() { - $fields = parent::getFirstLevelFields(); - $parent = $this->getDisplayHierarchy() ? 'tg.parent' : '0 as parent'; - return "$fields, $parent"; - } - protected function getProcessedModules($modules_tree) { + protected function getFirstLevelFields() + { + $fields = parent::getFirstLevelFields(); + $parent = $this->getDisplayHierarchy() ? 'tg.parent' : '0 as parent'; + return "$fields, $parent"; + } - $groups = array(); - foreach ($modules_tree as $group) { - $groups[$group["id"]] = $group; - } - // Build the module hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = array(); - } - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } + protected function getProcessedModules($modules_tree) + { + $groups = []; + foreach ($modules_tree as $group) { + $groups[$group['id']] = $group; + } - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], array("Tree", "cmpSortNames")); - } - } - //Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter($groups, function ($group) { - return !$group['have_parent']; - }); + // Build the module hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = []; + } - return array_values($groups); - } + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } - // FIXME: Hierarchy lops is broken - protected function getProcessedModules_old($modules_tree) { + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); + } + } - $tree_modules = array(); - $new_modules_root = array_filter($modules_tree, function ($module) { - return (isset($module['parent']) && ($module['parent'] == 0)); - }); + // Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter( + $groups, + function ($group) { + return !$group['have_parent']; + } + ); - $new_modules_child = array_filter($modules_tree, function ($module) { - return (isset($module['parent']) && ($module['parent'] != 0)); - }); + return array_values($groups); + } - $i = 0; - while (!empty($new_modules_child)) { - foreach ($new_modules_child as $i => $child) { - TreeGroup::recursive_modules_tree_view($new_modules_root, $new_modules_child, $i, $child); - } - } - foreach ($new_modules_root as $m) { - $tree_modules[] = $m; - } - return $tree_modules; - } + // FIXME: Hierarchy lops is broken + protected function getProcessedModules_old($modules_tree) + { + $tree_modules = []; + $new_modules_root = array_filter( + $modules_tree, + function ($module) { + return (isset($module['parent']) && ($module['parent'] == 0)); + } + ); - // FIXME with getProcessedModules_old - static function recursive_modules_tree_view (&$new_modules, &$new_modules_child, $i, $child) { - foreach ($new_modules as $index => $module) { - if ($module['id'] == $child['parent']) { - $new_modules[$index]['children'][] = $child; - unset($new_modules_child[$i]); - break; - } - else if (isset($new_modules[$index]['children'])) { - TreeGroup::recursive_modules_tree_view ($new_modules[$index]['children'], $new_modules_child, $i, $child); - } - } - } + $new_modules_child = array_filter( + $modules_tree, + function ($module) { + return (isset($module['parent']) && ($module['parent'] != 0)); + } + ); - static function processCounters(&$groups) { - $all_counters = array(); - foreach ($groups as $id => $group) { - $child_counters = array(); - if (!empty($groups[$id]['children'])) { - $child_counters = TreeGroup::processCounters($groups[$id]['children']); - } - if (!empty($child_counters)) { - foreach($child_counters as $type => $value) { - $groups[$id]['counters'][$type] += $value; - } - } - foreach($groups[$id]['counters'] as $type => $value) { - $all_counters[$type] += $value; - } - } - return $all_counters; - } + $i = 0; + while (!empty($new_modules_child)) { + foreach ($new_modules_child as $i => $child) { + self::recursive_modules_tree_view($new_modules_root, $new_modules_child, $i, $child); + } + } - /** - * @brief Recursive function to remove the empty groups - * - * @param groups All groups structure - * - * @return new_groups A new groups structure without empty groups - */ - protected function deleteEmptyGroups ($groups) { - if($this->displayAllGroups) return $groups; - $new_groups = array(); - foreach ($groups as $group) { - // If a group is empty, do not add to new_groups. - if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) { - continue; - } - // Tray to remove the children groups - if (!empty($group['children'])) { - $children = $this->deleteEmptyGroups ($group['children']); - if (empty($children)) unset($group['children']); - else $group['children'] = $children; - } - $new_groups[] = $group; - } - return $new_groups; - } + foreach ($new_modules_root as $m) { + $tree_modules[] = $m; + } - protected function deleteEmptyGroupsNotPropagate ($groups) { - if($this->displayAllGroups) return $groups; - $new_groups = array(); - foreach ($groups as $group) { - // Tray to remove the children groups - if (!empty($group['children'])) { - $children = $this->deleteEmptyGroupsNotPropagate ($group['children']); - if (empty($children)) { - unset($group['children']); - // If a group is empty, do not add to new_groups. - if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { - $new_groups[] = $group; - } - } else { - $group['children'] = $children; - $new_groups[] = $group; - } - } else { - // If a group is empty, do not add to new_groups. - if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { - $new_groups[] = $group; - } - } - } - return $new_groups; - } + return $tree_modules; + } - private static function extractGroupsWithIDs ($groups, $ids_hash) { - $result_groups = array(); - foreach ($groups as $group) { - if (isset($ids_hash[$group['id']])) { - $result_groups[] = $group; - } - else if (!empty($group['children'])) { - $result = self::extractGroupsWithIDs($group['children'], $ids_hash); - // Item found on children - if (!empty($result)) { - $result_groups = array_merge($result_groups, $result); - } - } - } + // FIXME with getProcessedModules_old + static function recursive_modules_tree_view(&$new_modules, &$new_modules_child, $i, $child) + { + foreach ($new_modules as $index => $module) { + if ($module['id'] == $child['parent']) { + $new_modules[$index]['children'][] = $child; + unset($new_modules_child[$i]); + break; + } else if (isset($new_modules[$index]['children'])) { + self::recursive_modules_tree_view($new_modules[$index]['children'], $new_modules_child, $i, $child); + } + } + } - return $result_groups; - } - private static function extractItemWithID ($items, $item_id, $item_type = "group", $strictACL = false) { - foreach ($items as $item) { - if ($item["type"] != $item_type) - continue; + static function processCounters(&$groups) + { + $all_counters = []; + foreach ($groups as $id => $group) { + $child_counters = []; + if (!empty($groups[$id]['children'])) { + $child_counters = self::processCounters($groups[$id]['children']); + } - // Item found - if ($strictACL && is_metaconsole()) { - foreach ($item["id"] as $server_id => $id) { - if ($id == $item_id) - return $item; - } - } - else { - if ($item["id"] == $item_id) - return $item; - } + if (!empty($child_counters)) { + foreach ($child_counters as $type => $value) { + $groups[$id]['counters'][$type] += $value; + } + } - if ($item["type"] == "group" && !empty($item["children"])) { - $result = self::extractItemWithID($item["children"], $item_id, $item_type, $strictACL); + foreach ($groups[$id]['counters'] as $type => $value) { + $all_counters[$type] += $value; + } + } - // Item found on children - if ($result !== false) - return $result; - } - } + return $all_counters; + } - // Item not found - return false; - } - protected function getDisplayHierarchy() { - return $this->filter['searchHirearchy'] || - (empty($this->filter['searchAgent']) && empty($this->filter['searchModule'])); - } + /** + * @brief Recursive function to remove the empty groups + * + * @param groups All groups structure + * + * @return new_groups A new groups structure without empty groups + */ + protected function deleteEmptyGroups($groups) + { + if ($this->displayAllGroups) { + return $groups; + } + + $new_groups = []; + foreach ($groups as $group) { + // If a group is empty, do not add to new_groups. + if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) { + continue; + } + + // Tray to remove the children groups + if (!empty($group['children'])) { + $children = $this->deleteEmptyGroups($group['children']); + if (empty($children)) { + unset($group['children']); + } else { + $group['children'] = $children; + } + } + + $new_groups[] = $group; + } + + return $new_groups; + } + + + protected function deleteEmptyGroupsNotPropagate($groups) + { + if ($this->displayAllGroups) { + return $groups; + } + + $new_groups = []; + foreach ($groups as $group) { + // Tray to remove the children groups + if (!empty($group['children'])) { + $children = $this->deleteEmptyGroupsNotPropagate($group['children']); + if (empty($children)) { + unset($group['children']); + // If a group is empty, do not add to new_groups. + if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { + $new_groups[] = $group; + } + } else { + $group['children'] = $children; + $new_groups[] = $group; + } + } else { + // If a group is empty, do not add to new_groups. + if (isset($group['counters']['total']) && $group['counters']['total'] != 0) { + $new_groups[] = $group; + } + } + } + + return $new_groups; + } + + + private static function extractGroupsWithIDs($groups, $ids_hash) + { + $result_groups = []; + foreach ($groups as $group) { + if (isset($ids_hash[$group['id']])) { + $result_groups[] = $group; + } else if (!empty($group['children'])) { + $result = self::extractGroupsWithIDs($group['children'], $ids_hash); + + // Item found on children + if (!empty($result)) { + $result_groups = array_merge($result_groups, $result); + } + } + } + + return $result_groups; + } + + + private static function extractItemWithID($items, $item_id, $item_type='group', $strictACL=false) + { + foreach ($items as $item) { + if ($item['type'] != $item_type) { + continue; + } + + // Item found + if ($strictACL && is_metaconsole()) { + foreach ($item['id'] as $server_id => $id) { + if ($id == $item_id) { + return $item; + } + } + } else { + if ($item['id'] == $item_id) { + return $item; + } + } + + if ($item['type'] == 'group' && !empty($item['children'])) { + $result = self::extractItemWithID($item['children'], $item_id, $item_type, $strictACL); + + // Item found on children + if ($result !== false) { + return $result; + } + } + } + + // Item not found + return false; + } + + + protected function getDisplayHierarchy() + { + return $this->filter['searchHirearchy'] || + (empty($this->filter['searchAgent']) && empty($this->filter['searchModule'])); + } + } - -?> - diff --git a/pandora_console/include/class/TreeGroupEdition.class.php b/pandora_console/include/class/TreeGroupEdition.class.php index dea62da238..55efebe976 100644 --- a/pandora_console/include/class/TreeGroupEdition.class.php +++ b/pandora_console/include/class/TreeGroupEdition.class.php @@ -1,108 +1,120 @@ id == -1) { - $this->getFirstLevel(); - } - } - - protected function getProcessedGroups () { - $processed_groups = array(); - // Index and process the groups - $groups = $this->getGroupCounters(); - - // If user have not permissions in parent, set parent node to 0 (all) - // Avoid to do foreach for admins - if (!users_can_manage_group_all("AR")) { - foreach ($groups as $id => $group) { - if (!isset($this->userGroups[$groups[$id]['parent']])) { - $groups[$id]['parent'] = 0; - } - } - } - // Build the group hierarchy - foreach ($groups as $id => $group) { - if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { - $parent = $groups[$id]['parent']; - // Parent exists - if (!isset($groups[$parent]['children'])) { - $groups[$parent]['children'] = array(); - } - // Store a reference to the group into the parent - $groups[$parent]['children'][] = &$groups[$id]; - // This group was introduced into a parent - $groups[$id]['have_parent'] = true; - } - } - - // Sort the children groups - foreach ($groups as $id => $group) { - if (isset($groups[$id]['children'])) { - usort($groups[$id]['children'], array("Tree", "cmpSortNames")); - } - } - //Filter groups and eliminates the reference to children groups out of her parent - $groups = array_filter($groups, function ($group) { - return !$group['have_parent']; - }); - - usort($groups, array("Tree", "cmpSortNames")); - return $groups; - } +class TreeGroupEdition extends TreeGroup +{ - protected function getGroupCounters() { - $messages = array( - 'confirm' => __('Confirm'), - 'cancel' => __('Cancel'), - 'messg' => __('Are you sure?') - ); - $sql = "SELECT id_grupo AS gid, + public function __construct($type, $rootType='', $id=-1, $rootID=-1, $serverID=false, $childrenMethod='on_demand', $access='AR') + { + global $config; + + parent::__construct($type, $rootType, $id, $rootID, $serverID, $childrenMethod, $access); + } + + + protected function getData() + { + if ($this->id == -1) { + $this->getFirstLevel(); + } + } + + + protected function getProcessedGroups() + { + $processed_groups = []; + // Index and process the groups + $groups = $this->getGroupCounters(); + + // If user have not permissions in parent, set parent node to 0 (all) + // Avoid to do foreach for admins + if (!users_can_manage_group_all('AR')) { + foreach ($groups as $id => $group) { + if (!isset($this->userGroups[$groups[$id]['parent']])) { + $groups[$id]['parent'] = 0; + } + } + } + + // Build the group hierarchy + foreach ($groups as $id => $group) { + if (isset($groups[$id]['parent']) && ($groups[$id]['parent'] != 0)) { + $parent = $groups[$id]['parent']; + // Parent exists + if (!isset($groups[$parent]['children'])) { + $groups[$parent]['children'] = []; + } + + // Store a reference to the group into the parent + $groups[$parent]['children'][] = &$groups[$id]; + // This group was introduced into a parent + $groups[$id]['have_parent'] = true; + } + } + + // Sort the children groups + foreach ($groups as $id => $group) { + if (isset($groups[$id]['children'])) { + usort($groups[$id]['children'], ['Tree', 'cmpSortNames']); + } + } + + // Filter groups and eliminates the reference to children groups out of her parent + $groups = array_filter( + $groups, + function ($group) { + return !$group['have_parent']; + } + ); + + usort($groups, ['Tree', 'cmpSortNames']); + return $groups; + } + + + protected function getGroupCounters() + { + $messages = [ + 'confirm' => __('Confirm'), + 'cancel' => __('Cancel'), + 'messg' => __('Are you sure?'), + ]; + $sql = 'SELECT id_grupo AS gid, nombre as name, parent, icon FROM tgrupo - "; + '; - $stats = db_get_all_rows_sql($sql); - $group_stats = array(); - foreach ($stats as $group) { - $group_stats[$group['gid']]['name'] = $group['name']; - $group_stats[$group['gid']]['parent'] = $group['parent']; - $group_stats[$group['gid']]['icon'] = $group['icon']; - $group_stats[$group['gid']]['id'] = $group['gid']; - $group_stats[$group['gid']]['type'] = 'group'; + $stats = db_get_all_rows_sql($sql); + $group_stats = []; + foreach ($stats as $group) { + $group_stats[$group['gid']]['name'] = $group['name']; + $group_stats[$group['gid']]['parent'] = $group['parent']; + $group_stats[$group['gid']]['icon'] = $group['icon']; + $group_stats[$group['gid']]['id'] = $group['gid']; + $group_stats[$group['gid']]['type'] = 'group'; + + $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); + $group_stats[$group['gid']]['delete']['messages'] = $messages; + $group_stats[$group['gid']]['edit'] = 1; + $group_stats[$group['gid']]['alerts'] = ''; + } + + return $group_stats; + } - $group_stats[$group['gid']] = $this->getProcessedItem($group_stats[$group['gid']]); - $group_stats[$group['gid']]['delete']['messages'] = $messages; - $group_stats[$group['gid']]['edit'] = 1; - $group_stats[$group['gid']]['alerts'] = ''; - } - return $group_stats; - } } - -?> - diff --git a/pandora_console/include/class/TreeModule.class.php b/pandora_console/include/class/TreeModule.class.php index 45f9259854..1e9cecaef4 100644 --- a/pandora_console/include/class/TreeModule.class.php +++ b/pandora_console/include/class/TreeModule.class.php @@ -1,60 +1,63 @@ L1fieldName = 'name'; - $this->L1fieldNameSql = 'tam.nombre'; - $this->L1inner = ''; - $this->L1orderByFinal = 'name'; + $this->L1fieldName = 'name'; + $this->L1fieldNameSql = 'tam.nombre'; + $this->L1inner = ''; + $this->L1orderByFinal = 'name'; - $this->L2condition = "AND tam.nombre = '" . $this->symbol2name($this->rootID) . "'"; - } + $this->L2condition = "AND tam.nombre = '".$this->symbol2name($this->rootID)."'"; + } + + + protected function getData() + { + if ($this->id == -1) { + $this->getFirstLevel(); + } else if ($this->type == 'module') { + $this->getSecondLevel(); + } else if ($this->type == 'agent') { + $this->getThirdLevel(); + } + } + + + protected function getProcessedItemsFirstLevel($items) + { + $processed_items = []; + foreach ($items as $key => $item) { + $name = $this->name2symbol($item['name']); + $processed_item = $this->getProcessedItem($item); + $processed_item['id'] = $name; + $processed_item['rootID'] = $name; + $processed_items[] = $processed_item; + } + + return $processed_items; + } - protected function getData() { - if ($this->id == -1) { - $this->getFirstLevel(); - } elseif ($this->type == 'module') { - $this->getSecondLevel(); - } elseif ($this->type == 'agent') { - $this->getThirdLevel(); - } - } - protected function getProcessedItemsFirstLevel($items){ - $processed_items = array(); - foreach ($items as $key => $item) { - $name = $this->name2symbol($item['name']); - $processed_item = $this->getProcessedItem($item); - $processed_item['id'] = $name; - $processed_item['rootID'] = $name; - $processed_items[] = $processed_item; - } - return $processed_items; - } } - -?> - diff --git a/pandora_console/include/class/TreeModuleGroup.class.php b/pandora_console/include/class/TreeModuleGroup.class.php index 06bc8fb6ff..ffe147e1f5 100644 --- a/pandora_console/include/class/TreeModuleGroup.class.php +++ b/pandora_console/include/class/TreeModuleGroup.class.php @@ -1,49 +1,52 @@ L1fieldName = 'id_module_group'; - $this->L1fieldNameSql = 'tam.id_module_group'; - $this->L1extraFields = array('tmg.name', 'tmg.id_mg AS id'); - $this->L1inner = 'INNER JOIN tmodule_group tmg ON tmg.id_mg = x2.g'; - $this->L1orderByFinal = 'tmg.name'; + $this->L1fieldName = 'id_module_group'; + $this->L1fieldNameSql = 'tam.id_module_group'; + $this->L1extraFields = [ + 'tmg.name', + 'tmg.id_mg AS id', + ]; + $this->L1inner = 'INNER JOIN tmodule_group tmg ON tmg.id_mg = x2.g'; + $this->L1orderByFinal = 'tmg.name'; + + $this->L2condition = 'AND tam.id_module_group = '.$this->rootID; + } + + + protected function getData() + { + if ($this->id == -1) { + $this->getFirstLevel(); + } else if ($this->type == 'module_group') { + $this->getSecondLevel(); + } else if ($this->type == 'agent') { + $this->getThirdLevel(); + } + } - $this->L2condition = "AND tam.id_module_group = " . $this->rootID; - } - protected function getData() { - if ($this->id == -1) { - $this->getFirstLevel(); - } elseif ($this->type == 'module_group') { - $this->getSecondLevel(); - } elseif ($this->type == 'agent') { - $this->getThirdLevel(); - } - } } - -?> - diff --git a/pandora_console/include/class/TreeOS.class.php b/pandora_console/include/class/TreeOS.class.php index 8d7724f209..eb594fe8f6 100644 --- a/pandora_console/include/class/TreeOS.class.php +++ b/pandora_console/include/class/TreeOS.class.php @@ -1,49 +1,53 @@ L1fieldName = 'id_os'; - $this->L1fieldNameSql = 'ta.id_os'; - $this->L1extraFields = array('tco.name', 'tco.id_os AS id', 'tco.icon_name AS iconHTML'); - $this->L1inner = 'INNER JOIN tconfig_os tco ON tco.id_os = x2.g'; - $this->L1orderByFinal = 'tco.name'; + $this->L1fieldName = 'id_os'; + $this->L1fieldNameSql = 'ta.id_os'; + $this->L1extraFields = [ + 'tco.name', + 'tco.id_os AS id', + 'tco.icon_name AS iconHTML', + ]; + $this->L1inner = 'INNER JOIN tconfig_os tco ON tco.id_os = x2.g'; + $this->L1orderByFinal = 'tco.name'; + + $this->L2condition = 'AND ta.id_os = '.$this->rootID; + } + + + protected function getData() + { + if ($this->id == -1) { + $this->getFirstLevel(); + } else if ($this->type == 'os') { + $this->getSecondLevel(); + } else if ($this->type == 'agent') { + $this->getThirdLevel(); + } + } - $this->L2condition = "AND ta.id_os = " . $this->rootID; - } - protected function getData() { - if ($this->id == -1) { - $this->getFirstLevel(); - } elseif ($this->type == 'os') { - $this->getSecondLevel(); - } elseif ($this->type == 'agent') { - $this->getThirdLevel(); - } - } } - -?> - diff --git a/pandora_console/include/class/TreeTag.class.php b/pandora_console/include/class/TreeTag.class.php index 374945005c..bdf41a7cdd 100644 --- a/pandora_console/include/class/TreeTag.class.php +++ b/pandora_console/include/class/TreeTag.class.php @@ -1,60 +1,65 @@ L1fieldName = 'id_tag'; - $this->L1fieldNameSql = 'ttm.id_tag'; - $this->L1innerInside = ' + $this->L1fieldName = 'id_tag'; + $this->L1fieldNameSql = 'ttm.id_tag'; + $this->L1innerInside = ' INNER JOIN ttag_module ttm ON ttm.id_agente_modulo = tam.id_agente_modulo '; - $this->L1extraFields = array('tt.name', 'tt.id_tag AS id'); - $this->L1inner = 'INNER JOIN ttag tt ON tt.id_tag = x2.g'; - $this->L1orderByFinal = 'tt.name'; + $this->L1extraFields = [ + 'tt.name', + 'tt.id_tag AS id', + ]; + $this->L1inner = 'INNER JOIN ttag tt ON tt.id_tag = x2.g'; + $this->L1orderByFinal = 'tt.name'; - $this->L2condition = "AND ttm.id_tag = " . $this->rootID; - $this->L2inner = $this->L1innerInside; + $this->L2condition = 'AND ttm.id_tag = '.$this->rootID; + $this->L2inner = $this->L1innerInside; - $this->L3forceTagCondition = true; - } + $this->L3forceTagCondition = true; + } + + + protected function getData() + { + if ($this->id == -1) { + $this->getFirstLevel(); + } else if ($this->type == 'tag') { + $this->getSecondLevel(); + } else if ($this->type == 'agent') { + $this->getThirdLevel(); + } + } + + + protected function getTagJoin() + { + return ''; + } - protected function getData() { - if ($this->id == -1) { - $this->getFirstLevel(); - } elseif ($this->type == 'tag') { - $this->getSecondLevel(); - } elseif ($this->type == 'agent') { - $this->getThirdLevel(); - } - } - protected function getTagJoin () { - return ''; - } } - -?> - diff --git a/pandora_console/include/config.inc.php b/pandora_console/include/config.inc.php index 3499a67852..28952a1bb4 100644 --- a/pandora_console/include/config.inc.php +++ b/pandora_console/include/config.inc.php @@ -2,42 +2,37 @@ // Pandora FMS - http://pandorafms.com // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas -// +// // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 -// +// // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. /** - * @package Include + * @package Include * @subpackage Config */ // Default values - // $config["dbname"]="pandora"; // $config["dbuser"]="pandora"; // $config["dbpass"]="pandora"; // $config["dbhost"]="localhost"; - // This is used for reporting, please add "/" character at the end // $config["homedir"]="/var/www/pandora_console/"; // $config["homeurl"]="/pandora_console/"; - // $config["auth"]["scheme"] = "mysql"; /** * Do not display any ERROR */ -error_reporting(E_ALL); +error_reporting(E_ALL); // Display ALL errors // error_reporting(E_ERROR); - -$ownDir = dirname(__FILE__) . DIRECTORY_SEPARATOR; -include ($ownDir . "config_process.php"); -?> +$ownDir = dirname(__FILE__).DIRECTORY_SEPARATOR; +require $ownDir.'config_process.php'; diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index 2d84531297..4de1f20d2f 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -4,311 +4,305 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. /** - * @package Include + * @package Include * @subpackage Config */ /** * Pandora build version and version */ -$build_version = 'PC181210'; -$pandora_version = 'v7.0NG.729'; +$build_version = 'PC190215'; +$pandora_version = 'v7.0NG.731'; // Do not overwrite default timezone set if defined. $script_tz = @date_default_timezone_get(); if (empty($script_tz)) { - date_default_timezone_set("Europe/Berlin"); - ini_set("date.timezone", "Europe/Berlin"); -} -else { - ini_set("date.timezone", $script_tz); + date_default_timezone_set('Europe/Berlin'); + ini_set('date.timezone', 'Europe/Berlin'); +} else { + ini_set('date.timezone', $script_tz); } -//home dir bad defined +// home dir bad defined if (!is_dir($config['homedir'])) { - $ownDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR; - $config['homedir'] = $ownDir; - $config["error"] = "homedir_bad_defined"; + $ownDir = dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR; + $config['homedir'] = $ownDir; + $config['error'] = 'homedir_bad_defined'; } -/* Help to debug problems. Override global PHP configuration */ +// Help to debug problems. Override global PHP configuration global $develop_bypass; if ($develop_bypass != 1) { - // error_reporting(E_ALL); - - if (version_compare(PHP_VERSION, '5.3.0') >= 0) - { - error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE); - } - else - { - error_reporting(E_ALL & ~E_NOTICE); - } - - ini_set("display_errors", 0); - ini_set("log_errors", 1); - ini_set("error_log", $config["homedir"]."/pandora_console.log"); -} -else { - // Develop mode, show all notices and errors on Console (and log it) - if (version_compare(PHP_VERSION, '5.3.0') >= 0) - { - error_reporting(E_ALL & ~E_DEPRECATED); - } - else - { - error_reporting(E_ALL); - } - ini_set("display_errors", 1); - ini_set("log_errors", 1); - ini_set("error_log", $config["homedir"]."/pandora_console.log"); + // error_reporting(E_ALL); + if (version_compare(PHP_VERSION, '5.3.0') >= 0) { + error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE); + } else { + error_reporting(E_ALL & ~E_NOTICE); + } + + ini_set('display_errors', 0); + ini_set('log_errors', 1); + ini_set('error_log', $config['homedir'].'/pandora_console.log'); +} else { + // Develop mode, show all notices and errors on Console (and log it) + if (version_compare(PHP_VERSION, '5.3.0') >= 0) { + error_reporting(E_ALL & ~E_DEPRECATED); + } else { + error_reporting(E_ALL); + } + + ini_set('display_errors', 1); + ini_set('log_errors', 1); + ini_set('error_log', $config['homedir'].'/pandora_console.log'); } // Check if mysqli is available -if (!(isset($config["mysqli"]))) { - $config["mysqli"] = extension_loaded('mysqli'); +if (!(isset($config['mysqli']))) { + $config['mysqli'] = extension_loaded('mysqli'); } -$config['start_time'] = microtime (true); +$config['start_time'] = microtime(true); -$ownDir = dirname(__FILE__) . '/'; -$ownDir = str_replace("\\", "/", $ownDir); +$ownDir = dirname(__FILE__).'/'; +$ownDir = str_replace('\\', '/', $ownDir); -//Set by default the MySQL connection for DB, because in older Pandora have not -//this token in the config.php +// Set by default the MySQL connection for DB, because in older Pandora have not +// this token in the config.php if (!isset($config['dbtype'])) { - $config['dbtype'] = 'mysql'; + $config['dbtype'] = 'mysql'; } if (!isset($config['dbport'])) { - switch ($config['dbtype']) { - case 'mysql': - $config['dbport'] = '3306'; - break; - case 'postgresql': - $config['dbport'] = '5432'; - break; - case 'oracle': - $config['dbport'] = '1521'; - break; - } + switch ($config['dbtype']) { + case 'mysql': + $config['dbport'] = '3306'; + break; + + case 'postgresql': + $config['dbport'] = '5432'; + break; + + case 'oracle': + $config['dbport'] = '1521'; + break; + } } -require_once ($ownDir . 'constants.php'); -require_once ($ownDir . 'functions_db.php'); -require_once ($ownDir . 'functions.php'); +require_once $ownDir.'constants.php'; +require_once $ownDir.'functions_db.php'; +require_once $ownDir.'functions.php'; -// We need a timezone BEFORE calling config_process_config. +// We need a timezone BEFORE calling config_process_config. // If not we will get ugly warnings. Set Europe/Madrid by default // Later will be replaced by the good one. -if(!is_dir($_SERVER['DOCUMENT_ROOT'] . $config["homeurl"]) || !is_dir($_SERVER['DOCUMENT_ROOT'] . $config["homeurl_static"])){ - $url = explode('/', $_SERVER['REQUEST_URI']); - $flag_url =0; - foreach ($url as $key => $value) { - if (strpos($value, 'index.php') !== false || $flag_url) { - $flag_url=1; - unset($url[$key]); - } - else if(strpos($value, 'enterprise') !== false || $flag_url){ - $flag_url=1; - unset($url[$key]); - } - } - $config["homeurl"] = rtrim(join("/", $url),"/"); - $config["homeurl_static"] = $config["homeurl"]; - $config["error"] = "homeurl_bad_defined"; - return; +if (!is_dir($_SERVER['DOCUMENT_ROOT'].$config['homeurl']) || !is_dir($_SERVER['DOCUMENT_ROOT'].$config['homeurl_static'])) { + $url = explode('/', $_SERVER['REQUEST_URI']); + $flag_url = 0; + foreach ($url as $key => $value) { + if (strpos($value, 'index.php') !== false || $flag_url) { + $flag_url = 1; + unset($url[$key]); + } else if (strpos($value, 'enterprise') !== false || $flag_url) { + $flag_url = 1; + unset($url[$key]); + } + } + + $config['homeurl'] = rtrim(join('/', $url), '/'); + $config['homeurl_static'] = $config['homeurl']; + $config['error'] = 'homeurl_bad_defined'; + return; } -if (!isset($config["homeurl_static"])) { - $config["homeurl_static"] = $config["homeurl"]; -} -else{ - if($config["homeurl_static"] != $config["homeurl"]){ - $url = explode('/', $_SERVER['REQUEST_URI']); - $flag_url =0; - foreach ($url as $key => $value) { - if (strpos($value, 'index.php') !== false || $flag_url) { - $flag_url=1; - unset($url[$key]); - } - else if(strpos($value, 'enterprise') !== false || $flag_url){ - $flag_url=1; - unset($url[$key]); - } - } - $config["homeurl"] = rtrim(join("/", $url),"/"); - $config["homeurl_static"] = $config["homeurl"]; - $config["error"] = "homeurl_bad_defined"; - return; - } +if (!isset($config['homeurl_static'])) { + $config['homeurl_static'] = $config['homeurl']; +} else { + if ($config['homeurl_static'] != $config['homeurl']) { + $url = explode('/', $_SERVER['REQUEST_URI']); + $flag_url = 0; + foreach ($url as $key => $value) { + if (strpos($value, 'index.php') !== false || $flag_url) { + $flag_url = 1; + unset($url[$key]); + } else if (strpos($value, 'enterprise') !== false || $flag_url) { + $flag_url = 1; + unset($url[$key]); + } + } + + $config['homeurl'] = rtrim(join('/', $url), '/'); + $config['homeurl_static'] = $config['homeurl']; + $config['error'] = 'homeurl_bad_defined'; + return; + } } db_select_engine(); $config['dbconnection'] = db_connect(); -if (! defined ('EXTENSIONS_DIR')) - define ('EXTENSIONS_DIR', 'extensions'); +if (! defined('EXTENSIONS_DIR')) { + define('EXTENSIONS_DIR', 'extensions'); +} -if (! defined ('ENTERPRISE_DIR')) - define ('ENTERPRISE_DIR', 'enterprise'); +if (! defined('ENTERPRISE_DIR')) { + define('ENTERPRISE_DIR', 'enterprise'); +} -require_once ($ownDir. 'functions_config.php'); +require_once $ownDir.'functions_config.php'; -date_default_timezone_set("Europe/Madrid"); +date_default_timezone_set('Europe/Madrid'); -////////////////////////////////////// -//// PLEASE DO NOT CHANGE ORDER ////// -////////////////////////////////////// -require_once ($config["homedir"].'/include/load_session.php'); +// +// PLEASE DO NOT CHANGE ORDER ////// +// +require_once $config['homedir'].'/include/load_session.php'; -if (session_status() === PHP_SESSION_NONE) session_start(); +if (session_status() === PHP_SESSION_NONE) { + session_start(); +} config_process_config(); config_prepare_session(); // Set a the system timezone default -if ((!isset($config["timezone"])) OR ($config["timezone"] == "")) { - $config["timezone"] = "Europe/Berlin"; +if ((!isset($config['timezone'])) or ($config['timezone'] == '')) { + $config['timezone'] = 'Europe/Berlin'; } -//////////////////////////////////////// -date_default_timezone_set($config["timezone"]); +date_default_timezone_set($config['timezone']); -require_once ($ownDir . 'streams.php'); -require_once ($ownDir . 'gettext.php'); +require_once $ownDir.'streams.php'; +require_once $ownDir.'gettext.php'; if (isset($_SERVER['REMOTE_ADDR'])) { - $config["remote_addr"] = $_SERVER['REMOTE_ADDR']; -} -else { - $config["remote_addr"] = null; + $config['remote_addr'] = $_SERVER['REMOTE_ADDR']; +} else { + $config['remote_addr'] = null; } // Save the global values -$config["global_block_size"] = $config["block_size"]; +$config['global_block_size'] = $config['block_size']; -if (isset ($config['id_user'])) { - config_user_set_custom_config(); -} +if (isset($config['id_user'])) { + config_user_set_custom_config(); +} // Check if inventory_changes_blacklist is setted, if not create it if (!isset($config['inventory_changes_blacklist'])) { - $config['inventory_changes_blacklist'] = array(); + $config['inventory_changes_blacklist'] = []; } -//NEW UPDATE MANAGER URL +// NEW UPDATE MANAGER URL if (!isset($config['url_update_manager'])) { - config_update_value('url_update_manager', - 'https://licensing.artica.es/pandoraupdate7/server.php'); + config_update_value( + 'url_update_manager', + 'https://licensing.artica.es/pandoraupdate7/server.php' + ); } if (defined('METACONSOLE')) { - enterprise_include_once('meta/include/functions_users_meta.php'); - enterprise_hook('set_meta_user_language'); + enterprise_include_once('meta/include/functions_users_meta.php'); + enterprise_hook('set_meta_user_language'); +} else { + set_user_language(); } -else - set_user_language(); -require_once ($ownDir . 'functions_extensions.php'); +require_once $ownDir.'functions_extensions.php'; -$config['extensions'] = extensions_get_extensions (); +$config['extensions'] = extensions_get_extensions(); // Detect if enterprise extension is installed // NOTICE: This variable (config[enterprise_installed] is used in several // sections. Faking or forcing to 1 will make pandora fails. - -if (file_exists ($config["homedir"] . '/' . ENTERPRISE_DIR . '/index.php')) { - $config['enterprise_installed'] = 1; - enterprise_include_once ('include/functions_enterprise.php'); -} -else { - $config['enterprise_installed'] = 0; +if (file_exists($config['homedir'].'/'.ENTERPRISE_DIR.'/index.php')) { + $config['enterprise_installed'] = 1; + enterprise_include_once('include/functions_enterprise.php'); +} else { + $config['enterprise_installed'] = 0; } // Function include_graphs_dependencies() it's called in the code below -require_once("include_graph_dependencies.php"); +require_once 'include_graph_dependencies.php'; -include_graphs_dependencies($config['homedir'] . '/'); +include_graphs_dependencies($config['homedir'].'/'); // Updates autorefresh time if (isset($_POST['vc_refr'])) { - config_update_value ('vc_refr', get_parameter('vc_refr', $config['vc_refr'])); + config_update_value('vc_refr', get_parameter('vc_refr', $config['vc_refr'])); } -//======= Autorefresh code ============================================= -if(isset($config['id_user'])){ - $select = db_process_sql("SELECT autorefresh_white_list FROM tusuario WHERE id_user = '" . $config['id_user'] . "'"); - if(isset($select[0]['value'])){ - $autorefresh_list = json_decode($select[0]['value']); - } - else{ - $autorefresh_list =null; - } - $config['autorefresh_white_list'] = array(); - $config['autorefresh_white_list'] = $autorefresh_list; -} -else{ - $config['autorefresh_white_list'] = null; +// ======= Autorefresh code ============================================= +if (isset($config['id_user'])) { + $select = db_process_sql("SELECT autorefresh_white_list FROM tusuario WHERE id_user = '".$config['id_user']."'"); + if (isset($select[0]['value'])) { + $autorefresh_list = json_decode($select[0]['value']); + } else { + $autorefresh_list = null; + } + + $config['autorefresh_white_list'] = []; + $config['autorefresh_white_list'] = $autorefresh_list; +} else { + $config['autorefresh_white_list'] = null; } + // Specific metaconsole autorefresh white list sections if (defined('METACONSOLE')) { - $config['autorefresh_white_list'][] = 'monitoring/tactical'; - $config['autorefresh_white_list'][] = 'monitoring/group_view'; - $config['autorefresh_white_list'][] = 'operation/tree'; - $config['autorefresh_white_list'][] = 'screens/screens'; + $config['autorefresh_white_list'][] = 'monitoring/tactical'; + $config['autorefresh_white_list'][] = 'monitoring/group_view'; + $config['autorefresh_white_list'][] = 'operation/tree'; + $config['autorefresh_white_list'][] = 'screens/screens'; } -//====================================================================== - - -//====================================================================== +// ====================================================================== +// ====================================================================== // Update the $config['homeurl'] with the full url with the special // cases (reverse proxy, others ports...). -//====================================================================== -$config["homeurl"] = ui_get_full_url(false); +// ====================================================================== +$config['homeurl'] = ui_get_full_url(false); -//====================================================================== +// ====================================================================== // Get the version of DB manager -//====================================================================== -switch ($config["dbtype"]) { - case "mysql": - if (!isset($config['quote_string'])) { - $config['db_quote_string'] = "\""; - } - break; - case "postgresql": - if (!isset($config['dbversion'])) { - $result = db_get_sql("select version();"); - $result_chunks = explode(" ", $result); - - $config['dbversion'] = $result_chunks[1]; - } - if (!isset($config['quote_string'])) { - $config['db_quote_string'] = "'"; - } - break; - case "oracle": - if (!isset($config['quote_string'])) { - $config['db_quote_string'] = "'"; - } - break; +// ====================================================================== +switch ($config['dbtype']) { + case 'mysql': + if (!isset($config['quote_string'])) { + $config['db_quote_string'] = '"'; + } + break; + + case 'postgresql': + if (!isset($config['dbversion'])) { + $result = db_get_sql('select version();'); + $result_chunks = explode(' ', $result); + + $config['dbversion'] = $result_chunks[1]; + } + + if (!isset($config['quote_string'])) { + $config['db_quote_string'] = "'"; + } + break; + + case 'oracle': + if (!isset($config['quote_string'])) { + $config['db_quote_string'] = "'"; + } + break; } -//====================================================================== -?> + +// ====================================================================== diff --git a/pandora_console/include/constants.php b/pandora_console/include/constants.php index 7ce0d2df69..ce7b91735c 100644 --- a/pandora_console/include/constants.php +++ b/pandora_console/include/constants.php @@ -3,551 +3,554 @@ // ================================================== // Copyright (c) 2005-2012 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. /** - * @package Include + * @package Include * @subpackage Constants */ -/* Enterprise hook constant */ -define ('ENTERPRISE_NOT_HOOK', -1); +// Enterprise hook constant +define('ENTERPRISE_NOT_HOOK', -1); -/* Others */ +// Others define('GROUP_ALL', 0); -/* Date and time formats */ -define('DATE_FORMAT', 'Y/m/d'); -define('DATE_FORMAT_JS', 'yy/mm/dd'); -define('TIME_FORMAT', 'H:i:s'); -define('TIME_FORMAT_JS', 'HH:mm:ss'); +// Date and time formats +define('DATE_FORMAT', 'Y/m/d'); +define('DATE_FORMAT_JS', 'yy/mm/dd'); +define('TIME_FORMAT', 'H:i:s'); +define('TIME_FORMAT_JS', 'HH:mm:ss'); -/* Events state constants */ -define ('EVENT_NEW', 0); -define ('EVENT_VALIDATE', 1); -define ('EVENT_PROCESS', 2); +// Events state constants +define('EVENT_NEW', 0); +define('EVENT_VALIDATE', 1); +define('EVENT_PROCESS', 2); -/* Agents disabled status */ -define ('AGENT_ENABLED', 0); -define ('AGENT_DISABLED', 1); +// Agents disabled status +define('AGENT_ENABLED', 0); +define('AGENT_DISABLED', 1); -/* Error report codes */ -define ('NOERR', 11111); -define ('ERR_GENERIC', -10000); -define ('ERR_EXIST', -20000); -define ('ERR_INCOMPLETE', -30000); -define ('ERR_DB', -40000); -define ('ERR_DB_HOST', -40001); -define ('ERR_DB_DB', -40002); -define ('ERR_FILE', -50000); -define ('ERR_NOCHANGES', -60000); -define ('ERR_NODATA', -70000); -define ('ERR_CONNECTION', -80000); -define ('ERR_DISABLED', -90000); -define ('ERR_WRONG', -100000); -define ('ERR_WRONG_NAME', -100001); -define ('ERR_WRONG_PARAMETERS', -100002); -define ('ERR_ACL', -110000); -define ('ERR_AUTH', -120000); -define ('ERR_COULDNT_RESOLVE_HOST', -130000); +// Error report codes +define('NOERR', 11111); +define('ERR_GENERIC', -10000); +define('ERR_EXIST', -20000); +define('ERR_INCOMPLETE', -30000); +define('ERR_DB', -40000); +define('ERR_DB_HOST', -40001); +define('ERR_DB_DB', -40002); +define('ERR_FILE', -50000); +define('ERR_NOCHANGES', -60000); +define('ERR_NODATA', -70000); +define('ERR_CONNECTION', -80000); +define('ERR_DISABLED', -90000); +define('ERR_WRONG', -100000); +define('ERR_WRONG_NAME', -100001); +define('ERR_WRONG_PARAMETERS', -100002); +define('ERR_ACL', -110000); +define('ERR_AUTH', -120000); +define('ERR_COULDNT_RESOLVE_HOST', -130000); -/* Event status code */ -define ('EVENT_STATUS_NEW', 0); -define ('EVENT_STATUS_INPROCESS', 2); -define ('EVENT_STATUS_VALIDATED', 1); +// Event status code +define('EVENT_STATUS_NEW', 0); +define('EVENT_STATUS_INPROCESS', 2); +define('EVENT_STATUS_VALIDATED', 1); -/* Seconds in a time unit constants */ -define('SECONDS_1MINUTE', 60); -define('SECONDS_2MINUTES', 120); -define('SECONDS_5MINUTES', 300); -define('SECONDS_10MINUTES', 600); -define('SECONDS_15MINUTES', 900); -define('SECONDS_30MINUTES', 1800); -define('SECONDS_1HOUR', 3600); -define('SECONDS_2HOUR', 7200); -define('SECONDS_3HOUR', 10800); -define('SECONDS_5HOUR', 18000); -define('SECONDS_6HOURS', 21600); -define('SECONDS_12HOURS', 43200); -define('SECONDS_1DAY', 86400); -define('SECONDS_2DAY', 172800); -define('SECONDS_4DAY', 345600); -define('SECONDS_5DAY', 432000); -define('SECONDS_1WEEK', 604800); -define('SECONDS_10DAY', 864000); -define('SECONDS_2WEEK', 1209600); -define('SECONDS_15DAYS', 1296000); -define('SECONDS_1MONTH', 2592000); -define('SECONDS_2MONTHS', 5184000); -define('SECONDS_3MONTHS', 7776000); -define('SECONDS_6MONTHS', 15552000); -define('SECONDS_1YEAR', 31104000); -define('SECONDS_2YEARS', 62208000); -define('SECONDS_3YEARS', 93312000); +// Seconds in a time unit constants +define('SECONDS_1MINUTE', 60); +define('SECONDS_2MINUTES', 120); +define('SECONDS_5MINUTES', 300); +define('SECONDS_10MINUTES', 600); +define('SECONDS_15MINUTES', 900); +define('SECONDS_30MINUTES', 1800); +define('SECONDS_1HOUR', 3600); +define('SECONDS_2HOUR', 7200); +define('SECONDS_3HOUR', 10800); +define('SECONDS_5HOUR', 18000); +define('SECONDS_6HOURS', 21600); +define('SECONDS_12HOURS', 43200); +define('SECONDS_1DAY', 86400); +define('SECONDS_2DAY', 172800); +define('SECONDS_4DAY', 345600); +define('SECONDS_5DAY', 432000); +define('SECONDS_1WEEK', 604800); +define('SECONDS_10DAY', 864000); +define('SECONDS_2WEEK', 1209600); +define('SECONDS_15DAYS', 1296000); +define('SECONDS_1MONTH', 2592000); +define('SECONDS_2MONTHS', 5184000); +define('SECONDS_3MONTHS', 7776000); +define('SECONDS_6MONTHS', 15552000); +define('SECONDS_1YEAR', 31104000); +define('SECONDS_2YEARS', 62208000); +define('SECONDS_3YEARS', 93312000); -/* Separator constats */ -define('SEPARATOR_COLUMN', ';'); -define('SEPARATOR_ROW', chr(10)); //chr(10) = '\n' -define('SEPARATOR_COLUMN_CSV', "#"); -define('SEPARATOR_ROW_CSV', "@\n"); +// Separator constats +define('SEPARATOR_COLUMN', ';'); +define('SEPARATOR_ROW', chr(10)); +// chr(10) = '\n' +define('SEPARATOR_COLUMN_CSV', '#'); +define('SEPARATOR_ROW_CSV', "@\n"); -/* Backup paths */ -switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - define ('BACKUP_DIR', 'attachment/backups'); - define ('BACKUP_FULLPATH', $config['homedir'] . '/' . BACKUP_DIR); - break; - case "oracle": - define ('BACKUP_DIR', 'DATA_PUMP_DIR'); - define ('BACKUP_FULLPATH', 'DATA_PUMP_DIR'); - break; +// Backup paths +switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + define('BACKUP_DIR', 'attachment/backups'); + define('BACKUP_FULLPATH', $config['homedir'].'/'.BACKUP_DIR); + break; + + case 'oracle': + define('BACKUP_DIR', 'DATA_PUMP_DIR'); + define('BACKUP_FULLPATH', 'DATA_PUMP_DIR'); + break; } -/* Color constants */ -define('COL_CRITICAL', '#FC4444'); -define('COL_WARNING', '#FAD403'); -define('COL_WARNING_DARK', '#FFB900'); -define('COL_NORMAL', '#80BA27'); -define('COL_NOTINIT', '#3BA0FF'); -define('COL_UNKNOWN', '#B2B2B2'); -define('COL_DOWNTIME', '#976DB1'); -define('COL_IGNORED', '#DDD'); -define('COL_ALERTFIRED', '#FFA631'); -define('COL_MINOR', '#F099A2'); -define('COL_MAJOR', '#C97A4A'); -define('COL_INFORMATIONAL', '#E4E4E4'); -define('COL_MAINTENANCE', '#3BA0FF'); +// Color constants +define('COL_CRITICAL', '#FC4444'); +define('COL_WARNING', '#FAD403'); +define('COL_WARNING_DARK', '#FFB900'); +define('COL_NORMAL', '#80BA27'); +define('COL_NOTINIT', '#3BA0FF'); +define('COL_UNKNOWN', '#B2B2B2'); +define('COL_DOWNTIME', '#976DB1'); +define('COL_IGNORED', '#DDD'); +define('COL_ALERTFIRED', '#FFA631'); +define('COL_MINOR', '#F099A2'); +define('COL_MAJOR', '#C97A4A'); +define('COL_INFORMATIONAL', '#E4E4E4'); +define('COL_MAINTENANCE', '#3BA0FF'); -define('COL_GRAPH1', '#C397F2'); -define('COL_GRAPH2', '#FFE66C'); -define('COL_GRAPH3', '#92CCA3'); -define('COL_GRAPH4', '#EA6D5B'); -define('COL_GRAPH5', '#6BD8DD'); -define('COL_GRAPH6', '#F49B31'); -define('COL_GRAPH7', '#999999'); -define('COL_GRAPH8', '#F2B8C1'); -define('COL_GRAPH9', '#C4E8C1'); -define('COL_GRAPH10', '#C1DBE5'); -define('COL_GRAPH11', '#C9C1e0'); -define('COL_GRAPH12', '#F45B95'); -define('COL_GRAPH13', '#E83128'); +define('COL_GRAPH1', '#C397F2'); +define('COL_GRAPH2', '#FFE66C'); +define('COL_GRAPH3', '#92CCA3'); +define('COL_GRAPH4', '#EA6D5B'); +define('COL_GRAPH5', '#6BD8DD'); +define('COL_GRAPH6', '#F49B31'); +define('COL_GRAPH7', '#999999'); +define('COL_GRAPH8', '#F2B8C1'); +define('COL_GRAPH9', '#C4E8C1'); +define('COL_GRAPH10', '#C1DBE5'); +define('COL_GRAPH11', '#C9C1e0'); +define('COL_GRAPH12', '#F45B95'); +define('COL_GRAPH13', '#E83128'); -/* The styles */ -/* Size of text in characters for truncate */ -define('GENERIC_SIZE_TEXT', 50); +/* + The styles */ +// Size of text in characters for truncate +define('GENERIC_SIZE_TEXT', 50); -/* Agent module status */ -define('AGENT_MODULE_STATUS_ALL', -1); -define('AGENT_MODULE_STATUS_CRITICAL_BAD', 1); -define('AGENT_MODULE_STATUS_CRITICAL_ALERT', 100); -define('AGENT_MODULE_STATUS_NO_DATA', 4); -define('AGENT_MODULE_STATUS_NORMAL', 0); -define('AGENT_MODULE_STATUS_NORMAL_ALERT', 300); -define('AGENT_MODULE_STATUS_NOT_NORMAL', 6); -define('AGENT_MODULE_STATUS_WARNING', 2); -define('AGENT_MODULE_STATUS_WARNING_ALERT', 200); -define('AGENT_MODULE_STATUS_UNKNOWN', 3); -define('AGENT_MODULE_STATUS_NOT_INIT', 5); +// Agent module status +define('AGENT_MODULE_STATUS_ALL', -1); +define('AGENT_MODULE_STATUS_CRITICAL_BAD', 1); +define('AGENT_MODULE_STATUS_CRITICAL_ALERT', 100); +define('AGENT_MODULE_STATUS_NO_DATA', 4); +define('AGENT_MODULE_STATUS_NORMAL', 0); +define('AGENT_MODULE_STATUS_NORMAL_ALERT', 300); +define('AGENT_MODULE_STATUS_NOT_NORMAL', 6); +define('AGENT_MODULE_STATUS_WARNING', 2); +define('AGENT_MODULE_STATUS_WARNING_ALERT', 200); +define('AGENT_MODULE_STATUS_UNKNOWN', 3); +define('AGENT_MODULE_STATUS_NOT_INIT', 5); -/* Agent status */ -define('AGENT_STATUS_ALL', -1); -define('AGENT_STATUS_CRITICAL', 1); -define('AGENT_STATUS_NORMAL', 0); -define('AGENT_STATUS_NOT_INIT', 5); -define('AGENT_STATUS_NOT_NORMAL', 6); -define('AGENT_STATUS_UNKNOWN', 3); -define('AGENT_STATUS_ALERT_FIRED', 4); -define('AGENT_STATUS_WARNING', 2); +// Agent status +define('AGENT_STATUS_ALL', -1); +define('AGENT_STATUS_CRITICAL', 1); +define('AGENT_STATUS_NORMAL', 0); +define('AGENT_STATUS_NOT_INIT', 5); +define('AGENT_STATUS_NOT_NORMAL', 6); +define('AGENT_STATUS_UNKNOWN', 3); +define('AGENT_STATUS_ALERT_FIRED', 4); +define('AGENT_STATUS_WARNING', 2); -/* Visual maps contants */ -//The items kind -define('STATIC_GRAPH', 0); -define('PERCENTILE_BAR', 3); -define('MODULE_GRAPH', 1); -define('AUTO_SLA_GRAPH', 14); -define('SIMPLE_VALUE', 2); -define('LABEL', 4); -define('ICON', 5); -define('SIMPLE_VALUE_MAX', 6); -define('SIMPLE_VALUE_MIN', 7); -define('SIMPLE_VALUE_AVG', 8); -define('PERCENTILE_BUBBLE', 9); -define('SERVICE', 10); //Enterprise Item. -define('GROUP_ITEM', 11); -define('BOX_ITEM', 12); -define('LINE_ITEM', 13); +/* + Visual maps contants */ +// The items kind +define('STATIC_GRAPH', 0); +define('PERCENTILE_BAR', 3); +define('MODULE_GRAPH', 1); +define('AUTO_SLA_GRAPH', 14); +define('SIMPLE_VALUE', 2); +define('LABEL', 4); +define('ICON', 5); +define('SIMPLE_VALUE_MAX', 6); +define('SIMPLE_VALUE_MIN', 7); +define('SIMPLE_VALUE_AVG', 8); +define('PERCENTILE_BUBBLE', 9); +define('SERVICE', 10); +// Enterprise Item. +define('GROUP_ITEM', 11); +define('BOX_ITEM', 12); +define('LINE_ITEM', 13); define('CIRCULAR_PROGRESS_BAR', 15); define('CIRCULAR_INTERIOR_PROGRESS_BAR', 16); -define('DONUT_GRAPH', 17); -define('BARS_GRAPH', 18); -define('CLOCK', 19); -//Some styles -define('MIN_WIDTH', 300); -define('MIN_HEIGHT', 120); -define('MIN_WIDTH_CAPTION', 420); -//The process for simple value -define('PROCESS_VALUE_NONE', 0); -define('PROCESS_VALUE_MIN', 1); -define('PROCESS_VALUE_MAX', 2); -define('PROCESS_VALUE_AVG', 3); -//Status -define('VISUAL_MAP_STATUS_CRITICAL_BAD', 1); -define('VISUAL_MAP_STATUS_CRITICAL_ALERT', 4); -define('VISUAL_MAP_STATUS_NORMAL', 0); -define('VISUAL_MAP_STATUS_WARNING', 2); -define('VISUAL_MAP_STATUS_UNKNOWN', 3); -define('VISUAL_MAP_STATUS_WARNING_ALERT', 10); -//Wizard -define('VISUAL_MAP_WIZARD_PARENTS_NONE', 0); -define('VISUAL_MAP_WIZARD_PARENTS_ITEM_MAP', 1); -define('VISUAL_MAP_WIZARD_PARENTS_AGENT_RELANTIONSHIP', 2); +define('DONUT_GRAPH', 17); +define('BARS_GRAPH', 18); +define('CLOCK', 19); +define('COLOR_CLOUD', 20); +// Some styles +define('MIN_WIDTH', 300); +define('MIN_HEIGHT', 120); +define('MIN_WIDTH_CAPTION', 420); +// The process for simple value +define('PROCESS_VALUE_NONE', 0); +define('PROCESS_VALUE_MIN', 1); +define('PROCESS_VALUE_MAX', 2); +define('PROCESS_VALUE_AVG', 3); +// Status +define('VISUAL_MAP_STATUS_CRITICAL_BAD', 1); +define('VISUAL_MAP_STATUS_CRITICAL_ALERT', 4); +define('VISUAL_MAP_STATUS_NORMAL', 0); +define('VISUAL_MAP_STATUS_WARNING', 2); +define('VISUAL_MAP_STATUS_UNKNOWN', 3); +define('VISUAL_MAP_STATUS_WARNING_ALERT', 10); +// Wizard +define('VISUAL_MAP_WIZARD_PARENTS_NONE', 0); +define('VISUAL_MAP_WIZARD_PARENTS_ITEM_MAP', 1); +define('VISUAL_MAP_WIZARD_PARENTS_AGENT_RELANTIONSHIP', 2); -/* Service constants */ -//Status -define('SERVICE_STATUS_UNKNOWN', -1); -define('SERVICE_STATUS_NORMAL', 0); -define('SERVICE_STATUS_CRITICAL', 1); -define('SERVICE_STATUS_WARNING', 2); -define('SERVICE_STATUS_ALERT', 4); -//Default weights -define('SERVICE_WEIGHT_CRITICAL', 1); -define('SERVICE_WEIGHT_WARNING', 0.5); -define('SERVICE_ELEMENT_WEIGHT_CRITICAL', 1); -define('SERVICE_ELEMENT_WEIGHT_WARNING', 0.5); -define('SERVICE_ELEMENT_WEIGHT_OK', 0); -define('SERVICE_ELEMENT_WEIGHT_UNKNOWN', 0); -//Modes -define('SERVICE_MODE_MANUAL', 0); -define('SERVICE_MODE_AUTO', 1); -define('SERVICE_MODE_SIMPLE', 2); +/* + Service constants */ +// Status +define('SERVICE_STATUS_UNKNOWN', -1); +define('SERVICE_STATUS_NORMAL', 0); +define('SERVICE_STATUS_CRITICAL', 1); +define('SERVICE_STATUS_WARNING', 2); +define('SERVICE_STATUS_ALERT', 4); +// Default weights +define('SERVICE_WEIGHT_CRITICAL', 1); +define('SERVICE_WEIGHT_WARNING', 0.5); +define('SERVICE_ELEMENT_WEIGHT_CRITICAL', 1); +define('SERVICE_ELEMENT_WEIGHT_WARNING', 0.5); +define('SERVICE_ELEMENT_WEIGHT_OK', 0); +define('SERVICE_ELEMENT_WEIGHT_UNKNOWN', 0); +// Modes +define('SERVICE_MODE_MANUAL', 0); +define('SERVICE_MODE_AUTO', 1); +define('SERVICE_MODE_SIMPLE', 2); -/* Status images */ -//For modules -define ('STATUS_MODULE_OK', 'module_ok.png'); -define ('STATUS_MODULE_CRITICAL', 'module_critical.png'); -define ('STATUS_MODULE_WARNING', 'module_warning.png'); -define ('STATUS_MODULE_NO_DATA', 'module_no_data.png'); -define ('STATUS_MODULE_UNKNOWN', 'module_unknown.png'); -//For agents -define ('STATUS_AGENT_CRITICAL', 'agent_critical.png'); -define ('STATUS_AGENT_WARNING', 'agent_warning.png'); -define ('STATUS_AGENT_DOWN', 'agent_down.png'); -define ('STATUS_AGENT_UNKNOWN', 'agent_unknown.png'); -define ('STATUS_AGENT_OK', 'agent_ok.png'); -define ('STATUS_AGENT_NO_DATA', 'agent_no_data.png'); -define ('STATUS_AGENT_NO_MONITORS', 'agent_no_monitors.png'); -define ('STATUS_AGENT_NOT_INIT', 'agent_notinit.png'); -//For alerts -define ('STATUS_ALERT_FIRED', 'alert_fired.png'); -define ('STATUS_ALERT_NOT_FIRED', 'alert_not_fired.png'); -define ('STATUS_ALERT_DISABLED', 'alert_disabled.png'); -//For servers -define ('STATUS_SERVER_OK', 'server_ok.png'); -define ('STATUS_SERVER_DOWN', 'server_down.png'); +/* + Status images */ +// For modules +define('STATUS_MODULE_OK', 'module_ok.png'); +define('STATUS_MODULE_CRITICAL', 'module_critical.png'); +define('STATUS_MODULE_WARNING', 'module_warning.png'); +define('STATUS_MODULE_NO_DATA', 'module_no_data.png'); +define('STATUS_MODULE_UNKNOWN', 'module_unknown.png'); +// For agents +define('STATUS_AGENT_CRITICAL', 'agent_critical.png'); +define('STATUS_AGENT_WARNING', 'agent_warning.png'); +define('STATUS_AGENT_DOWN', 'agent_down.png'); +define('STATUS_AGENT_UNKNOWN', 'agent_unknown.png'); +define('STATUS_AGENT_OK', 'agent_ok.png'); +define('STATUS_AGENT_NO_DATA', 'agent_no_data.png'); +define('STATUS_AGENT_NO_MONITORS', 'agent_no_monitors.png'); +define('STATUS_AGENT_NOT_INIT', 'agent_notinit.png'); +// For alerts +define('STATUS_ALERT_FIRED', 'alert_fired.png'); +define('STATUS_ALERT_NOT_FIRED', 'alert_not_fired.png'); +define('STATUS_ALERT_DISABLED', 'alert_disabled.png'); +// For servers +define('STATUS_SERVER_OK', 'server_ok.png'); +define('STATUS_SERVER_DOWN', 'server_down.png'); -/* Status images (ball) */ -//For modules -define ('STATUS_MODULE_OK_BALL', 'module_ok_ball.png'); -define ('STATUS_MODULE_CRITICAL_BALL', 'module_critical_ball.png'); -define ('STATUS_MODULE_WARNING_BALL', 'module_warning_ball.png'); -define ('STATUS_MODULE_NO_DATA_BALL', 'module_no_data_ball.png'); -define ('STATUS_MODULE_UNKNOWN_BALL', 'module_unknown_ball.png'); -//For agents -define ('STATUS_AGENT_CRITICAL_BALL', 'agent_critical_ball.png'); -define ('STATUS_AGENT_WARNING_BALL', 'agent_warning_ball.png'); -define ('STATUS_AGENT_DOWN_BALL', 'agent_down_ball.png'); -define ('STATUS_AGENT_UNKNOWN_BALL', 'agent_unknown_ball.png'); -define ('STATUS_AGENT_OK_BALL', 'agent_ok_ball.png'); -define ('STATUS_AGENT_NO_DATA_BALL', 'agent_no_data_ball.png'); -define ('STATUS_AGENT_NO_MONITORS_BALL', 'agent_no_monitors_ball.png'); -define ('STATUS_AGENT_NOT_INIT_BALL', 'agent_notinit_ball.png'); -//For alerts -define ('STATUS_ALERT_FIRED_BALL', 'alert_fired_ball.png'); -define ('STATUS_ALERT_NOT_FIRED_BALL', 'alert_not_fired_ball.png'); -define ('STATUS_ALERT_DISABLED_BALL', 'alert_disabled_ball.png'); -//For servers -define ('STATUS_SERVER_OK_BALL', 'server_ok_ball.png'); -define ('STATUS_SERVER_DOWN_BALL', 'server_down_ball.png'); +/* + Status images (ball) */ +// For modules +define('STATUS_MODULE_OK_BALL', 'module_ok_ball.png'); +define('STATUS_MODULE_CRITICAL_BALL', 'module_critical_ball.png'); +define('STATUS_MODULE_WARNING_BALL', 'module_warning_ball.png'); +define('STATUS_MODULE_NO_DATA_BALL', 'module_no_data_ball.png'); +define('STATUS_MODULE_UNKNOWN_BALL', 'module_unknown_ball.png'); +// For agents +define('STATUS_AGENT_CRITICAL_BALL', 'agent_critical_ball.png'); +define('STATUS_AGENT_WARNING_BALL', 'agent_warning_ball.png'); +define('STATUS_AGENT_DOWN_BALL', 'agent_down_ball.png'); +define('STATUS_AGENT_UNKNOWN_BALL', 'agent_unknown_ball.png'); +define('STATUS_AGENT_OK_BALL', 'agent_ok_ball.png'); +define('STATUS_AGENT_NO_DATA_BALL', 'agent_no_data_ball.png'); +define('STATUS_AGENT_NO_MONITORS_BALL', 'agent_no_monitors_ball.png'); +define('STATUS_AGENT_NOT_INIT_BALL', 'agent_notinit_ball.png'); +// For alerts +define('STATUS_ALERT_FIRED_BALL', 'alert_fired_ball.png'); +define('STATUS_ALERT_NOT_FIRED_BALL', 'alert_not_fired_ball.png'); +define('STATUS_ALERT_DISABLED_BALL', 'alert_disabled_ball.png'); +// For servers +define('STATUS_SERVER_OK_BALL', 'server_ok_ball.png'); +define('STATUS_SERVER_DOWN_BALL', 'server_down_ball.png'); -/* Events criticity */ -define ('EVENT_CRIT_MAINTENANCE', 0); -define ('EVENT_CRIT_INFORMATIONAL', 1); -define ('EVENT_CRIT_NORMAL', 2); -define ('EVENT_CRIT_MINOR', 5); -define ('EVENT_CRIT_WARNING', 3); -define ('EVENT_CRIT_MAJOR', 6); -define ('EVENT_CRIT_CRITICAL', 4); -define ('EVENT_CRIT_WARNING_OR_CRITICAL', 34); -define ('EVENT_CRIT_NOT_NORMAL', 20); -define ('EVENT_CRIT_OR_NORMAL', 21); +// Events criticity +define('EVENT_CRIT_MAINTENANCE', 0); +define('EVENT_CRIT_INFORMATIONAL', 1); +define('EVENT_CRIT_NORMAL', 2); +define('EVENT_CRIT_MINOR', 5); +define('EVENT_CRIT_WARNING', 3); +define('EVENT_CRIT_MAJOR', 6); +define('EVENT_CRIT_CRITICAL', 4); +define('EVENT_CRIT_WARNING_OR_CRITICAL', 34); +define('EVENT_CRIT_NOT_NORMAL', 20); +define('EVENT_CRIT_OR_NORMAL', 21); -/* Id Module (more use in component)*/ -define ('MODULE_DATA', 1); -define ('MODULE_NETWORK', 2); -define ('MODULE_SNMP', 2); -define ('MODULE_PLUGIN', 4); -define ('MODULE_PREDICTION', 5); -define ('MODULE_WMI', 6); -define ('MODULE_WEB', 7); -define ('MODULE_WUX', 8); +// Id Module (more use in component) +define('MODULE_DATA', 1); +define('MODULE_NETWORK', 2); +define('MODULE_SNMP', 2); +define('MODULE_PLUGIN', 4); +define('MODULE_PREDICTION', 5); +define('MODULE_WMI', 6); +define('MODULE_WEB', 7); +define('MODULE_WUX', 8); -/* Type of Modules of Prediction */ -define ('MODULE_PREDICTION_SERVICE', 2); -define ('MODULE_PREDICTION_SYNTHETIC', 3); -define ('MODULE_PREDICTION_NETFLOW', 4); -define ('MODULE_PREDICTION_CLUSTER', 5); -define ('MODULE_PREDICTION_CLUSTER_AA', 6); -define ('MODULE_PREDICTION_CLUSTER_AP', 7); +// Type of Modules of Prediction +define('MODULE_PREDICTION_SERVICE', 2); +define('MODULE_PREDICTION_SYNTHETIC', 3); +define('MODULE_PREDICTION_NETFLOW', 4); +define('MODULE_PREDICTION_CLUSTER', 5); +define('MODULE_PREDICTION_CLUSTER_AA', 6); +define('MODULE_PREDICTION_CLUSTER_AP', 7); -/* SNMP CONSTANTS */ -define('SNMP_DIR_MIBS', "attachment/mibs"); +// SNMP CONSTANTS +define('SNMP_DIR_MIBS', 'attachment/mibs'); -define('SNMP_TRAP_TYPE_NONE', -1); -define('SNMP_TRAP_TYPE_COLD_START', 0); -define('SNMP_TRAP_TYPE_WARM_START', 1); -define('SNMP_TRAP_TYPE_LINK_DOWN', 2); -define('SNMP_TRAP_TYPE_LINK_UP', 3); -define('SNMP_TRAP_TYPE_AUTHENTICATION_FAILURE', 4); -define('SNMP_TRAP_TYPE_OTHER', 5); +define('SNMP_TRAP_TYPE_NONE', -1); +define('SNMP_TRAP_TYPE_COLD_START', 0); +define('SNMP_TRAP_TYPE_WARM_START', 1); +define('SNMP_TRAP_TYPE_LINK_DOWN', 2); +define('SNMP_TRAP_TYPE_LINK_UP', 3); +define('SNMP_TRAP_TYPE_AUTHENTICATION_FAILURE', 4); +define('SNMP_TRAP_TYPE_OTHER', 5); -/* PASSWORD POLICIES */ -define('PASSSWORD_POLICIES_OK', 0); -define('PASSSWORD_POLICIES_FIRST_CHANGE', 1); -define('PASSSWORD_POLICIES_EXPIRED', 2); +// PASSWORD POLICIES +define('PASSSWORD_POLICIES_OK', 0); +define('PASSSWORD_POLICIES_FIRST_CHANGE', 1); +define('PASSSWORD_POLICIES_EXPIRED', 2); -/* SERVER TYPES */ -define('SERVER_TYPE_DATA', 0); -define('SERVER_TYPE_NETWORK', 1); -define('SERVER_TYPE_SNMP', 2); -define('SERVER_TYPE_RECON', 3); -define('SERVER_TYPE_PLUGIN', 4); -define('SERVER_TYPE_PREDICTION', 5); -define('SERVER_TYPE_WMI', 6); -define('SERVER_TYPE_EXPORT', 7); -define('SERVER_TYPE_INVENTORY', 8); -define('SERVER_TYPE_WEB', 9); -define('SERVER_TYPE_EVENT', 10); -define('SERVER_TYPE_ENTERPRISE_ICMP', 11); -define('SERVER_TYPE_ENTERPRISE_SNMP', 12); -define('SERVER_TYPE_ENTERPRISE_SATELLITE', 13); -define('SERVER_TYPE_ENTERPRISE_TRANSACTIONAL', 14); -define('SERVER_TYPE_MAINFRAME', 15); -define('SERVER_TYPE_SYNC', 16); -define('SERVER_TYPE_WUX', 17); -define('SERVER_TYPE_SYSLOG', 18); -define('SERVER_TYPE_AUTOPROVISION', 19); -define('SERVER_TYPE_MIGRATION', 20); +// SERVER TYPES +define('SERVER_TYPE_DATA', 0); +define('SERVER_TYPE_NETWORK', 1); +define('SERVER_TYPE_SNMP', 2); +define('SERVER_TYPE_RECON', 3); +define('SERVER_TYPE_PLUGIN', 4); +define('SERVER_TYPE_PREDICTION', 5); +define('SERVER_TYPE_WMI', 6); +define('SERVER_TYPE_EXPORT', 7); +define('SERVER_TYPE_INVENTORY', 8); +define('SERVER_TYPE_WEB', 9); +define('SERVER_TYPE_EVENT', 10); +define('SERVER_TYPE_ENTERPRISE_ICMP', 11); +define('SERVER_TYPE_ENTERPRISE_SNMP', 12); +define('SERVER_TYPE_ENTERPRISE_SATELLITE', 13); +define('SERVER_TYPE_ENTERPRISE_TRANSACTIONAL', 14); +define('SERVER_TYPE_MAINFRAME', 15); +define('SERVER_TYPE_SYNC', 16); +define('SERVER_TYPE_WUX', 17); +define('SERVER_TYPE_SYSLOG', 18); +define('SERVER_TYPE_AUTOPROVISION', 19); +define('SERVER_TYPE_MIGRATION', 20); -/* REPORTS */ -define('REPORT_TOP_N_MAX', 1); -define('REPORT_TOP_N_MIN', 2); -define('REPORT_TOP_N_AVG', 0); +// REPORTS +define('REPORT_TOP_N_MAX', 1); +define('REPORT_TOP_N_MIN', 2); +define('REPORT_TOP_N_AVG', 0); -define('REPORT_TOP_N_ONLY_GRAPHS', 2); -define('REPORT_TOP_N_SHOW_TABLE_GRAPS', 1); -define('REPORT_TOP_N_ONLY_TABLE', 0); +define('REPORT_TOP_N_ONLY_GRAPHS', 2); +define('REPORT_TOP_N_SHOW_TABLE_GRAPS', 1); +define('REPORT_TOP_N_ONLY_TABLE', 0); -define('REPORT_EXCEPTION_CONDITION_EVERYTHING', 0); -define('REPORT_EXCEPTION_CONDITION_GE', 1); -define('REPORT_EXCEPTION_CONDITION_LE', 5); -define('REPORT_EXCEPTION_CONDITION_L', 2); -define('REPORT_EXCEPTION_CONDITION_G', 6); -define('REPORT_EXCEPTION_CONDITION_E', 7); -define('REPORT_EXCEPTION_CONDITION_NE', 8); -define('REPORT_EXCEPTION_CONDITION_OK', 3); -define('REPORT_EXCEPTION_CONDITION_NOT_OK', 4); +define('REPORT_EXCEPTION_CONDITION_EVERYTHING', 0); +define('REPORT_EXCEPTION_CONDITION_GE', 1); +define('REPORT_EXCEPTION_CONDITION_LE', 5); +define('REPORT_EXCEPTION_CONDITION_L', 2); +define('REPORT_EXCEPTION_CONDITION_G', 6); +define('REPORT_EXCEPTION_CONDITION_E', 7); +define('REPORT_EXCEPTION_CONDITION_NE', 8); +define('REPORT_EXCEPTION_CONDITION_OK', 3); +define('REPORT_EXCEPTION_CONDITION_NOT_OK', 4); -define('REPORT_ITEM_ORDER_BY_AGENT_NAME', 3); -define('REPORT_ITEM_ORDER_BY_ASCENDING', 2); -define('REPORT_ITEM_ORDER_BY_DESCENDING', 1); -define('REPORT_ITEM_ORDER_BY_UNSORT', 0); +define('REPORT_ITEM_ORDER_BY_AGENT_NAME', 3); +define('REPORT_ITEM_ORDER_BY_ASCENDING', 2); +define('REPORT_ITEM_ORDER_BY_DESCENDING', 1); +define('REPORT_ITEM_ORDER_BY_UNSORT', 0); -define('REPORT_OLD_TYPE_SIMPLE_GRAPH', 1); -define('REPORT_OLD_TYPE_CUSTOM_GRAPH', 2); -define('REPORT_OLD_TYPE_SLA', 3); -define('REPORT_OLD_TYPE_MONITOR_REPORT', 6); -define('REPORT_OLD_TYPE_AVG_VALUE', 7); -define('REPORT_OLD_TYPE_MAX_VALUE', 8); -define('REPORT_OLD_TYPE_MIN_VALUE', 9); -define('REPORT_OLD_TYPE_SUMATORY', 10); +define('REPORT_OLD_TYPE_SIMPLE_GRAPH', 1); +define('REPORT_OLD_TYPE_CUSTOM_GRAPH', 2); +define('REPORT_OLD_TYPE_SLA', 3); +define('REPORT_OLD_TYPE_MONITOR_REPORT', 6); +define('REPORT_OLD_TYPE_AVG_VALUE', 7); +define('REPORT_OLD_TYPE_MAX_VALUE', 8); +define('REPORT_OLD_TYPE_MIN_VALUE', 9); +define('REPORT_OLD_TYPE_SUMATORY', 10); -define('REPORT_GENERAL_NOT_GROUP_BY_AGENT', 0); -define('REPORT_GENERAL_GROUP_BY_AGENT', 1); +define('REPORT_GENERAL_NOT_GROUP_BY_AGENT', 0); +define('REPORT_GENERAL_GROUP_BY_AGENT', 1); -define('REPORTING_CUSTOM_GRAPH_LEGEND_EACH_MODULE_VERTICAL_SIZE', 15); +define('REPORTING_CUSTOM_GRAPH_LEGEND_EACH_MODULE_VERTICAL_SIZE', 15); -/* POLICIES */ +// POLICIES +define('POLICY_UPDATED', 0); +define('POLICY_PENDING_DATABASE', 1); +define('POLICY_PENDING_ALL', 2); -define("POLICY_UPDATED", 0); -define("POLICY_PENDING_DATABASE", 1); -define("POLICY_PENDING_ALL", 2); +define('STATUS_IN_QUEUE_OUT', 0); +define('STATUS_IN_QUEUE_IN', 1); +define('STATUS_IN_QUEUE_APPLYING', 2); -define("STATUS_IN_QUEUE_OUT", 0); -define("STATUS_IN_QUEUE_IN", 1); -define("STATUS_IN_QUEUE_APPLYING", 2); +define('MODULE_UNLINKED', 0); +define('MODULE_LINKED', 1); +define('MODULE_PENDING_UNLINK', 10); +define('MODULE_PENDING_LINK', 11); -define("MODULE_UNLINKED", 0); -define("MODULE_LINKED", 1); -define("MODULE_PENDING_UNLINK", 10); -define("MODULE_PENDING_LINK", 11); +// EVENTS +define('EVENTS_GOING_UNKNOWN', 'going_unknown'); +define('EVENTS_UNKNOWN', 'unknown'); +define('EVENTS_ALERT_FIRED', 'alert_fired'); +define('EVENTS_ALERT_RECOVERED', 'alert_recovered'); +define('EVENTS_ALERT_CEASED', 'alert_ceased'); +define('EVENTS_ALERT_MANUAL_VALIDATION', 'alert_manual_validation'); +define('EVENTS_RECON_HOST_DETECTED', 'recon_host_detected'); +define('EVENTS_SYSTEM', 'system'); +define('EVENTS_ERROR', 'error'); +define('EVENTS_NEW_AGENT', 'new_agent'); +define('EVENTS_GOING_UP_WARNING', 'going_up_warning'); +define('EVENTS_GOING_UP_CRITICAL', 'going_up_critical'); +define('EVENTS_GOING_DOWN_WARNING', 'going_down_warning'); +define('EVENTS_GOING_DOWN_NORMAL', 'going_down_normal'); +define('EVENTS_GOING_DOWN_CRITICAL', 'going_down_critical'); +define('EVENTS_GOING_UP_NORMAL', 'going_up_normal'); +define('EVENTS_CONFIGURATION_CHANGE', 'configuration_change'); -/* EVENTS */ -define("EVENTS_GOING_UNKNOWN" , 'going_unknown'); -define("EVENTS_UNKNOWN", 'unknown'); -define("EVENTS_ALERT_FIRED", 'alert_fired'); -define("EVENTS_ALERT_RECOVERED", 'alert_recovered'); -define("EVENTS_ALERT_CEASED", 'alert_ceased'); -define("EVENTS_ALERT_MANUAL_VALIDATION", 'alert_manual_validation'); -define("EVENTS_RECON_HOST_DETECTED", 'recon_host_detected'); -define("EVENTS_SYSTEM", 'system'); -define("EVENTS_ERROR", 'error'); -define("EVENTS_NEW_AGENT", 'new_agent'); -define("EVENTS_GOING_UP_WARNING", 'going_up_warning'); -define("EVENTS_GOING_UP_CRITICAL", 'going_up_critical'); -define("EVENTS_GOING_DOWN_WARNING", 'going_down_warning'); -define("EVENTS_GOING_DOWN_NORMAL", 'going_down_normal'); -define("EVENTS_GOING_DOWN_CRITICAL", 'going_down_critical'); -define("EVENTS_GOING_UP_NORMAL", 'going_up_normal'); -define("EVENTS_CONFIGURATION_CHANGE", 'configuration_change'); +// CUSTOM GRAPHS +define('CUSTOM_GRAPH_AREA', 0); +define('CUSTOM_GRAPH_STACKED_AREA', 1); +define('CUSTOM_GRAPH_LINE', 2); +define('CUSTOM_GRAPH_STACKED_LINE', 3); +define('CUSTOM_GRAPH_BULLET_CHART', 4); +define('CUSTOM_GRAPH_GAUGE', 5); +define('CUSTOM_GRAPH_HBARS', 6); +define('CUSTOM_GRAPH_VBARS', 7); +define('CUSTOM_GRAPH_PIE', 8); +define('CUSTOM_GRAPH_BULLET_CHART_THRESHOLD', 9); -/* CUSTOM GRAPHS */ -define("CUSTOM_GRAPH_AREA", 0); -define("CUSTOM_GRAPH_STACKED_AREA", 1); -define("CUSTOM_GRAPH_LINE", 2); -define("CUSTOM_GRAPH_STACKED_LINE", 3); -define("CUSTOM_GRAPH_BULLET_CHART", 4); -define("CUSTOM_GRAPH_GAUGE", 5); -define("CUSTOM_GRAPH_HBARS", 6); -define("CUSTOM_GRAPH_VBARS", 7); -define("CUSTOM_GRAPH_PIE", 8); -define("CUSTOM_GRAPH_BULLET_CHART_THRESHOLD", 9); +// COLLECTIONS +define('COLLECTION_PENDING_APPLY', 0); +define('COLLECTION_CORRECT', 1); +define('COLLECTION_ERROR_LOST_DIRECTORY', 2); +define('COLLECTION_UNSAVED', 3); -/* COLLECTIONS */ -define("COLLECTION_PENDING_APPLY", 0); -define("COLLECTION_CORRECT", 1); -define("COLLECTION_ERROR_LOST_DIRECTORY", 2); -define("COLLECTION_UNSAVED", 3); +// PAGINATION +define('PAGINATION_BLOCKS_LIMIT', 15); -/* PAGINATION */ -define("PAGINATION_BLOCKS_LIMIT", 15); +// CHARTS +define('CHART_DEFAULT_WIDTH', 150); +define('CHART_DEFAULT_HEIGHT', 110); -/* CHARTS */ -define("CHART_DEFAULT_WIDTH", 150); -define("CHART_DEFAULT_HEIGHT", 110); +define('CHART_DEFAULT_ALPHA', 50); -define("CHART_DEFAULT_ALPHA", 50); +// Statwin +define('STATWIN_DEFAULT_CHART_WIDTH', 555); +define('STATWIN_DEFAULT_CHART_HEIGHT', 245); -/* Statwin */ -define("STATWIN_DEFAULT_CHART_WIDTH", 555); -define("STATWIN_DEFAULT_CHART_HEIGHT", 245); +// Dashboard +define('DASHBOARD_DEFAULT_COUNT_CELLS', 1); -/* Dashboard */ -define("DASHBOARD_DEFAULT_COUNT_CELLS", 1); +define('OPTION_TEXT', 1); +define('OPTION_SINGLE_SELECT', 2); +define('OPTION_MULTIPLE_SELECT', 3); +define('OPTION_BOOLEAN', 4); +define('OPTION_TEXTAREA', 5); +define('OPTION_TREE_GROUP_SELECT', 6); +define('OPTION_SINGLE_SELECT_TIME', 7); +define('OPTION_CUSTOM_INPUT', 8); +define('OPTION_AGENT_AUTOCOMPLETE', 9); +define('OPTION_SELECT_MULTISELECTION', 10); +define('OPTION_COLOR_PICKER', 11); -define("OPTION_TEXT", 1); -define("OPTION_SINGLE_SELECT", 2); -define("OPTION_MULTIPLE_SELECT", 3); -define("OPTION_BOOLEAN", 4); -define("OPTION_TEXTAREA", 5); -define("OPTION_TREE_GROUP_SELECT", 6); -define("OPTION_SINGLE_SELECT_TIME", 7); -define("OPTION_CUSTOM_INPUT", 8); -define("OPTION_AGENT_AUTOCOMPLETE", 9); -define("OPTION_SELECT_MULTISELECTION", 10); -define("OPTION_COLOR_PICKER", 11); +// Transactional map constants +define('NODE_TYPE', 0); +define('ARROW_TYPE', 1); -define("DASHBOARD_WIDGET_ID_VISUAL_CONSOLE", 22); +// SAML attributes constants +define('SAML_ROLE_AND_TAG', 'eduPersonEntitlement'); +define('SAML_USER_DESC', 'commonName'); +define('SAML_ID_USER_IN_PANDORA', 'eduPersonTargetedId'); +define('SAML_GROUP_IN_PANDORA', 'schacHomeOrganization'); +define('SAML_MAIL_IN_PANDORA', 'mail'); +define('SAML_DEFAULT_PROFILES_AND_TAGS_FORM', 'urn:mace:rediris.es:entitlement:monitoring:'); -/* Transactional map constants */ -define("NODE_TYPE", 0); -define("ARROW_TYPE", 1); +// Other constants +define('STATUS_OK', 0); +define('STATUS_ERROR', 1); -/* SAML attributes constants */ -define("SAML_ROLE_AND_TAG", "eduPersonEntitlement"); -define("SAML_USER_DESC", "commonName"); -define("SAML_ID_USER_IN_PANDORA", "eduPersonTargetedId"); -define("SAML_GROUP_IN_PANDORA", "schacHomeOrganization"); -define("SAML_MAIL_IN_PANDORA", "mail"); -define("SAML_DEFAULT_PROFILES_AND_TAGS_FORM", "urn:mace:rediris.es:entitlement:monitoring:"); +// Maps (new networkmaps and new visualmaps) +define('MAP_TYPE_NETWORKMAP', 0); +define('MAP_TYPE_VISUALMAP', 1); -/* Other constants */ -define("STATUS_OK", 0); -define("STATUS_ERROR", 1); +define('MAP_REFRESH_TIME', SECONDS_5MINUTES); -/* Maps (new networkmaps and new visualmaps) */ -define("MAP_TYPE_NETWORKMAP", 0); -define("MAP_TYPE_VISUALMAP", 1); +define('MAP_SUBTYPE_TOPOLOGY', 0); +define('MAP_SUBTYPE_POLICIES', 1); +define('MAP_SUBTYPE_GROUPS', 2); +define('MAP_SUBTYPE_RADIAL_DYNAMIC', 3); -define("MAP_REFRESH_TIME", SECONDS_5MINUTES); +define('MAP_GENERATION_CIRCULAR', 0); +define('MAP_GENERATION_PLANO', 1); +define('MAP_GENERATION_RADIAL', 2); +define('MAP_GENERATION_SPRING1', 3); +define('MAP_GENERATION_SPRING2', 4); -define("MAP_SUBTYPE_TOPOLOGY", 0); -define("MAP_SUBTYPE_POLICIES", 1); -define("MAP_SUBTYPE_GROUPS", 2); -define("MAP_SUBTYPE_RADIAL_DYNAMIC", 3); +define('MAP_SOURCE_GROUP', 0); +define('MAP_SOURCE_IP_MASK', 1); -define("MAP_GENERATION_CIRCULAR", 0); -define("MAP_GENERATION_PLANO", 1); -define("MAP_GENERATION_RADIAL", 2); -define("MAP_GENERATION_SPRING1", 3); -define("MAP_GENERATION_SPRING2", 4); +define('NETWORKMAP_DEFAULT_WIDTH', 800); +define('NETWORKMAP_DEFAULT_HEIGHT', 800); -define("MAP_SOURCE_GROUP", 0); -define("MAP_SOURCE_IP_MASK", 1); +// Background options +define('CENTER', 0); +define('MOSAIC', 1); +define('STRECH', 2); +define('FIT_WIDTH', 3); +define('FIT_HEIGH', 4); -define("NETWORKMAP_DEFAULT_WIDTH", 800); -define("NETWORKMAP_DEFAULT_HEIGHT", 800); +// Items of maps +define('ITEM_TYPE_AGENT_NETWORKMAP', 0); +define('ITEM_TYPE_MODULE_NETWORKMAP', 1); +define('ITEM_TYPE_EDGE_NETWORKMAP', 2); +define('ITEM_TYPE_FICTIONAL_NODE', 3); +define('ITEM_TYPE_MODULEGROUP_NETWORKMAP', 4); +define('ITEM_TYPE_GROUP_NETWORKMAP', 5); +define('ITEM_TYPE_POLICY_NETWORKMAP', 6); -/* Background options */ -define("CENTER", 0); -define("MOSAIC", 1); -define("STRECH", 2); -define("FIT_WIDTH", 3); -define("FIT_HEIGH", 4); +// Another constants new networkmap +define('DEFAULT_NODE_WIDTH', 30); +define('DEFAULT_NODE_HEIGHT', 30); +define('DEFAULT_NODE_SHAPE', 'circle'); +define('DEFAULT_NODE_COLOR', COL_NOTINIT); +define('DEFAULT_NODE_IMAGE', 'images/networkmap/unknown.png'); -/* Items of maps */ -define("ITEM_TYPE_AGENT_NETWORKMAP", 0); -define("ITEM_TYPE_MODULE_NETWORKMAP", 1); -define("ITEM_TYPE_EDGE_NETWORKMAP", 2); -define("ITEM_TYPE_FICTIONAL_NODE", 3); -define("ITEM_TYPE_MODULEGROUP_NETWORKMAP", 4); -define("ITEM_TYPE_GROUP_NETWORKMAP", 5); -define("ITEM_TYPE_POLICY_NETWORKMAP", 6); - -/* Another constants new networkmap */ -define("DEFAULT_NODE_WIDTH", 30); -define("DEFAULT_NODE_HEIGHT", 30); -define("DEFAULT_NODE_SHAPE", "circle"); -define("DEFAULT_NODE_COLOR", COL_NOTINIT); -define("DEFAULT_NODE_IMAGE", "images/networkmap/unknown.png"); - -define("NODE_IMAGE_PADDING", 5); -?> +define('NODE_IMAGE_PADDING', 5); diff --git a/pandora_console/include/db/mysql.php b/pandora_console/include/db/mysql.php index 9982ec24fb..49ffb2d101 100644 --- a/pandora_console/include/db/mysql.php +++ b/pandora_console/include/db/mysql.php @@ -4,123 +4,141 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function mysql_connect_db($host=null, $db=null, $user=null, $pass=null, $port=null, $charset=null) +{ + global $config; -function mysql_connect_db($host = null, $db = null, $user = null, $pass = null, $port = null, $charset = null) { - global $config; - - if ($host === null) - $host = $config["dbhost"]; - if ($db === null) - $db = $config["dbname"]; - if ($user === null) - $user = $config["dbuser"]; - if ($pass === null) - $pass = $config["dbpass"]; - if ($port === null) - $port = $config["dbport"]; + if ($host === null) { + $host = $config['dbhost']; + } - // Check if mysqli is available - if (!isset($config["mysqli"])) { - $config["mysqli"] = extension_loaded(mysqli); - } - - // Non-persistent connection: This will help to avoid mysql errors like "has gone away" or locking problems - // If you want persistent connections change it to mysql_pconnect(). - if ($config["mysqli"]) { - $connect_id = mysqli_connect($host, $user, $pass, $db, $port); - if (mysqli_connect_errno() > 0) { - return false; - } - db_change_cache_id ($db, $host); + if ($db === null) { + $db = $config['dbname']; + } - if (isset($charset)) { - mysqli_set_charset($connect_id, $charset); - } + if ($user === null) { + $user = $config['dbuser']; + } - mysqli_select_db($connect_id, $db); - } - else { - $connect_id = @mysql_connect($host . ":" . $port, $user, $pass, true); - if (! $connect_id) { - return false; - } + if ($pass === null) { + $pass = $config['dbpass']; + } - db_change_cache_id ($db, $host); + if ($port === null) { + $port = $config['dbport']; + } - if (isset($charset)) { - @mysql_set_charset($connect_id, $charset); - } + // Check if mysqli is available + if (!isset($config['mysqli'])) { + $config['mysqli'] = extension_loaded(mysqli); + } - mysql_select_db($db, $connect_id); - } - - return $connect_id; + // Non-persistent connection: This will help to avoid mysql errors like "has gone away" or locking problems + // If you want persistent connections change it to mysql_pconnect(). + if ($config['mysqli']) { + $connect_id = mysqli_connect($host, $user, $pass, $db, $port); + if (mysqli_connect_errno() > 0) { + return false; + } + + db_change_cache_id($db, $host); + + if (isset($charset)) { + mysqli_set_charset($connect_id, $charset); + } + + mysqli_select_db($connect_id, $db); + } else { + $connect_id = @mysql_connect($host.':'.$port, $user, $pass, true); + if (! $connect_id) { + return false; + } + + db_change_cache_id($db, $host); + + if (isset($charset)) { + @mysql_set_charset($connect_id, $charset); + } + + mysql_select_db($db, $connect_id); + } + + return $connect_id; } -function mysql_db_get_all_rows_sql ($sql, $search_history_db = false, $cache = true, $dbconnection = false) { - global $config; - - $history = array (); - - if ($dbconnection === false) { - $dbconnection = $config['dbconnection']; - } - - // To disable globally SQL cache depending on global variable. - // Used in several critical places like Metaconsole trans-server queries - if (isset($config["dbcache"])) - $cache = $config["dbcache"]; - - // Read from the history DB if necessary - if ($search_history_db && $config['history_db_enabled'] == 1) { - $cache = false; - $history = false; - - // Connect to the history DB - if (! isset ($config['history_db_connection']) || $config['history_db_connection'] === false) { - $config['history_db_connection'] = db_connect($config['history_db_host'], $config['history_db_name'], $config['history_db_user'], io_output_password($config['history_db_pass']), $config['history_db_port'], false); - } - if ($config['history_db_connection'] !== false) { - $history = mysql_db_process_sql ($sql, 'affected_rows', $config['history_db_connection'], false); - } - - if ($history === false) { - $history = array (); - } - } - $return = mysql_db_process_sql ($sql, - 'affected_rows', $dbconnection, $cache); - - - if ($return === false) { - $return = array (); - } - - // Append result to the history DB data - if (! empty ($return)) { - foreach ($return as $row) { - array_push ($history, $row); - } - } - - if (! empty ($history)) - return $history; - //Return false, check with === or !== - return false; + +function mysql_db_get_all_rows_sql($sql, $search_history_db=false, $cache=true, $dbconnection=false) +{ + global $config; + + $history = []; + + if ($dbconnection === false) { + $dbconnection = $config['dbconnection']; + } + + // To disable globally SQL cache depending on global variable. + // Used in several critical places like Metaconsole trans-server queries + if (isset($config['dbcache'])) { + $cache = $config['dbcache']; + } + + // Read from the history DB if necessary + if ($search_history_db && $config['history_db_enabled'] == 1) { + $cache = false; + $history = false; + + // Connect to the history DB + if (! isset($config['history_db_connection']) || $config['history_db_connection'] === false) { + $config['history_db_connection'] = db_connect($config['history_db_host'], $config['history_db_name'], $config['history_db_user'], io_output_password($config['history_db_pass']), $config['history_db_port'], false); + } + + if ($config['history_db_connection'] !== false) { + $history = mysql_db_process_sql($sql, 'affected_rows', $config['history_db_connection'], false); + } + + if ($history === false) { + $history = []; + } + } + + $return = mysql_db_process_sql( + $sql, + 'affected_rows', + $dbconnection, + $cache + ); + + if ($return === false) { + $return = []; + } + + // Append result to the history DB data + if (! empty($return)) { + foreach ($return as $row) { + array_push($history, $row); + } + } + + if (! empty($history)) { + return $history; + } + + // Return false, check with === or !== + return false; } -/** + +/** * Get the first value of the first row of a table in the database. - * + * * @param string Field name to get * @param string Table to retrieve the data * @param string Field to filter elements @@ -128,35 +146,52 @@ function mysql_db_get_all_rows_sql ($sql, $search_history_db = false, $cache = t * * @return mixed Value of first column of the first row. False if there were no row. */ -function mysql_db_get_value ($field, $table, $field_search = 1, $condition = 1, $search_history_db = false) { - if (is_int ($condition)) { - $sql = sprintf ("SELECT %s FROM %s WHERE %s = %d LIMIT 1", - $field, $table, $field_search, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT %s FROM %s WHERE %s = %f LIMIT 1", - $field, $table, $field_search, $condition); - } - else { - $sql = sprintf ("SELECT %s FROM %s WHERE %s = '%s' LIMIT 1", - $field, $table, $field_search, $condition); - } - - $result = db_get_all_rows_sql ($sql, $search_history_db); - - if ($result === false) - return false; - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; +function mysql_db_get_value($field, $table, $field_search=1, $condition=1, $search_history_db=false) +{ + if (is_int($condition)) { + $sql = sprintf( + 'SELECT %s FROM %s WHERE %s = %d LIMIT 1', + $field, + $table, + $field_search, + $condition + ); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf( + 'SELECT %s FROM %s WHERE %s = %f LIMIT 1', + $field, + $table, + $field_search, + $condition + ); + } else { + $sql = sprintf( + "SELECT %s FROM %s WHERE %s = '%s' LIMIT 1", + $field, + $table, + $field_search, + $condition + ); + } + + $result = db_get_all_rows_sql($sql, $search_history_db); + + if ($result === false) { + return false; + } + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } -/** + +/** * Get the first row of a database query into a table. * * The SQL statement executed would be something like: @@ -166,72 +201,90 @@ function mysql_db_get_value ($field, $table, $field_search = 1, $condition = 1, * @param string Field to filter elements * @param string Condition the field must have. * @param mixed Fields to select (array or string or false/empty for *) - * + * * @return mixed The first row of a database query or false. */ -function mysql_db_get_row ($table, $field_search, $condition, $fields = false) { - if (empty ($fields)) { - $fields = '*'; - } - else { - if (is_array ($fields)) - $fields = implode (',', $fields); - else if (! is_string ($fields)) - return false; - } - - if (is_int ($condition)) { - $sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = %d LIMIT 1", - $fields, $table, $field_search, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = %f LIMIT 1", - $fields, $table, $field_search, $condition); - } - else { - $sql = sprintf ("SELECT %s FROM `%s` WHERE `%s` = '%s' LIMIT 1", - $fields, $table, $field_search, $condition); - } - $result = db_get_all_rows_sql ($sql); - - if ($result === false) - return false; - - return $result[0]; +function mysql_db_get_row($table, $field_search, $condition, $fields=false) +{ + if (empty($fields)) { + $fields = '*'; + } else { + if (is_array($fields)) { + $fields = implode(',', $fields); + } else if (! is_string($fields)) { + return false; + } + } + + if (is_int($condition)) { + $sql = sprintf( + 'SELECT %s FROM `%s` WHERE `%s` = %d LIMIT 1', + $fields, + $table, + $field_search, + $condition + ); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf( + 'SELECT %s FROM `%s` WHERE `%s` = %f LIMIT 1', + $fields, + $table, + $field_search, + $condition + ); + } else { + $sql = sprintf( + "SELECT %s FROM `%s` WHERE `%s` = '%s' LIMIT 1", + $fields, + $table, + $field_search, + $condition + ); + } + + $result = db_get_all_rows_sql($sql); + + if ($result === false) { + return false; + } + + return $result[0]; } + /** * Get all the rows in a table of the database. - * + * * @param string Database table name. * @param string Field to order by. - * @param string $order The type of order, by default 'ASC'. + * @param string $order The type of order, by default 'ASC'. * * @return mixed A matrix with all the values in the table */ -function mysql_db_get_all_rows_in_table($table, $order_field = "", $order = 'ASC') { - $sql = " +function mysql_db_get_all_rows_in_table($table, $order_field='', $order='ASC') +{ + $sql = ' SELECT * - FROM `".$table."`"; - - if (!empty($order_field)) { - if (is_array($order_field)) { - foreach ($order_field as $i => $o) { - $order_field[$i] = $o . " " . $order; - } - $sql .= " - ORDER BY " . implode(",", $order_field); - } - else { - $sql .= " - ORDER BY ".$order_field . " " . $order; - } - - } - - return db_get_all_rows_sql($sql); + FROM `'.$table.'`'; + + if (!empty($order_field)) { + if (is_array($order_field)) { + foreach ($order_field as $i => $o) { + $order_field[$i] = $o.' '.$order; + } + + $sql .= ' + ORDER BY '.implode(',', $order_field); + } else { + $sql .= ' + ORDER BY '.$order_field.' '.$order; + } + } + + return db_get_all_rows_sql($sql); } + /** * Inserts strings into database * @@ -244,52 +297,53 @@ function mysql_db_get_all_rows_in_table($table, $order_field = "", $order = 'ASC * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function mysql_db_process_sql_insert($table, $values) { - //Empty rows or values not processed - - if (empty ($values)) - return false; - - $values = (array) $values; - - $query = sprintf ("INSERT INTO `%s` ", $table); - $fields = array (); - $values_str = ''; - $i = 1; - $max = count ($values); - foreach ($values as $field => $value) { //Add the correct escaping to values - if ($field[0] != "`") { - $field = "`".$field."`"; - } - - array_push ($fields, $field); - - if (is_null ($value)) { - $values_str .= "NULL"; - } - elseif (is_int ($value) || is_bool ($value)) { - $values_str .= sprintf ("%d", $value); - } - else if (is_float ($value) || is_double ($value)) { - $values_str .= sprintf ("%f", $value); - } - else { - $values_str .= sprintf ("'%s'", $value); - } - - if ($i < $max) { - $values_str .= ","; - } - $i++; - } - - $query .= '('.implode (', ', $fields).')'; - - $query .= ' VALUES ('.$values_str.')'; - - return db_process_sql ($query, 'insert_id'); +function mysql_db_process_sql_insert($table, $values) +{ + // Empty rows or values not processed + if (empty($values)) { + return false; + } + + $values = (array) $values; + + $query = sprintf('INSERT INTO `%s` ', $table); + $fields = []; + $values_str = ''; + $i = 1; + $max = count($values); + foreach ($values as $field => $value) { + // Add the correct escaping to values + if ($field[0] != '`') { + $field = '`'.$field.'`'; + } + + array_push($fields, $field); + + if (is_null($value)) { + $values_str .= 'NULL'; + } else if (is_int($value) || is_bool($value)) { + $values_str .= sprintf('%d', $value); + } else if (is_float($value) || is_double($value)) { + $values_str .= sprintf('%f', $value); + } else { + $values_str .= sprintf("'%s'", $value); + } + + if ($i < $max) { + $values_str .= ','; + } + + $i++; + } + + $query .= '('.implode(', ', $fields).')'; + + $query .= ' VALUES ('.$values_str.')'; + + return db_process_sql($query, 'insert_id'); } + /** * This function comes back with an array in case of SELECT * in case of UPDATE, DELETE etc. with affected rows @@ -299,159 +353,187 @@ function mysql_db_process_sql_insert($table, $values) { * @param string SQL statement to execute * * @param string What type of info to return in case of INSERT/UPDATE. - * 'affected_rows' will return mysql_affected_rows (default value) - * 'insert_id' will return the ID of an autoincrement value - * 'info' will return the full (debug) information of a query + * 'affected_rows' will return mysql_affected_rows (default value) + * 'insert_id' will return the ID of an autoincrement value + * 'info' will return the full (debug) information of a query * * @return mixed An array with the rows, columns and values in a multidimensional array or false in error */ -function mysql_db_process_sql($sql, $rettype = "affected_rows", $dbconnection = '', $cache = true) { - global $config; - global $sql_cache; - - $retval = array(); - - if ($sql == '') - return false; - - if ($cache && ! empty ($sql_cache[$sql_cache['id']][$sql])) { - $retval = $sql_cache[$sql_cache['id']][$sql]; - $sql_cache['saved'][$sql_cache['id']]++; - db_add_database_debug_trace ($sql); - } - else { - $start = microtime (true); - - if ($dbconnection == '') { - $dbconnection = $config['dbconnection']; - } - - if ($config["mysqli"] === true) { - $result = mysqli_query ($dbconnection, $sql); - } - else { - $result = mysql_query ($sql, $dbconnection); - } - - $time = microtime (true) - $start; - if ($result === false) { - $backtrace = debug_backtrace (); - if ($config["mysqli"] === true) { - $error = sprintf ('%s (\'%s\') in %s on line %d', - mysqli_error ($dbconnection), $sql, $backtrace[0]['file'], $backtrace[0]['line']); - db_add_database_debug_trace ($sql, mysqli_error ($dbconnection)); - } - else { - $error = sprintf ('%s (\'%s\') in %s on line %d', - mysql_error (), $sql, $backtrace[0]['file'], $backtrace[0]['line']); - db_add_database_debug_trace ($sql, mysql_error ($dbconnection)); - } - set_error_handler ('db_sql_error_handler'); - trigger_error ($error); - restore_error_handler (); - return false; - } - elseif ($result === true) { - if ($config["mysqli"] === true) { - if ($rettype == "insert_id") { - $result = mysqli_insert_id ($dbconnection); - } - elseif ($rettype == "info") { - $result = mysqli_info ($dbconnection); - } - else { - $result = mysqli_affected_rows ($dbconnection); - } +function mysql_db_process_sql($sql, $rettype='affected_rows', $dbconnection='', $cache=true) +{ + global $config; + global $sql_cache; - db_add_database_debug_trace ($sql, $result, mysqli_affected_rows ($dbconnection), - array ('time' => $time)); - } - else { - if ($rettype == "insert_id") { - $result = mysql_insert_id ($dbconnection); - } - elseif ($rettype == "info") { - $result = mysql_info ($dbconnection); - } - else { - $result = mysql_affected_rows ($dbconnection); - } + $retval = []; - db_add_database_debug_trace ($sql, $result, mysql_affected_rows ($dbconnection), - array ('time' => $time)); - } - - return $result; - } - else { - if ($config["mysqli"] === true) { - db_add_database_debug_trace ($sql, 0, mysqli_affected_rows ($dbconnection), - array ('time' => $time)); - while ($row = mysqli_fetch_assoc ($result)) { - array_push ($retval, $row); - } - - if ($cache === true) - $sql_cache[$sql_cache ['id']][$sql] = $retval; - mysqli_free_result ($result); - } - else { - db_add_database_debug_trace ($sql, 0, mysql_affected_rows ($dbconnection), - array ('time' => $time)); - while ($row = mysql_fetch_assoc ($result)) { - array_push ($retval, $row); - } + if ($sql == '') { + return false; + } - if ($cache === true) - $sql_cache[$sql_cache ['id']][$sql] = $retval; - mysql_free_result ($result); - } - } - } - - if (! empty ($retval)) - return $retval; - //Return false, check with === or !== - return false; + if ($cache && ! empty($sql_cache[$sql_cache['id']][$sql])) { + $retval = $sql_cache[$sql_cache['id']][$sql]; + $sql_cache['saved'][$sql_cache['id']]++; + db_add_database_debug_trace($sql); + } else { + $start = microtime(true); + + if ($dbconnection == '') { + $dbconnection = $config['dbconnection']; + } + + if ($config['mysqli'] === true) { + $result = mysqli_query($dbconnection, $sql); + } else { + $result = mysql_query($sql, $dbconnection); + } + + $time = (microtime(true) - $start); + if ($result === false) { + $backtrace = debug_backtrace(); + if ($config['mysqli'] === true) { + $error = sprintf( + '%s (\'%s\') in %s on line %d', + mysqli_error($dbconnection), + $sql, + $backtrace[0]['file'], + $backtrace[0]['line'] + ); + db_add_database_debug_trace($sql, mysqli_error($dbconnection)); + } else { + $error = sprintf( + '%s (\'%s\') in %s on line %d', + mysql_error(), + $sql, + $backtrace[0]['file'], + $backtrace[0]['line'] + ); + db_add_database_debug_trace($sql, mysql_error($dbconnection)); + } + + set_error_handler('db_sql_error_handler'); + trigger_error($error); + restore_error_handler(); + return false; + } else if ($result === true) { + if ($config['mysqli'] === true) { + if ($rettype == 'insert_id') { + $result = mysqli_insert_id($dbconnection); + } else if ($rettype == 'info') { + $result = mysqli_info($dbconnection); + } else { + $result = mysqli_affected_rows($dbconnection); + } + + db_add_database_debug_trace( + $sql, + $result, + mysqli_affected_rows($dbconnection), + ['time' => $time] + ); + } else { + if ($rettype == 'insert_id') { + $result = mysql_insert_id($dbconnection); + } else if ($rettype == 'info') { + $result = mysql_info($dbconnection); + } else { + $result = mysql_affected_rows($dbconnection); + } + + db_add_database_debug_trace( + $sql, + $result, + mysql_affected_rows($dbconnection), + ['time' => $time] + ); + } + + return $result; + } else { + if ($config['mysqli'] === true) { + db_add_database_debug_trace( + $sql, + 0, + mysqli_affected_rows($dbconnection), + ['time' => $time] + ); + while ($row = mysqli_fetch_assoc($result)) { + array_push($retval, $row); + } + + if ($cache === true) { + $sql_cache[$sql_cache['id']][$sql] = $retval; + } + + mysqli_free_result($result); + } else { + db_add_database_debug_trace( + $sql, + 0, + mysql_affected_rows($dbconnection), + ['time' => $time] + ); + while ($row = mysql_fetch_assoc($result)) { + array_push($retval, $row); + } + + if ($cache === true) { + $sql_cache[$sql_cache['id']][$sql] = $retval; + } + + mysql_free_result($result); + } + } + } + + if (! empty($retval)) { + return $retval; + } + + // Return false, check with === or !== + return false; } + /** - * * Escape string to set it properly to use in sql queries - * + * * @param string String to be cleaned. - * + * * @return string String cleaned. */ -function mysql_escape_string_sql($string) { - global $config; +function mysql_escape_string_sql($string) +{ + global $config; - $dbconnection = $config['dbconnection']; - if ($dbconnection == null) { - $dbconnection = mysql_connect_db(); - } - if ($config["mysqli"] === true) { - $str = mysqli_real_escape_string($dbconnection, $string); - } - else { - $str = mysql_real_escape_string($string); - } - - return $str; + $dbconnection = $config['dbconnection']; + if ($dbconnection == null) { + $dbconnection = mysql_connect_db(); + } + + if ($config['mysqli'] === true) { + $str = mysqli_real_escape_string($dbconnection, $string); + } else { + $str = mysql_real_escape_string($string); + } + + return $str; } -function mysql_encapsule_fields_with_same_name_to_instructions($field) { - $return = $field; - - if (is_string($return)) { - if ($return[0] !== '`') { - $return = '`' . $return . '`'; - } - } - - return $return; + +function mysql_encapsule_fields_with_same_name_to_instructions($field) +{ + $return = $field; + + if (is_string($return)) { + if ($return[0] !== '`') { + $return = '`'.$return.'`'; + } + } + + return $return; } + /** * Get the first value of the first row of a table in the database from an * array with filter conditions. @@ -477,32 +559,40 @@ function mysql_encapsule_fields_with_same_name_to_instructions($field) { * * @return mixed Value of first column of the first row. False if there were no row. */ -function mysql_db_get_value_filter ($field, $table, $filter, $where_join = 'AND', $search_history_db = false) { - if (! is_array ($filter) || empty ($filter)) - return false; - - /* Avoid limit and offset if given */ - unset ($filter['limit']); - unset ($filter['offset']); - - $sql = sprintf ("SELECT %s FROM %s WHERE %s LIMIT 1", - $field, $table, - db_format_array_where_clause_sql ($filter, $where_join)); - - $result = db_get_all_rows_sql ($sql, $search_history_db); - - if ($result === false) - return false; - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; +function mysql_db_get_value_filter($field, $table, $filter, $where_join='AND', $search_history_db=false) +{ + if (! is_array($filter) || empty($filter)) { + return false; + } + + // Avoid limit and offset if given + unset($filter['limit']); + unset($filter['offset']); + + $sql = sprintf( + 'SELECT %s FROM %s WHERE %s LIMIT 1', + $field, + $table, + db_format_array_where_clause_sql($filter, $where_join) + ); + + $result = db_get_all_rows_sql($sql, $search_history_db); + + if ($result === false) { + return false; + } + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } + /** * Formats an array of values into a SQL where clause string. * @@ -566,145 +656,143 @@ function mysql_db_get_value_filter ($field, $table, $filter, $where_join = 'AND' * @return string Values joined into an SQL string that can fits into the WHERE * clause of an SQL sentence. */ -function mysql_db_format_array_where_clause_sql ($values, $join = 'AND', $prefix = false) { - - $fields = array (); - - if (! is_array ($values)) { - return ''; - } - - $query = ''; - $limit = ''; - $offset = ''; - $order = ''; - $group = ''; - if (isset ($values['limit'])) { - $limit = sprintf (' LIMIT %d', $values['limit']); - unset ($values['limit']); - } - - if (isset ($values['offset'])) { - $offset = sprintf (' OFFSET %d', $values['offset']); - unset ($values['offset']); - } - - if (isset ($values['order'])) { - if (is_array($values['order'])) { - if (!isset($values['order']['order'])) { - $orderTexts = array(); - foreach ($values['order'] as $orderItem) { - $orderTexts[] = $orderItem['field'] . ' ' . $orderItem['order']; - } - $order = ' ORDER BY ' . implode(', ', $orderTexts); - } - else { - $order = sprintf (' ORDER BY %s %s', $values['order']['field'], $values['order']['order']); - } - } - else { - $order = sprintf (' ORDER BY %s', $values['order']); - } - unset ($values['order']); - } - - if (isset ($values['group'])) { - $group = sprintf (' GROUP BY %s', $values['group']); - unset ($values['group']); - } - - $i = 1; - $max = count ($values); - foreach ($values as $field => $value) { - if (is_numeric ($field)) { - /* User provide the exact operation to do */ - $query .= $value; - - if ($i < $max) { - $query .= ' '.$join.' '; - } - $i++; - continue; - } - - if ($field[0] != "`") { - //If the field is as ., don't scape. - if (strstr($field, '.') === false) - $field = "`".$field."`"; - } - - if (is_null ($value)) { - $query .= sprintf ("%s IS NULL", $field); - } - elseif (is_int ($value) || is_bool ($value)) { - $query .= sprintf ("%s = %d", $field, $value); - } - else if (is_float ($value) || is_double ($value)) { - $query .= sprintf ("%s = %f", $field, $value); - } - elseif (is_array ($value)) { - $query .= sprintf ('%s IN ("%s")', $field, implode ('", "', $value)); - } - else { - if ($value === "") { - //Search empty string - $query .= sprintf ("%s = ''", $field); - } - else if ($value[0] == ">") { - $value = substr($value,1,strlen($value)-1); - $query .= sprintf ("%s > '%s'", $field, $value); - } - else if ($value[0] == "<") { - if ($value[1] == ">") { - $value = substr($value,2,strlen($value)-2); - $query .= sprintf ("%s <> '%s'", $field, $value); - } - else { - $value = substr($value,1,strlen($value)-1); - $query .= sprintf ("%s < '%s'", $field, $value); - } - } - else if ($value[0] == '%') { - $query .= sprintf ("%s LIKE '%s'", $field, $value); - } - else { - $query .= sprintf ("%s = '%s'", $field, $value); - } - } - - if ($i < $max) { - $query .= ' '.$join.' '; - } - $i++; - } - - return (! empty ($query) ? $prefix: '').$query.$group.$order.$limit.$offset; +function mysql_db_format_array_where_clause_sql($values, $join='AND', $prefix=false) +{ + $fields = []; + + if (! is_array($values)) { + return ''; + } + + $query = ''; + $limit = ''; + $offset = ''; + $order = ''; + $group = ''; + if (isset($values['limit'])) { + $limit = sprintf(' LIMIT %d', $values['limit']); + unset($values['limit']); + } + + if (isset($values['offset'])) { + $offset = sprintf(' OFFSET %d', $values['offset']); + unset($values['offset']); + } + + if (isset($values['order'])) { + if (is_array($values['order'])) { + if (!isset($values['order']['order'])) { + $orderTexts = []; + foreach ($values['order'] as $orderItem) { + $orderTexts[] = $orderItem['field'].' '.$orderItem['order']; + } + + $order = ' ORDER BY '.implode(', ', $orderTexts); + } else { + $order = sprintf(' ORDER BY %s %s', $values['order']['field'], $values['order']['order']); + } + } else { + $order = sprintf(' ORDER BY %s', $values['order']); + } + + unset($values['order']); + } + + if (isset($values['group'])) { + $group = sprintf(' GROUP BY %s', $values['group']); + unset($values['group']); + } + + $i = 1; + $max = count($values); + foreach ($values as $field => $value) { + if (is_numeric($field)) { + // User provide the exact operation to do + $query .= $value; + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + $i++; + continue; + } + + if ($field[0] != '`') { + // If the field is as
        ., don't scape. + if (strstr($field, '.') === false) { + $field = '`'.$field.'`'; + } + } + + if (is_null($value)) { + $query .= sprintf('%s IS NULL', $field); + } else if (is_int($value) || is_bool($value)) { + $query .= sprintf('%s = %d', $field, $value); + } else if (is_float($value) || is_double($value)) { + $query .= sprintf('%s = %f', $field, $value); + } else if (is_array($value)) { + $query .= sprintf('%s IN ("%s")', $field, implode('", "', $value)); + } else { + if ($value === '') { + // Search empty string + $query .= sprintf("%s = ''", $field); + } else if ($value[0] == '>') { + $value = substr($value, 1, (strlen($value) - 1)); + $query .= sprintf("%s > '%s'", $field, $value); + } else if ($value[0] == '<') { + if ($value[1] == '>') { + $value = substr($value, 2, (strlen($value) - 2)); + $query .= sprintf("%s <> '%s'", $field, $value); + } else { + $value = substr($value, 1, (strlen($value) - 1)); + $query .= sprintf("%s < '%s'", $field, $value); + } + } else if ($value[0] == '%') { + $query .= sprintf("%s LIKE '%s'", $field, $value); + } else { + $query .= sprintf("%s = '%s'", $field, $value); + } + } + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + $i++; + } + + return (! empty($query) ? $prefix : '').$query.$group.$order.$limit.$offset; } + /** * Get the first value of the first row of a table result from query. * * @param string SQL select statement to execute. * * @return the first value of the first row of a table result from query. - * */ -function mysql_db_get_value_sql($sql, $dbconnection = false) { - $sql .= " LIMIT 1"; - $result = mysql_db_get_all_rows_sql ($sql, false, true, $dbconnection); - - if ($result === false) - return false; - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; +function mysql_db_get_value_sql($sql, $dbconnection=false) +{ + $sql .= ' LIMIT 1'; + $result = mysql_db_get_all_rows_sql($sql, false, true, $dbconnection); + + if ($result === false) { + return false; + } + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } + /** * Get the first row of an SQL database query. * @@ -712,16 +800,19 @@ function mysql_db_get_value_sql($sql, $dbconnection = false) { * * @return mixed The first row of the result or false */ -function mysql_db_get_row_sql ($sql, $search_history_db = false) { - $sql .= " LIMIT 1"; - $result = db_get_all_rows_sql ($sql, $search_history_db); - - if ($result === false) - return false; - - return $result[0]; +function mysql_db_get_row_sql($sql, $search_history_db=false) +{ + $sql .= ' LIMIT 1'; + $result = db_get_all_rows_sql($sql, $search_history_db); + + if ($result === false) { + return false; + } + + return $result[0]; } + /** * Get the row of a table in the database using a complex filter. * @@ -746,29 +837,32 @@ function mysql_db_get_row_sql ($sql, $search_history_db = false) { * * @return mixed Array of the row or false in case of error. */ -function mysql_db_get_row_filter ($table, $filter, $fields = false, $where_join = 'AND', $historydb = false) { - if (empty ($fields)) { - $fields = '*'; - } - else { - if (is_array ($fields)) - $fields = implode (',', $fields); - else if (! is_string ($fields)) - return false; - } - - if (is_array ($filter)) - $filter = db_format_array_where_clause_sql ($filter, $where_join, ' WHERE '); - else if (is_string ($filter)) - $filter = 'WHERE '.$filter; - else - $filter = ''; - - $sql = sprintf ('SELECT %s FROM %s %s', $fields, $table, $filter); - - return db_get_row_sql ($sql, $historydb); +function mysql_db_get_row_filter($table, $filter, $fields=false, $where_join='AND', $historydb=false) +{ + if (empty($fields)) { + $fields = '*'; + } else { + if (is_array($fields)) { + $fields = implode(',', $fields); + } else if (! is_string($fields)) { + return false; + } + } + + if (is_array($filter)) { + $filter = db_format_array_where_clause_sql($filter, $where_join, ' WHERE '); + } else if (is_string($filter)) { + $filter = 'WHERE '.$filter; + } else { + $filter = ''; + } + + $sql = sprintf('SELECT %s FROM %s %s', $fields, $table, $filter); + + return db_get_row_sql($sql, $historydb); } + /** * Get all the rows of a table in the database that matches a filter. * @@ -789,68 +883,74 @@ function mysql_db_get_row_filter ($table, $filter, $fields = false, $where_join * @param mixed Fields of the table to retrieve. Can be an array or a coma * separated string. All fields are retrieved by default * @param string Condition of the filter (AND, OR). - * @param bool $returnSQL Return a string with SQL instead the data, by default false. + * @param boolean $returnSQL Return a string with SQL instead the data, by default false. * * @return mixed Array of the row or false in case of error. */ -function mysql_db_get_all_rows_filter ($table, $filter = array(), $fields = false, $where_join = 'AND', $search_history_db = false, $returnSQL = false) { - //TODO: Validate and clean fields - if (empty ($fields)) { - $fields = '*'; - } - elseif (is_array ($fields)) { - $fields = implode (',', $fields); - } - elseif (! is_string ($fields)) { - return false; - } - - //TODO: Validate and clean filter options - if (is_array ($filter)) { - $filter = db_format_array_where_clause_sql ($filter, $where_join, ' WHERE '); - } - elseif (is_string ($filter)) { - $filter = 'WHERE '.$filter; - } - else { - $filter = ''; - } - - $sql = sprintf ('SELECT %s - FROM %s %s', $fields, $table, $filter); - - if ($returnSQL) - return $sql; - else - return db_get_all_rows_sql ($sql, $search_history_db); +function mysql_db_get_all_rows_filter($table, $filter=[], $fields=false, $where_join='AND', $search_history_db=false, $returnSQL=false) +{ + // TODO: Validate and clean fields + if (empty($fields)) { + $fields = '*'; + } else if (is_array($fields)) { + $fields = implode(',', $fields); + } else if (! is_string($fields)) { + return false; + } + + // TODO: Validate and clean filter options + if (is_array($filter)) { + $filter = db_format_array_where_clause_sql($filter, $where_join, ' WHERE '); + } else if (is_string($filter)) { + $filter = 'WHERE '.$filter; + } else { + $filter = ''; + } + + $sql = sprintf( + 'SELECT %s + FROM %s %s', + $fields, + $table, + $filter + ); + + if ($returnSQL) { + return $sql; + } else { + return db_get_all_rows_sql($sql, $search_history_db); + } } + /** * Return the count of rows of query. * - * @param $sql + * @param $sql * @return integer The count of rows of query. */ -function mysql_db_get_num_rows ($sql) { - global $config; - - if ($config["mysqli"] === true) { - $result = mysqli_query($config['dbconnection'], $sql); - - if ($result) { - return mysqli_num_rows($result); - } - } - else { - $result = mysql_query($sql, $config['dbconnection']); +function mysql_db_get_num_rows($sql) +{ + global $config; - if ($result) { - return mysql_num_rows($result); - } - } - return 0; + if ($config['mysqli'] === true) { + $result = mysqli_query($config['dbconnection'], $sql); + + if ($result) { + return mysqli_num_rows($result); + } + } else { + $result = mysql_query($sql, $config['dbconnection']); + + if ($result) { + return mysql_num_rows($result); + } + } + + return 0; } + /** * Get all the rows in a table of the databes filtering from a field. * @@ -861,23 +961,24 @@ function mysql_db_get_num_rows ($sql) { * * @return mixed A matrix with all the values in the table that matches the condition in the field or false */ -function mysql_db_get_all_rows_field_filter ($table, $field, $condition, $order_field = "") { - if (is_int ($condition) || is_bool ($condition)) { - $sql = sprintf ("SELECT * FROM `%s` WHERE `%s` = %d", $table, $field, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT * FROM `%s` WHERE `%s` = %f", $table, $field, $condition); - } - else { - $sql = sprintf ("SELECT * FROM `%s` WHERE `%s` = '%s'", $table, $field, $condition); - } - - if ($order_field != "") - $sql .= sprintf (" ORDER BY %s", $order_field); - - return db_get_all_rows_sql ($sql); +function mysql_db_get_all_rows_field_filter($table, $field, $condition, $order_field='') +{ + if (is_int($condition) || is_bool($condition)) { + $sql = sprintf('SELECT * FROM `%s` WHERE `%s` = %d', $table, $field, $condition); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf('SELECT * FROM `%s` WHERE `%s` = %f', $table, $field, $condition); + } else { + $sql = sprintf("SELECT * FROM `%s` WHERE `%s` = '%s'", $table, $field, $condition); + } + + if ($order_field != '') { + $sql .= sprintf(' ORDER BY %s', $order_field); + } + + return db_get_all_rows_sql($sql); } + /** * Get all the rows in a table of the databes filtering from a field. * @@ -886,19 +987,22 @@ function mysql_db_get_all_rows_field_filter ($table, $field, $condition, $order_ * * @return mixed A matrix with all the values in the table that matches the condition in the field */ -function mysql_db_get_all_fields_in_table ($table, $field = '', $condition = '', $order_field = '') { - $sql = sprintf ("SELECT * FROM `%s`", $table); - - if ($condition != '') { - $sql .= sprintf (" WHERE `%s` = '%s'", $field, $condition); - } - - if ($order_field != "") - $sql .= sprintf (" ORDER BY %s", $order_field); - - return db_get_all_rows_sql ($sql); +function mysql_db_get_all_fields_in_table($table, $field='', $condition='', $order_field='') +{ + $sql = sprintf('SELECT * FROM `%s`', $table); + + if ($condition != '') { + $sql .= sprintf(" WHERE `%s` = '%s'", $field, $condition); + } + + if ($order_field != '') { + $sql .= sprintf(' ORDER BY %s', $order_field); + } + + return db_get_all_rows_sql($sql); } + /** * Formats an array of values into a SQL string. * @@ -922,41 +1026,41 @@ function mysql_db_get_all_fields_in_table ($table, $field = '', $condition = '', * @return string Values joined into an SQL string that can fits into an UPDATE * sentence. */ -function mysql_db_format_array_to_update_sql ($values) { - $fields = array (); - - foreach ($values as $field => $value) { - if (is_numeric ($field)) { - array_push ($fields, $value); - continue; - } - else if ($field[0] == "`") { - $field = str_replace('`', '', $field); - } - - if ($value === NULL) { - $sql = sprintf ("`%s` = NULL", $field); - } - elseif (is_int ($value) || is_bool ($value)) { - $sql = sprintf ("`%s` = %d", $field, $value); - } - elseif (is_float ($value) || is_double ($value)) { - $sql = sprintf ("`%s` = %f", $field, $value); - } - else { - /* String */ - if (isset ($value[0]) && $value[0] == '`') - /* Don't round with quotes if it references a field */ - $sql = sprintf ("`%s` = %s", $field, $value); - else - $sql = sprintf ("`%s` = '%s'", $field, $value); - } - array_push ($fields, $sql); - } - - return implode (", ", $fields); +function mysql_db_format_array_to_update_sql($values) +{ + $fields = []; + + foreach ($values as $field => $value) { + if (is_numeric($field)) { + array_push($fields, $value); + continue; + } else if ($field[0] == '`') { + $field = str_replace('`', '', $field); + } + + if ($value === null) { + $sql = sprintf('`%s` = NULL', $field); + } else if (is_int($value) || is_bool($value)) { + $sql = sprintf('`%s` = %d', $field, $value); + } else if (is_float($value) || is_double($value)) { + $sql = sprintf('`%s` = %f', $field, $value); + } else { + // String + if (isset($value[0]) && $value[0] == '`') { + // Don't round with quotes if it references a field + $sql = sprintf('`%s` = %s', $field, $value); + } else { + $sql = sprintf("`%s` = '%s'", $field, $value); + } + } + + array_push($fields, $sql); + } + + return implode(', ', $fields); } + /** * Updates a database record. * @@ -975,30 +1079,33 @@ function mysql_db_format_array_to_update_sql ($values) { * @param mixed An associative array of field and value matches. Will be joined * with operator specified by $where_join. A custom string can also be provided. * If nothing is provided, the update will affect all rows. - * @param string When a $where parameter is given, this will work as the glue - * between the fields. "AND" operator will be use by default. Other values might - * be "OR", "AND NOT", "XOR" + * @param string When a $where parameter is given, this will work as the glue + * between the fields. "AND" operator will be use by default. Other values might + * be "OR", "AND NOT", "XOR" * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function mysql_db_process_sql_update($table, $values, $where = false, $where_join = 'AND') { - $query = sprintf ("UPDATE `%s` SET %s", - $table, - db_format_array_to_update_sql ($values)); - - if ($where) { - if (is_string ($where)) { - // No clean, the caller should make sure all input is clean, this is a raw function - $query .= " WHERE " . $where; - } - else if (is_array ($where)) { - $query .= db_format_array_where_clause_sql ($where, $where_join, ' WHERE '); - } - } - - return db_process_sql ($query); +function mysql_db_process_sql_update($table, $values, $where=false, $where_join='AND') +{ + $query = sprintf( + 'UPDATE `%s` SET %s', + $table, + db_format_array_to_update_sql($values) + ); + + if ($where) { + if (is_string($where)) { + // No clean, the caller should make sure all input is clean, this is a raw function + $query .= ' WHERE '.$where; + } else if (is_array($where)) { + $query .= db_format_array_where_clause_sql($where, $where_join, ' WHERE '); + } + } + + return db_process_sql($query); } + /** * Delete database records. * @@ -1021,271 +1128,300 @@ function mysql_db_process_sql_update($table, $values, $where = false, $where_joi * @param mixed An associative array of field and value matches. Will be joined * with operator specified by $where_join. A custom string can also be provided. * If nothing is provided, the update will affect all rows. - * @param string When a $where parameter is given, this will work as the glue - * between the fields. "AND" operator will be use by default. Other values might - * be "OR", "AND NOT", "XOR" + * @param string When a $where parameter is given, this will work as the glue + * between the fields. "AND" operator will be use by default. Other values might + * be "OR", "AND NOT", "XOR" * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function mysql_db_process_sql_delete($table, $where, $where_join = 'AND') { - if (empty ($where)) - /* Should avoid any mistake that lead to deleting all data */ - return false; - - $query = sprintf ("DELETE FROM `%s` WHERE ", $table); - - if ($where) { - if (is_string ($where)) { - /* FIXME: Should we clean the string for sanity? - Who cares if this is deleting data... */ - $query .= $where; - } - else if (is_array ($where)) { - $query .= db_format_array_where_clause_sql ($where, $where_join); - } - } - - return db_process_sql ($query); +function mysql_db_process_sql_delete($table, $where, $where_join='AND') +{ + if (empty($where)) { + // Should avoid any mistake that lead to deleting all data + return false; + } + + $query = sprintf('DELETE FROM `%s` WHERE ', $table); + + if ($where) { + if (is_string($where)) { + /* + FIXME: Should we clean the string for sanity? + Who cares if this is deleting data... */ + $query .= $where; + } else if (is_array($where)) { + $query .= db_format_array_where_clause_sql($where, $where_join); + } + } + + return db_process_sql($query); } + /** * Get row by row the DB by SQL query. The first time pass the SQL query and * rest of times pass none for iterate in table and extract row by row, and * the end return false. * - * @param bool $new Default true, if true start to query. - * @param resource $result The resource of mysql for access to query. - * @param string $sql + * @param boolean $new Default true, if true start to query. + * @param resource $result The resource of mysql for access to query. + * @param string $sql * @return mixed The row or false in error. */ -function mysql_db_get_all_row_by_steps_sql($new = true, &$result, $sql = null) { - global $config; +function mysql_db_get_all_row_by_steps_sql($new=true, &$result, $sql=null) +{ + global $config; - if ($config["mysqli"] === true) { - if ($new == true) - $result = mysqli_query($config['dbconnection'], $sql); - - if ($result) { - return mysqli_fetch_assoc($result); - } - } - else { - if ($new == true) - $result = mysql_query($sql); + if ($config['mysqli'] === true) { + if ($new == true) { + $result = mysqli_query($config['dbconnection'], $sql); + } - if ($result) { - return mysql_fetch_assoc($result); - } - } - return array(); + if ($result) { + return mysqli_fetch_assoc($result); + } + } else { + if ($new == true) { + $result = mysql_query($sql); + } + + if ($result) { + return mysql_fetch_assoc($result); + } + } + + return []; } + /** * Starts a database transaction. */ -function mysql_db_process_sql_begin() { - global $config; +function mysql_db_process_sql_begin() +{ + global $config; - if ($config["mysqli"]) { - mysqli_query ($config['dbconnection'], 'SET AUTOCOMMIT = 0'); - mysqli_query ($config['dbconnection'], 'START TRANSACTION'); - } - else { - mysql_query ('SET AUTOCOMMIT = 0'); - mysql_query ('START TRANSACTION'); - } + if ($config['mysqli']) { + mysqli_query($config['dbconnection'], 'SET AUTOCOMMIT = 0'); + mysqli_query($config['dbconnection'], 'START TRANSACTION'); + } else { + mysql_query('SET AUTOCOMMIT = 0'); + mysql_query('START TRANSACTION'); + } } + /** * Commits a database transaction. */ -function mysql_db_process_sql_commit() { - global $config; +function mysql_db_process_sql_commit() +{ + global $config; - if ($config["mysqli"]) { - mysqli_query ($config['dbconnection'], 'COMMIT'); - mysqli_query ($config['dbconnection'], 'SET AUTOCOMMIT = 1'); - } - else { - mysql_query ('COMMIT'); - mysql_query ('SET AUTOCOMMIT = 1'); - } + if ($config['mysqli']) { + mysqli_query($config['dbconnection'], 'COMMIT'); + mysqli_query($config['dbconnection'], 'SET AUTOCOMMIT = 1'); + } else { + mysql_query('COMMIT'); + mysql_query('SET AUTOCOMMIT = 1'); + } } + /** * Rollbacks a database transaction. */ -function mysql_db_process_sql_rollback() { - global $config; +function mysql_db_process_sql_rollback() +{ + global $config; - if ($config["mysqli"]) { - mysqli_query ($config['dbconnection'], 'ROLLBACK '); - mysqli_query ($config['dbconnection'], 'SET AUTOCOMMIT = 1'); - } - else { - mysql_query ('ROLLBACK '); - mysql_query ('SET AUTOCOMMIT = 1'); - } + if ($config['mysqli']) { + mysqli_query($config['dbconnection'], 'ROLLBACK '); + mysqli_query($config['dbconnection'], 'SET AUTOCOMMIT = 1'); + } else { + mysql_query('ROLLBACK '); + mysql_query('SET AUTOCOMMIT = 1'); + } } + /** * Put quotes if magic_quotes protection * * @param string Text string to be protected with quotes if magic_quotes protection is disabled */ -function mysql_safe_sql_string($string) { - if (get_magic_quotes_gpc () == 0) - return $string; - - global $config; - - return mysql_real_escape_string($config['dbconnection'], $string); +function mysql_safe_sql_string($string) +{ + if (get_magic_quotes_gpc() == 0) { + return $string; + } + + global $config; + + return mysql_real_escape_string($config['dbconnection'], $string); } + /** * Get last error. - * + * * @return string Return the string error. */ -function mysql_db_get_last_error() { - global $config; +function mysql_db_get_last_error() +{ + global $config; - if ($config["mysqli"]) { - return mysqli_error(); - } - else { - return mysql_error(); - } + if ($config['mysqli']) { + return mysqli_error(); + } else { + return mysql_error(); + } } + /** * This function gets the time from either system or sql based on preference and returns it * - * @return int Unix timestamp + * @return integer Unix timestamp */ -function mysql_get_system_time() { - global $config; - - static $time = 0; - - if ($time != 0) - return $time; - - if ($config["timesource"] == "sql") { - $time = db_get_sql ("SELECT UNIX_TIMESTAMP();"); - if (empty ($time)) { - return time (); - } - return $time; - } - else { - return time (); - } +function mysql_get_system_time() +{ + global $config; + + static $time = 0; + + if ($time != 0) { + return $time; + } + + if ($config['timesource'] == 'sql') { + $time = db_get_sql('SELECT UNIX_TIMESTAMP();'); + if (empty($time)) { + return time(); + } + + return $time; + } else { + return time(); + } } + /** * Get the type of field. - * - * @param string $table The table to examine the type of field. + * + * @param string $table The table to examine the type of field. * @param integer $field The field order in table. - * + * * @return mixed Return the type name or False in error case. */ -function mysql_db_get_type_field_table($table, $field) { - global $config; +function mysql_db_get_type_field_table($table, $field) +{ + global $config; - if ($config["mysqli"]) { - $result = mysqli_query($config['dbconnection'], 'SELECT parameters FROM ' . $table); - - return mysqli_fetch_field_direct($result, $field); - } - else { - $result = mysql_query('SELECT parameters FROM ' . $table); + if ($config['mysqli']) { + $result = mysqli_query($config['dbconnection'], 'SELECT parameters FROM '.$table); - return mysql_field_type($result, $field); - } + return mysqli_fetch_field_direct($result, $field); + } else { + $result = mysql_query('SELECT parameters FROM '.$table); + + return mysql_field_type($result, $field); + } } -function mysql_get_fields($table) { - global $config; - - return db_get_all_rows_sql("SHOW COLUMNS FROM " . $table); + +function mysql_get_fields($table) +{ + global $config; + + return db_get_all_rows_sql('SHOW COLUMNS FROM '.$table); } + /** * Process a file with an oracle schema sentences. * Based on the function which installs the pandoradb.sql schema. - * - * @param string $path File path. - * @param bool $handle_error Whether to handle the mysqli_query/mysql_query errors or throw an exception. - * - * @return bool Return the final status of the operation. + * + * @param string $path File path. + * @param boolean $handle_error Whether to handle the mysqli_query/mysql_query errors or throw an exception. + * + * @return boolean Return the final status of the operation. */ -function mysql_db_process_file ($path, $handle_error = true) { - global $config; - - if (file_exists($path)) { - $file_content = file($path); - $query = ""; - - // Begin the transaction - mysql_db_process_sql_begin(); - - foreach ($file_content as $sql_line) { - if (trim($sql_line) != "" && strpos($sql_line, "--") === false) { - - $query .= $sql_line; - - if (preg_match("/;[\040]*\$/", $sql_line)) { - if ($config["mysqli"]) { - $query_result = mysqli_query($config['dbconnection'], $query); - } - else { - $query_result = mysql_query($query); - } - if (!$result = $query_result) { - // Error. Rollback the transaction - mysql_db_process_sql_rollback(); - - $error_message = mysql_error(); - - // Handle the error - if ($handle_error) { - $backtrace = debug_backtrace(); - $error = sprintf('%s (\'%s\') in %s on line %d', - $error_message, $query, $backtrace[0]['file'], $backtrace[0]['line']); - db_add_database_debug_trace ($query, $error_message); - set_error_handler('db_sql_error_handler'); - trigger_error($error); - restore_error_handler(); - - return false; - } - // Throw an exception with the error message - else { - throw new Exception($error_message); - } - } - $query = ""; - } - } - } - - // No errors. Commit the transaction - mysql_db_process_sql_commit(); - - return true; - } - else { - return false; - } +function mysql_db_process_file($path, $handle_error=true) +{ + global $config; + + if (file_exists($path)) { + $file_content = file($path); + $query = ''; + + // Begin the transaction + mysql_db_process_sql_begin(); + + foreach ($file_content as $sql_line) { + if (trim($sql_line) != '' && strpos($sql_line, '--') === false) { + $query .= $sql_line; + + if (preg_match("/;[\040]*\$/", $sql_line)) { + if ($config['mysqli']) { + $query_result = mysqli_query($config['dbconnection'], $query); + } else { + $query_result = mysql_query($query); + } + + if (!$result = $query_result) { + // Error. Rollback the transaction + mysql_db_process_sql_rollback(); + + if ($config['mysqli']) { + $error_message = mysqli_error($config['dbconnection']); + } else { + $error_message = mysql_error(); + } + + // Handle the error + if ($handle_error) { + $backtrace = debug_backtrace(); + $error = sprintf( + '%s (\'%s\') in %s on line %d', + $error_message, + $query, + $backtrace[0]['file'], + $backtrace[0]['line'] + ); + db_add_database_debug_trace($query, $error_message); + set_error_handler('db_sql_error_handler'); + trigger_error($error); + restore_error_handler(); + + return false; + } + // Throw an exception with the error message + else { + throw new Exception($error_message); + } + } + + $query = ''; + } + } + } + + // No errors. Commit the transaction + mysql_db_process_sql_commit(); + return true; + } else { + return false; + } } -// --------------------------------------------------------------- -// Initiates a transaction and run the queries of an sql file -// --------------------------------------------------------------- -function db_run_sql_file ($location) { +// --------------------------------------------------------------- +// Initiates a transaction and run the queries of an sql file +// --------------------------------------------------------------- +function db_run_sql_file($location) +{ global $config; // Load file @@ -1296,40 +1432,39 @@ function db_run_sql_file ($location) { foreach ($lines as $line) { $line = trim($line); if ($line && !preg_match('/^--/', $line) && !preg_match('/^\/\*/', $line)) { - - $line = preg_replace('/;$/',"__;__", $line); + $line = preg_replace('/;$/', '__;__', $line); $commands .= $line; } } // Convert to array - $commands = explode("__;__", $commands); + $commands = explode('__;__', $commands); if ($config['mysqli']) { - $mysqli = new mysqli($config["dbhost"], $config["dbuser"], $config["dbpass"], $config["dbname"], $config["dbport"]); + $mysqli = new mysqli($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbname'], $config['dbport']); // Run commands $mysqli->query($config['dbconnection'], 'SET AUTOCOMMIT = 0'); $mysqli->query($config['dbconnection'], 'START TRANSACTION'); - } - else { + } else { // Run commands - mysql_db_process_sql_begin(); // Begin transaction + mysql_db_process_sql_begin(); + // Begin transaction } foreach ($commands as $command) { if (trim($command)) { - $command .= ";"; + $command .= ';'; if ($config['mysqli']) { $result = $mysqli->query($command); - } - else { + } else { $result = mysql_query($command); } if (!$result) { - break; // Error + break; + // Error } } } @@ -1338,22 +1473,21 @@ function db_run_sql_file ($location) { if ($config['mysqli']) { $mysqli->query($config['dbconnection'], 'COMMIT'); $mysqli->query($config['dbconnection'], 'SET AUTOCOMMIT = 1'); + } else { + mysql_db_process_sql_commit(); + // Save results } - else { - mysql_db_process_sql_commit(); // Save results - } + return true; - } - else { + } else { if ($config['mysqli']) { $mysqli->query($config['dbconnection'], 'ROLLBACK '); $mysqli->query($config['dbconnection'], 'SET AUTOCOMMIT = 1'); + } else { + mysql_db_process_sql_rollback(); + // Undo results } - else { - mysql_db_process_sql_rollback(); // Undo results - } + return false; } } - -?> diff --git a/pandora_console/include/db/oracle.php b/pandora_console/include/db/oracle.php index 4e7cec79f4..436cd3147f 100644 --- a/pandora_console/include/db/oracle.php +++ b/pandora_console/include/db/oracle.php @@ -4,65 +4,74 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function oracle_connect_db($host=null, $db=null, $user=null, $pass=null, $port=null, $new_connection=true) +{ + global $config; -function oracle_connect_db($host = null, $db = null, $user = null, $pass = null, $port = null, $new_connection = true) { - global $config; - - if ($host === null) - $host = $config["dbhost"]; - if ($db === null) - $db = $config["dbname"]; - if ($user === null) - $user = $config["dbuser"]; - if ($pass === null) - $pass = $config["dbpass"]; - if ($port === null) - $port = $config["dbport"]; - - // Non-persistent connection: This will help to avoid mysql errors like "has gone away" or locking problems - // If you want persistent connections change it to oci_pconnect(). - if ($new_connection) - $connect_id = oci_new_connect($user, $pass, '//' . $host . ':' . $port . '/' . $db); - else - $connect_id = oci_connect($user, $pass, '//' . $host . ':' . $port . '/' . $db); - - if (! $connect_id) { - return false; - } - - // Set date and timestamp formats for this session - $datetime_tz_format = oci_parse($connect_id , 'alter session set NLS_TIMESTAMP_TZ_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); - $datetime_format = oci_parse($connect_id , 'alter session set NLS_TIMESTAMP_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); - $date_format = oci_parse($connect_id , 'alter session set NLS_DATE_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); - $decimal_separator = oci_parse($connect_id , 'alter session set NLS_NUMERIC_CHARACTERS =\'.,\''); - - db_change_cache_id($host, $db); - - oci_execute($datetime_tz_format); - oci_execute($datetime_format); - oci_execute($date_format); - oci_execute($decimal_separator); - - oci_free_statement($datetime_tz_format); - oci_free_statement($datetime_format); - oci_free_statement($date_format); - oci_free_statement($decimal_separator); - - return $connect_id; + if ($host === null) { + $host = $config['dbhost']; + } + + if ($db === null) { + $db = $config['dbname']; + } + + if ($user === null) { + $user = $config['dbuser']; + } + + if ($pass === null) { + $pass = $config['dbpass']; + } + + if ($port === null) { + $port = $config['dbport']; + } + + // Non-persistent connection: This will help to avoid mysql errors like "has gone away" or locking problems + // If you want persistent connections change it to oci_pconnect(). + if ($new_connection) { + $connect_id = oci_new_connect($user, $pass, '//'.$host.':'.$port.'/'.$db); + } else { + $connect_id = oci_connect($user, $pass, '//'.$host.':'.$port.'/'.$db); + } + + if (! $connect_id) { + return false; + } + + // Set date and timestamp formats for this session + $datetime_tz_format = oci_parse($connect_id, 'alter session set NLS_TIMESTAMP_TZ_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); + $datetime_format = oci_parse($connect_id, 'alter session set NLS_TIMESTAMP_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); + $date_format = oci_parse($connect_id, 'alter session set NLS_DATE_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); + $decimal_separator = oci_parse($connect_id, 'alter session set NLS_NUMERIC_CHARACTERS =\'.,\''); + + db_change_cache_id($host, $db); + + oci_execute($datetime_tz_format); + oci_execute($datetime_format); + oci_execute($date_format); + oci_execute($decimal_separator); + + oci_free_statement($datetime_tz_format); + oci_free_statement($datetime_format); + oci_free_statement($date_format); + oci_free_statement($decimal_separator); + + return $connect_id; } -/** + +/** * Get the first value of the first row of a table in the database. - * + * * @param string Field name to get * @param string Table to retrieve the data * @param string Field to filter elements @@ -70,42 +79,58 @@ function oracle_connect_db($host = null, $db = null, $user = null, $pass = null, * * @return mixed Value of first column of the first row. False if there were no row. */ -function oracle_db_get_value ($field, $table, $field_search = 1, $condition = 1, $search_history_db = false) { - - if (is_int ($condition)) { - $sql = sprintf ("SELECT * +function oracle_db_get_value($field, $table, $field_search=1, $condition=1, $search_history_db=false) +{ + if (is_int($condition)) { + $sql = sprintf( + 'SELECT * FROM (SELECT %s FROM %s WHERE %s = %d) - WHERE rownum < 2", - $field, $table, $field_search, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT * + WHERE rownum < 2', + $field, + $table, + $field_search, + $condition + ); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf( + 'SELECT * FROM (SELECT %s FROM %s WHERE %s = %f) - WHERE rownum < 2", - $field, $table, $field_search, $condition); - } - else { - $sql = sprintf ("SELECT * + WHERE rownum < 2', + $field, + $table, + $field_search, + $condition + ); + } else { + $sql = sprintf( + "SELECT * FROM (SELECT %s FROM %s WHERE %s = '%s') WHERE rownum < 2", - $field, $table, $field_search, $condition); - } - - $result = db_get_all_rows_sql ($sql, $search_history_db); - - if ($result === false) - return false; - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; + $field, + $table, + $field_search, + $condition + ); + } + + $result = db_get_all_rows_sql($sql, $search_history_db); + + if ($result === false) { + return false; + } + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } -/** + +/** * Get the first row of a database query into a table. * * The SQL statement executed would be something like: @@ -115,90 +140,113 @@ function oracle_db_get_value ($field, $table, $field_search = 1, $condition = 1, * @param string Field to filter elements * @param string Condition the field must have. * @param mixed Fields to select (array or string or false/empty for *) - * + * * @return mixed The first row of a database query or false. */ -function oracle_db_get_row ($table, $field_search, $condition, $fields = false) { - if (empty ($fields)) { - $fields = '*'; - } - else { - if (is_array ($fields)) - $fields = implode (',', $fields); - else if (! is_string ($fields)) - return false; - } - - if (is_int ($condition)) { - $sql = sprintf ('SELECT * FROM (SELECT %s FROM %s WHERE %s = %d) WHERE rownum < 2', - $fields, $table, $field_search, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT * FROM (SELECT %s FROM %s WHERE \"%s\" = %f) WHERE rownum < 2", - $fields, $table, $field_search, $condition); - } - else { - $sql = sprintf ("SELECT * FROM (SELECT %s FROM %s WHERE %s = '%s') WHERE rownum < 2", - $fields, $table, $field_search, $condition); - } - $result = db_get_all_rows_sql ($sql); - - if ($result === false) - return false; - - return $result[0]; +function oracle_db_get_row($table, $field_search, $condition, $fields=false) +{ + if (empty($fields)) { + $fields = '*'; + } else { + if (is_array($fields)) { + $fields = implode(',', $fields); + } else if (! is_string($fields)) { + return false; + } + } + + if (is_int($condition)) { + $sql = sprintf( + 'SELECT * FROM (SELECT %s FROM %s WHERE %s = %d) WHERE rownum < 2', + $fields, + $table, + $field_search, + $condition + ); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf( + 'SELECT * FROM (SELECT %s FROM %s WHERE "%s" = %f) WHERE rownum < 2', + $fields, + $table, + $field_search, + $condition + ); + } else { + $sql = sprintf( + "SELECT * FROM (SELECT %s FROM %s WHERE %s = '%s') WHERE rownum < 2", + $fields, + $table, + $field_search, + $condition + ); + } + + $result = db_get_all_rows_sql($sql); + + if ($result === false) { + return false; + } + + return $result[0]; } -function oracle_db_get_all_rows_sql ($sql, $search_history_db = false, $cache = true, $dbconnection = false) { - global $config; - - $history = array (); - - if ($dbconnection === false) { - $dbconnection = $config['dbconnection']; - } - - // To disable globally SQL cache depending on global variable. - // Used in several critical places like Metaconsole trans-server queries - if (isset($config["dbcache"])) - $cache = $config["dbcache"]; - - // Read from the history DB if necessary - if ($search_history_db && $config['history_db_enabled'] == 1) { - $cache = false; - $history = false; - - // Connect to the history DB - if (! isset ($config['history_db_connection']) || $config['history_db_connection'] === false) { - $config['history_db_connection'] = db_connect($config['history_db_host'], $config['history_db_name'], $config['history_db_user'], io_output_password($config['history_db_pass']), $config['history_db_port'], false); - } - if ($config['history_db_connection'] !== false) { - $history = oracle_db_process_sql ($sql, 'affected_rows', $config['history_db_connection'], false); - } - - if ($history === false) { - $history = array (); - } - } - - $return = oracle_db_process_sql ($sql, 'affected_rows', $dbconnection, $cache); - if ($return === false) { - $return = array (); - } - - // Append result to the history DB data - if (! empty ($return)) { - foreach ($return as $row) { - array_push ($history, $row); - } - } - - if (! empty ($history)) - return $history; - //Return false, check with === or !== - return false; + +function oracle_db_get_all_rows_sql($sql, $search_history_db=false, $cache=true, $dbconnection=false) +{ + global $config; + + $history = []; + + if ($dbconnection === false) { + $dbconnection = $config['dbconnection']; + } + + // To disable globally SQL cache depending on global variable. + // Used in several critical places like Metaconsole trans-server queries + if (isset($config['dbcache'])) { + $cache = $config['dbcache']; + } + + // Read from the history DB if necessary + if ($search_history_db && $config['history_db_enabled'] == 1) { + $cache = false; + $history = false; + + // Connect to the history DB + if (! isset($config['history_db_connection']) || $config['history_db_connection'] === false) { + $config['history_db_connection'] = db_connect($config['history_db_host'], $config['history_db_name'], $config['history_db_user'], io_output_password($config['history_db_pass']), $config['history_db_port'], false); + } + + if ($config['history_db_connection'] !== false) { + $history = oracle_db_process_sql($sql, 'affected_rows', $config['history_db_connection'], false); + } + + if ($history === false) { + $history = []; + } + } + + $return = oracle_db_process_sql($sql, 'affected_rows', $dbconnection, $cache); + if ($return === false) { + $return = []; + } + + // Append result to the history DB data + if (! empty($return)) { + foreach ($return as $row) { + array_push($history, $row); + } + } + + if (! empty($history)) { + return $history; + } + + // Return false, check with === or !== + return false; } + /** * This function comes back with an array in case of SELECT * in case of UPDATE, DELETE etc. with affected rows @@ -208,179 +256,200 @@ function oracle_db_get_all_rows_sql ($sql, $search_history_db = false, $cache = * @param string SQL statement to execute * * @param string What type of info to return in case of INSERT/UPDATE. - * 'affected_rows' will return mysql_affected_rows (default value) - * 'insert_id' will return the ID of an autoincrement value - * 'info' will return the full (debug) information of a query + * 'affected_rows' will return mysql_affected_rows (default value) + * 'insert_id' will return the ID of an autoincrement value + * 'info' will return the full (debug) information of a query * - * @param bool Set autocommit transaction mode true/false + * @param bool Set autocommit transaction mode true/false * * @return mixed An array with the rows, columns and values in a multidimensional array or false in error */ // TODO: Return debug info of the query -function oracle_db_process_sql($sql, $rettype = "affected_rows", $dbconnection = '', $cache = true, &$status = null, $autocommit = true) { - global $config; - global $sql_cache; - - $retval = array(); - - if ($sql == '') - return false; - - if ($cache && ! empty ($sql_cache[$sql_cache['id']][$sql])) { - $retval = $sql_cache[$sql_cache['id']][$sql]; - $sql_cache['saved'][$sql_cache['id']]++; - db_add_database_debug_trace ($sql); - } - else { - $id = 0; - $parse_query = explode(' ', trim(preg_replace('/\s\s+/', ' ', $sql))); - $table_name = preg_replace('/\((\w*|,\w*)*\)|\(\w*|,\w*/', '', preg_replace('/\s/', '', $parse_query[2])); - $type = explode(' ', strtoupper(trim($sql))); - - $start = microtime (true); - - if (empty($dbconnection)) { - $dbconnection = $config['dbconnection']; - } - - if ($type[0] == 'INSERT') { - $query = oci_parse($dbconnection, 'BEGIN insert_id(:table_name, :sql, :out); END;'); - } - // Prevent execution of insert_id stored procedure - else if ($type[0] == '/INSERT') { - $query = oci_parse($dbconnection, substr($sql,1)); - } - else { - $query = oci_parse($dbconnection, $sql); - } - - //If query is an insert retrieve Id field - if ($type[0] == 'INSERT') { - oci_bind_by_name($query, ":table_name", $table_name, 32); - oci_bind_by_name($query, ":sql", $sql, -1); - oci_bind_by_name($query, ":out", $id, 40); - } - - if (!$autocommit) { - $result = oci_execute($query, OCI_NO_AUTO_COMMIT); - } - else { - $result = oci_execute($query); - } - $time = microtime (true) - $start; - - $config['oracle_error_query'] = null; - if ($result === false) { - $backtrace = debug_backtrace (); - $e = oci_error($query); - - $config['oracle_error_query'] = $query; - - - $error = sprintf ('%s (\'%s\') in %s on line %d', - htmlentities($e['message'], ENT_QUOTES), $sql, $backtrace[0]['file'], $backtrace[0]['line']); - db_add_database_debug_trace ($sql, htmlentities($e['message'], ENT_QUOTES)); - - set_error_handler ('db_sql_error_handler'); - trigger_error ($error); - restore_error_handler (); - - return false; - } - else { - $status = oci_statement_type($query); - $rows = oci_num_rows($query); - - if ($status !== 'SELECT') { //The query NOT IS a select - if ($rettype == "insert_id") { - $result = $id; - } - elseif ($rettype == "info") { - //TODO: return debug information of the query $result = pg_result_status($result, PGSQL_STATUS_STRING); - $result = ''; - } - else { - $result = $rows; - } - db_add_database_debug_trace ($sql, $result, $rows, - array ('time' => $time)); - - return $result; - } - else { //The query IS a select. - db_add_database_debug_trace ($sql, 0, $rows, array ('time' => $time)); - while ($row = oci_fetch_assoc($query)) { - $i = 1; - $result_temp = array(); - foreach ($row as $key => $value) { - $column_type = oci_field_type($query, $key); - // Support for Clob fields larger than 4000bytes - //if ($sql == 'SELECT * FROM tgrupo ORDER BY dbms_lob.substr(nombre,4000,1) ASC') echo $i .' '.$column_type.' '.$key.'
        '; - if ($column_type == 'CLOB') { - $column_name = oci_field_name($query, $i); - // Protect against a NULL CLOB - if (is_object($row[$column_name])) { - $clob_data = $row[$column_name]->load(); - $row[$column_name]->free(); - $value = $clob_data; - } - else { - $value = ''; - } - } - $result_temp[strtolower($key)] = $value; - $i++; - } - array_push($retval, $result_temp); - //array_push($retval, $row); - } - - if ($cache === true) - $sql_cache[$sql_cache['id']][$sql] = $retval; - oci_free_statement ($query); - } - } - } - - if (! empty ($retval)) { - return $retval; - } - - //Return false, check with === or !== - return false; +function oracle_db_process_sql($sql, $rettype='affected_rows', $dbconnection='', $cache=true, &$status=null, $autocommit=true) +{ + global $config; + global $sql_cache; + + $retval = []; + + if ($sql == '') { + return false; + } + + if ($cache && ! empty($sql_cache[$sql_cache['id']][$sql])) { + $retval = $sql_cache[$sql_cache['id']][$sql]; + $sql_cache['saved'][$sql_cache['id']]++; + db_add_database_debug_trace($sql); + } else { + $id = 0; + $parse_query = explode(' ', trim(preg_replace('/\s\s+/', ' ', $sql))); + $table_name = preg_replace('/\((\w*|,\w*)*\)|\(\w*|,\w*/', '', preg_replace('/\s/', '', $parse_query[2])); + $type = explode(' ', strtoupper(trim($sql))); + + $start = microtime(true); + + if (empty($dbconnection)) { + $dbconnection = $config['dbconnection']; + } + + if ($type[0] == 'INSERT') { + $query = oci_parse($dbconnection, 'BEGIN insert_id(:table_name, :sql, :out); END;'); + } + // Prevent execution of insert_id stored procedure + else if ($type[0] == '/INSERT') { + $query = oci_parse($dbconnection, substr($sql, 1)); + } else { + $query = oci_parse($dbconnection, $sql); + } + + // If query is an insert retrieve Id field + if ($type[0] == 'INSERT') { + oci_bind_by_name($query, ':table_name', $table_name, 32); + oci_bind_by_name($query, ':sql', $sql, -1); + oci_bind_by_name($query, ':out', $id, 40); + } + + if (!$autocommit) { + $result = oci_execute($query, OCI_NO_AUTO_COMMIT); + } else { + $result = oci_execute($query); + } + + $time = (microtime(true) - $start); + + $config['oracle_error_query'] = null; + if ($result === false) { + $backtrace = debug_backtrace(); + $e = oci_error($query); + + $config['oracle_error_query'] = $query; + + $error = sprintf( + '%s (\'%s\') in %s on line %d', + htmlentities($e['message'], ENT_QUOTES), + $sql, + $backtrace[0]['file'], + $backtrace[0]['line'] + ); + db_add_database_debug_trace($sql, htmlentities($e['message'], ENT_QUOTES)); + + set_error_handler('db_sql_error_handler'); + trigger_error($error); + restore_error_handler(); + + return false; + } else { + $status = oci_statement_type($query); + $rows = oci_num_rows($query); + + if ($status !== 'SELECT') { + // The query NOT IS a select + if ($rettype == 'insert_id') { + $result = $id; + } else if ($rettype == 'info') { + // TODO: return debug information of the query $result = pg_result_status($result, PGSQL_STATUS_STRING); + $result = ''; + } else { + $result = $rows; + } + + db_add_database_debug_trace( + $sql, + $result, + $rows, + ['time' => $time] + ); + + return $result; + } else { + // The query IS a select. + db_add_database_debug_trace($sql, 0, $rows, ['time' => $time]); + while ($row = oci_fetch_assoc($query)) { + $i = 1; + $result_temp = []; + foreach ($row as $key => $value) { + $column_type = oci_field_type($query, $key); + // Support for Clob fields larger than 4000bytes + // if ($sql == 'SELECT * FROM tgrupo ORDER BY dbms_lob.substr(nombre,4000,1) ASC') echo $i .' '.$column_type.' '.$key.'
        '; + if ($column_type == 'CLOB') { + $column_name = oci_field_name($query, $i); + // Protect against a NULL CLOB + if (is_object($row[$column_name])) { + $clob_data = $row[$column_name]->load(); + $row[$column_name]->free(); + $value = $clob_data; + } else { + $value = ''; + } + } + + $result_temp[strtolower($key)] = $value; + $i++; + } + + array_push($retval, $result_temp); + // array_push($retval, $row); + } + + if ($cache === true) { + $sql_cache[$sql_cache['id']][$sql] = $retval; + } + + oci_free_statement($query); + } + } + } + + if (! empty($retval)) { + return $retval; + } + + // Return false, check with === or !== + return false; } + /** * Get all the rows in a table of the database. - * + * * @param string Database table name. * @param string Field to order by. - * @param string $order The type of order, by default 'ASC'. + * @param string $order The type of order, by default 'ASC'. * * @return mixed A matrix with all the values in the table */ -function oracle_db_get_all_rows_in_table($table, $order_field = "", $order = 'ASC') { - if ($order_field != "") { - - // Clob fields are not allowed in ORDER BY statements, they need cast to varchar2 datatype - $type = db_get_value_filter ('data_type', 'user_tab_columns', - array ('table_name' => strtoupper($table), 'column_name' => strtoupper($order_field)), 'AND'); - if ($type == 'CLOB') { - return db_get_all_rows_sql ('SELECT * - FROM ' . $table . ' - ORDER BY dbms_lob.substr(' . $order_field . ',4000,1) ' . $order); - } - else { - return db_get_all_rows_sql ('SELECT * - FROM ' . $table . ' - ORDER BY ' . $order_field . ' ' . $order); - } - } - else { - return db_get_all_rows_sql ('SELECT * FROM ' . $table); - } +function oracle_db_get_all_rows_in_table($table, $order_field='', $order='ASC') +{ + if ($order_field != '') { + // Clob fields are not allowed in ORDER BY statements, they need cast to varchar2 datatype + $type = db_get_value_filter( + 'data_type', + 'user_tab_columns', + [ + 'table_name' => strtoupper($table), + 'column_name' => strtoupper($order_field), + ], + 'AND' + ); + if ($type == 'CLOB') { + return db_get_all_rows_sql( + 'SELECT * + FROM '.$table.' + ORDER BY dbms_lob.substr('.$order_field.',4000,1) '.$order + ); + } else { + return db_get_all_rows_sql( + 'SELECT * + FROM '.$table.' + ORDER BY '.$order_field.' '.$order + ); + } + } else { + return db_get_all_rows_sql('SELECT * FROM '.$table); + } } + /** * Inserts strings into database * @@ -394,76 +463,80 @@ function oracle_db_get_all_rows_in_table($table, $order_field = "", $order = 'AS * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function oracle_db_process_sql_insert($table, $values, $autocommit = true) { - //Empty rows or values not processed - if (empty ($values)) - return false; - - $values = (array) $values; - - $query = sprintf ('INSERT INTO %s ', $table); - $fields = array (); - $values_str = ''; - $i = 1; - $max = count ($values); - foreach ($values as $field => $value) { - array_push ($fields, $field); - - if (is_null ($value)) { - $values_str .= "NULL"; - } - elseif (is_int ($value) || is_bool ($value)) { - $values_str .= sprintf("%d", $value); - } - else if (is_float ($value) || is_double ($value)) { - $values_str .= sprintf("%f", $value); - } - else if (substr($value,0,1) == '#') { - $values_str .= sprintf("%s", substr($value,1)); - } - else { - $values_str .= sprintf("'%s'", $value); - } - - if ($i < $max) { - $values_str .= ","; - } - $i++; - } - - $query .= '(' . implode(', ', $fields) . ')'; - - $query .= ' VALUES (' . $values_str . ')'; - $status = ''; - - return db_process_sql($query, 'insert_id', '', true, $status, $autocommit); +function oracle_db_process_sql_insert($table, $values, $autocommit=true) +{ + // Empty rows or values not processed + if (empty($values)) { + return false; + } + + $values = (array) $values; + + $query = sprintf('INSERT INTO %s ', $table); + $fields = []; + $values_str = ''; + $i = 1; + $max = count($values); + foreach ($values as $field => $value) { + array_push($fields, $field); + + if (is_null($value)) { + $values_str .= 'NULL'; + } else if (is_int($value) || is_bool($value)) { + $values_str .= sprintf('%d', $value); + } else if (is_float($value) || is_double($value)) { + $values_str .= sprintf('%f', $value); + } else if (substr($value, 0, 1) == '#') { + $values_str .= sprintf('%s', substr($value, 1)); + } else { + $values_str .= sprintf("'%s'", $value); + } + + if ($i < $max) { + $values_str .= ','; + } + + $i++; + } + + $query .= '('.implode(', ', $fields).')'; + + $query .= ' VALUES ('.$values_str.')'; + $status = ''; + + return db_process_sql($query, 'insert_id', '', true, $status, $autocommit); } + /** * Escape string to set it properly to use in sql queries - * + * * @param string String to be cleaned. - * + * * @return string String cleaned. */ -function oracle_escape_string_sql($string) { - return str_replace(array('"', "'", '\\'), array('\\"', '\\\'', '\\\\'), $string); +function oracle_escape_string_sql($string) +{ + return str_replace(['"', "'", '\\'], ['\\"', '\\\'', '\\\\'], $string); } -function oracle_encapsule_fields_with_same_name_to_instructions($field) { - $return = $field; - - if (is_string($return)) { - if ($return[0] !== '"') { - // The columns declared without quotes are converted to uppercase in oracle. - // A column named asd is equal to asd, ASD or "ASD", but no to "asd". - $return = '"' . $return . '"'; - } - } - - return $return; + +function oracle_encapsule_fields_with_same_name_to_instructions($field) +{ + $return = $field; + + if (is_string($return)) { + if ($return[0] !== '"') { + // The columns declared without quotes are converted to uppercase in oracle. + // A column named asd is equal to asd, ASD or "ASD", but no to "asd". + $return = '"'.$return.'"'; + } + } + + return $return; } + /** * Get the first value of the first row of a table in the database from an * array with filter conditions. @@ -493,31 +566,39 @@ function oracle_encapsule_fields_with_same_name_to_instructions($field) { * * @return mixed Value of first column of the first row. False if there were no row. */ -function oracle_db_get_value_filter ($field, $table, $filter, $where_join = 'AND', $search_history_db = false) { - if (! is_array ($filter) || empty ($filter)) - return false; - - /* Avoid limit and offset if given */ - unset ($filter['limit']); - unset ($filter['offset']); - - $sql = sprintf ("SELECT * FROM (SELECT %s FROM %s WHERE %s) WHERE rownum < 2", - $field, $table, - db_format_array_where_clause_sql ($filter, $where_join)); - $result = db_get_all_rows_sql ($sql, $search_history_db); - - if ($result === false) - return false; - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; +function oracle_db_get_value_filter($field, $table, $filter, $where_join='AND', $search_history_db=false) +{ + if (! is_array($filter) || empty($filter)) { + return false; + } + + // Avoid limit and offset if given + unset($filter['limit']); + unset($filter['offset']); + + $sql = sprintf( + 'SELECT * FROM (SELECT %s FROM %s WHERE %s) WHERE rownum < 2', + $field, + $table, + db_format_array_where_clause_sql($filter, $where_join) + ); + $result = db_get_all_rows_sql($sql, $search_history_db); + + if ($result === false) { + return false; + } + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } + /** * Formats an array of values into a SQL where clause string. * @@ -556,155 +637,159 @@ function oracle_db_get_value_filter ($field, $table, $filter, $where_join = 'AND // SELECT * FROM table WHERE VALUE = 10 ORDER BY name DESC - IMPORTANT!!! OFFSET is not allowed in this function because Oracle needs to recode the complete query. + IMPORTANT!!! OFFSET is not allowed in this function because Oracle needs to recode the complete query. use oracle_recode_query() function instead * * @return string Values joined into an SQL string that can fits into the WHERE * clause of an SQL sentence. */ -function oracle_db_format_array_where_clause_sql ($values, $join = 'AND', $prefix = false) { - - $fields = array (); - - if (! is_array ($values)) { - return ''; - } - - $query = ''; - $limit = ''; - $order = ''; - $group = ''; - if (isset($values['offset'])) { - return ''; - } - - if (isset ($values['limit'])) { - $limit = sprintf (' AND rownum <= %d', $values['limit']); - unset ($values['limit']); - } - - if (isset ($values['order'])) { - if (is_array($values['order'])) { - if (!isset($values['order']['order'])) { - $orderTexts = array(); - foreach ($values['order'] as $orderItem) { - $orderTexts[] = $orderItem['field'] . ' ' . $orderItem['order']; - } - $order = ' ORDER BY ' . implode(', ', $orderTexts); - } - else { - $order = sprintf (' ORDER BY %s %s', $values['order']['field'], $values['order']['order']); - } - } - else { - $order = sprintf (' ORDER BY %s', $values['order']); - } - unset ($values['order']); - } - - if (isset ($values['group'])) { - $group = sprintf (' GROUP BY %s', $values['group']); - unset ($values['group']); - } - - $i = 1; - $max = count ($values); - foreach ($values as $field => $value) { - if ($i == 1) { - $query .= ' ( '; - } - if ($field == '1' AND $value == '1') { - $query .= sprintf("'%s' = '%s'", $field, $value); - - if ($i < $max) { - $query .= ' '.$join.' '; - } - if ($i == $max) { - $query .= ' ) '; - } - $i++; - continue; - } - else if (is_numeric ($field)) { - /* User provide the exact operation to do */ - $query .= $value; - - if ($i < $max) { - $query .= ' '.$join.' '; - } - if ($i == $max) { - $query .= ' ) '; - } - $i++; - continue; - } - - if (is_null ($value)) { - $query .= sprintf ("%s IS NULL", $field); - } - elseif (is_int ($value) || is_bool ($value)) { - $query .= sprintf ("%s = %d", $field, $value); - } - else if (is_float ($value) || is_double ($value)) { - $query .= sprintf ("%s = %f", $field, $value); - } - elseif (is_array ($value)) { - $query .= sprintf ("%s IN ('%s')", $field, implode ("', '", $value)); - } - else { - if ($value[0] == ">") { - $value = substr($value,1,strlen($value)-1); - - if (is_nan($value)) - $query .= sprintf ("%s > '%s'", $field, $value); - else - $query .= sprintf ("%s > %s", $field, $value); - } - else if ($value[0] == "<") { - if ($value[1] == ">") { - $value = substr($value,2,strlen($value)-2); - - if (is_nan($value)) - $query .= sprintf ("%s <> '%s'", $field, $value); - else - $query .= sprintf ("%s <> %s", $field, $value); - } - else { - $value = substr($value,1,strlen($value)-1); - - if (is_nan($value)) - $query .= sprintf ("%s < '%s'", $field, $value); - else - $query .= sprintf ("%s < %s", $field, $value); - } - } - else if ($value[0] == '%') { - $query .= sprintf ("%s LIKE '%s'", $field, $value); - } - else { - $query .= sprintf ("%s = '%s'", $field, $value); - } - } - - if ($i < $max) { - $query .= ' '.$join.' '; - } - if ($i == $max) { - $query .= ' ) '; - } - $i++; - } - return (! empty ($query) ? $prefix: '').$query.$limit.$group.$order; +function oracle_db_format_array_where_clause_sql($values, $join='AND', $prefix=false) +{ + $fields = []; + + if (! is_array($values)) { + return ''; + } + + $query = ''; + $limit = ''; + $order = ''; + $group = ''; + if (isset($values['offset'])) { + return ''; + } + + if (isset($values['limit'])) { + $limit = sprintf(' AND rownum <= %d', $values['limit']); + unset($values['limit']); + } + + if (isset($values['order'])) { + if (is_array($values['order'])) { + if (!isset($values['order']['order'])) { + $orderTexts = []; + foreach ($values['order'] as $orderItem) { + $orderTexts[] = $orderItem['field'].' '.$orderItem['order']; + } + + $order = ' ORDER BY '.implode(', ', $orderTexts); + } else { + $order = sprintf(' ORDER BY %s %s', $values['order']['field'], $values['order']['order']); + } + } else { + $order = sprintf(' ORDER BY %s', $values['order']); + } + + unset($values['order']); + } + + if (isset($values['group'])) { + $group = sprintf(' GROUP BY %s', $values['group']); + unset($values['group']); + } + + $i = 1; + $max = count($values); + foreach ($values as $field => $value) { + if ($i == 1) { + $query .= ' ( '; + } + + if ($field == '1' and $value == '1') { + $query .= sprintf("'%s' = '%s'", $field, $value); + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + if ($i == $max) { + $query .= ' ) '; + } + + $i++; + continue; + } else if (is_numeric($field)) { + // User provide the exact operation to do + $query .= $value; + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + if ($i == $max) { + $query .= ' ) '; + } + + $i++; + continue; + } + + if (is_null($value)) { + $query .= sprintf('%s IS NULL', $field); + } else if (is_int($value) || is_bool($value)) { + $query .= sprintf('%s = %d', $field, $value); + } else if (is_float($value) || is_double($value)) { + $query .= sprintf('%s = %f', $field, $value); + } else if (is_array($value)) { + $query .= sprintf("%s IN ('%s')", $field, implode("', '", $value)); + } else { + if ($value[0] == '>') { + $value = substr($value, 1, (strlen($value) - 1)); + + if (is_nan($value)) { + $query .= sprintf("%s > '%s'", $field, $value); + } else { + $query .= sprintf('%s > %s', $field, $value); + } + } else if ($value[0] == '<') { + if ($value[1] == '>') { + $value = substr($value, 2, (strlen($value) - 2)); + + if (is_nan($value)) { + $query .= sprintf("%s <> '%s'", $field, $value); + } else { + $query .= sprintf('%s <> %s', $field, $value); + } + } else { + $value = substr($value, 1, (strlen($value) - 1)); + + if (is_nan($value)) { + $query .= sprintf("%s < '%s'", $field, $value); + } else { + $query .= sprintf('%s < %s', $field, $value); + } + } + } else if ($value[0] == '%') { + $query .= sprintf("%s LIKE '%s'", $field, $value); + } else { + $query .= sprintf("%s = '%s'", $field, $value); + } + } + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + if ($i == $max) { + $query .= ' ) '; + } + + $i++; + } + + return (! empty($query) ? $prefix : '').$query.$limit.$group.$order; } + /** * Formats an SQL query to use LIMIT and OFFSET Mysql like statements in Oracle. * * This function is useful to generate an SQL sentence from * a list of values. Example code: + * * @param string Join operator. AND by default. - * @param string A prefix to be added to the string. It's useful when + * @param string A prefix to be added to the string. It's useful when * offset could be given to avoid this cases: $values = array (); @@ -733,179 +818,177 @@ function oracle_db_format_array_where_clause_sql ($values, $join = 'AND', $prefi * @param string Sql from SELECT to WHERE reserved words: SELECT * FROM mytable WHERE * @param array Conditions to filter the element. See db_format_array_where_clause_sql() - * for the format. LIMIT + OFFSET are allowed in this function: + * for the format. LIMIT + OFFSET are allowed in this function: - $values = array(); - $values['limit'] = x; + $values = array(); + $values['limit'] = x; $values['offset'] = y; * @param string Join operator for the elements in the filter. - * @param bool Whether to return Sql or execute. Note that if you return data in a string format then after execute the query you have + * @param bool Whether to return Sql or execute. Note that if you return data in a string format then after execute the query you have * to discard RNUM column. * * @return string Values joined into an SQL string that fits Oracle SQL sintax * clause of an SQL sentence. **/ -function oracle_recode_query ($sql, $values, $join = 'AND', $return = true) { - $fields = array (); - - if (! is_array ($values) || empty($sql)) { - return ''; - } - - $query = ''; - $limit = ''; - $offset = ''; - $order = ''; - $group = ''; - $pre_query = ''; - $post_query = ''; - // LIMIT + OFFSET options have to be recoded into a subquery - if (isset ($values['limit']) && isset($values['offset'])) { - $down = $values['offset']; - $top = $values['offset'] + $values['limit']; - $pre_query = 'SELECT * FROM (SELECT ROWNUM AS rnum, a.* FROM ('; - $post_query = sprintf(") a) WHERE rnum > %d AND rnum <= %d", $down, $top); - unset ($values['limit']); - unset ($values['offset']); - } - else if (isset ($values['limit'])) { - $limit = sprintf (' AND rownum <= %d', $values['limit']); - unset ($values['limit']); - } - // OFFSET without LIMIT option is not supported - else if (isset ($values['offset'])) { - unset ($values['offset']); - } - - if (isset ($values['order'])) { - if (is_array($values['order'])) { - if (!isset($values['order']['order'])) { - $orderTexts = array(); - foreach ($values['order'] as $orderItem) { - $orderTexts[] = $orderItem['field'] . ' ' . $orderItem['order']; - } - $order = ' ORDER BY ' . implode(', ', $orderTexts); - } - else { - $order = sprintf (' ORDER BY %s %s', $values['order']['field'], $values['order']['order']); - } - } - else { - $order = sprintf (' ORDER BY %s', $values['order']); - } - unset ($values['order']); - } - - if (isset ($values['group'])) { - $group = sprintf (' GROUP BY %s', $values['group']); - unset ($values['group']); - } - - $i = 1; - $max = count ($values); - foreach ($values as $field => $value) { - if ($i == 1) { - $query .= ' ( '; - } - - if (is_numeric ($field)) { - /* User provide the exact operation to do */ - $query .= $value; - - if ($i < $max) { - $query .= ' '.$join.' '; - } - $i++; - continue; - } - - if (is_null ($value)) { - $query .= sprintf ("%s IS NULL", $field); - } - elseif (is_int ($value) || is_bool ($value)) { - $query .= sprintf ("%s = %d", $field, $value); - } - else if (is_float ($value) || is_double ($value)) { - $query .= sprintf ("%s = %f", $field, $value); - } - elseif (is_array ($value)) { - $query .= sprintf ("%s IN ('%s')", $field, implode ("', '", $value)); - } - else { - if ($value[0] == ">") { - $value = substr($value,1,strlen($value) - 1); - $query .= sprintf ("%s > '%s'", $field, $value); - } - else if ($value[0] == "<") { - if ($value[1] == ">") { - $value = substr($value,2,strlen($value) - 2); - $query .= sprintf ("%s <> '%s'", $field, $value); - } - else { - $value = substr($value,1,strlen($value) - 1); - $query .= sprintf ("%s < '%s'", $field, $value); - } - } - else if ($value[0] == '%') { - $query .= sprintf ("%s LIKE '%s'", $field, $value); - } - else { - $query .= sprintf ("%s = '%s'", $field, $value); - } - } - - if ($i < $max) { - $query .= ' '.$join.' '; - } - if ($i == $max) { - $query .= ' ) '; - } - $i++; - } - - $result = $pre_query.$sql.$query.$limit.$group.$order.$post_query; - if ($return) { - return $result; - } - else { - - $result = oracle_db_process_sql($result); - if ($result !== false) { - for ($i=0; $i < count($result); $i++) { - unset($result[$i]['RNUM']); - } - } - return $result; - } +function oracle_recode_query($sql, $values, $join='AND', $return=true) +{ + $fields = []; + + if (! is_array($values) || empty($sql)) { + return ''; + } + + $query = ''; + $limit = ''; + $offset = ''; + $order = ''; + $group = ''; + $pre_query = ''; + $post_query = ''; + // LIMIT + OFFSET options have to be recoded into a subquery + if (isset($values['limit']) && isset($values['offset'])) { + $down = $values['offset']; + $top = ($values['offset'] + $values['limit']); + $pre_query = 'SELECT * FROM (SELECT ROWNUM AS rnum, a.* FROM ('; + $post_query = sprintf(') a) WHERE rnum > %d AND rnum <= %d', $down, $top); + unset($values['limit']); + unset($values['offset']); + } else if (isset($values['limit'])) { + $limit = sprintf(' AND rownum <= %d', $values['limit']); + unset($values['limit']); + } + // OFFSET without LIMIT option is not supported + else if (isset($values['offset'])) { + unset($values['offset']); + } + + if (isset($values['order'])) { + if (is_array($values['order'])) { + if (!isset($values['order']['order'])) { + $orderTexts = []; + foreach ($values['order'] as $orderItem) { + $orderTexts[] = $orderItem['field'].' '.$orderItem['order']; + } + + $order = ' ORDER BY '.implode(', ', $orderTexts); + } else { + $order = sprintf(' ORDER BY %s %s', $values['order']['field'], $values['order']['order']); + } + } else { + $order = sprintf(' ORDER BY %s', $values['order']); + } + + unset($values['order']); + } + + if (isset($values['group'])) { + $group = sprintf(' GROUP BY %s', $values['group']); + unset($values['group']); + } + + $i = 1; + $max = count($values); + foreach ($values as $field => $value) { + if ($i == 1) { + $query .= ' ( '; + } + + if (is_numeric($field)) { + // User provide the exact operation to do + $query .= $value; + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + $i++; + continue; + } + + if (is_null($value)) { + $query .= sprintf('%s IS NULL', $field); + } else if (is_int($value) || is_bool($value)) { + $query .= sprintf('%s = %d', $field, $value); + } else if (is_float($value) || is_double($value)) { + $query .= sprintf('%s = %f', $field, $value); + } else if (is_array($value)) { + $query .= sprintf("%s IN ('%s')", $field, implode("', '", $value)); + } else { + if ($value[0] == '>') { + $value = substr($value, 1, (strlen($value) - 1)); + $query .= sprintf("%s > '%s'", $field, $value); + } else if ($value[0] == '<') { + if ($value[1] == '>') { + $value = substr($value, 2, (strlen($value) - 2)); + $query .= sprintf("%s <> '%s'", $field, $value); + } else { + $value = substr($value, 1, (strlen($value) - 1)); + $query .= sprintf("%s < '%s'", $field, $value); + } + } else if ($value[0] == '%') { + $query .= sprintf("%s LIKE '%s'", $field, $value); + } else { + $query .= sprintf("%s = '%s'", $field, $value); + } + } + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + if ($i == $max) { + $query .= ' ) '; + } + + $i++; + } + + $result = $pre_query.$sql.$query.$limit.$group.$order.$post_query; + if ($return) { + return $result; + } else { + $result = oracle_db_process_sql($result); + if ($result !== false) { + for ($i = 0; $i < count($result); $i++) { + unset($result[$i]['RNUM']); + } + } + + return $result; + } } + /** * Get the first value of the first row of a table result from query. * * @param string SQL select statement to execute. * * @return the first value of the first row of a table result from query. - * */ -function oracle_db_get_value_sql($sql, $dbconnection = false) { - $sql = "SELECT * FROM (" . $sql . ") WHERE rownum < 2"; - $result = oracle_db_get_all_rows_sql ($sql, false, true, $dbconnection); - - if ($result === false) - return false; - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; +function oracle_db_get_value_sql($sql, $dbconnection=false) +{ + $sql = 'SELECT * FROM ('.$sql.') WHERE rownum < 2'; + $result = oracle_db_get_all_rows_sql($sql, false, true, $dbconnection); + + if ($result === false) { + return false; + } + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } + /** * Get the first row of an SQL database query. * @@ -913,16 +996,19 @@ function oracle_db_get_value_sql($sql, $dbconnection = false) { * * @return mixed The first row of the result or false */ -function oracle_db_get_row_sql ($sql, $search_history_db = false) { - $sql = "SELECT * FROM (" . $sql . ") WHERE rownum < 2"; - $result = oracle_db_get_all_rows_sql($sql, $search_history_db); - - if ($result === false) - return false; - - return $result[0]; +function oracle_db_get_row_sql($sql, $search_history_db=false) +{ + $sql = 'SELECT * FROM ('.$sql.') WHERE rownum < 2'; + $result = oracle_db_get_all_rows_sql($sql, $search_history_db); + + if ($result === false) { + return false; + } + + return $result[0]; } + /** * Get the row of a table in the database using a complex filter. * @@ -947,29 +1033,32 @@ function oracle_db_get_row_sql ($sql, $search_history_db = false) { * * @return mixed Array of the row or false in case of error. */ -function oracle_db_get_row_filter ($table, $filter, $fields = false, $where_join = 'AND') { - if (empty ($fields)) { - $fields = '*'; - } - else { - if (is_array ($fields)) - $fields = implode (',', $fields); - else if (! is_string ($fields)) - return false; - } - - if (is_array ($filter)) - $filter = db_format_array_where_clause_sql ($filter, $where_join, ' WHERE '); - else if (is_string ($filter)) - $filter = 'WHERE '.$filter; - else - $filter = ''; - - $sql = sprintf ('SELECT %s FROM %s %s', $fields, $table, $filter); - - return db_get_row_sql ($sql); +function oracle_db_get_row_filter($table, $filter, $fields=false, $where_join='AND') +{ + if (empty($fields)) { + $fields = '*'; + } else { + if (is_array($fields)) { + $fields = implode(',', $fields); + } else if (! is_string($fields)) { + return false; + } + } + + if (is_array($filter)) { + $filter = db_format_array_where_clause_sql($filter, $where_join, ' WHERE '); + } else if (is_string($filter)) { + $filter = 'WHERE '.$filter; + } else { + $filter = ''; + } + + $sql = sprintf('SELECT %s FROM %s %s', $fields, $table, $filter); + + return db_get_row_sql($sql); } + /** * Get all the rows of a table in the database that matches a filter. * @@ -990,69 +1079,70 @@ function oracle_db_get_row_filter ($table, $filter, $fields = false, $where_join * @param mixed Fields of the table to retrieve. Can be an array or a coma * separated string. All fields are retrieved by default * @param string Condition of the filter (AND, OR). - * @param bool $returnSQL Return a string with SQL instead the data, by default false. + * @param boolean $returnSQL Return a string with SQL instead the data, by default false. * * @return mixed Array of the row or false in case of error. */ -function oracle_db_get_all_rows_filter ($table, $filter = array(), $fields = false, $where_join = 'AND', $search_history_db = false, $returnSQL = false) { - //TODO: Validate and clean fields - if (empty($fields)) { - $fields = '*'; - } - elseif (is_array($fields)) { - $fields = implode(' , ', $fields); - } - elseif (!is_string($fields)) { - return false; - } - - //TODO: Validate and clean filter options - if (is_array ($filter)) { - $filter = db_format_array_where_clause_sql ($filter, $where_join, ' WHERE '); - } - elseif (is_string ($filter)) { - $filter = 'WHERE '.$filter; - } - else { - $filter = ''; - } - - $sql = sprintf ('SELECT %s FROM %s %s', $fields, $table, $filter); - - if ($returnSQL) - return $sql; - else - return db_get_all_rows_sql ($sql, $search_history_db); +function oracle_db_get_all_rows_filter($table, $filter=[], $fields=false, $where_join='AND', $search_history_db=false, $returnSQL=false) +{ + // TODO: Validate and clean fields + if (empty($fields)) { + $fields = '*'; + } else if (is_array($fields)) { + $fields = implode(' , ', $fields); + } else if (!is_string($fields)) { + return false; + } + + // TODO: Validate and clean filter options + if (is_array($filter)) { + $filter = db_format_array_where_clause_sql($filter, $where_join, ' WHERE '); + } else if (is_string($filter)) { + $filter = 'WHERE '.$filter; + } else { + $filter = ''; + } + + $sql = sprintf('SELECT %s FROM %s %s', $fields, $table, $filter); + + if ($returnSQL) { + return $sql; + } else { + return db_get_all_rows_sql($sql, $search_history_db); + } } + /** * Return the count of rows of query. * - * @param $sql + * @param $sql * @return integer The count of rows of query. */ -function oracle_db_get_num_rows ($sql) { - global $config; - - $type = explode(' ',strtoupper(trim($sql))); - if ($type[0] == 'SELECT') { - $sql = "SELECT count(*) as NUM FROM (" . $sql . ")"; - } - $query = oci_parse($config['dbconnection'], $sql); - oci_execute($query); - if ($type[0] == 'SELECT') { - $row = oci_fetch_assoc($query); - $rows = $row['NUM']; - } - else { - $rows = oci_num_rows($query); - } - - oci_free_statement($query); - - return $rows; +function oracle_db_get_num_rows($sql) +{ + global $config; + + $type = explode(' ', strtoupper(trim($sql))); + if ($type[0] == 'SELECT') { + $sql = 'SELECT count(*) as NUM FROM ('.$sql.')'; + } + + $query = oci_parse($config['dbconnection'], $sql); + oci_execute($query); + if ($type[0] == 'SELECT') { + $row = oci_fetch_assoc($query); + $rows = $row['NUM']; + } else { + $rows = oci_num_rows($query); + } + + oci_free_statement($query); + + return $rows; } + /** * Get all the rows in a table of the database filtering from a field. * @@ -1063,29 +1153,45 @@ function oracle_db_get_num_rows ($sql) { * * @return mixed A matrix with all the values in the table that matches the condition in the field or false */ -function oracle_db_get_all_rows_field_filter ($table, $field, $condition, $order_field = "") { - if (is_int ($condition) || is_bool ($condition)) { - $sql = sprintf ("SELECT * +function oracle_db_get_all_rows_field_filter($table, $field, $condition, $order_field='') +{ + if (is_int($condition) || is_bool($condition)) { + $sql = sprintf( + 'SELECT * FROM %s - WHERE %s = %d", $table, $field, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT * + WHERE %s = %d', + $table, + $field, + $condition + ); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf( + 'SELECT * FROM %s - WHERE %s = %f", $table, $field, $condition); - } - else { - $sql = sprintf ("SELECT * + WHERE %s = %f', + $table, + $field, + $condition + ); + } else { + $sql = sprintf( + "SELECT * FROM %s - WHERE %s = '%s'", $table, $field, $condition); - } - - if ($order_field != "") - $sql .= sprintf (" ORDER BY %s", $order_field); - - return db_get_all_rows_sql ($sql); + WHERE %s = '%s'", + $table, + $field, + $condition + ); + } + + if ($order_field != '') { + $sql .= sprintf(' ORDER BY %s', $order_field); + } + + return db_get_all_rows_sql($sql); } + /** * Get all the rows in a table of the database filtering from a field. * @@ -1094,19 +1200,22 @@ function oracle_db_get_all_rows_field_filter ($table, $field, $condition, $order * * @return mixed A matrix with all the values in the table that matches the condition in the field */ -function oracle_db_get_all_fields_in_table ($table, $field = '', $condition = '', $order_field = '') { - $sql = sprintf ("SELECT * FROM %s", $table); - - if ($condition != '') { - $sql .= sprintf (" WHERE %s = '%s'", $field, $condition); - } - - if ($order_field != "") - $sql .= sprintf (" ORDER BY %s", $order_field); - - return db_get_all_rows_sql ($sql); +function oracle_db_get_all_fields_in_table($table, $field='', $condition='', $order_field='') +{ + $sql = sprintf('SELECT * FROM %s', $table); + + if ($condition != '') { + $sql .= sprintf(" WHERE %s = '%s'", $field, $condition); + } + + if ($order_field != '') { + $sql .= sprintf(' ORDER BY %s', $order_field); + } + + return db_get_all_rows_sql($sql); } + /** * Formats an array of values into a SQL string. * @@ -1130,45 +1239,43 @@ function oracle_db_get_all_fields_in_table ($table, $field = '', $condition = '' * @return string Values joined into an SQL string that can fits into an UPDATE * sentence. */ -function oracle_db_format_array_to_update_sql ($values) { - $fields = array (); - - foreach ($values as $field => $value) { - if (is_numeric($field)) { - array_push ($fields, $value); - continue; - } - else if ($field[0] == "`") { - $field = str_replace('`', '', $field); - } - - if ($value === NULL) { - $sql = sprintf ("%s = NULL", $field); - } - elseif (is_int ($value) || is_bool ($value)) { - $sql = sprintf ("%s = %d", $field, $value); - } - elseif (is_float ($value) || is_double ($value)) { - $sql = sprintf ("%s = %f", $field, $value); - } - else { - /* String */ - if (isset ($value[0]) && $value[0] == '`') - /* Don't round with quotes if it references a field */ - $sql = sprintf ("%s = %s", $field, str_replace('`', '', $value)); - else if (substr($value, 0,1) == '#') { - $sql = sprintf ("%s = %s", $field, substr($value,1)); - } - else { - $sql = sprintf ("%s = '%s'", $field, $value); - } - } - array_push ($fields, $sql); - } - - return implode (", ", $fields); +function oracle_db_format_array_to_update_sql($values) +{ + $fields = []; + + foreach ($values as $field => $value) { + if (is_numeric($field)) { + array_push($fields, $value); + continue; + } else if ($field[0] == '`') { + $field = str_replace('`', '', $field); + } + + if ($value === null) { + $sql = sprintf('%s = NULL', $field); + } else if (is_int($value) || is_bool($value)) { + $sql = sprintf('%s = %d', $field, $value); + } else if (is_float($value) || is_double($value)) { + $sql = sprintf('%s = %f', $field, $value); + } else { + // String + if (isset($value[0]) && $value[0] == '`') { + // Don't round with quotes if it references a field + $sql = sprintf('%s = %s', $field, str_replace('`', '', $value)); + } else if (substr($value, 0, 1) == '#') { + $sql = sprintf('%s = %s', $field, substr($value, 1)); + } else { + $sql = sprintf("%s = '%s'", $field, $value); + } + } + + array_push($fields, $sql); + } + + return implode(', ', $fields); } + /** * Updates a database record. * @@ -1187,31 +1294,35 @@ function oracle_db_format_array_to_update_sql ($values) { * @param mixed An associative array of field and value matches. Will be joined * with operator specified by $where_join. A custom string can also be provided. * If nothing is provided, the update will affect all rows. - * @param string When a $where parameter is given, this will work as the glue - * between the fields. "AND" operator will be use by default. Other values might - * be "OR", "AND NOT", "XOR" + * @param string When a $where parameter is given, this will work as the glue + * between the fields. "AND" operator will be use by default. Other values might + * be "OR", "AND NOT", "XOR" * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function oracle_db_process_sql_update($table, $values, $where = false, $where_join = 'AND', $autocommit = true) { - $query = sprintf ("UPDATE %s SET %s", - $table, - db_format_array_to_update_sql ($values)); - - if ($where) { - if (is_string ($where)) { - // No clean, the caller should make sure all input is clean, this is a raw function - $query .= " WHERE " . $where; - } - else if (is_array ($where)) { - $query .= db_format_array_where_clause_sql ($where, $where_join, ' WHERE '); - } - } - $status = ''; - - return db_process_sql ($query, "affected_rows", '', true, $status, $autocommit); +function oracle_db_process_sql_update($table, $values, $where=false, $where_join='AND', $autocommit=true) +{ + $query = sprintf( + 'UPDATE %s SET %s', + $table, + db_format_array_to_update_sql($values) + ); + + if ($where) { + if (is_string($where)) { + // No clean, the caller should make sure all input is clean, this is a raw function + $query .= ' WHERE '.$where; + } else if (is_array($where)) { + $query .= db_format_array_where_clause_sql($where, $where_join, ' WHERE '); + } + } + + $status = ''; + + return db_process_sql($query, 'affected_rows', '', true, $status, $autocommit); } + /** * Delete database records. * @@ -1234,54 +1345,59 @@ function oracle_db_process_sql_update($table, $values, $where = false, $where_jo * @param mixed An associative array of field and value matches. Will be joined * with operator specified by $where_join. A custom string can also be provided. * If nothing is provided, the update will affect all rows. - * @param string When a $where parameter is given, this will work as the glue - * between the fields. "AND" operator will be use by default. Other values might - * be "OR", "AND NOT", "XOR" + * @param string When a $where parameter is given, this will work as the glue + * between the fields. "AND" operator will be use by default. Other values might + * be "OR", "AND NOT", "XOR" * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function oracle_db_process_sql_delete($table, $where, $where_join = 'AND') { - if (empty ($where)) - /* Should avoid any mistake that lead to deleting all data */ - return false; - - $query = sprintf ("DELETE FROM %s WHERE ", $table); - - if ($where) { - if (is_string ($where)) { - /* FIXME: Should we clean the string for sanity? - Who cares if this is deleting data... */ - $query .= $where; - } - else if (is_array ($where)) { - $query .= db_format_array_where_clause_sql ($where, $where_join); - } - } - - return db_process_sql ($query); +function oracle_db_process_sql_delete($table, $where, $where_join='AND') +{ + if (empty($where)) { + // Should avoid any mistake that lead to deleting all data + return false; + } + + $query = sprintf('DELETE FROM %s WHERE ', $table); + + if ($where) { + if (is_string($where)) { + /* + FIXME: Should we clean the string for sanity? + Who cares if this is deleting data... */ + $query .= $where; + } else if (is_array($where)) { + $query .= db_format_array_where_clause_sql($where, $where_join); + } + } + + return db_process_sql($query); } -function oracle_db_process_sql_delete_temp ($table, $where, $where_join = 'AND') { - if (empty ($where)) - /* Should avoid any mistake that lead to deleting all data */ - return false; - - $query = sprintf ("DELETE FROM %s WHERE ", $table); - - if ($where) { - if (is_string ($where)) { - /* FIXME: Should we clean the string for sanity? - Who cares if this is deleting data... */ - $query .= $where; - } - else if (is_array ($where)) { - $query .= db_format_array_where_clause_sql ($where, $where_join); - } - } - - $result = ''; - - return db_process_sql ($query, "affected_rows", '', true, $result, false); + +function oracle_db_process_sql_delete_temp($table, $where, $where_join='AND') +{ + if (empty($where)) { + // Should avoid any mistake that lead to deleting all data + return false; + } + + $query = sprintf('DELETE FROM %s WHERE ', $table); + + if ($where) { + if (is_string($where)) { + /* + FIXME: Should we clean the string for sanity? + Who cares if this is deleting data... */ + $query .= $where; + } else if (is_array($where)) { + $query .= db_format_array_where_clause_sql($where, $where_join); + } + } + + $result = ''; + + return db_process_sql($query, 'affected_rows', '', true, $result, false); } @@ -1290,299 +1406,328 @@ function oracle_db_process_sql_delete_temp ($table, $where, $where_join = 'AND') * rest of times pass none for iterate in table and extract row by row, and * the end return false. * - * @param bool $new Default true, if true start to query. - * @param resource $result The resource of oracle for access to query. - * @param string $sql + * @param boolean $new Default true, if true start to query. + * @param resource $result The resource of oracle for access to query. + * @param string $sql * @return mixed The row or false in error. */ -function oracle_db_get_all_row_by_steps_sql($new = true, &$result, $sql = null) { - global $config; - - if ($new == true) { - $result = oci_parse($config['dbconnection'], $sql); - oci_execute($result); - } - $row = oci_fetch_assoc($result); - - $result_temp = array(); - if ($row) { - foreach ($row as $key => $value) { - $column_type = oci_field_type($result, $key); - // Support for Clob field larger than 4000bytes - if ($column_type == 'CLOB') { - $column_name = oci_field_name($result, $key); - $column_name = oci_field_name($result, $key); - // protect against a NULL CLOB - if (is_object($row[$column_name])) { - $clob_data = $row[$column_name]->load(); - $row[$column_name]->free(); - $value = $clob_data; - } - else { - $value = ''; - } - } - $result_temp[strtolower($key)] = $value; - } - } - - if (!$row) { - oci_free_statement($result); - } +function oracle_db_get_all_row_by_steps_sql($new=true, &$result, $sql=null) +{ + global $config; -// return $row; - return $result_temp; + if ($new == true) { + $result = oci_parse($config['dbconnection'], $sql); + oci_execute($result); + } + + $row = oci_fetch_assoc($result); + + $result_temp = []; + if ($row) { + foreach ($row as $key => $value) { + $column_type = oci_field_type($result, $key); + // Support for Clob field larger than 4000bytes + if ($column_type == 'CLOB') { + $column_name = oci_field_name($result, $key); + $column_name = oci_field_name($result, $key); + // protect against a NULL CLOB + if (is_object($row[$column_name])) { + $clob_data = $row[$column_name]->load(); + $row[$column_name]->free(); + $value = $clob_data; + } else { + $value = ''; + } + } + + $result_temp[strtolower($key)] = $value; + } + } + + if (!$row) { + oci_free_statement($result); + } + + // return $row; + return $result_temp; } + /** * Starts a database transaction. */ -function oracle_db_process_sql_begin() { - global $config; - - $query = oci_parse($config['dbconnection'], 'SET TRANSACTION READ WRITE'); - oci_execute($query); - oci_free_statement($query); +function oracle_db_process_sql_begin() +{ + global $config; + + $query = oci_parse($config['dbconnection'], 'SET TRANSACTION READ WRITE'); + oci_execute($query); + oci_free_statement($query); } + /** * Commits a database transaction. */ -function oracle_db_process_sql_commit() { - global $config; - - oci_commit($config['dbconnection']); +function oracle_db_process_sql_commit() +{ + global $config; + + oci_commit($config['dbconnection']); } + /** * Rollbacks a database transaction. */ -function oracle_db_process_sql_rollback() { - global $config; - - oci_rollback($config['dbconnection']); +function oracle_db_process_sql_rollback() +{ + global $config; + + oci_rollback($config['dbconnection']); } + /** * Put quotes if magic_quotes protection * * @param string Text string to be protected with quotes if magic_quotes protection is disabled */ -function oracle_safe_sql_string($string) { - if (get_magic_quotes_gpc () == 0) - return $string; - - return oracle_escape_string_sql($string); +function oracle_safe_sql_string($string) +{ + if (get_magic_quotes_gpc() == 0) { + return $string; + } + + return oracle_escape_string_sql($string); } + /** * Get last error. - * + * * @return string Return the string error. */ -function oracle_db_get_last_error() { - global $config; - - if (empty($config['oracle_error_query'])) { - return null; - } - - $ora_erno = oci_error($config['oracle_error_query']); - - return $ora_erno['message']; +function oracle_db_get_last_error() +{ + global $config; + + if (empty($config['oracle_error_query'])) { + return null; + } + + $ora_erno = oci_error($config['oracle_error_query']); + + return $ora_erno['message']; } + /** * This function gets the time from either system or sql based on preference and returns it * - * @return int Unix timestamp + * @return integer Unix timestamp */ -function oracle_get_system_time() { - global $config; - - static $time = 0; - - if ($time != 0) - return $time; - - if ($config["timesource"] == "sql") { - $time = db_get_sql ("SELECT ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (" . SECONDS_1DAY . ")) as dt FROM dual"); - if (empty ($time)) { - return time (); - } - return $time; - } - else { - return time (); - } +function oracle_get_system_time() +{ + global $config; + + static $time = 0; + + if ($time != 0) { + return $time; + } + + if ($config['timesource'] == 'sql') { + $time = db_get_sql("SELECT ceil((sysdate - to_date('19700101000000','YYYYMMDDHH24MISS')) * (".SECONDS_1DAY.')) as dt FROM dual'); + if (empty($time)) { + return time(); + } + + return $time; + } else { + return time(); + } } + /** * Get the type of field. - * - * @param string $table The table to examine the type of field. + * + * @param string $table The table to examine the type of field. * @param integer $field The field order in table. - * + * * @return mixed Return the type name or False in error case. */ -function oracle_db_get_type_field_table($table, $field) { - global $config; - - $query = oci_parse($config['dbconnection'], - "SELECT * FROM " . $table . " WHERE rownum < 2"); - oci_execute($query); - - $type = oci_field_type($query, $field+1); - oci_free_statement($query); - - return $type; +function oracle_db_get_type_field_table($table, $field) +{ + global $config; + + $query = oci_parse( + $config['dbconnection'], + 'SELECT * FROM '.$table.' WHERE rownum < 2' + ); + oci_execute($query); + + $type = oci_field_type($query, ($field + 1)); + oci_free_statement($query); + + return $type; } + /** - * Get all field names of a table and recode fields + * Get all field names of a table and recode fields * for clob datatype as "dbms_lob.substr(, 4000 ,1) as ". - * - * @param string $table The table to retrieve all column names. + * + * @param string $table The table to retrieve all column names. * @param integer $return_mode Whether to return as array (by default) or as comma separated string. - * + * * @return mixed Return an array/string of table fields or false if something goes wrong. */ -function oracle_list_all_field_table($table_name, $return_mode = 'array') { - if (empty($table_name)) { - return false; - } - - $fields_info = db_get_all_rows_field_filter('user_tab_columns', 'table_name', strtoupper($table_name)); - if (empty($fields_info)) { - return false; - } - $field_list = array(); - foreach ($fields_info as $field) { - if ($field['data_type'] == 'CLOB') { - $new_field = 'dbms_lob.substr(' . $field['table_name'] . '.' . $field['column_name'] . ', 4000, 1) as ' . strtolower($field['column_name']); - $field_list[] = $new_field; - } - else { - $field_list[] = strtolower($field['table_name'] . '.' . $field['column_name']); - } - } - // Return as comma separated string - if ($return_mode == 'string') { - return implode(',', $field_list); - } - // Return as array - else { - return $field_list; - } +function oracle_list_all_field_table($table_name, $return_mode='array') +{ + if (empty($table_name)) { + return false; + } + + $fields_info = db_get_all_rows_field_filter('user_tab_columns', 'table_name', strtoupper($table_name)); + if (empty($fields_info)) { + return false; + } + + $field_list = []; + foreach ($fields_info as $field) { + if ($field['data_type'] == 'CLOB') { + $new_field = 'dbms_lob.substr('.$field['table_name'].'.'.$field['column_name'].', 4000, 1) as '.strtolower($field['column_name']); + $field_list[] = $new_field; + } else { + $field_list[] = strtolower($field['table_name'].'.'.$field['column_name']); + } + } + + // Return as comma separated string + if ($return_mode == 'string') { + return implode(',', $field_list); + } + // Return as array + else { + return $field_list; + } } + /** * Process a file with an oracle schema sentences. * Based on the function which installs the pandoradb.sql schema. - * - * @param string $path File path. - * @param bool $handle_error Whether to handle the oci_execute errors or throw an exception. - * - * @return bool Return the final status of the operation. + * + * @param string $path File path. + * @param boolean $handle_error Whether to handle the oci_execute errors or throw an exception. + * + * @return boolean Return the final status of the operation. */ -function oracle_db_process_file ($path, $handle_error = true) { - global $config; - - if (file_exists($path)) { - $file_content = file($path); - - $query = ""; - $plsql_block = false; - - // Begin the transaction - oracle_db_process_sql_begin(); - - $datetime_tz_format = oci_parse($connection, 'alter session set NLS_TIMESTAMP_TZ_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); - $datetime_format = oci_parse($connection, 'alter session set NLS_TIMESTAMP_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); - $date_format = oci_parse($connection, 'alter session set NLS_DATE_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); - $decimal_separator = oci_parse($connection, 'alter session set NLS_NUMERIC_CHARACTERS =\',.\''); +function oracle_db_process_file($path, $handle_error=true) +{ + global $config; - oci_execute($datetime_tz_format); - oci_execute($datetime_format); - oci_execute($date_format); - oci_execute($decimal_separator); + if (file_exists($path)) { + $file_content = file($path); - oci_free_statement($datetime_tz_format); - oci_free_statement($datetime_format); - oci_free_statement($date_format); - oci_free_statement($decimal_separator); - - foreach ($file_content as $sql_line) { - $clean_line = trim($sql_line); - $comment = preg_match("/^(\s|\t)*--.*$/", $clean_line); - if ($comment) { - continue; - } - - if (empty($clean_line)) { - continue; - } - - //Support for PL/SQL blocks - if (preg_match("/^BEGIN$/", $clean_line)) { - $query .= $clean_line . ' '; - $plsql_block = true; - } - else{ - $query .= $clean_line; - } - - //Check query's end with a back slash and any returns in the end of line or if it's a PL/SQL block 'END;;' string - if ((preg_match("/;[\040]*\$/", $clean_line) && !$plsql_block) || - (preg_match("/^END;;[\040]*\$/", $clean_line) && $plsql_block)) { - $plsql_block = false; - //Execute and clean buffer - - //Delete the last semicolon from current query - $query = substr($query, 0, strlen($query) - 1); - $sql = oci_parse($config['dbconnection'], $query); - $result = oci_execute($sql, OCI_NO_AUTO_COMMIT); - - if (!$result) { - // Error. Rollback the transaction - oracle_db_process_sql_rollback(); - - $e = oci_error($sql); - - // Handle the error - if ($handle_error) { - $backtrace = debug_backtrace(); - $error = sprintf('%s (\'%s\') in %s on line %d', - htmlentities($e['message'], ENT_QUOTES), $query, $backtrace[0]['file'], $backtrace[0]['line']); - db_add_database_debug_trace ($query, htmlentities($e['message'], ENT_QUOTES)); - set_error_handler('db_sql_error_handler'); - trigger_error($error); - restore_error_handler(); - - return false; - } - // Throw an exception with the error message - else { - throw new Exception($e['message']); - } - } - - $query = ""; - oci_free_statement($sql); - } - } - - // No errors. Commit the transaction - oracle_db_process_sql_commit(); - - return true; - } - else { - return false; - } + $query = ''; + $plsql_block = false; + + // Begin the transaction + oracle_db_process_sql_begin(); + + $datetime_tz_format = oci_parse($connection, 'alter session set NLS_TIMESTAMP_TZ_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); + $datetime_format = oci_parse($connection, 'alter session set NLS_TIMESTAMP_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); + $date_format = oci_parse($connection, 'alter session set NLS_DATE_FORMAT =\'YYYY-MM-DD HH24:MI:SS\''); + $decimal_separator = oci_parse($connection, 'alter session set NLS_NUMERIC_CHARACTERS =\',.\''); + + oci_execute($datetime_tz_format); + oci_execute($datetime_format); + oci_execute($date_format); + oci_execute($decimal_separator); + + oci_free_statement($datetime_tz_format); + oci_free_statement($datetime_format); + oci_free_statement($date_format); + oci_free_statement($decimal_separator); + + foreach ($file_content as $sql_line) { + $clean_line = trim($sql_line); + $comment = preg_match("/^(\s|\t)*--.*$/", $clean_line); + if ($comment) { + continue; + } + + if (empty($clean_line)) { + continue; + } + + // Support for PL/SQL blocks + if (preg_match('/^BEGIN$/', $clean_line)) { + $query .= $clean_line.' '; + $plsql_block = true; + } else { + $query .= $clean_line; + } + + // Check query's end with a back slash and any returns in the end of line or if it's a PL/SQL block 'END;;' string + if ((preg_match("/;[\040]*\$/", $clean_line) && !$plsql_block) + || (preg_match("/^END;;[\040]*\$/", $clean_line) && $plsql_block) + ) { + $plsql_block = false; + // Execute and clean buffer + // Delete the last semicolon from current query + $query = substr($query, 0, (strlen($query) - 1)); + $sql = oci_parse($config['dbconnection'], $query); + $result = oci_execute($sql, OCI_NO_AUTO_COMMIT); + + if (!$result) { + // Error. Rollback the transaction + oracle_db_process_sql_rollback(); + + $e = oci_error($sql); + + // Handle the error + if ($handle_error) { + $backtrace = debug_backtrace(); + $error = sprintf( + '%s (\'%s\') in %s on line %d', + htmlentities($e['message'], ENT_QUOTES), + $query, + $backtrace[0]['file'], + $backtrace[0]['line'] + ); + db_add_database_debug_trace($query, htmlentities($e['message'], ENT_QUOTES)); + set_error_handler('db_sql_error_handler'); + trigger_error($error); + restore_error_handler(); + + return false; + } + // Throw an exception with the error message + else { + throw new Exception($e['message']); + } + } + + $query = ''; + oci_free_statement($sql); + } + } + + // No errors. Commit the transaction + oracle_db_process_sql_commit(); + + return true; + } else { + return false; + } } -function oracle_format_float_to_php($val) { - return floatval(str_replace(',', '.', $val)); + +function oracle_format_float_to_php($val) +{ + return floatval(str_replace(',', '.', $val)); } -?> diff --git a/pandora_console/include/db/postgresql.php b/pandora_console/include/db/postgresql.php index 1b74f21b07..3d1b2be627 100644 --- a/pandora_console/include/db/postgresql.php +++ b/pandora_console/include/db/postgresql.php @@ -4,48 +4,55 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function postgresql_connect_db($host=null, $db=null, $user=null, $pass=null, $port=null) +{ + global $config; -function postgresql_connect_db($host = null, $db = null, $user = null, $pass = null, $port = null) { - global $config; - - if ($host === null) - $host = $config["dbhost"]; - if ($db === null) - $db = $config["dbname"]; - if ($user === null) - $user = $config["dbuser"]; - if ($pass === null) - $pass = $config["dbpass"]; - if ($port === null) - $port = $config["dbport"]; - - $connect_id = pg_connect("host='" . $host . "'" . - " port=" . $port . - " dbname='" . $db . "'" . - " user='" . $user . "'" . - " password='" . $pass . "'", PGSQL_CONNECT_FORCE_NEW); - - if (! $connect_id) { - return false; - } - - db_change_cache_id($host, $db); - - return $connect_id; + if ($host === null) { + $host = $config['dbhost']; + } + + if ($db === null) { + $db = $config['dbname']; + } + + if ($user === null) { + $user = $config['dbuser']; + } + + if ($pass === null) { + $pass = $config['dbpass']; + } + + if ($port === null) { + $port = $config['dbport']; + } + + $connect_id = pg_connect( + "host='".$host."'".' port='.$port." dbname='".$db."'"." user='".$user."'"." password='".$pass."'", + PGSQL_CONNECT_FORCE_NEW + ); + + if (! $connect_id) { + return false; + } + + db_change_cache_id($host, $db); + + return $connect_id; } -/** + +/** * Get the first value of the first row of a table in the database. - * + * * @param string Field name to get * @param string Table to retrieve the data * @param string Field to filter elements @@ -53,37 +60,56 @@ function postgresql_connect_db($host = null, $db = null, $user = null, $pass = n * * @return mixed Value of first column of the first row. False if there were no row. */ -function postgresql_db_get_value ($field, $table, $field_search = 1, $condition = 1, $search_history_db = false) { - if ($field_search[0] == '`') - $field_search = str_replace ('`', '', $field_search); - - if (is_int ($condition)) { - $sql = sprintf ("SELECT %s FROM %s WHERE %s = %d LIMIT 1", - $field, $table, $field_search, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT %s FROM %s WHERE %s = %f LIMIT 1", - $field, $table, $field_search, $condition); - } - else { - $sql = sprintf ("SELECT %s FROM %s WHERE %s = '%s' LIMIT 1", - $field, $table, $field_search, $condition); - } - $result = db_get_all_rows_sql ($sql, $search_history_db); - - if ($result === false) - return false; - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; +function postgresql_db_get_value($field, $table, $field_search=1, $condition=1, $search_history_db=false) +{ + if ($field_search[0] == '`') { + $field_search = str_replace('`', '', $field_search); + } + + if (is_int($condition)) { + $sql = sprintf( + 'SELECT %s FROM %s WHERE %s = %d LIMIT 1', + $field, + $table, + $field_search, + $condition + ); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf( + 'SELECT %s FROM %s WHERE %s = %f LIMIT 1', + $field, + $table, + $field_search, + $condition + ); + } else { + $sql = sprintf( + "SELECT %s FROM %s WHERE %s = '%s' LIMIT 1", + $field, + $table, + $field_search, + $condition + ); + } + + $result = db_get_all_rows_sql($sql, $search_history_db); + + if ($result === false) { + return false; + } + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } -/** + +/** * Get the first row of a database query into a table. * * The SQL statement executed would be something like: @@ -93,204 +119,239 @@ function postgresql_db_get_value ($field, $table, $field_search = 1, $condition * @param string Field to filter elements * @param string Condition the field must have. * @param mixed Fields to select (array or string or false/empty for *) - * + * * @return mixed The first row of a database query or false. */ -function postgresql_db_get_row ($table, $field_search, $condition, $fields = false) { - if (empty ($fields)) { - $fields = '*'; - } - else { - if (is_array ($fields)) - $fields = implode (',', $fields); - else if (! is_string ($fields)) - return false; - } - - if (is_int ($condition)) { - $sql = sprintf ('SELECT %s FROM "%s" WHERE "%s" = %d LIMIT 1', - $fields, $table, $field_search, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT %s FROM \"%s\" WHERE \"%s\" = %f LIMIT 1", - $fields, $table, $field_search, $condition); - } - else { - $sql = sprintf ("SELECT %s FROM \"%s\" WHERE \"%s\" = '%s' LIMIT 1", - $fields, $table, $field_search, $condition); - } - $result = db_get_all_rows_sql ($sql); - - if ($result === false) - return false; - - return $result[0]; +function postgresql_db_get_row($table, $field_search, $condition, $fields=false) +{ + if (empty($fields)) { + $fields = '*'; + } else { + if (is_array($fields)) { + $fields = implode(',', $fields); + } else if (! is_string($fields)) { + return false; + } + } + + if (is_int($condition)) { + $sql = sprintf( + 'SELECT %s FROM "%s" WHERE "%s" = %d LIMIT 1', + $fields, + $table, + $field_search, + $condition + ); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf( + 'SELECT %s FROM "%s" WHERE "%s" = %f LIMIT 1', + $fields, + $table, + $field_search, + $condition + ); + } else { + $sql = sprintf( + "SELECT %s FROM \"%s\" WHERE \"%s\" = '%s' LIMIT 1", + $fields, + $table, + $field_search, + $condition + ); + } + + $result = db_get_all_rows_sql($sql); + + if ($result === false) { + return false; + } + + return $result[0]; } -function postgresql_db_get_all_rows_sql ($sql, $search_history_db = false, $cache = true, $dbconnection = false) { - global $config; - - $history = array (); - - if ($dbconnection === false) { - $dbconnection = $config['dbconnection']; - } - - // To disable globally SQL cache depending on global variable. - // Used in several critical places like Metaconsole trans-server queries - if (isset($config["dbcache"])) - $cache = $config["dbcache"]; - - // Read from the history DB if necessary - if ($search_history_db && $config['history_db_enabled'] == 1) { - $cache = false; - $history = false; - - // Connect to the history DB - $history_db_connection = db_connect($config['history_db_host'], $config['history_db_name'], $config['history_db_user'], $config['history_db_pass'], io_output_password($config['history_db_port'], false)); - if ($history_db_connection !== false) { - $history = postgresql_db_process_sql ($sql, 'affected_rows', $config['history_db_connection'], false); - } - - if ($history === false) { - $history = array (); - } - } - - $return = postgresql_db_process_sql ($sql, 'affected_rows', $dbconnection, $cache); - if ($return === false) { - $return = array (); - } - - // Append result to the history DB data - if (! empty ($return)) { - foreach ($return as $row) { - array_push ($history, $row); - } - } - - if (! empty ($history)) - return $history; - - //Return false, check with === or !== - return false; + +function postgresql_db_get_all_rows_sql($sql, $search_history_db=false, $cache=true, $dbconnection=false) +{ + global $config; + + $history = []; + + if ($dbconnection === false) { + $dbconnection = $config['dbconnection']; + } + + // To disable globally SQL cache depending on global variable. + // Used in several critical places like Metaconsole trans-server queries + if (isset($config['dbcache'])) { + $cache = $config['dbcache']; + } + + // Read from the history DB if necessary + if ($search_history_db && $config['history_db_enabled'] == 1) { + $cache = false; + $history = false; + + // Connect to the history DB + $history_db_connection = db_connect($config['history_db_host'], $config['history_db_name'], $config['history_db_user'], $config['history_db_pass'], io_output_password($config['history_db_port'], false)); + if ($history_db_connection !== false) { + $history = postgresql_db_process_sql($sql, 'affected_rows', $config['history_db_connection'], false); + } + + if ($history === false) { + $history = []; + } + } + + $return = postgresql_db_process_sql($sql, 'affected_rows', $dbconnection, $cache); + if ($return === false) { + $return = []; + } + + // Append result to the history DB data + if (! empty($return)) { + foreach ($return as $row) { + array_push($history, $row); + } + } + + if (! empty($history)) { + return $history; + } + + // Return false, check with === or !== + return false; } -function postgresql_insert_id($dbconnection = '') { - global $config; - - if ($dbconnection !== '') { - $insert_query = pg_query($dbconnection, "SELECT lastval();"); - $insert_id = pg_fetch_row($insert_query); - $result = $insert_id[0]; - } - else { - $insert_query = pg_query($config['dbconnection'], "SELECT lastval();"); - $insert_id = pg_fetch_row($insert_query); - $result = $insert_id[0]; - } - - return $result; + +function postgresql_insert_id($dbconnection='') +{ + global $config; + + if ($dbconnection !== '') { + $insert_query = pg_query($dbconnection, 'SELECT lastval();'); + $insert_id = pg_fetch_row($insert_query); + $result = $insert_id[0]; + } else { + $insert_query = pg_query($config['dbconnection'], 'SELECT lastval();'); + $insert_id = pg_fetch_row($insert_query); + $result = $insert_id[0]; + } + + return $result; } -function postgresql_db_process_sql($sql, $rettype = "affected_rows", $dbconnection = '', $cache = true, &$status = null) { - global $config; - global $sql_cache; - - $retval = array(); - - if ($sql == '') - return false; - - if ($cache && ! empty ($sql_cache[$sql_cache['id']][$sql])) { - $retval = $sql_cache[$sql_cache['id']][$sql]; - $sql_cache['saved'][$sql_cache['id']]++; - db_add_database_debug_trace ($sql); - } - else { - $start = microtime (true); - if ($dbconnection !== '') { - pg_send_query($dbconnection, $sql); - $result = pg_get_result($dbconnection); - } - else { - pg_send_query($config['dbconnection'], $sql); - $result = pg_get_result($config['dbconnection']); - } - $time = microtime (true) - $start; - - $resultError = pg_result_error($result); - - if (($result === false) || (!empty($resultError))) { - $backtrace = debug_backtrace (); - $error = sprintf ('%s (\'%s\') in %s on line %d', - pg_result_error($result), $sql, $backtrace[0]['file'], $backtrace[0]['line']); - db_add_database_debug_trace ($sql, pg_result_error($result)); - set_error_handler ('db_sql_error_handler'); - trigger_error ($error); - restore_error_handler (); - - return false; - } - else { - $status = pg_result_status($result); - $rows = pg_affected_rows($result); - - if ($status !== 2) { //The query NOT IS a select - if ($rettype == "insert_id") { - $result = postgresql_insert_id($dbconnection); - } - elseif ($rettype == "info") { - $result = pg_result_status($result, PGSQL_STATUS_STRING); - } - else { - $rows = pg_affected_rows($result); - $result = $rows; - } - db_add_database_debug_trace ($sql, $result, $rows, - array ('time' => $time)); - - return $result; - } - else { //The query IS a select. - db_add_database_debug_trace ($sql, 0, $rows, array ('time' => $time)); - while ($row = pg_fetch_assoc($result)) { - array_push($retval, $row); - } - - if ($cache === true) - $sql_cache[$sql_cache['id']][$sql] = $retval; - pg_free_result ($result); - } - } - } - - if (! empty ($retval)) { - return $retval; - } - - //Return false, check with === or !== - return false; + +function postgresql_db_process_sql($sql, $rettype='affected_rows', $dbconnection='', $cache=true, &$status=null) +{ + global $config; + global $sql_cache; + + $retval = []; + + if ($sql == '') { + return false; + } + + if ($cache && ! empty($sql_cache[$sql_cache['id']][$sql])) { + $retval = $sql_cache[$sql_cache['id']][$sql]; + $sql_cache['saved'][$sql_cache['id']]++; + db_add_database_debug_trace($sql); + } else { + $start = microtime(true); + if ($dbconnection !== '') { + pg_send_query($dbconnection, $sql); + $result = pg_get_result($dbconnection); + } else { + pg_send_query($config['dbconnection'], $sql); + $result = pg_get_result($config['dbconnection']); + } + + $time = (microtime(true) - $start); + + $resultError = pg_result_error($result); + + if (($result === false) || (!empty($resultError))) { + $backtrace = debug_backtrace(); + $error = sprintf( + '%s (\'%s\') in %s on line %d', + pg_result_error($result), + $sql, + $backtrace[0]['file'], + $backtrace[0]['line'] + ); + db_add_database_debug_trace($sql, pg_result_error($result)); + set_error_handler('db_sql_error_handler'); + trigger_error($error); + restore_error_handler(); + + return false; + } else { + $status = pg_result_status($result); + $rows = pg_affected_rows($result); + + if ($status !== 2) { + // The query NOT IS a select + if ($rettype == 'insert_id') { + $result = postgresql_insert_id($dbconnection); + } else if ($rettype == 'info') { + $result = pg_result_status($result, PGSQL_STATUS_STRING); + } else { + $rows = pg_affected_rows($result); + $result = $rows; + } + + db_add_database_debug_trace( + $sql, + $result, + $rows, + ['time' => $time] + ); + + return $result; + } else { + // The query IS a select. + db_add_database_debug_trace($sql, 0, $rows, ['time' => $time]); + while ($row = pg_fetch_assoc($result)) { + array_push($retval, $row); + } + + if ($cache === true) { + $sql_cache[$sql_cache['id']][$sql] = $retval; + } + + pg_free_result($result); + } + } + } + + if (! empty($retval)) { + return $retval; + } + + // Return false, check with === or !== + return false; } + /** * Get all the rows in a table of the database. - * + * * @param string Database table name. * @param string Field to order by. - * @param string $order The type of order, by default 'ASC'. + * @param string $order The type of order, by default 'ASC'. * * @return mixed A matrix with all the values in the table */ -function postgresql_db_get_all_rows_in_table($table, $order_field = "", $order = 'ASC') { - if ($order_field != "") { - return db_get_all_rows_sql ('SELECT * FROM "'.$table.'" ORDER BY '.$order_field . ' ' . $order); - } - else { - return db_get_all_rows_sql ('SELECT * FROM "'.$table.'"'); - } +function postgresql_db_get_all_rows_in_table($table, $order_field='', $order='ASC') +{ + if ($order_field != '') { + return db_get_all_rows_sql('SELECT * FROM "'.$table.'" ORDER BY '.$order_field.' '.$order); + } else { + return db_get_all_rows_sql('SELECT * FROM "'.$table.'"'); + } } + /** * Inserts strings into database * @@ -303,79 +364,83 @@ function postgresql_db_get_all_rows_in_table($table, $order_field = "", $order = * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function postgresql_db_process_sql_insert($table, $values) { - //Empty rows or values not processed - if (empty ($values)) - return false; - - $values = (array) $values; - - $query = sprintf ('INSERT INTO "%s" ', $table); - $fields = array (); - $values_str = ''; - $i = 1; - $max = count ($values); - foreach ($values as $field => $value) { - //Add the correct escaping to values - if ($field[0] != '"') { - $field = '"' . $field . '"'; - } - - array_push ($fields, $field); - - if (is_null ($value)) { - $values_str .= "NULL"; - } - elseif (is_int ($value) || is_bool ($value)) { - $values_str .= sprintf("%d", $value); - } - else if (is_float ($value) || is_double ($value)) { - $values_str .= sprintf("%f", $value); - } - elseif (is_string($value) && (strtoupper($value) === 'NULL')) { - $values_str .= "NULL"; - } - else { - $values_str .= sprintf("'%s'", $value); - } - - if ($i < $max) { - $values_str .= ","; - } - $i++; - } - - $query .= '(' . implode(', ', $fields) . ')'; - $query .= ' VALUES (' . $values_str . ')'; - - return db_process_sql($query, 'insert_id'); +function postgresql_db_process_sql_insert($table, $values) +{ + // Empty rows or values not processed + if (empty($values)) { + return false; + } + + $values = (array) $values; + + $query = sprintf('INSERT INTO "%s" ', $table); + $fields = []; + $values_str = ''; + $i = 1; + $max = count($values); + foreach ($values as $field => $value) { + // Add the correct escaping to values + if ($field[0] != '"') { + $field = '"'.$field.'"'; + } + + array_push($fields, $field); + + if (is_null($value)) { + $values_str .= 'NULL'; + } else if (is_int($value) || is_bool($value)) { + $values_str .= sprintf('%d', $value); + } else if (is_float($value) || is_double($value)) { + $values_str .= sprintf('%f', $value); + } else if (is_string($value) && (strtoupper($value) === 'NULL')) { + $values_str .= 'NULL'; + } else { + $values_str .= sprintf("'%s'", $value); + } + + if ($i < $max) { + $values_str .= ','; + } + + $i++; + } + + $query .= '('.implode(', ', $fields).')'; + $query .= ' VALUES ('.$values_str.')'; + + return db_process_sql($query, 'insert_id'); } + /** * Escape string to set it properly to use in sql queries - * + * * @param string String to be cleaned. - * + * * @return string String cleaned. */ -function postgresql_escape_string_sql($string) { - $str = pg_escape_string($string); - - return $str; +function postgresql_escape_string_sql($string) +{ + $str = pg_escape_string($string); + + return $str; } -function postgresql_encapsule_fields_with_same_name_to_instructions($field) { - $return = $field; - - if (is_string($return)) { - if ($return[0] !== '"') { - $return = '"' . $return . '"'; - } - } - - return $return; + +function postgresql_encapsule_fields_with_same_name_to_instructions($field) +{ + $return = $field; + + if (is_string($return)) { + if ($return[0] !== '"') { + $return = '"'.$return.'"'; + } + } + + return $return; } + /** * Get the first value of the first row of a table in the database from an * array with filter conditions. @@ -401,35 +466,41 @@ function postgresql_encapsule_fields_with_same_name_to_instructions($field) { * * @return mixed Value of first column of the first row. False if there were no row. */ -function postgresql_db_get_value_filter ($field, $table, $filter, $where_join = 'AND', $search_history_db = false) { - if (! is_array ($filter) || empty ($filter)) - return false; - - /* Avoid limit and offset if given */ - unset ($filter['limit']); - unset ($filter['offset']); - - - if (strstr($field, "(") === false) { - //It is a field. - $field = '"' . $field . '"'; - } - - $sql = sprintf ("SELECT %s FROM \"%s\" WHERE %s LIMIT 1", - $field, $table, - db_format_array_where_clause_sql ($filter, $where_join)); - - $result = db_get_all_rows_sql ($sql, $search_history_db); - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; +function postgresql_db_get_value_filter($field, $table, $filter, $where_join='AND', $search_history_db=false) +{ + if (! is_array($filter) || empty($filter)) { + return false; + } + + // Avoid limit and offset if given + unset($filter['limit']); + unset($filter['offset']); + + if (strstr($field, '(') === false) { + // It is a field. + $field = '"'.$field.'"'; + } + + $sql = sprintf( + 'SELECT %s FROM "%s" WHERE %s LIMIT 1', + $field, + $table, + db_format_array_where_clause_sql($filter, $where_join) + ); + + $result = db_get_all_rows_sql($sql, $search_history_db); + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } + /** * Formats an array of values into a SQL where clause string. * @@ -493,141 +564,140 @@ function postgresql_db_get_value_filter ($field, $table, $filter, $where_join = * @return string Values joined into an SQL string that can fits into the WHERE * clause of an SQL sentence. */ -function postgresql_db_format_array_where_clause_sql ($values, $join = 'AND', $prefix = false) { - - $fields = array (); - - if (! is_array ($values)) { - return ''; - } - - $query = ''; - $limit = ''; - $offset = ''; - $order = ''; - $group = ''; - if (isset ($values['limit'])) { - $limit = sprintf (' LIMIT %d', $values['limit']); - unset ($values['limit']); - } - - if (isset ($values['offset'])) { - $offset = sprintf (' OFFSET %d', $values['offset']); - unset ($values['offset']); - } - - if (isset ($values['order'])) { - if (is_array($values['order'])) { - if (!isset($values['order']['order'])) { - $orderTexts = array(); - foreach ($values['order'] as $orderItem) { - $orderTexts[] = $orderItem['field'] . ' ' . $orderItem['order']; - } - $order = ' ORDER BY ' . implode(', ', $orderTexts); - } - else { - $order = sprintf (' ORDER BY %s %s', $values['order']['field'], $values['order']['order']); - } - } - else { - $order = sprintf (' ORDER BY %s', $values['order']); - } - unset ($values['order']); - } - - if (isset ($values['group'])) { - $group = sprintf (' GROUP BY %s', $values['group']); - unset ($values['group']); - } - - $i = 1; - $max = count ($values); - foreach ($values as $field => $value) { - if (is_numeric ($field)) { - /* User provide the exact operation to do */ - $query .= $value; - - if ($i < $max) { - $query .= ' '.$join.' '; - } - $i++; - continue; - } - - if ($field[0] != "\"") { - //If the field is as
        ., don't scape. - if (strstr($field, '.') === false) - $field = "\"".$field."\""; - } - - if (is_null ($value)) { - $query .= sprintf ("%s IS NULL", $field); - } - elseif (is_int ($value) || is_bool ($value)) { - $query .= sprintf ("%s = %d", $field, $value); - } - else if (is_float ($value) || is_double ($value)) { - $query .= sprintf ("%s = %f", $field, $value); - } - elseif (is_array ($value)) { - $query .= sprintf ("%s IN ('%s')", $field, implode ("', '", $value)); - } - else { - if ($value[0] == ">") { - $value = substr($value,1,strlen($value)-1); - $query .= sprintf ("%s > '%s'", $field, $value); - } - else if ($value[0] == "<") { - if ($value[1] == ">") { - $value = substr($value,2,strlen($value)-2); - $query .= sprintf ("%s <> '%s'", $field, $value); - } - else { - $value = substr($value,1,strlen($value)-1); - $query .= sprintf ("%s < '%s'", $field, $value); - } - } - else if ($value[0] == '%') { - $query .= sprintf ("%s LIKE '%s'", $field, $value); - } - else { - $query .= sprintf ("%s = '%s'", $field, $value); - } - } - - if ($i < $max) { - $query .= ' '.$join.' '; - } - $i++; - } - - return (! empty ($query) ? $prefix: '').$query.$group.$order.$limit.$offset; +function postgresql_db_format_array_where_clause_sql($values, $join='AND', $prefix=false) +{ + $fields = []; + + if (! is_array($values)) { + return ''; + } + + $query = ''; + $limit = ''; + $offset = ''; + $order = ''; + $group = ''; + if (isset($values['limit'])) { + $limit = sprintf(' LIMIT %d', $values['limit']); + unset($values['limit']); + } + + if (isset($values['offset'])) { + $offset = sprintf(' OFFSET %d', $values['offset']); + unset($values['offset']); + } + + if (isset($values['order'])) { + if (is_array($values['order'])) { + if (!isset($values['order']['order'])) { + $orderTexts = []; + foreach ($values['order'] as $orderItem) { + $orderTexts[] = $orderItem['field'].' '.$orderItem['order']; + } + + $order = ' ORDER BY '.implode(', ', $orderTexts); + } else { + $order = sprintf(' ORDER BY %s %s', $values['order']['field'], $values['order']['order']); + } + } else { + $order = sprintf(' ORDER BY %s', $values['order']); + } + + unset($values['order']); + } + + if (isset($values['group'])) { + $group = sprintf(' GROUP BY %s', $values['group']); + unset($values['group']); + } + + $i = 1; + $max = count($values); + foreach ($values as $field => $value) { + if (is_numeric($field)) { + // User provide the exact operation to do + $query .= $value; + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + $i++; + continue; + } + + if ($field[0] != '"') { + // If the field is as
        ., don't scape. + if (strstr($field, '.') === false) { + $field = '"'.$field.'"'; + } + } + + if (is_null($value)) { + $query .= sprintf('%s IS NULL', $field); + } else if (is_int($value) || is_bool($value)) { + $query .= sprintf('%s = %d', $field, $value); + } else if (is_float($value) || is_double($value)) { + $query .= sprintf('%s = %f', $field, $value); + } else if (is_array($value)) { + $query .= sprintf("%s IN ('%s')", $field, implode("', '", $value)); + } else { + if ($value[0] == '>') { + $value = substr($value, 1, (strlen($value) - 1)); + $query .= sprintf("%s > '%s'", $field, $value); + } else if ($value[0] == '<') { + if ($value[1] == '>') { + $value = substr($value, 2, (strlen($value) - 2)); + $query .= sprintf("%s <> '%s'", $field, $value); + } else { + $value = substr($value, 1, (strlen($value) - 1)); + $query .= sprintf("%s < '%s'", $field, $value); + } + } else if ($value[0] == '%') { + $query .= sprintf("%s LIKE '%s'", $field, $value); + } else { + $query .= sprintf("%s = '%s'", $field, $value); + } + } + + if ($i < $max) { + $query .= ' '.$join.' '; + } + + $i++; + } + + return (! empty($query) ? $prefix : '').$query.$group.$order.$limit.$offset; } + /** * Get the first value of the first row of a table result from query. * * @param string SQL select statement to execute. * * @return the first value of the first row of a table result from query. - * */ -function postgresql_db_get_value_sql($sql, $dbconnection = false) { - $sql .= " LIMIT 1"; - $result = postgresql_db_get_all_rows_sql ($sql, false, true, $dbconnection); - - if ($result === false) - return false; - - $row = array_shift($result); - $value = array_shift($row); - - if ($value === null) - return false; - - return $value; +function postgresql_db_get_value_sql($sql, $dbconnection=false) +{ + $sql .= ' LIMIT 1'; + $result = postgresql_db_get_all_rows_sql($sql, false, true, $dbconnection); + + if ($result === false) { + return false; + } + + $row = array_shift($result); + $value = array_shift($row); + + if ($value === null) { + return false; + } + + return $value; } + /** * Get the first row of an SQL database query. * @@ -635,16 +705,19 @@ function postgresql_db_get_value_sql($sql, $dbconnection = false) { * * @return mixed The first row of the result or false */ -function postgresql_db_get_row_sql ($sql, $search_history_db = false) { - $sql .= " LIMIT 1"; - $result = postgresql_db_get_all_rows_sql($sql, $search_history_db); - - if ($result === false) - return false; - - return $result[0]; +function postgresql_db_get_row_sql($sql, $search_history_db=false) +{ + $sql .= ' LIMIT 1'; + $result = postgresql_db_get_all_rows_sql($sql, $search_history_db); + + if ($result === false) { + return false; + } + + return $result[0]; } + /** * Get the row of a table in the database using a complex filter. * @@ -669,29 +742,32 @@ function postgresql_db_get_row_sql ($sql, $search_history_db = false) { * * @return mixed Array of the row or false in case of error. */ -function postgresql_db_get_row_filter ($table, $filter, $fields = false, $where_join = 'AND') { - if (empty ($fields)) { - $fields = '*'; - } - else { - if (is_array ($fields)) - $fields = implode (',', $fields); - else if (! is_string ($fields)) - return false; - } - - if (is_array ($filter)) - $filter = db_format_array_where_clause_sql ($filter, $where_join, ' WHERE '); - else if (is_string ($filter)) - $filter = 'WHERE '.$filter; - else - $filter = ''; - - $sql = sprintf ('SELECT %s FROM %s %s', $fields, $table, $filter); - - return db_get_row_sql ($sql); +function postgresql_db_get_row_filter($table, $filter, $fields=false, $where_join='AND') +{ + if (empty($fields)) { + $fields = '*'; + } else { + if (is_array($fields)) { + $fields = implode(',', $fields); + } else if (! is_string($fields)) { + return false; + } + } + + if (is_array($filter)) { + $filter = db_format_array_where_clause_sql($filter, $where_join, ' WHERE '); + } else if (is_string($filter)) { + $filter = 'WHERE '.$filter; + } else { + $filter = ''; + } + + $sql = sprintf('SELECT %s FROM %s %s', $fields, $table, $filter); + + return db_get_row_sql($sql); } + /** * Get all the rows of a table in the database that matches a filter. * @@ -712,53 +788,54 @@ function postgresql_db_get_row_filter ($table, $filter, $fields = false, $where_ * @param mixed Fields of the table to retrieve. Can be an array or a coma * separated string. All fields are retrieved by default * @param string Condition of the filter (AND, OR). - * @param bool $returnSQL Return a string with SQL instead the data, by default false. + * @param boolean $returnSQL Return a string with SQL instead the data, by default false. * * @return mixed Array of the row or false in case of error. */ -function postgresql_db_get_all_rows_filter ($table, $filter = array(), $fields = false, $where_join = 'AND', $search_history_db = false, $returnSQL = false) { - //TODO: Validate and clean fields - if (empty($fields)) { - $fields = '*'; - } - elseif (is_array($fields)) { - $fields = implode(',', $fields); - } - elseif (!is_string($fields)) { - return false; - } - - //TODO: Validate and clean filter options - if (is_array ($filter)) { - $filter = db_format_array_where_clause_sql ($filter, $where_join, ' WHERE '); - } - elseif (is_string ($filter)) { - $filter = 'WHERE '.$filter; - } - else { - $filter = ''; - } - - $sql = sprintf ('SELECT %s FROM %s %s', $fields, $table, $filter); - - if ($returnSQL) - return $sql; - else - return db_get_all_rows_sql ($sql, $search_history_db); +function postgresql_db_get_all_rows_filter($table, $filter=[], $fields=false, $where_join='AND', $search_history_db=false, $returnSQL=false) +{ + // TODO: Validate and clean fields + if (empty($fields)) { + $fields = '*'; + } else if (is_array($fields)) { + $fields = implode(',', $fields); + } else if (!is_string($fields)) { + return false; + } + + // TODO: Validate and clean filter options + if (is_array($filter)) { + $filter = db_format_array_where_clause_sql($filter, $where_join, ' WHERE '); + } else if (is_string($filter)) { + $filter = 'WHERE '.$filter; + } else { + $filter = ''; + } + + $sql = sprintf('SELECT %s FROM %s %s', $fields, $table, $filter); + + if ($returnSQL) { + return $sql; + } else { + return db_get_all_rows_sql($sql, $search_history_db); + } } + /** * Return the count of rows of query. * - * @param $sql + * @param $sql * @return integer The count of rows of query. */ -function postgresql_db_get_num_rows ($sql) { - $result = pg_query($sql); - - return pg_num_rows($result); +function postgresql_db_get_num_rows($sql) +{ + $result = pg_query($sql); + + return pg_num_rows($result); } + /** * Get all the rows in a table of the databes filtering from a field. * @@ -769,23 +846,24 @@ function postgresql_db_get_num_rows ($sql) { * * @return mixed A matrix with all the values in the table that matches the condition in the field or false */ -function postgresql_db_get_all_rows_field_filter ($table, $field, $condition, $order_field = "") { - if (is_int ($condition) || is_bool ($condition)) { - $sql = sprintf ("SELECT * FROM \"%s\" WHERE \"%s\" = %d", $table, $field, $condition); - } - else if (is_float ($condition) || is_double ($condition)) { - $sql = sprintf ("SELECT * FROM \"%s\" WHERE \"%s\" = %f", $table, $field, $condition); - } - else { - $sql = sprintf ("SELECT * FROM \"%s\" WHERE \"%s\" = '%s'", $table, $field, $condition); - } - - if ($order_field != "") - $sql .= sprintf (" ORDER BY %s", $order_field); - - return db_get_all_rows_sql ($sql); +function postgresql_db_get_all_rows_field_filter($table, $field, $condition, $order_field='') +{ + if (is_int($condition) || is_bool($condition)) { + $sql = sprintf('SELECT * FROM "%s" WHERE "%s" = %d', $table, $field, $condition); + } else if (is_float($condition) || is_double($condition)) { + $sql = sprintf('SELECT * FROM "%s" WHERE "%s" = %f', $table, $field, $condition); + } else { + $sql = sprintf("SELECT * FROM \"%s\" WHERE \"%s\" = '%s'", $table, $field, $condition); + } + + if ($order_field != '') { + $sql .= sprintf(' ORDER BY %s', $order_field); + } + + return db_get_all_rows_sql($sql); } + /** * Get all the rows in a table of the databes filtering from a field. * @@ -794,19 +872,22 @@ function postgresql_db_get_all_rows_field_filter ($table, $field, $condition, $o * * @return mixed A matrix with all the values in the table that matches the condition in the field */ -function postgresql_db_get_all_fields_in_table ($table, $field = '', $condition = '', $order_field = '') { - $sql = sprintf ("SELECT * FROM \"%s\"", $table); - - if ($condition != '') { - $sql .= sprintf (" WHERE \"%s\" = '%s'", $field, $condition); - } - - if ($order_field != "") - $sql .= sprintf (" ORDER BY %s", $order_field); - - return db_get_all_rows_sql ($sql); +function postgresql_db_get_all_fields_in_table($table, $field='', $condition='', $order_field='') +{ + $sql = sprintf('SELECT * FROM "%s"', $table); + + if ($condition != '') { + $sql .= sprintf(" WHERE \"%s\" = '%s'", $field, $condition); + } + + if ($order_field != '') { + $sql .= sprintf(' ORDER BY %s', $order_field); + } + + return db_get_all_rows_sql($sql); } + /** * Formats an array of values into a SQL string. * @@ -830,41 +911,41 @@ function postgresql_db_get_all_fields_in_table ($table, $field = '', $condition * @return string Values joined into an SQL string that can fits into an UPDATE * sentence. */ -function postgresql_db_format_array_to_update_sql ($values) { - $fields = array (); - - foreach ($values as $field => $value) { - if (is_numeric($field)) { - array_push ($fields, $value); - continue; - } - else if ($field[0] == "`") { - $field = str_replace('`', '', $field); - } - - if ($value === NULL) { - $sql = sprintf ("\"%s\" = NULL", $field); - } - elseif (is_int ($value) || is_bool ($value)) { - $sql = sprintf ("\"%s\" = %d", $field, $value); - } - elseif (is_float ($value) || is_double ($value)) { - $sql = sprintf ("\"%s\" = %f", $field, $value); - } - else { - /* String */ - if (isset ($value[0]) && $value[0] == '`') - /* Don't round with quotes if it references a field */ - $sql = sprintf ("\"%s\" = %s", $field, $value); - else - $sql = sprintf ("\"%s\" = '%s'", $field, $value); - } - array_push ($fields, $sql); - } - - return implode (", ", $fields); +function postgresql_db_format_array_to_update_sql($values) +{ + $fields = []; + + foreach ($values as $field => $value) { + if (is_numeric($field)) { + array_push($fields, $value); + continue; + } else if ($field[0] == '`') { + $field = str_replace('`', '', $field); + } + + if ($value === null) { + $sql = sprintf('"%s" = NULL', $field); + } else if (is_int($value) || is_bool($value)) { + $sql = sprintf('"%s" = %d', $field, $value); + } else if (is_float($value) || is_double($value)) { + $sql = sprintf('"%s" = %f', $field, $value); + } else { + // String + if (isset($value[0]) && $value[0] == '`') { + // Don't round with quotes if it references a field + $sql = sprintf('"%s" = %s', $field, $value); + } else { + $sql = sprintf("\"%s\" = '%s'", $field, $value); + } + } + + array_push($fields, $sql); + } + + return implode(', ', $fields); } + /** * Updates a database record. * @@ -883,30 +964,33 @@ function postgresql_db_format_array_to_update_sql ($values) { * @param mixed An associative array of field and value matches. Will be joined * with operator specified by $where_join. A custom string can also be provided. * If nothing is provided, the update will affect all rows. - * @param string When a $where parameter is given, this will work as the glue - * between the fields. "AND" operator will be use by default. Other values might - * be "OR", "AND NOT", "XOR" + * @param string When a $where parameter is given, this will work as the glue + * between the fields. "AND" operator will be use by default. Other values might + * be "OR", "AND NOT", "XOR" * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function postgresql_db_process_sql_update($table, $values, $where = false, $where_join = 'AND') { - $query = sprintf ("UPDATE \"%s\" SET %s", - $table, - db_format_array_to_update_sql ($values)); - - if ($where) { - if (is_string ($where)) { - // No clean, the caller should make sure all input is clean, this is a raw function - $query .= " WHERE " . $where; - } - else if (is_array ($where)) { - $query .= db_format_array_where_clause_sql ($where, $where_join, ' WHERE '); - } - } - - return db_process_sql ($query); +function postgresql_db_process_sql_update($table, $values, $where=false, $where_join='AND') +{ + $query = sprintf( + 'UPDATE "%s" SET %s', + $table, + db_format_array_to_update_sql($values) + ); + + if ($where) { + if (is_string($where)) { + // No clean, the caller should make sure all input is clean, this is a raw function + $query .= ' WHERE '.$where; + } else if (is_array($where)) { + $query .= db_format_array_where_clause_sql($where, $where_join, ' WHERE '); + } + } + + return db_process_sql($query); } + /** * Delete database records. * @@ -929,131 +1013,150 @@ function postgresql_db_process_sql_update($table, $values, $where = false, $wher * @param mixed An associative array of field and value matches. Will be joined * with operator specified by $where_join. A custom string can also be provided. * If nothing is provided, the update will affect all rows. - * @param string When a $where parameter is given, this will work as the glue - * between the fields. "AND" operator will be use by default. Other values might - * be "OR", "AND NOT", "XOR" + * @param string When a $where parameter is given, this will work as the glue + * between the fields. "AND" operator will be use by default. Other values might + * be "OR", "AND NOT", "XOR" * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function postgresql_db_process_sql_delete($table, $where, $where_join = 'AND') { - if (empty ($where)) - /* Should avoid any mistake that lead to deleting all data */ - return false; - - $query = sprintf ("DELETE FROM \"%s\" WHERE ", $table); - - if ($where) { - if (is_string ($where)) { - /* FIXME: Should we clean the string for sanity? - Who cares if this is deleting data... */ - $query .= $where; - } - else if (is_array ($where)) { - $query .= db_format_array_where_clause_sql ($where, $where_join); - } - } - - return db_process_sql ($query); +function postgresql_db_process_sql_delete($table, $where, $where_join='AND') +{ + if (empty($where)) { + // Should avoid any mistake that lead to deleting all data + return false; + } + + $query = sprintf('DELETE FROM "%s" WHERE ', $table); + + if ($where) { + if (is_string($where)) { + /* + FIXME: Should we clean the string for sanity? + Who cares if this is deleting data... */ + $query .= $where; + } else if (is_array($where)) { + $query .= db_format_array_where_clause_sql($where, $where_join); + } + } + + return db_process_sql($query); } + /** * Get row by row the DB by SQL query. The first time pass the SQL query and * rest of times pass none for iterate in table and extract row by row, and * the end return false. * - * @param bool $new Default true, if true start to query. - * @param resource $result The resource of mysql for access to query. - * @param string $sql + * @param boolean $new Default true, if true start to query. + * @param resource $result The resource of mysql for access to query. + * @param string $sql * @return mixed The row or false in error. */ -function postgresql_db_get_all_row_by_steps_sql($new = true, &$result, $sql = null) { - if ($new == true) - $result = pg_query($sql); - - return pg_fetch_assoc($result); +function postgresql_db_get_all_row_by_steps_sql($new=true, &$result, $sql=null) +{ + if ($new == true) { + $result = pg_query($sql); + } + + return pg_fetch_assoc($result); } + /** * Starts a database transaction. */ -function postgresql_db_process_sql_begin() { - pg_query('BEGIN TRANSACTION'); +function postgresql_db_process_sql_begin() +{ + pg_query('BEGIN TRANSACTION'); } + /** * Commits a database transaction. */ -function postgresql_db_process_sql_commit() { - pg_query('COMMIT TRANSACTION'); +function postgresql_db_process_sql_commit() +{ + pg_query('COMMIT TRANSACTION'); } + /** * Rollbacks a database transaction. */ -function postgresql_db_process_sql_rollback() { - pg_query('ROLLBACK TRANSACTION'); +function postgresql_db_process_sql_rollback() +{ + pg_query('ROLLBACK TRANSACTION'); } + /** * Put quotes if magic_quotes protection * * @param string Text string to be protected with quotes if magic_quotes protection is disabled */ -function postgresql_safe_sql_string($string) { - if (get_magic_quotes_gpc () == 0) - return $string; - global $config; - - return pg_escape_string($config['dbconnection'], $string); +function postgresql_safe_sql_string($string) +{ + if (get_magic_quotes_gpc() == 0) { + return $string; + } + + global $config; + + return pg_escape_string($config['dbconnection'], $string); } + /** * Get last error. - * + * * @return string Return the string error. */ -function postgresql_db_get_last_error() { - return pg_last_error(); +function postgresql_db_get_last_error() +{ + return pg_last_error(); } + /** * This function gets the time from either system or sql based on preference and returns it * - * @return int Unix timestamp + * @return integer Unix timestamp */ -function postgresql_get_system_time() { - global $config; - - static $time = 0; - - if ($time != 0) - return $time; - - if ($config["timesource"] == "sql") { - $time = db_get_sql ("SELECT ceil(date_part('epoch', CURRENT_TIMESTAMP));"); - if (empty ($time)) { - return time (); - } - return $time; - } - else { - return time (); - } +function postgresql_get_system_time() +{ + global $config; + + static $time = 0; + + if ($time != 0) { + return $time; + } + + if ($config['timesource'] == 'sql') { + $time = db_get_sql("SELECT ceil(date_part('epoch', CURRENT_TIMESTAMP));"); + if (empty($time)) { + return time(); + } + + return $time; + } else { + return time(); + } } + /** * Get the type of field. - * - * @param string $table The table to examine the type of field. + * + * @param string $table The table to examine the type of field. * @param integer $field The field order in table. - * + * * @return mixed Return the type name or False in error case. */ -function postgresql_db_get_type_field_table($table, $field) { - $result = pg_query('SELECT parameters FROM ' . $table); - - return pg_field_type($result, $field); +function postgresql_db_get_type_field_table($table, $field) +{ + $result = pg_query('SELECT parameters FROM '.$table); + + return pg_field_type($result, $field); } - - -?> diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php index d36c68ada2..6f13388fc0 100644 --- a/pandora_console/include/functions.php +++ b/pandora_console/include/functions.php @@ -3,280 +3,315 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. /** - * @package Include + * @package Include * @subpackage Generic_Functions */ /** - * Include the html and ui functions. + * Include the html and ui functions. */ -require_once ('functions_html.php'); -require_once ('functions_ui.php'); -require_once('functions_io.php'); +require_once 'functions_html.php'; +require_once 'functions_ui.php'; +require_once 'functions_io.php'; /** * Check referer to avoid external attacks * * @return bool true if all is ok, false if referer is not equal to current web page */ -//function check_referer() { -// global $config; -// -// //If it is disabled the check referer security -// if (!$config["referer_security"]) -// return true; -// -// $referer = ''; -// if (isset($_SERVER['HTTP_REFERER'])) { -// $referer = $_SERVER['HTTP_REFERER']; -// } -// -// // If refresh is performed then dont't check referer -// // This is done due to problems with HTTP_REFERER var when metarefresh is performed -// if ($config["refr"] > 0) -// return true; -// -// //Check if the referer have a port (for example when apache run in other port to 80) -// if (preg_match('/http(s?):\/\/.*:[0-9]*/', $referer) == 1) { -// $url = $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $config["homeurl"]; -// } -// else { -// $url = ui_get_full_url(); -// $url = preg_replace('/http(s?):\/\//','',$url); -// } -// -// // Remove protocol from referer -// $referer = preg_replace('/http(s?):\/\//','',$referer); -// $referer = preg_replace('/\?.*/','',$referer); -// -// if (strpos($url, $referer) === 0) { -// return true; -// } -// else { -// return false; -// } -//} +// function check_referer() { +// global $config; +// +// If it is disabled the check referer security +// if (!$config["referer_security"]) +// return true; +// +// $referer = ''; +// if (isset($_SERVER['HTTP_REFERER'])) { +// $referer = $_SERVER['HTTP_REFERER']; +// } +// +// If refresh is performed then dont't check referer +// This is done due to problems with HTTP_REFERER var when metarefresh is performed +// if ($config["refr"] > 0) +// return true; +// +// Check if the referer have a port (for example when apache run in other port to 80) +// if (preg_match('/http(s?):\/\/.*:[0-9]*/', $referer) == 1) { +// $url = $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $config["homeurl"]; +// } +// else { +// $url = ui_get_full_url(); +// $url = preg_replace('/http(s?):\/\//','',$url); +// } +// +// Remove protocol from referer +// $referer = preg_replace('/http(s?):\/\//','',$referer); +// $referer = preg_replace('/\?.*/','',$referer); +// +// if (strpos($url, $referer) === 0) { +// return true; +// } +// else { +// return false; +// } +// } +function https_is_running() +{ + if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) + && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' + ) { + return true; + } -function https_is_running() { - if(isset ($_SERVER['HTTP_X_FORWARDED_PROTO']) - && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { - return true; - } - if (isset ($_SERVER['HTTPS']) - && ($_SERVER['HTTPS'] === true - || $_SERVER['HTTPS'] == 'on')) { - - return true; - } - - return false; + if (isset($_SERVER['HTTPS']) + && ($_SERVER['HTTPS'] === true + || $_SERVER['HTTPS'] == 'on') + ) { + return true; + } + + return false; } + /** * Cleans an object or an array and casts all values as integers * - * @param mixed $value String or array of strings to be cleaned - * @param int $min If value is smaller than min it will return false - * @param int $max if value is larger than max it will return false + * @param mixed $value String or array of strings to be cleaned + * @param integer $min If value is smaller than min it will return false + * @param integer $max if value is larger than max it will return false * - * @return mixed The cleaned string. If an array was passed, the invalid values + * @return mixed The cleaned string. If an array was passed, the invalid values * will be removed */ -function safe_int ($value, $min = false, $max = false) { - if (is_array ($value)) { - foreach ($value as $key => $check) { - $check = safe_int ($check, $min, $max); - if ($check !== false) { - $value[$key] = $check; - } - else { - unset ($value[$key]); - } - } - } - else { - $value = (int) $value; //Cast as integer - if (($min !== false && $value < $min) || ($max !== false && $value > $max)) { - //If it's smaller than min or larger than max return false - return false; - } - } - - return $value; +function safe_int($value, $min=false, $max=false) +{ + if (is_array($value)) { + foreach ($value as $key => $check) { + $check = safe_int($check, $min, $max); + if ($check !== false) { + $value[$key] = $check; + } else { + unset($value[$key]); + } + } + } else { + $value = (int) $value; + // Cast as integer + if (($min !== false && $value < $min) || ($max !== false && $value > $max)) { + // If it's smaller than min or larger than max return false + return false; + } + } + + return $value; } -/** + +/** * Cleans a string of special characters (|,@,$,%,/,\,=,?,*,&,#) * Useful for filenames and graphs - * + * * @param string String to be cleaned - * + * * @return string Special characters cleaned. */ -function output_clean_strict ($string) { - return preg_replace ('/[\|\@\$\%\/\(\)\=\?\*\&\#]/', '', $string); +function output_clean_strict($string) +{ + return preg_replace('/[\|\@\$\%\/\(\)\=\?\*\&\#]/', '', $string); } -/** - * Performs an extra clean to a string removing all but alphanumerical + +/** + * Performs an extra clean to a string removing all but alphanumerical * characters _ and / The string is also stripped to 125 characters from after :// * It's useful on sec and sec2, to avoid the use of malicious parameters. - * + * * TODO: Make this multibyte safe (I don't know if there is an attack vector there) * * @param string String to clean * @param default_string String that will be returned if invalid characters are found. - * + * * @return string Cleaned string */ -function safe_url_extraclean ($string, $default_string = '') { - - /* Strip the string to 125 characters */ - $string = substr ($string, 0, 125); - - /* Search for unwanted characters */ - if (preg_match ('/[^a-zA-Z0-9_\/\.\-]|(\/\/)|(\.\.)/', $string)) { - return $default_string; - } - - return $string; +function safe_url_extraclean($string, $default_string='') +{ + // Strip the string to 125 characters + $string = substr($string, 0, 125); + + // Search for unwanted characters + if (preg_match('/[^a-zA-Z0-9_\/\.\-]|(\/\/)|(\.\.)/', $string)) { + return $default_string; + } + + return $string; } -/** + +/** * List files in a directory in the local path. - * - * @param string $directory Local path. - * @param string $stringSearch String to match the values. - * @param string $searchHandler Pattern of files to match. - * @param bool $return Whether to print or return the list. - * + * + * @param string $directory Local path. + * @param string $stringSearch String to match the values. + * @param string $searchHandler Pattern of files to match. + * @param boolean $return Whether to print or return the list. + * * @return string he list of files if $return parameter is true. */ -function list_files ($directory, $stringSearch, $searchHandler, $return = false) { - $errorHandler = false; - $result = array (); - if (! $directoryHandler = @opendir ($directory)) { - echo ("
        \nerror: directory \"$directory\" doesn't exist!\n
        \n"); - return $errorHandler = true; - } - if ($searchHandler == 0) { - while (false !== ($fileName = @readdir ($directoryHandler))) { - $result[$fileName] = $fileName; - } - } - if ($searchHandler == 1) { - while (false !== ($fileName = @readdir ($directoryHandler))) { - if ((@substr_count ($fileName, $stringSearch) > 0) || (@substr_count ($fileName, strtoupper($stringSearch)) > 0)) { - $result[$fileName] = $fileName; - } - } - } - if (($errorHandler == true) && (@count ($result) === 0)) { - echo ("
        \nerror: no filetype \"$fileExtension\" found!\n
        \n"); - } - else { - asort ($result); - if ($return === false) { - echo ("
        \n");
        -			print_r ($result);
        -			echo ("
        \n"); - } - return $result; - } +function list_files($directory, $stringSearch, $searchHandler, $return=false) +{ + $errorHandler = false; + $result = []; + if (! $directoryHandler = @opendir($directory)) { + echo "
        \nerror: directory \"$directory\" doesn't exist!\n
        \n"; + return $errorHandler = true; + } + + if ($searchHandler == 0) { + while (false !== ($fileName = @readdir($directoryHandler))) { + $result[$fileName] = $fileName; + } + } + + if ($searchHandler == 1) { + while (false !== ($fileName = @readdir($directoryHandler))) { + if ((@substr_count($fileName, $stringSearch) > 0) || (@substr_count($fileName, strtoupper($stringSearch)) > 0)) { + $result[$fileName] = $fileName; + } + } + } + + if (($errorHandler == true) && (@count($result) === 0)) { + echo "
        \nerror: no filetype \"$fileExtension\" found!\n
        \n"; + } else { + asort($result); + if ($return === false) { + echo "
        \n";
        +            print_r($result);
        +            echo "
        \n"; + } + + return $result; + } } -/** + +/** * Format a number with decimals and thousands separator. * * If the number is zero or it's integer value, no decimals are * shown. Otherwise, the number of decimals are given in the call. - * - * @param float $number Number to be rendered - * @param int $decimals numbers after comma to be shown. Default value: 1 - * + * + * @param float $number Number to be rendered + * @param integer $decimals numbers after comma to be shown. Default value: 1 + * * @return string A formatted number for use in output */ -function format_numeric ($number, $decimals = 1) { - //Translate to float in case there are characters in the string so - // fmod doesn't throw a notice - $number = (float) $number; - - if ($number == 0) - return 0; - - // Translators: This is separator of decimal point - $dec_point = __("."); - // Translators: This is separator of decimal point - $thousands_sep = __(","); - - /* If has decimals */ - if (fmod ($number, 1) > 0) - return number_format ($number, $decimals, $dec_point, $thousands_sep); - - return number_format ($number, 0, $dec_point, $thousands_sep); +function format_numeric($number, $decimals=1) +{ + // Translate to float in case there are characters in the string so + // fmod doesn't throw a notice + $number = (float) $number; + + if ($number == 0) { + return 0; + } + + // Translators: This is separator of decimal point + $dec_point = __('.'); + // Translators: This is separator of decimal point + $thousands_sep = __(','); + + // If has decimals + if (fmod($number, 1) > 0) { + return number_format($number, $decimals, $dec_point, $thousands_sep); + } + + return number_format($number, 0, $dec_point, $thousands_sep); } -/** - * Render numeric data for a graph. It adds magnitude suffix to the number + +/** + * Render numeric data for a graph. It adds magnitude suffix to the number * (M for millions, K for thousands...) base-10 * * TODO: base-2 multiplication - * - * @param float $number Number to be rendered - * @param int $decimals Numbers after comma. Default value: 1 + * + * @param float $number Number to be rendered + * @param integer $decimals Numbers after comma. Default value: 1 * @param dec_point Decimal separator character. Default value: . * @param thousands_sep Thousands separator character. Default value: , - * + * * @return string A string with the number and the multiplier */ -function format_for_graph ($number , $decimals = 1, $dec_point = ".", $thousands_sep = ",") { - $shorts = array ("", "K", "M", "G", "T", "P", "E", "Z", "Y"); - $pos = 0; - while ($number >= 1000) { //as long as the number can be divided by 1000 - $pos++; //Position in array starting with 0 - $number = $number / 1000; - } - - return remove_right_zeros(format_numeric ($number, $decimals)). $shorts[$pos]; //This will actually do the rounding and the decimals +function format_for_graph($number, $decimals=1, $dec_point='.', $thousands_sep=',') +{ + $shorts = [ + '', + 'K', + 'M', + 'G', + 'T', + 'P', + 'E', + 'Z', + 'Y', + ]; + $pos = 0; + while ($number >= 1000) { + // as long as the number can be divided by 1000 + $pos++; + // Position in array starting with 0 + $number = ($number / 1000); + } + + return remove_right_zeros(format_numeric($number, $decimals)).$shorts[$pos]; + // This will actually do the rounding and the decimals } -function human_milliseconds_to_string($seconds) { - $ret = ""; - - /*** get the days ***/ - $days = intval(intval($seconds) / (360000*24)); - if($days > 0) - $ret .= "$days days "; - - /*** get the hours ***/ - $hours = (intval($seconds) / 360000) % 24; - if($hours > 0) - $ret .= "$hours hours "; - /*** get the minutes ***/ - $minutes = (intval($seconds) / 6000) % 60; - if($minutes > 0) - $ret .= "$minutes minutes "; - - /*** get the seconds ***/ - $seconds = intval($seconds / 100) % 60; - if ($seconds > 0) +function human_milliseconds_to_string($seconds) +{ + $ret = ''; + + // get the days + $days = intval(intval($seconds) / (360000 * 24)); + if ($days > 0) { + $ret .= "$days days "; + } + + // get the hours + $hours = ((intval($seconds) / 360000) % 24); + if ($hours > 0) { + $ret .= "$hours hours "; + } + + // get the minutes + $minutes = ((intval($seconds) / 6000) % 60); + if ($minutes > 0) { + $ret .= "$minutes minutes "; + } + + // get the seconds + $seconds = (intval($seconds / 100) % 60); + if ($seconds > 0) { $ret .= "$seconds seconds"; - + } + return $ret; } + /** * Rounds an integer to a multiple of 5. * @@ -297,844 +332,935 @@ function human_milliseconds_to_string($seconds) { * * @param Number rounded to a multiple of rounder */ -function format_integer_round ($number, $rounder = 5) { - return (int) ($number / $rounder + 0.5) * $rounder; +function format_integer_round($number, $rounder=5) +{ + return ((int) ($number / $rounder + 0.5) * $rounder); } -/** - * INTERNAL: Use ui_print_timestamp for output Get a human readable string of + +/** + * INTERNAL: Use ui_print_timestamp for output Get a human readable string of * the difference between current time and given timestamp. - * + * * TODO: Make sense out of all these time functions and stick with 2 or 3 * - * @param int $timestamp Unixtimestamp to compare with current time. - * @param string $units The type of unit, by default 'large'. - * + * @param integer $timestamp Unixtimestamp to compare with current time. + * @param string $units The type of unit, by default 'large'. + * * @return string A human readable string of the diference between current * time and a given timestamp. */ -function human_time_comparation ($timestamp, $units = 'large') { - global $config; - - if (!is_numeric ($timestamp)) { - $timestamp = time_w_fixed_tz($timestamp); - } - - $seconds = get_system_time () - $timestamp; - - // $seconds could be negative, because get_system_time() could return cached value - // (that might be the time a session begins at). - // So negative values are to be rounded off to 'NOW'. - if ( $seconds < 0 ) { - $seconds = 0; - } - - return human_time_description_raw($seconds, false, $units); +function human_time_comparation($timestamp, $units='large') +{ + global $config; + + if (!is_numeric($timestamp)) { + $timestamp = time_w_fixed_tz($timestamp); + } + + $seconds = (get_system_time() - $timestamp); + + // $seconds could be negative, because get_system_time() could return cached value + // (that might be the time a session begins at). + // So negative values are to be rounded off to 'NOW'. + if ($seconds < 0) { + $seconds = 0; + } + + return human_time_description_raw($seconds, false, $units); } + /** * This function gets the time from either system or sql based on preference and returns it * - * @return int Unix timestamp + * @return integer Unix timestamp */ -function get_system_time () { - global $config; - - switch ($config["dbtype"]) { - case "mysql": - return mysql_get_system_time(); - break; - case "postgresql": - return postgresql_get_system_time(); - break; - case "oracle": - return oracle_get_system_time(); - break; - } +function get_system_time() +{ + global $config; + + switch ($config['dbtype']) { + case 'mysql': + return mysql_get_system_time(); + + break; + case 'postgresql': + return postgresql_get_system_time(); + + break; + case 'oracle': + return oracle_get_system_time(); + + break; + } } + /** * This function provide the user language configuration if is not default, otherwise return the system language * - * @param string $id_user - * - * @return string user active language code + * @param string $id_user + * + * @return string user active language code */ -function get_user_language ($id_user = null) { - global $config; - - $quick_language = get_parameter('quick_language_change', 0); - - if ($quick_language) { - $language = get_parameter('language', 0); - - if (defined('METACONSOLE')) { - - if ($id_user == null) - $id_user = $config['id_user']; - - if ($language !== 0) - update_user($id_user, array('language' => $language)); - - } - - if ($language === 'default') { - return $config['language']; - } - - if ($language !== 0) { - return $language; - } - } - - if ($id_user === null && isset($config['id_user'])) { - $id_user = $config['id_user']; - } - - if ($id_user !== null) { - $userinfo = get_user_info ($id_user); - if ($userinfo['language'] != 'default') { - return $userinfo['language']; - } - } - - return $config['language']; +function get_user_language($id_user=null) +{ + global $config; + + $quick_language = get_parameter('quick_language_change', 0); + + if ($quick_language) { + $language = get_parameter('language', 0); + + if (defined('METACONSOLE')) { + if ($id_user == null) { + $id_user = $config['id_user']; + } + + if ($language !== 0) { + update_user($id_user, ['language' => $language]); + } + } + + if ($language === 'default') { + return $config['language']; + } + + if ($language !== 0) { + return $language; + } + } + + if ($id_user === null && isset($config['id_user'])) { + $id_user = $config['id_user']; + } + + if ($id_user !== null) { + $userinfo = get_user_info($id_user); + if ($userinfo['language'] != 'default') { + return $userinfo['language']; + } + } + + return $config['language']; } + /** * This function get the user language and set it on the system */ -function set_user_language() { - global $config; - global $l10n; - - $l10n = NULL; - $user_language = get_user_language (); - - if (file_exists ('./include/languages/' . $user_language . '.mo')) { - $l10n = new gettext_reader (new CachedFileReader ('./include/languages/'.$user_language.'.mo')); - $l10n->load_tables(); - } +function set_user_language() +{ + global $config; + global $l10n; + + $l10n = null; + $user_language = get_user_language(); + + if (file_exists('./include/languages/'.$user_language.'.mo')) { + $l10n = new gettext_reader(new CachedFileReader('./include/languages/'.$user_language.'.mo')); + $l10n->load_tables(); + } } -/** + +/** * INTERNAL (use ui_print_timestamp for output): Transform an amount of time in seconds into a human readable * strings of minutes, hours or days. - * - * @param int $seconds Seconds elapsed time - * @param int $exactly If it's true, return the exactly human time - * @param string $units The type of unit, by default 'large'. - * + * + * @param integer $seconds Seconds elapsed time + * @param integer $exactly If it's true, return the exactly human time + * @param string $units The type of unit, by default 'large'. + * * @return string A human readable translation of minutes. */ -function human_time_description_raw ($seconds, $exactly = false, $units = 'large') { - - switch ($units) { - case 'large': - $secondsString = __('seconds'); - $daysString = __('days'); - $monthsString = __('months'); - $yearsString = __('years'); - $minutesString = __('minutes'); - $hoursString = __('hours'); - $nowString = __('Now'); - break; - case 'tiny': - $secondsString = __('s'); - $daysString = __('d'); - $monthsString = __('M'); - $yearsString = __('Y'); - $minutesString = __('m'); - $hoursString = __('h'); - $nowString = __('N'); - break; - } - - if (empty ($seconds)) { - return $nowString; - // slerena 25/03/09 - // Most times $seconds is empty is because last contact is current date - // Put here "uknown" or N/A or something similar is not a good idea - } - - if ($exactly) { - $returnDate = ''; - - $years = floor($seconds / SECONDS_1YEAR); - - if ($years != 0) { - $seconds = $seconds - ($years * SECONDS_1YEAR); - - $returnDate .= "$years $yearsString "; - } - - $months = floor($seconds / SECONDS_1MONTH); - - if ($months != 0) { - $seconds = $seconds - ($months * SECONDS_1MONTH); - - $returnDate .= "$months $monthsString "; - } - - $days = floor($seconds / SECONDS_1DAY); - - if ($days != 0) { - $seconds = $seconds - ($days * SECONDS_1DAY); - - $returnDate .= "$days $daysString "; - } - - $returnTime = ''; - - $hours = floor($seconds / SECONDS_1HOUR); - - if ($hours != 0) { - $seconds = $seconds - ($hours * SECONDS_1HOUR); - - $returnTime .= "$hours $hoursString "; - } - - $mins = floor($seconds / 60); - - if ($mins != 0) { - $seconds = $seconds - ($mins * 60); - - $returnTime .= "$mins $minutesString "; - - } - - $seconds = (int) $seconds; - - if ($seconds != 0) { - $returnTime .= "$seconds $secondsString "; - } - - $return = ' '; - - if ($returnDate != '') { - $return = $returnDate; - } - - if ($returnTime != '') { - $return .= $returnTime; - } - - if ($return == ' ') { - return $nowString; - } - else { - return $return; - } - - } - - if ($seconds < SECONDS_1MINUTE) - return format_numeric ($seconds, 0)." " . $secondsString; - - if ($seconds < SECONDS_1HOUR) { - $minutes = floor($seconds / 60); - $seconds = $seconds % SECONDS_1MINUTE; - if ($seconds == 0) - return $minutes.' ' . $minutesString; - $seconds = sprintf ("%02d", $seconds); - return $minutes.' '. $minutesString . ' ' .$seconds.' ' . $secondsString; - } - - if ($seconds < SECONDS_1DAY) - return format_numeric ($seconds / SECONDS_1HOUR, 0)." " . $hoursString; - - if ($seconds < SECONDS_1MONTH) - return format_numeric ($seconds / SECONDS_1DAY, 0) . " " . $daysString; - - if ($seconds < SECONDS_6MONTHS) - return format_numeric ($seconds / SECONDS_1MONTH, 0)." ". $monthsString; - - return "+6 " . $monthsString; +function human_time_description_raw($seconds, $exactly=false, $units='large') +{ + switch ($units) { + case 'large': + $secondsString = __('seconds'); + $daysString = __('days'); + $monthsString = __('months'); + $yearsString = __('years'); + $minutesString = __('minutes'); + $hoursString = __('hours'); + $nowString = __('Now'); + break; + + case 'tiny': + $secondsString = __('s'); + $daysString = __('d'); + $monthsString = __('M'); + $yearsString = __('Y'); + $minutesString = __('m'); + $hoursString = __('h'); + $nowString = __('N'); + break; + } + + if (empty($seconds)) { + return $nowString; + // slerena 25/03/09 + // Most times $seconds is empty is because last contact is current date + // Put here "uknown" or N/A or something similar is not a good idea + } + + if ($exactly) { + $returnDate = ''; + + $years = floor($seconds / SECONDS_1YEAR); + + if ($years != 0) { + $seconds = ($seconds - ($years * SECONDS_1YEAR)); + + $returnDate .= "$years $yearsString "; + } + + $months = floor($seconds / SECONDS_1MONTH); + + if ($months != 0) { + $seconds = ($seconds - ($months * SECONDS_1MONTH)); + + $returnDate .= "$months $monthsString "; + } + + $days = floor($seconds / SECONDS_1DAY); + + if ($days != 0) { + $seconds = ($seconds - ($days * SECONDS_1DAY)); + + $returnDate .= "$days $daysString "; + } + + $returnTime = ''; + + $hours = floor($seconds / SECONDS_1HOUR); + + if ($hours != 0) { + $seconds = ($seconds - ($hours * SECONDS_1HOUR)); + + $returnTime .= "$hours $hoursString "; + } + + $mins = floor($seconds / 60); + + if ($mins != 0) { + $seconds = ($seconds - ($mins * 60)); + + $returnTime .= "$mins $minutesString "; + } + + $seconds = (int) $seconds; + + if ($seconds != 0) { + $returnTime .= "$seconds $secondsString "; + } + + $return = ' '; + + if ($returnDate != '') { + $return = $returnDate; + } + + if ($returnTime != '') { + $return .= $returnTime; + } + + if ($return == ' ') { + return $nowString; + } else { + return $return; + } + } + + if ($seconds < SECONDS_1MINUTE) { + return format_numeric($seconds, 0).' '.$secondsString; + } + + if ($seconds < SECONDS_1HOUR) { + $minutes = floor($seconds / 60); + $seconds = ($seconds % SECONDS_1MINUTE); + if ($seconds == 0) { + return $minutes.' '.$minutesString; + } + + $seconds = sprintf('%02d', $seconds); + return $minutes.' '.$minutesString.' '.$seconds.' '.$secondsString; + } + + if ($seconds < SECONDS_1DAY) { + return format_numeric(($seconds / SECONDS_1HOUR), 0).' '.$hoursString; + } + + if ($seconds < SECONDS_1MONTH) { + return format_numeric(($seconds / SECONDS_1DAY), 0).' '.$daysString; + } + + if ($seconds < SECONDS_6MONTHS) { + return format_numeric(($seconds / SECONDS_1MONTH), 0).' '.$monthsString; + } + + return '+6 '.$monthsString; } -/** + +/** * INTERNAL (use ui_print_timestamp for output): Transform an amount of time in seconds into a human readable * strings of minutes, hours or days. Used in alert views. - * - * @param int $seconds Seconds elapsed time - * @param int $exactly If it's true, return the exactly human time - * @param string $units The type of unit, by default 'large'. - * + * + * @param integer $seconds Seconds elapsed time + * @param integer $exactly If it's true, return the exactly human time + * @param string $units The type of unit, by default 'large'. + * * @return string A human readable translation of minutes. */ -function human_time_description_alerts ($seconds, $exactly = false, $units = 'tiny') { - switch ($units) { - case 'large': - $secondsString = __('seconds'); - $daysString = __('days'); - $monthsString = __('months'); - $yearsString = __('years'); - $minutesString = __('minutes'); - $hoursString = __('hours'); - $nowString = __('Now'); - break; - case 'tiny': - $secondsString = __('s'); - $daysString = __('d'); - $monthsString = __('M'); - $yearsString = __('Y'); - $minutesString = __('m'); - $hoursString = __('h'); - $nowString = __('N'); - break; - } - - if (empty ($seconds)) { - return $nowString; - // slerena 25/03/09 - // Most times $seconds is empty is because last contact is current date - // Put here "uknown" or N/A or something similar is not a good idea - } - - if ($exactly) { - $returnDate = ''; - - $years = floor($seconds / SECONDS_1YEAR); - - if ($years != 0) { - $seconds = $seconds - ($years * SECONDS_1YEAR); - - $returnDate .= "$years $yearsString "; - } - - $months = floor($seconds / SECONDS_1MONTH); - - if ($months != 0) { - $seconds = $seconds - ($months * SECONDS_1MONTH); - - $returnDate .= "$months $monthsString "; - } - - $days = floor($seconds / SECONDS_1DAY); - - if ($days != 0) { - $seconds = $seconds - ($days * SECONDS_1DAY); - - $returnDate .= "$days $daysString "; - } - - $returnTime = ''; - - $hours = floor($seconds / SECONDS_1HOUR); - - if ($hours != 0) { - $seconds = $seconds - ($hours * SECONDS_1HOUR); - - $returnTime .= "$hours $hoursString "; - } - - $mins = floor($seconds / SECONDS_1MINUTE); - - if ($mins != 0) { - $seconds = $seconds - ($mins * SECONDS_1MINUTE); - - if ($hours == 0) { - $returnTime .= "$mins $minutesString "; - } - else { - $returnTime = sprintf("%02d",$hours) . "$hoursString" . - sprintf("%02d",$mins) . "$minutesString"; - } - } - - if ($seconds != 0) { - if ($hours == 0) { - $returnTime .= "$seconds $secondsString "; - } - else { - $returnTime = sprintf("%02d",$hours) . "$hoursString" . - sprintf("%02d",$mins) . "$minutesString" . - sprintf("%02d",$seconds) . "$secondsString"; - } - } - - $return = ' '; - - if ($returnDate != '') { - $return = $returnDate; - } - - if ($returnTime != '') { - $return .= $returnTime; - } - - if ($return == ' ') { - return $nowString; - } - else { - return $return; - } - - } - - if ($seconds < 60) - return format_numeric ($seconds, 0)." " . $secondsString; - - if ($seconds < SECONDS_1HOUR) { - $minutes = floor($seconds / SECONDS_1MINUTE); - $seconds = $seconds % SECONDS_1MINUTE; - if ($seconds == 0) - return $minutes.' ' . $minutesString; - $seconds = sprintf ("%02d", $seconds); - return $minutes.' '. $minutesString . ' ' .$seconds.' ' . $secondsString; - } - - if ($seconds < SECONDS_1DAY) - return format_numeric ($seconds / SECONDS_1HOUR, 0)." " . $hoursString; - - if ($seconds < SECONDS_1MONTH) - return format_numeric ($seconds / SECONDS_1DAY, 0) . " " . $daysString; - - if ($seconds < SECONDS_6MONTHS) - return format_numeric ($seconds / SECONDS_1MONTH, 0)." ". $monthsString; - - return "+6 " . $monthsString; +function human_time_description_alerts($seconds, $exactly=false, $units='tiny') +{ + switch ($units) { + case 'large': + $secondsString = __('seconds'); + $daysString = __('days'); + $monthsString = __('months'); + $yearsString = __('years'); + $minutesString = __('minutes'); + $hoursString = __('hours'); + $nowString = __('Now'); + break; + + case 'tiny': + $secondsString = __('s'); + $daysString = __('d'); + $monthsString = __('M'); + $yearsString = __('Y'); + $minutesString = __('m'); + $hoursString = __('h'); + $nowString = __('N'); + break; + } + + if (empty($seconds)) { + return $nowString; + // slerena 25/03/09 + // Most times $seconds is empty is because last contact is current date + // Put here "uknown" or N/A or something similar is not a good idea + } + + if ($exactly) { + $returnDate = ''; + + $years = floor($seconds / SECONDS_1YEAR); + + if ($years != 0) { + $seconds = ($seconds - ($years * SECONDS_1YEAR)); + + $returnDate .= "$years $yearsString "; + } + + $months = floor($seconds / SECONDS_1MONTH); + + if ($months != 0) { + $seconds = ($seconds - ($months * SECONDS_1MONTH)); + + $returnDate .= "$months $monthsString "; + } + + $days = floor($seconds / SECONDS_1DAY); + + if ($days != 0) { + $seconds = ($seconds - ($days * SECONDS_1DAY)); + + $returnDate .= "$days $daysString "; + } + + $returnTime = ''; + + $hours = floor($seconds / SECONDS_1HOUR); + + if ($hours != 0) { + $seconds = ($seconds - ($hours * SECONDS_1HOUR)); + + $returnTime .= "$hours $hoursString "; + } + + $mins = floor($seconds / SECONDS_1MINUTE); + + if ($mins != 0) { + $seconds = ($seconds - ($mins * SECONDS_1MINUTE)); + + if ($hours == 0) { + $returnTime .= "$mins $minutesString "; + } else { + $returnTime = sprintf('%02d', $hours)."$hoursString".sprintf('%02d', $mins)."$minutesString"; + } + } + + if ($seconds != 0) { + if ($hours == 0) { + $returnTime .= "$seconds $secondsString "; + } else { + $returnTime = sprintf('%02d', $hours)."$hoursString".sprintf('%02d', $mins)."$minutesString".sprintf('%02d', $seconds)."$secondsString"; + } + } + + $return = ' '; + + if ($returnDate != '') { + $return = $returnDate; + } + + if ($returnTime != '') { + $return .= $returnTime; + } + + if ($return == ' ') { + return $nowString; + } else { + return $return; + } + } + + if ($seconds < 60) { + return format_numeric($seconds, 0).' '.$secondsString; + } + + if ($seconds < SECONDS_1HOUR) { + $minutes = floor($seconds / SECONDS_1MINUTE); + $seconds = ($seconds % SECONDS_1MINUTE); + if ($seconds == 0) { + return $minutes.' '.$minutesString; + } + + $seconds = sprintf('%02d', $seconds); + return $minutes.' '.$minutesString.' '.$seconds.' '.$secondsString; + } + + if ($seconds < SECONDS_1DAY) { + return format_numeric(($seconds / SECONDS_1HOUR), 0).' '.$hoursString; + } + + if ($seconds < SECONDS_1MONTH) { + return format_numeric(($seconds / SECONDS_1DAY), 0).' '.$daysString; + } + + if ($seconds < SECONDS_6MONTHS) { + return format_numeric(($seconds / SECONDS_1MONTH), 0).' '.$monthsString; + } + + return '+6 '.$monthsString; } -/** + +/** * @deprecated Get current time minus some seconds. (Do your calculations yourself on unix timestamps) - * - * @param int $seconds Seconds to substract from current time. - * - * @return int The current time minus the seconds given. + * + * @param integer $seconds Seconds to substract from current time. + * + * @return integer The current time minus the seconds given. */ -function human_date_relative ($seconds) { - $ahora = date("Y/m/d H:i:s"); - $ahora_s = date("U"); - $ayer = date ("Y/m/d H:i:s", $ahora_s - $seconds); - - return $ayer; +function human_date_relative($seconds) +{ + $ahora = date('Y/m/d H:i:s'); + $ahora_s = date('U'); + $ayer = date('Y/m/d H:i:s', ($ahora_s - $seconds)); + + return $ayer; } -/** + +/** * @deprecated Use ui_print_timestamp instead */ -function render_time ($lapse) { - $myhour = intval (($lapse*30) / 60); - if ($myhour == 0) - $output = "00"; - else - $output = $myhour; - $output .= ":"; - $mymin = fmod ($lapse * 30, 60); - if ($mymin == 0) - $output .= "00"; - else - $output .= $mymin; - - return $output; +function render_time($lapse) +{ + $myhour = intval(($lapse * 30) / 60); + if ($myhour == 0) { + $output = '00'; + } else { + $output = $myhour; + } + + $output .= ':'; + $mymin = fmod(($lapse * 30), 60); + if ($mymin == 0) { + $output .= '00'; + } else { + $output .= $mymin; + } + + return $output; } -/** + +/** * Get a parameter from a request between values. * * It checks first on post request, if there were nothing defined, it * would return get request - * - * @param string $name key of the parameter in the $_POST or $_GET array - * @param array $values The list of values that parameter to be. - * @param mixed $default default value if the key wasn't found - * - * @return mixed Whatever was in that parameter, cleaned however + * + * @param string $name key of the parameter in the $_POST or $_GET array + * @param array $values The list of values that parameter to be. + * @param mixed $default default value if the key wasn't found + * + * @return mixed Whatever was in that parameter, cleaned however */ -function get_parameterBetweenListValues ($name, $values, $default) { - $parameter = $default; - // POST has precedence - if (isset($_POST[$name])) - $parameter = get_parameter_post ($name, $default); - - if (isset($_GET[$name])) - $parameter = get_parameter_get ($name, $default); - - foreach($values as $value) { - if ($value == $parameter) { - return $value; - } - } - - return $default; +function get_parameterBetweenListValues($name, $values, $default) +{ + $parameter = $default; + // POST has precedence + if (isset($_POST[$name])) { + $parameter = get_parameter_post($name, $default); + } + + if (isset($_GET[$name])) { + $parameter = get_parameter_get($name, $default); + } + + foreach ($values as $value) { + if ($value == $parameter) { + return $value; + } + } + + return $default; } -/** + +/** * Get a parameter from a checkbox. - * + * * Is checked if the checkbox is sent to fix html bad design * - * @param string $name key of the parameter in the $_POST or $_GET array - * @param mixed $default default value if the key wasn't found - * - * @return mixed Whatever was in that parameter, cleaned however - * + * @param string $name key of the parameter in the $_POST or $_GET array + * @param mixed $default default value if the key wasn't found + * + * @return mixed Whatever was in that parameter, cleaned however */ -function get_parameter_checkbox ($name, $default = '') { - $sent = get_parameter($name.'_sent', 0); - - // If is not sent, return the default - if (!$sent) { - return $default; - } - - // If sent, get parameter normally - return get_parameter($name, 0); + +function get_parameter_checkbox($name, $default='') +{ + $sent = get_parameter($name.'_sent', 0); + + // If is not sent, return the default + if (!$sent) { + return $default; + } + + // If sent, get parameter normally + return get_parameter($name, 0); } -function get_cookie($name, $default = '') { - if (isset($_COOKIE[$name])) { - return $_COOKIE[$name]; - } - else { - return $default; - } + +function get_cookie($name, $default='') +{ + if (isset($_COOKIE[$name])) { + return $_COOKIE[$name]; + } else { + return $default; + } } -function set_cookie($name, $value) { - if (is_null($value)) { - unset($_COOKIE[$value]); - setcookie($name, null, -1, '/'); - } - else { - setcookie($name, $value); - } + +function set_cookie($name, $value) +{ + if (is_null($value)) { + unset($_COOKIE[$value]); + setcookie($name, null, -1, '/'); + } else { + setcookie($name, $value); + } } -/** + +/** * Get a parameter from a request. * * It checks first on post request, if there were nothing defined, it * would return get request - * - * @param string $name key of the parameter in the $_POST or $_GET array - * @param mixed $default default value if the key wasn't found - * - * @return mixed Whatever was in that parameter, cleaned however + * + * @param string $name key of the parameter in the $_POST or $_GET array + * @param mixed $default default value if the key wasn't found + * + * @return mixed Whatever was in that parameter, cleaned however */ -function get_parameter ($name, $default = '') { - // POST has precedence - if (isset($_POST[$name])) - return get_parameter_post ($name, $default); - - if (isset($_GET[$name])) - return get_parameter_get ($name, $default); - - return $default; +function get_parameter($name, $default='') +{ + // POST has precedence + if (isset($_POST[$name])) { + return get_parameter_post($name, $default); + } + + if (isset($_GET[$name])) { + return get_parameter_get($name, $default); + } + + return $default; } -/** + +/** * Get a parameter from a get request. * - * @param string $name key of the parameter in the $_GET array - * @param mixed $default default value if the key wasn't found - * - * @return mixed Whatever was in that parameter, cleaned however + * @param string $name key of the parameter in the $_GET array + * @param mixed $default default value if the key wasn't found + * + * @return mixed Whatever was in that parameter, cleaned however */ -function get_parameter_get ($name, $default = "") { - if ((isset ($_GET[$name])) && ($_GET[$name] != "")) - return io_safe_input ($_GET[$name]); - - return $default; +function get_parameter_get($name, $default='') +{ + if ((isset($_GET[$name])) && ($_GET[$name] != '')) { + return io_safe_input($_GET[$name]); + } + + return $default; } -/** + +/** * Get a parameter from a post request. * - * @param string $name key of the parameter in the $_POST array - * @param mixed $default default value if the key wasn't found - * - * @return mixed Whatever was in that parameter, cleaned however + * @param string $name key of the parameter in the $_POST array + * @param mixed $default default value if the key wasn't found + * + * @return mixed Whatever was in that parameter, cleaned however */ -function get_parameter_post ($name, $default = "") { - if ((isset ($_POST[$name])) && ($_POST[$name] != "")) { - return io_safe_input ($_POST[$name]); - } - - return $default; +function get_parameter_post($name, $default='') +{ + if ((isset($_POST[$name])) && ($_POST[$name] != '')) { + return io_safe_input($_POST[$name]); + } + + return $default; } -/** + +/** * Get name of a priority value. - * - * @param int $priority Priority value - * + * + * @param integer $priority Priority value + * * @return string Name of given priority */ -function get_alert_priority ($priority = 0) { - global $config; - - switch ($priority) { - case 0: - return __('Maintenance'); - break; - case 1: - return __('Informational'); - break; - case 2: - return __('Normal'); - break; - case 3: - return __('Warning'); - break; - case 4: - return __('Critical'); - break; - case 5: - return __('Minor'); - break; - case 6: - return __('Major'); - break; - } - - return ''; +function get_alert_priority($priority=0) +{ + global $config; + + switch ($priority) { + case 0: + return __('Maintenance'); + + break; + case 1: + return __('Informational'); + + break; + case 2: + return __('Normal'); + + break; + case 3: + return __('Warning'); + + break; + case 4: + return __('Critical'); + + break; + case 5: + return __('Minor'); + + break; + case 6: + return __('Major'); + + break; + } + + return ''; } -/** - * Gets a translated string of names of days based on the boolean properties of it's input ($row["monday"] = (bool) 1 will output Mon) - * - * @param array $row The array of boolean values to check. They should have monday -> sunday in boolean - * + +/** + * Gets a translated string of names of days based on the boolean properties of it's input ($row["monday"] = (bool) 1 will output Mon) + * + * @param array $row The array of boolean values to check. They should have monday -> sunday in boolean + * * @return string Translated names of days */ -function get_alert_days ($row) { - global $config; - $days_output = ""; - - $check = $row["monday"] + $row["tuesday"] + $row["wednesday"] + $row["thursday"] + $row["friday"] + $row["saturday"] + $row["sunday"]; - - if ($check == 7) { - return __('All'); - } - elseif ($check == 0) { - return __('None'); - } - - if ($row["monday"] != 0) - $days_output .= __('Mon')." "; - if ($row["tuesday"] != 0) - $days_output .= __('Tue')." "; - if ($row["wednesday"] != 0) - $days_output .= __('Wed')." "; - if ($row["thursday"] != 0) - $days_output .= __('Thu')." "; - if ($row["friday"] != 0) - $days_output .= __('Fri')." "; - if ($row["saturday"] != 0) - $days_output .= __('Sat')." "; - if ($row["sunday"] != 0) - $days_output .= __('Sun'); - - if ($check > 1) { - return str_replace (" ",", ",$days_output); - } - - return rtrim ($days_output); +function get_alert_days($row) +{ + global $config; + $days_output = ''; + + $check = ($row['monday'] + $row['tuesday'] + $row['wednesday'] + $row['thursday'] + $row['friday'] + $row['saturday'] + $row['sunday']); + + if ($check == 7) { + return __('All'); + } else if ($check == 0) { + return __('None'); + } + + if ($row['monday'] != 0) { + $days_output .= __('Mon').' '; + } + + if ($row['tuesday'] != 0) { + $days_output .= __('Tue').' '; + } + + if ($row['wednesday'] != 0) { + $days_output .= __('Wed').' '; + } + + if ($row['thursday'] != 0) { + $days_output .= __('Thu').' '; + } + + if ($row['friday'] != 0) { + $days_output .= __('Fri').' '; + } + + if ($row['saturday'] != 0) { + $days_output .= __('Sat').' '; + } + + if ($row['sunday'] != 0) { + $days_output .= __('Sun'); + } + + if ($check > 1) { + return str_replace(' ', ', ', $days_output); + } + + return rtrim($days_output); } -/** + +/** * Gets the alert times values and returns them as string - * + * * @param array Array with time_from and time_to in it's keys - * + * * @return string A string with the concatenated values */ -function get_alert_times ($row2) { - if ($row2["time_from"]) { - $time_from_table = $row2["time_from"]; - } - else { - $time_from_table = __('N/A'); - } - if ($row2["time_to"]) { - $time_to_table = $row2["time_to"]; - } - else { - $time_to_table = __('N/A'); - } - if ($time_to_table == $time_from_table) - return __('N/A'); - - return substr ($time_from_table, 0, 5)." - ".substr ($time_to_table, 0, 5); +function get_alert_times($row2) +{ + if ($row2['time_from']) { + $time_from_table = $row2['time_from']; + } else { + $time_from_table = __('N/A'); + } + + if ($row2['time_to']) { + $time_to_table = $row2['time_to']; + } else { + $time_to_table = __('N/A'); + } + + if ($time_to_table == $time_from_table) { + return __('N/A'); + } + + return substr($time_from_table, 0, 5).' - '.substr($time_to_table, 0, 5); } + /** * Checks if a module is of type "data" * * @param string $module_name Module name to check. * - * @return bool True if the module is of type "data" + * @return boolean True if the module is of type "data" */ -function is_module_data ($module_name) { - return preg_match ('/\_data$/', $module_name); +function is_module_data($module_name) +{ + return preg_match('/\_data$/', $module_name); } + /** * Checks if a module is of type "proc" * * @param string $module_name Module name to check. * - * @return bool true if the module is of type "proc" + * @return boolean true if the module is of type "proc" */ -function is_module_proc ($module_name) { - return preg_match ('/\_proc$/', $module_name); +function is_module_proc($module_name) +{ + return preg_match('/\_proc$/', $module_name); } + /** * Checks if a module is of type "inc" * * @param string $module_name Module name to check. * - * @return bool true if the module is of type "inc" + * @return boolean true if the module is of type "inc" */ -function is_module_inc ($module_name) { - return preg_match ('/\_inc$/', $module_name); +function is_module_inc($module_name) +{ + return preg_match('/\_inc$/', $module_name); } + /** * Checks if a module is of type "string" * * @param string $module_name Module name to check. * - * @return bool true if the module is of type "string" + * @return boolean true if the module is of type "string" */ -function is_module_data_string ($module_name) { - return preg_match ('/\_string$/', $module_name); +function is_module_data_string($module_name) +{ + return preg_match('/\_string$/', $module_name); } + /** * Checks if a module data is uncompressed according * to the module type. * * @param string module_type Type of the module. * - * @return bool true if the module data is uncompressed. + * @return boolean true if the module data is uncompressed. */ -function is_module_uncompressed ($module_type) { - if (strstr($module_type, 'async') !== false || strstr($module_type, 'log4x') !== false) { - return true; - } - return false; +function is_module_uncompressed($module_type) +{ + if (strstr($module_type, 'async') !== false || strstr($module_type, 'log4x') !== false) { + return true; + } + + return false; } + /** * Get all event types in an array * * @return array module_name Module name to check. */ -function get_event_types ($id_type = false) { - global $config; - - $types = array(); - - $types['critical'] = __('Monitor Critical'); - $types['warning'] = __('Monitor Warning'); - $types['normal'] = __('Monitor Normal'); - $types['unknown'] = __('Unknown'); - $types['going_unknown'] = __('Monitor Unknown'); +function get_event_types($id_type=false) +{ + global $config; - $types['alert_fired'] = __('Alert fired'); - $types['alert_recovered'] = __('Alert recovered'); - $types['alert_ceased'] = __('Alert ceased'); - $types['alert_manual_validation'] = __('Alert manual validation'); - - $types['new_agent'] = __('Agent created'); - $types['recon_host_detected'] = __('Recon host detected'); - $types['system'] = __('System'); - $types['error'] = __('Error'); - $types['configuration_change'] = __('Configuration change'); + $types = []; - // This types are impersonated by the monitor 'x' types - // $types['going_up_normal'] = __('Going Normal'); - // $types['going_up_warning'] = __('Going Warning'); - // $types['going_up_critical'] = __('Going Critical'); - // $types['going_down_warning'] = __('Going down Warning'); - // $types['going_down_normal'] = __('Going down Normal'); - // $types['going_down_critical'] = __('Going down Critical'); + $types['critical'] = __('Monitor Critical'); + $types['warning'] = __('Monitor Warning'); + $types['normal'] = __('Monitor Normal'); + $types['unknown'] = __('Unknown'); + $types['going_unknown'] = __('Monitor Unknown'); - foreach ($types as $key => $type) { - $types[$key] = ui_print_truncate_text($type, GENERIC_SIZE_TEXT, false, true, false); - } - - if ($id_type === false) { - return $types; - } - else { - return $types[$id_type]; - } + $types['alert_fired'] = __('Alert fired'); + $types['alert_recovered'] = __('Alert recovered'); + $types['alert_ceased'] = __('Alert ceased'); + $types['alert_manual_validation'] = __('Alert manual validation'); + + $types['new_agent'] = __('Agent created'); + $types['recon_host_detected'] = __('Recon host detected'); + $types['system'] = __('System'); + $types['error'] = __('Error'); + $types['configuration_change'] = __('Configuration change'); + + // This types are impersonated by the monitor 'x' types + // $types['going_up_normal'] = __('Going Normal'); + // $types['going_up_warning'] = __('Going Warning'); + // $types['going_up_critical'] = __('Going Critical'); + // $types['going_down_warning'] = __('Going down Warning'); + // $types['going_down_normal'] = __('Going down Normal'); + // $types['going_down_critical'] = __('Going down Critical'); + foreach ($types as $key => $type) { + $types[$key] = ui_print_truncate_text($type, GENERIC_SIZE_TEXT, false, true, false); + } + + if ($id_type === false) { + return $types; + } else { + return $types[$id_type]; + } } + /** * Get an array with all the priorities. * * @return array An array with all the priorities. */ -function get_priorities ($priority_param = false) { - global $config; - - $priorities = array (); - $priorities[EVENT_CRIT_MAINTENANCE] = __('Maintenance'); - $priorities[EVENT_CRIT_INFORMATIONAL] = __('Informational'); - $priorities[EVENT_CRIT_NORMAL] = __('Normal'); - $priorities[EVENT_CRIT_MINOR] = __('Minor'); - $priorities[EVENT_CRIT_WARNING] = __('Warning'); - $priorities[EVENT_CRIT_MAJOR] = __('Major'); - $priorities[EVENT_CRIT_CRITICAL] = __('Critical'); - $priorities[EVENT_CRIT_WARNING_OR_CRITICAL] = __('Warning').'/'.__('Critical'); - $priorities[EVENT_CRIT_NOT_NORMAL] = __('Not normal'); - $priorities[EVENT_CRIT_OR_NORMAL] = __('Critical') . '/' . __('Normal'); - - foreach ($priorities as $key => $priority) { - $priorities[$key] = ui_print_truncate_text($priority, GENERIC_SIZE_TEXT, false, true, false); - } - - if ($priority_param === false) { - return $priorities; - } - else { - return $priorities[$priority_param]; - } +function get_priorities($priority_param=false) +{ + global $config; + + $priorities = []; + $priorities[EVENT_CRIT_MAINTENANCE] = __('Maintenance'); + $priorities[EVENT_CRIT_INFORMATIONAL] = __('Informational'); + $priorities[EVENT_CRIT_NORMAL] = __('Normal'); + $priorities[EVENT_CRIT_MINOR] = __('Minor'); + $priorities[EVENT_CRIT_WARNING] = __('Warning'); + $priorities[EVENT_CRIT_MAJOR] = __('Major'); + $priorities[EVENT_CRIT_CRITICAL] = __('Critical'); + $priorities[EVENT_CRIT_WARNING_OR_CRITICAL] = __('Warning').'/'.__('Critical'); + $priorities[EVENT_CRIT_NOT_NORMAL] = __('Not normal'); + $priorities[EVENT_CRIT_OR_NORMAL] = __('Critical').'/'.__('Normal'); + + foreach ($priorities as $key => $priority) { + $priorities[$key] = ui_print_truncate_text($priority, GENERIC_SIZE_TEXT, false, true, false); + } + + if ($priority_param === false) { + return $priorities; + } else { + return $priorities[$priority_param]; + } } + /** * Get priority name from priority value. * - * @param int $priority value (integer) as stored eg. in database. + * @param integer $priority value (integer) as stored eg. in database. * * @return string priority string. */ -function get_priority_name ($priority) { - switch ($priority) { - case 0: - return __('Maintenance'); - break; - case 1: - return __('Informational'); - break; - case 2: - return __('Normal'); - break; - case 3: - return __('Warning'); - break; - case 4: - return __('Critical'); - break; - case 5: - return __('Minor'); - break; - case 6: - return __('Major'); - break; - default: - return __('All'); - break; - } +function get_priority_name($priority) +{ + switch ($priority) { + case 0: + return __('Maintenance'); + + break; + case 1: + return __('Informational'); + + break; + case 2: + return __('Normal'); + + break; + case 3: + return __('Warning'); + + break; + case 4: + return __('Critical'); + + break; + case 5: + return __('Minor'); + + break; + case 6: + return __('Major'); + + break; + default: + return __('All'); + break; + } } + /** * Get priority class (CSS class) from priority value. * @@ -1142,35 +1268,44 @@ function get_priority_name ($priority) { * * @return string CSS priority class. */ -function get_priority_class($priority) { - switch ($priority) { - case 0: - return "datos_blue"; - break; - case 1: - return "datos_grey"; - break; - case 2: - return "datos_green"; - break; - case 3: - return "datos_yellow"; - break; - case 4: - return "datos_red"; - break; - case 5: - return "datos_pink"; - break; - case 6: - return "datos_brown"; - break; - default: - return "datos_grey"; - break; - } +function get_priority_class($priority) +{ + switch ($priority) { + case 0: + return 'datos_blue'; + + break; + case 1: + return 'datos_grey'; + + break; + case 2: + return 'datos_green'; + + break; + case 3: + return 'datos_yellow'; + + break; + case 4: + return 'datos_red'; + + break; + case 5: + return 'datos_pink'; + + break; + case 6: + return 'datos_brown'; + + break; + default: + return 'datos_grey'; + break; + } } + /** * Get priority style from priority class (CSS class). * @@ -1178,256 +1313,310 @@ function get_priority_class($priority) { * * @return string CSS priority class. */ -function get_priority_style($priority_class) { - switch ($priority_class) { - case "datos_blue": - $style_css_criticity = 'background-color: ' . COL_MAINTENANCE . '; color: #FFFFFF;'; - break; - case "datos_grey": - $style_css_criticity = 'background-color: ' . COL_UNKNOWN . '; color: #FFFFFF;'; - break; - case "datos_green": - $style_css_criticity = 'background-color: ' . COL_NORMAL . '; color: #FFFFFF;'; - break; - case "datos_yellow": - $style_css_criticity = 'background-color: ' . COL_WARNING . ';'; - break; - case "datos_red": - $style_css_criticity = 'background-color: ' . COL_CRITICAL . '; color: #FFFFFF;'; - break; - case "datos_pink": - $style_css_criticity = 'background-color: ' . COL_MINOR . ';'; - break; - case "datos_brown": - $style_css_criticity = 'background-color: ' . COL_MAJOR . '; color: #FFFFFF;'; - break; - case "datos_grey": - default: - $style_css_criticity = 'background-color: ' . COL_UNKNOWN . '; color: #FFFFFF;'; - break; - } - - return $style_css_criticity; +function get_priority_style($priority_class) +{ + switch ($priority_class) { + case 'datos_blue': + $style_css_criticity = 'background-color: '.COL_MAINTENANCE.'; color: #FFFFFF;'; + break; + + case 'datos_grey': + $style_css_criticity = 'background-color: '.COL_UNKNOWN.'; color: #FFFFFF;'; + break; + + case 'datos_green': + $style_css_criticity = 'background-color: '.COL_NORMAL.'; color: #FFFFFF;'; + break; + + case 'datos_yellow': + $style_css_criticity = 'background-color: '.COL_WARNING.';'; + break; + + case 'datos_red': + $style_css_criticity = 'background-color: '.COL_CRITICAL.'; color: #FFFFFF;'; + break; + + case 'datos_pink': + $style_css_criticity = 'background-color: '.COL_MINOR.';'; + break; + + case 'datos_brown': + $style_css_criticity = 'background-color: '.COL_MAJOR.'; color: #FFFFFF;'; + break; + + case 'datos_grey': + default: + $style_css_criticity = 'background-color: '.COL_UNKNOWN.'; color: #FFFFFF;'; + break; + } + + return $style_css_criticity; } + /** * Check if the enterprise version is installed. - * + * * @return boolean If it is installed return true, otherwise return false. */ -function enterprise_installed() { - $return = false; - - if (defined('PANDORA_ENTERPRISE')) { - if (PANDORA_ENTERPRISE) { - $return = true; - } - } - - return $return; +function enterprise_installed() +{ + $return = false; + + if (defined('PANDORA_ENTERPRISE')) { + if (PANDORA_ENTERPRISE) { + $return = true; + } + } + + return $return; } + /** * Check if the license is PANDORA-FREE. - * + * * @return boolean. */ -function license_free() { - $return = true; - - $pandora_license = db_get_value ('value', 'tupdate_settings', '`key`', 'customer_key'); - if ($pandora_license !== 'PANDORA-FREE') $return = false; - - return $return; +function license_free() +{ + $return = true; + + $pandora_license = db_get_value('value', 'tupdate_settings', '`key`', 'customer_key'); + if ($pandora_license !== 'PANDORA-FREE') { + $return = false; + } + + return $return; } + /** * TODO: Document enterprise functions */ -function enterprise_hook ($function_name, $parameters = false) { - if (function_exists ($function_name)) { - if (!is_array ($parameters)) - return call_user_func ($function_name); - - return call_user_func_array ($function_name, $parameters); - } - - return ENTERPRISE_NOT_HOOK; +function enterprise_hook($function_name, $parameters=false) +{ + if (function_exists($function_name)) { + if (!is_array($parameters)) { + return call_user_func($function_name); + } + + return call_user_func_array($function_name, $parameters); + } + + return ENTERPRISE_NOT_HOOK; } + /** * TODO: Document enterprise functions */ -function enterprise_include ($filename) { - global $config; - - // Load enterprise extensions - $filepath = realpath ($config["homedir"] . '/' . ENTERPRISE_DIR . '/' . $filename); - - if ($filepath === false) - return ENTERPRISE_NOT_HOOK; - - if (strncmp ($config["homedir"], $filepath, strlen ($config["homedir"])) != 0) { - return ENTERPRISE_NOT_HOOK; - } - - if (file_exists ($filepath)) { - include ($filepath); - return true; - } - - return ENTERPRISE_NOT_HOOK; -} +function enterprise_include($filename) +{ + global $config; -function enterprise_include_once ($filename) { - global $config; - - // Load enterprise extensions - $filepath = realpath ($config["homedir"].'/'.ENTERPRISE_DIR.'/'.$filename); - - if ($filepath === false) - return ENTERPRISE_NOT_HOOK; - - if (strncmp ($config["homedir"], $filepath, strlen ($config["homedir"])) != 0) - return ENTERPRISE_NOT_HOOK; - - if (file_exists ($filepath)) { - require_once ($filepath); - return true; - } - - return ENTERPRISE_NOT_HOOK; + // Load enterprise extensions + $filepath = realpath($config['homedir'].'/'.ENTERPRISE_DIR.'/'.$filename); + + if ($filepath === false) { + return ENTERPRISE_NOT_HOOK; + } + + if (strncmp($config['homedir'], $filepath, strlen($config['homedir'])) != 0) { + return ENTERPRISE_NOT_HOOK; + } + + if (file_exists($filepath)) { + include $filepath; + return true; + } + + return ENTERPRISE_NOT_HOOK; } -//These are wrapper functions for PHP. Don't document them -if (!function_exists ("mb_strtoupper")) { - //Multibyte not loaded - use wrapper functions - //You should really load multibyte especially for foreign charsets - - /** - * @ignore - */ - function mb_strtoupper ($string, $encoding = false) { - return strtoupper ($string); - } - - /** - * @ignore - */ - function mb_strtolower ($string, $encoding = false) { - return strtoupper ($string); - } - - /** - * @ignore - */ - function mb_substr ($string, $start, $length, $encoding = false) { - return substr ($string, $start, $length); - } - - /** - * @ignore - */ - function mb_strlen ($string, $encoding = false) { - return strlen ($string); - } - - /** - * @ignore - */ - function mb_strimwidth ($string, $start, $length, $trimmarker = false, $encoding = false) { - return substr ($string, $start, $length); - } +function enterprise_include_once($filename) +{ + global $config; + + // Load enterprise extensions + $filepath = realpath($config['homedir'].'/'.ENTERPRISE_DIR.'/'.$filename); + + if ($filepath === false) { + return ENTERPRISE_NOT_HOOK; + } + + if (strncmp($config['homedir'], $filepath, strlen($config['homedir'])) != 0) { + return ENTERPRISE_NOT_HOOK; + } + + if (file_exists($filepath)) { + include_once $filepath; + return true; + } + + return ENTERPRISE_NOT_HOOK; } + +// These are wrapper functions for PHP. Don't document them +if (!function_exists('mb_strtoupper')) { + // Multibyte not loaded - use wrapper functions + // You should really load multibyte especially for foreign charsets + + + /** + * @ignore + */ + function mb_strtoupper($string, $encoding=false) + { + return strtoupper($string); + } + + + /** + * @ignore + */ + function mb_strtolower($string, $encoding=false) + { + return strtoupper($string); + } + + + /** + * @ignore + */ + function mb_substr($string, $start, $length, $encoding=false) + { + return substr($string, $start, $length); + } + + + /** + * @ignore + */ + function mb_strlen($string, $encoding=false) + { + return strlen($string); + } + + + /** + * @ignore + */ + function mb_strimwidth($string, $start, $length, $trimmarker=false, $encoding=false) + { + return substr($string, $start, $length); + } + + +} + + /** * Put quotes if magic_quotes protection * * @param string Text string to be protected with quotes if magic_quotes protection is disabled */ -function safe_sql_string($string) { - global $config; - - switch ($config["dbtype"]) { - case "mysql": - return mysql_safe_sql_string($string); - break; - case "postgresql": - return postgresql_safe_sql_string($string); - break; - case "oracle": - return oracle_safe_sql_string($string); - break; - } +function safe_sql_string($string) +{ + global $config; + + switch ($config['dbtype']) { + case 'mysql': + return mysql_safe_sql_string($string); + + break; + case 'postgresql': + return postgresql_safe_sql_string($string); + + break; + case 'oracle': + return oracle_safe_sql_string($string); + + break; + } } -function is_metaconsole() { - global $config; - return (bool) $config['metaconsole']; + +function is_metaconsole() +{ + global $config; + return (bool) $config['metaconsole']; } + /** * @brief Check if there is management operations are allowed in current context * (node // meta) * - * @return bool + * @return boolean */ -function is_management_allowed($hkey = '') { - global $config; - return ( (is_metaconsole() && $config["centralized_management"]) - || (!is_metaconsole() && !$config["centralized_management"]) - || (!is_metaconsole() && $config["centralized_management"]) && $hkey == generate_hash_to_api()); +function is_management_allowed($hkey='') +{ + global $config; + return ( (is_metaconsole() && $config['centralized_management']) + || (!is_metaconsole() && !$config['centralized_management']) + || (!is_metaconsole() && $config['centralized_management']) && $hkey == generate_hash_to_api()); } + /** * @brief Check if there is centralized management in metaconsole environment. - * Usefull to display some policy features on metaconsole. + * Usefull to display some policy features on metaconsole. * - * @return bool + * @return boolean */ -function is_central_policies() { - global $config; - return is_metaconsole() && $config["centralized_management"]; +function is_central_policies() +{ + global $config; + return is_metaconsole() && $config['centralized_management']; } + /** * @brief Check if there is centralized management in node environment. Usefull - * to reduce the policy functionallity on nodes. + * to reduce the policy functionallity on nodes. * - * @return bool + * @return boolean */ -function is_central_policies_on_node() { - global $config; - return (!is_metaconsole()) && $config["centralized_management"]; +function is_central_policies_on_node() +{ + global $config; + return (!is_metaconsole()) && $config['centralized_management']; } + /** * Checks if current execution is under an AJAX request. * * This functions checks if an 'AJAX' constant is defined * - * @return bool True if the request was done via AJAX. False otherwise + * @return boolean True if the request was done via AJAX. False otherwise */ -function is_ajax () { - return defined ('AJAX'); +function is_ajax() +{ + return defined('AJAX'); } + /** * Check if a code is an error code - * + * * @param int code of an operation. Tipically the id of a module, agent... or a code error - * - * @return bool true if a result code is an error or false otherwise + * + * @return boolean true if a result code is an error or false otherwise */ -function is_error($code) { - if ($code !== true AND ($code <= ERR_GENERIC || $code === false)) { - return true; - } - else { - return false; - } +function is_error($code) +{ + if ($code !== true and ($code <= ERR_GENERIC || $code === false)) { + return true; + } else { + return false; + } } + + /** * Transform an array of database result into an indexed array. * @@ -1442,370 +1631,393 @@ function is_error($code) { * @return array An array having the given index as fields and the given values * as value. */ -function index_array ($array, $index = 'id', $value = 'name') { - $retval = array (); - - if (! is_array ($array)) - return $retval; - - foreach ($array as $index_array => $element) { - if (!is_null($index)) { - if (! isset ($element[$index])) - continue; - } - if ($value === false) { - $retval[$element[$index]] = $element; - continue; - } - - if (! isset ($element[$value])) - continue; - - if (is_null($index)) { - $retval[$index_array] = $element[$value]; - } - else { - $retval[$element[$index]] = $element[$value]; - } - } - - return $retval; +function index_array($array, $index='id', $value='name') +{ + $retval = []; + + if (! is_array($array)) { + return $retval; + } + + foreach ($array as $index_array => $element) { + if (!is_null($index)) { + if (! isset($element[$index])) { + continue; + } + } + + if ($value === false) { + $retval[$element[$index]] = $element; + continue; + } + + if (! isset($element[$value])) { + continue; + } + + if (is_null($index)) { + $retval[$index_array] = $element[$value]; + } else { + $retval[$element[$index]] = $element[$value]; + } + } + + return $retval; } + /** * Return a graph type (string) given a module_type * * This function is useful to determine what kind of graph will be - * used, depending on the source data type, depending if it's + * used, depending on the source data type, depending if it's * numeric, boolean or a string type. * - * @param int Id of module type + * @param int Id of module type * @return string Graph type, as used in stat_win.php (Graphs launcher) */ -function return_graphtype ($id_module_type) { - switch ($id_module_type) { - case 3: - case 10: - case 17: - case 23: - return "string"; - break; - case 2: - case 6: - case 21: - case 18: - case 9: - case 31: - case 100: - return "boolean"; - break; - case 24: - return "log4x"; - break; - default: - return "sparse"; - break; - } + +function return_graphtype($id_module_type) +{ + switch ($id_module_type) { + case 3: + case 10: + case 17: + case 23: + return 'string'; + + break; + case 2: + case 6: + case 21: + case 18: + case 9: + case 31: + case 100: + return 'boolean'; + + break; + case 24: + return 'log4x'; + + break; + default: + return 'sparse'; + break; + } } + /** * Translate the key in assoc array to numeric offset. - * + * * @param array $array The array to return the offset. - * @param mixed $key The key to translate to offset. - * + * @param mixed $key The key to translate to offset. + * * @return mixed The offset or false is fail. */ -function array_key_to_offset($array, $key) { - $offset = array_search($key, array_keys($array)); - - return $offset; +function array_key_to_offset($array, $key) +{ + $offset = array_search($key, array_keys($array)); + + return $offset; } + /** * Make a snmpwalk and return it. - * - * @param string $ip_target The target address. - * @param string $snmp_version Version of the snmp: 1,2,2c or 3. - * @param string $snmp_community. - * @param string $snmp3_auth_user. - * @param string $snmp3_security_level. - * @param string $snmp3_auth_method. - * @param string $snmp3_auth_pass. - * @param string $snmp3_privacy_method. - * @param string $snmp3_privacy_pass. - * @param integer $quick_print 0 for all details, 1 for only value. - * + * + * @param string $ip_target The target address. + * @param string $snmp_version Version of the snmp: 1,2,2c or 3. + * @param string $snmp_community. + * @param string $snmp3_auth_user. + * @param string $snmp3_security_level. + * @param string $snmp3_auth_method. + * @param string $snmp3_auth_pass. + * @param string $snmp3_privacy_method. + * @param string $snmp3_privacy_pass. + * @param integer $quick_print 0 for all details, 1 for only value. + * * @return array SNMP result. */ -function get_snmpwalk($ip_target, $snmp_version, $snmp_community = '', - $snmp3_auth_user = '', $snmp3_security_level = '', - $snmp3_auth_method = '', $snmp3_auth_pass = '', - $snmp3_privacy_method = '', $snmp3_privacy_pass = '', - $quick_print = 0, $base_oid = "", $snmp_port = '', $server_to_exec = 0) { - - global $config; - - // Note: quick_print is ignored - - // Fix for snmp port - if (!empty($snmp_port)) { - $ip_target = $ip_target.':'.$snmp_port; - } - - // Escape the base OID - if ($base_oid != "") { - $base_oid = escapeshellarg ($base_oid); - } - - if (empty($config['snmpwalk'])) { - switch (PHP_OS) { - case "FreeBSD": - $snmpwalk_bin = '/usr/local/bin/snmpwalk'; - break; - case "NetBSD": - $snmpwalk_bin = '/usr/pkg/bin/snmpwalk'; - break; - default: - $snmpwalk_bin = 'snmpwalk'; - break; - } - } - else { - $snmpwalk_bin = $config['snmpwalk']; - } - - switch (PHP_OS) { - case "WIN32": - case "WINNT": - case "Windows": - $error_redir_dir = 'NUL'; - break; - default: - $error_redir_dir = '/dev/null'; - break; - } +function get_snmpwalk( + $ip_target, + $snmp_version, + $snmp_community='', + $snmp3_auth_user='', + $snmp3_security_level='', + $snmp3_auth_method='', + $snmp3_auth_pass='', + $snmp3_privacy_method='', + $snmp3_privacy_pass='', + $quick_print=0, + $base_oid='', + $snmp_port='', + $server_to_exec=0, + $extra_arguments='' +) { + global $config; - $output = array(); - $rc = 0; - switch ($snmp_version) { - case '3': - switch ($snmp3_security_level) { - case "authNoPriv": - $command_str = $snmpwalk_bin . - ' -m ALL -Oa -v 3' . - ' -u ' . escapeshellarg($snmp3_auth_user) . - ' -A ' . escapeshellarg($snmp3_auth_pass) . - ' -l ' . escapeshellarg($snmp3_security_level) . - ' -a ' . escapeshellarg($snmp3_auth_method) . - ' ' . escapeshellarg($ip_target) . - ' ' . $base_oid . - ' 2> ' . $error_redir_dir; - break; - case "noAuthNoPriv": - $command_str = $snmpwalk_bin . - ' -m ALL -Oa -v 3' . - ' -u ' . escapeshellarg($snmp3_auth_user) . - ' -l ' . escapeshellarg($snmp3_security_level) . - ' ' . escapeshellarg($ip_target) . - ' ' . $base_oid . - ' 2> ' . $error_redir_dir; - break; - default: - $command_str = $snmpwalk_bin . - ' -m ALL -Oa -v 3' . - ' -u ' . escapeshellarg($snmp3_auth_user) . - ' -A ' . escapeshellarg($snmp3_auth_pass) . - ' -l ' . escapeshellarg($snmp3_security_level) . - ' -a ' . escapeshellarg($snmp3_auth_method) . - ' -x ' . escapeshellarg($snmp3_privacy_method) . - ' -X ' . escapeshellarg($snmp3_privacy_pass) . - ' ' . escapeshellarg($ip_target) . - ' ' . $base_oid . - ' 2> ' . $error_redir_dir; - break; - } - break; - case '2': - case '2c': - case '1': - default: - $command_str = $snmpwalk_bin . ' -m ALL -Oa -v ' . escapeshellarg($snmp_version) . ' -c ' . escapeshellarg(io_safe_output($snmp_community)) . ' ' . escapeshellarg($ip_target) . ' ' . $base_oid . ' 2> ' . $error_redir_dir; - break; - } - - if (enterprise_installed()) { - if ($server_to_exec != 0) { - $server_data = db_get_row('tserver','id_server', $server_to_exec); - exec("ssh pandora_exec_proxy@" . $server_data['ip_address'] . " \"" . $command_str . "\"", $output, $rc); - } - else { - exec($command_str, $output, $rc); - } - } - else { - exec($command_str, $output, $rc); - } - - // Parse the output of snmpwalk - $snmpwalk = array(); - foreach ($output as $line) { - - // Separate the OID from the value - $full_oid = explode (' = ', $line); - if (isset ($full_oid[1])) { - $snmpwalk[$full_oid[0]] = $full_oid[1]; - } - } - - return $snmpwalk; + // Note: quick_print is ignored + // Fix for snmp port + if (!empty($snmp_port)) { + $ip_target = $ip_target.':'.$snmp_port; + } + + // Escape the base OID + if ($base_oid != '') { + $base_oid = escapeshellarg($base_oid); + } + + if (empty($config['snmpwalk'])) { + switch (PHP_OS) { + case 'FreeBSD': + $snmpwalk_bin = '/usr/local/bin/snmpwalk'; + break; + + case 'NetBSD': + $snmpwalk_bin = '/usr/pkg/bin/snmpwalk'; + break; + + default: + $snmpwalk_bin = 'snmpwalk'; + break; + } + } else { + $snmpwalk_bin = $config['snmpwalk']; + } + + switch (PHP_OS) { + case 'WIN32': + case 'WINNT': + case 'Windows': + $error_redir_dir = 'NUL'; + break; + + default: + $error_redir_dir = '/dev/null'; + break; + } + + $output = []; + $rc = 0; + switch ($snmp_version) { + case '3': + switch ($snmp3_security_level) { + case 'authNoPriv': + $command_str = $snmpwalk_bin.' -m ALL -Oa '.$extra_arguments.' -v 3'.' -u '.escapeshellarg($snmp3_auth_user).' -A '.escapeshellarg($snmp3_auth_pass).' -l '.escapeshellarg($snmp3_security_level).' -a '.escapeshellarg($snmp3_auth_method).' '.escapeshellarg($ip_target).' '.$base_oid.' 2> '.$error_redir_dir; + break; + + case 'noAuthNoPriv': + $command_str = $snmpwalk_bin.' -m ALL -Oa '.$extra_arguments.' -v 3'.' -u '.escapeshellarg($snmp3_auth_user).' -l '.escapeshellarg($snmp3_security_level).' '.escapeshellarg($ip_target).' '.$base_oid.' 2> '.$error_redir_dir; + break; + + default: + $command_str = $snmpwalk_bin.' -m ALL -Oa '.$extra_arguments.' -v 3'.' -u '.escapeshellarg($snmp3_auth_user).' -A '.escapeshellarg($snmp3_auth_pass).' -l '.escapeshellarg($snmp3_security_level).' -a '.escapeshellarg($snmp3_auth_method).' -x '.escapeshellarg($snmp3_privacy_method).' -X '.escapeshellarg($snmp3_privacy_pass).' '.escapeshellarg($ip_target).' '.$base_oid.' 2> '.$error_redir_dir; + break; + } + break; + + case '2': + case '2c': + case '1': + default: + $command_str = $snmpwalk_bin.' -m ALL '.$extra_arguments.' -Oa -v '.escapeshellarg($snmp_version).' -c '.escapeshellarg(io_safe_output($snmp_community)).' '.escapeshellarg($ip_target).' '.$base_oid.' 2> '.$error_redir_dir; + break; + } + + if (enterprise_installed()) { + if ($server_to_exec != 0) { + $server_data = db_get_row('tserver', 'id_server', $server_to_exec); + exec('ssh pandora_exec_proxy@'.$server_data['ip_address'].' "'.$command_str.'"', $output, $rc); + } else { + exec($command_str, $output, $rc); + } + } else { + exec($command_str, $output, $rc); + } + + // Parse the output of snmpwalk + $snmpwalk = []; + foreach ($output as $line) { + // Separate the OID from the value + $full_oid = explode(' = ', $line); + if (isset($full_oid[1])) { + $snmpwalk[$full_oid[0]] = $full_oid[1]; + } + } + + return $snmpwalk; } + /** * Copy from: * http://stackoverflow.com/questions/1605844/imagettfbbox-returns-wrong-dimensions-when-using-space-characters-inside-text */ -function calculateTextBox($font_size, $font_angle, $font_file, $text) { - $box = imagettfbbox($font_size, $font_angle, $font_file, $text); - - $min_x = min(array($box[0], $box[2], $box[4], $box[6])); - $max_x = max(array($box[0], $box[2], $box[4], $box[6])); - $min_y = min(array($box[1], $box[3], $box[5], $box[7])); - $max_y = max(array($box[1], $box[3], $box[5], $box[7])); - - return array( - 'left' => ($min_x >= -1) ? -abs($min_x + 1) : abs($min_x + 2), - 'top' => abs($min_y), - 'width' => $max_x - $min_x, - 'height' => $max_y - $min_y, - 'box' => $box - ); +function calculateTextBox($font_size, $font_angle, $font_file, $text) +{ + $box = imagettfbbox($font_size, $font_angle, $font_file, $text); + + $min_x = min([$box[0], $box[2], $box[4], $box[6]]); + $max_x = max([$box[0], $box[2], $box[4], $box[6]]); + $min_y = min([$box[1], $box[3], $box[5], $box[7]]); + $max_y = max([$box[1], $box[3], $box[5], $box[7]]); + + return [ + 'left' => ($min_x >= -1) ? -abs($min_x + 1) : abs($min_x + 2), + 'top' => abs($min_y), + 'width' => ($max_x - $min_x), + 'height' => ($max_y - $min_y), + 'box' => $box, + ]; } + /** * Convert a string to an image - * + * * @param string $ip_target The target address. - * + * * @return array SNMP result. */ -function string2image($string, $width, $height, $fontsize = 3, - $degrees = '0', $bgcolor = '#FFFFFF', $textcolor = '#000000', - $padding_left = 4, $padding_top = 1, $home_url = '') { - - global $config; - - $string = str_replace('#','',$string); - - //Set the size of image from the size of text - if ($width === false) { - $size = calculateTextBox($fontsize, 0, $config['fontpath'], $string); - - $fix_value = 1 * $fontsize; //Fix the imagettfbbox cut the tail of "p" character. - - $width = $size['width'] + $padding_left + $fix_value; - $height = $size['height'] + $padding_top + $fix_value; - - $padding_top = $padding_top + $fix_value; - } - - $im = ImageCreate($width,$height); - $bgrgb = html_html2rgb($bgcolor); - $bgc = ImageColorAllocate($im,$bgrgb[0],$bgrgb[1],$bgrgb[2]); - // Set the string - $textrgb = html_html2rgb($textcolor); - imagettftext ($im, $fontsize, 0, $padding_left, $height - $padding_top, - ImageColorAllocate($im,$textrgb[0],$textrgb[1],$textrgb[2]), - $config['fontpath'], $string); - //imagestring($im, $fontsize, $padding_left, $padding_top, $string, ImageColorAllocate($im,$textrgb[0],$textrgb[1],$textrgb[2])); - // Rotates the image - $rotated = imagerotate($im, $degrees, 0) ; - - //Cleaned string file name (as the slash) - $stringFile = str_replace('/', '___', $string); - - // Generate the image - $file_url = $config['attachment_store'] . '/string2image-'.$stringFile.'.gif'; - imagegif($rotated, $file_url); - imagedestroy($rotated); - - $file_url = str_replace('#','%23',$file_url); - $file_url = str_replace('%','%25',$file_url); - $file_url = str_replace($config['attachment_store'], $home_url . 'attachment', $file_url); - - return $file_url; +function string2image( + $string, + $width, + $height, + $fontsize=3, + $degrees='0', + $bgcolor='#FFFFFF', + $textcolor='#000000', + $padding_left=4, + $padding_top=1, + $home_url='' +) { + global $config; + + $string = str_replace('#', '', $string); + + // Set the size of image from the size of text + if ($width === false) { + $size = calculateTextBox($fontsize, 0, $config['fontpath'], $string); + + $fix_value = (1 * $fontsize); + // Fix the imagettfbbox cut the tail of "p" character. + $width = ($size['width'] + $padding_left + $fix_value); + $height = ($size['height'] + $padding_top + $fix_value); + + $padding_top = ($padding_top + $fix_value); + } + + $im = imagecreate($width, $height); + $bgrgb = html_html2rgb($bgcolor); + $bgc = imagecolorallocate($im, $bgrgb[0], $bgrgb[1], $bgrgb[2]); + // Set the string + $textrgb = html_html2rgb($textcolor); + imagettftext( + $im, + $fontsize, + 0, + $padding_left, + ($height - $padding_top), + imagecolorallocate($im, $textrgb[0], $textrgb[1], $textrgb[2]), + $config['fontpath'], + $string + ); + // imagestring($im, $fontsize, $padding_left, $padding_top, $string, ImageColorAllocate($im,$textrgb[0],$textrgb[1],$textrgb[2])); + // Rotates the image + $rotated = imagerotate($im, $degrees, 0); + + // Cleaned string file name (as the slash) + $stringFile = str_replace('/', '___', $string); + + // Generate the image + $file_url = $config['attachment_store'].'/string2image-'.$stringFile.'.gif'; + imagegif($rotated, $file_url); + imagedestroy($rotated); + + $file_url = str_replace('#', '%23', $file_url); + $file_url = str_replace('%', '%25', $file_url); + $file_url = str_replace($config['attachment_store'], $home_url.'attachment', $file_url); + + return $file_url; } + /** -* Function to restrict SQL on custom-user-defined queries -* -* @param string SQL code -* @return string SQL code validated (it will return empty if SQL is not ok) -**/ + * Function to restrict SQL on custom-user-defined queries + * + * @param string SQL code + * @return string SQL code validated (it will return empty if SQL is not ok) + **/ -function check_sql ($sql) { - // We remove "*" to avoid things like SELECT * FROM tusuario - - //Check that it not delete_ as "delete_pending" (this is a common field in pandora tables). - - if (preg_match("/\*|delete[^_]|drop|alter|modify|password|pass|insert|update/i", $sql)) { - return ""; - } - return $sql; + +function check_sql($sql) +{ + // We remove "*" to avoid things like SELECT * FROM tusuario + // Check that it not delete_ as "delete_pending" (this is a common field in pandora tables). + if (preg_match('/\*|delete[^_]|drop|alter|modify|password|pass|insert|update/i', $sql)) { + return ''; + } + + return $sql; } + /** * Check if login session variables are set. * * It will stop the execution if those variables were not set - * + * * @param boolean $output Set return instead the output. By default true. * - * @return bool 0 on success exit() on no success + * @return boolean 0 on success exit() on no success */ -function check_login ($output = true) { - global $config; - - if (!isset ($config["homedir"])) { - if (!$output) { - return false; - } - - // No exists $config. Exit inmediatly - include("general/noaccess.php"); - exit; - } - - if ((isset($_SESSION["id_usuario"])) AND ($_SESSION["id_usuario"] != "")) { - if (is_user ($_SESSION["id_usuario"])) { - $config['id_user'] = $_SESSION["id_usuario"]; - - return true; - } - } - else { - require_once($config["homedir"].'/mobile/include/user.class.php'); - if (isset($_SESSION['user'])) { - $user = $_SESSION['user']; - $id_user = $user->getIdUser(); - if (is_user ($id_user)) { - return true; - } - } - } - - if (!$output) { - return false; - } - - db_pandora_audit("No session", "Trying to access without a valid session", "N/A"); - include ($config["homedir"]."/general/noaccess.php"); - exit; +function check_login($output=true) +{ + global $config; + + if (!isset($config['homedir'])) { + if (!$output) { + return false; + } + + // No exists $config. Exit inmediatly + include 'general/noaccess.php'; + exit; + } + + if ((isset($_SESSION['id_usuario'])) and ($_SESSION['id_usuario'] != '')) { + if (is_user($_SESSION['id_usuario'])) { + $config['id_user'] = $_SESSION['id_usuario']; + + return true; + } + } else { + include_once $config['homedir'].'/mobile/include/user.class.php'; + + if (isset($_SESSION['user'])) { + $user = $_SESSION['user']; + $id_user = $user->getIdUser(); + if (is_user($id_user)) { + return true; + } + } + } + + if (!$output) { + return false; + } + + db_pandora_audit('No session', 'Trying to access without a valid session', 'N/A'); + include $config['homedir'].'/general/noaccess.php'; + exit; } + /** * Check access privileges to resources * @@ -1821,65 +2033,69 @@ function check_login ($output = true) { * LM - Alert Management * PM - Pandora Management * - * @param int $id_user User id - * @param int $id_group Agents group id to check from - * @param string $access Access privilege - * @param bool $onlyOneGroup Flag to check acl for specified group only (not to roots up, or check acl for 'All' group when $id_group is 0). + * @param integer $id_user User id + * @param integer $id_group Agents group id to check from + * @param string $access Access privilege + * @param boolean $onlyOneGroup Flag to check acl for specified group only (not to roots up, or check acl for 'All' group when $id_group is 0). * - * @return bool 1 if the user has privileges, 0 if not. + * @return boolean 1 if the user has privileges, 0 if not. */ -function check_acl($id_user, $id_group, $access, $onlyOneGroup = false) { - if (empty ($id_user)) { - //User ID needs to be specified - trigger_error ("Security error: check_acl got an empty string for user id", E_USER_WARNING); - return 0; - } - elseif (is_user_admin ($id_user)) { - return 1; - } - else { - $id_group = (int) $id_group; - } +function check_acl($id_user, $id_group, $access, $onlyOneGroup=false) +{ + if (empty($id_user)) { + // User ID needs to be specified + trigger_error('Security error: check_acl got an empty string for user id', E_USER_WARNING); + return 0; + } else if (is_user_admin($id_user)) { + return 1; + } else { + $id_group = (int) $id_group; + } - if ($id_group != 0 || $onlyOneGroup === true) { - $groups_list_acl = users_get_groups ($id_user, $access, false, true, null); - } - else{ - $groups_list_acl = get_users_acl($id_user); - } + if ($id_group != 0 || $onlyOneGroup === true) { + $groups_list_acl = users_get_groups($id_user, $access, false, true, null); + } else { + $groups_list_acl = get_users_acl($id_user); + } - if(is_array($groups_list_acl)){ - if(isset($groups_list_acl[$id_group])){ - $access = get_acl_column($access); - if(isset($groups_list_acl[$id_group][$access]) - && $groups_list_acl[$id_group][$access] > 0){ - return 1; - } - else{ - return 0; - } - } - } + if (is_array($groups_list_acl)) { + if (isset($groups_list_acl[$id_group])) { + $access = get_acl_column($access); + if (isset($groups_list_acl[$id_group][$access]) + && $groups_list_acl[$id_group][$access] > 0 + ) { + return 1; + } else { + return 0; + } + } + } - return 0; + return 0; } + /** * Check the ACL of a list of groups. * * @param string $id_user to check the ACL - * @param Array $groups. All groups to check + * @param array $groups. All groups to check * @param string $access. Profile to check * - * @return bool True if at least one of this groups check the ACL + * @return boolean True if at least one of this groups check the ACL */ -function check_acl_one_of_groups($id_user, $groups, $access) { - foreach ($groups as $group) { - if (check_acl($id_user, $group, $access)) return true; - } - return false; +function check_acl_one_of_groups($id_user, $groups, $access) +{ + foreach ($groups as $group) { + if (check_acl($id_user, $group, $access)) { + return true; + } + } + + return false; } + /** * Get the name of the database column of one access flag * @@ -1887,92 +2103,117 @@ function check_acl_one_of_groups($id_user, $groups, $access) { * * @return string Column name */ -function get_acl_column($access) { - switch ($access) { - case "IR": - return "incident_view"; - break; - case "IW": - return "incident_edit"; - break; - case "IM": - return "incident_management"; - break; - case "AR": - return "agent_view"; - break; - case "AW": - return "agent_edit"; - break; - case "AD": - return "agent_disable"; - break; - case "LW": - return "alert_edit"; - break; - case "LM": - return "alert_management"; - break; - case "PM": - return "pandora_management"; - break; - case "DM": - return "db_management"; - break; - case "UM": - return "user_management"; - break; - case "RR": - return "report_view"; - break; - case "RW": - return "report_edit"; - break; - case "RM": - return "report_management"; - break; - case "ER": - return "event_view"; - break; - case "EW": - return "event_edit"; - break; - case "EM": - return "event_management"; - break; - case "MR": - return "map_view"; - break; - case "MW": - return "map_edit"; - break; - case "MM": - return "map_management"; - break; - case "VR": - return "vconsole_view"; - break; - case "VW": - return "vconsole_edit"; - break; - case "VM": - return "vconsole_management"; - break; - default: - return ""; - break; - } +function get_acl_column($access) +{ + switch ($access) { + case 'IR': + return 'incident_view'; + + break; + case 'IW': + return 'incident_edit'; + + break; + case 'IM': + return 'incident_management'; + + break; + case 'AR': + return 'agent_view'; + + break; + case 'AW': + return 'agent_edit'; + + break; + case 'AD': + return 'agent_disable'; + + break; + case 'LW': + return 'alert_edit'; + + break; + case 'LM': + return 'alert_management'; + + break; + case 'PM': + return 'pandora_management'; + + break; + case 'DM': + return 'db_management'; + + break; + case 'UM': + return 'user_management'; + + break; + case 'RR': + return 'report_view'; + + break; + case 'RW': + return 'report_edit'; + + break; + case 'RM': + return 'report_management'; + + break; + case 'ER': + return 'event_view'; + + break; + case 'EW': + return 'event_edit'; + + break; + case 'EM': + return 'event_management'; + + break; + case 'MR': + return 'map_view'; + + break; + case 'MW': + return 'map_edit'; + + break; + case 'MM': + return 'map_management'; + + break; + case 'VR': + return 'vconsole_view'; + + break; + case 'VW': + return 'vconsole_edit'; + + break; + case 'VM': + return 'vconsole_management'; + + break; + default: + return ''; + break; + } } -function get_users_acl($id_user){ - static $users_acl_cache = array(); +function get_users_acl($id_user) +{ + static $users_acl_cache = []; - if (is_array($users_acl_cache[$id_user])) { - $rowdup = $users_acl_cache[$id_user]; - } - else { - $query = sprintf("SELECT sum(tperfil.incident_view) as incident_view, + if (is_array($users_acl_cache[$id_user])) { + $rowdup = $users_acl_cache[$id_user]; + } else { + $query = sprintf( + "SELECT sum(tperfil.incident_view) as incident_view, sum(tperfil.incident_edit) as incident_edit, sum(tperfil.incident_management) as incident_management, sum(tperfil.agent_view) as agent_view, @@ -1997,18 +2238,22 @@ function get_users_acl($id_user){ sum(tperfil.vconsole_management) as vconsole_management FROM tusuario_perfil, tperfil WHERE tusuario_perfil.id_perfil = tperfil.id_perfil - AND tusuario_perfil.id_usuario = '%s'", $id_user); - - $rowdup = db_get_all_rows_sql ($query); - $users_acl_cache[$id_user] = $rowdup; - } + AND tusuario_perfil.id_usuario = '%s'", + $id_user + ); - if (empty ($rowdup) || !$rowdup) - return 0; - - return $rowdup; + $rowdup = db_get_all_rows_sql($query); + $users_acl_cache[$id_user] = $rowdup; + } + + if (empty($rowdup) || !$rowdup) { + return 0; + } + + return $rowdup; } + /** * Get the name of a plugin * @@ -2016,10 +2261,12 @@ function get_users_acl($id_user){ * * @return string The name of the given plugin */ -function dame_nombre_pluginid ($id_plugin) { - return (string) db_get_value ('name', 'tplugin', 'id', (int) $id_plugin); +function dame_nombre_pluginid($id_plugin) +{ + return (string) db_get_value('name', 'tplugin', 'id', (int) $id_plugin); } + /** * Get the operating system id. * @@ -2027,10 +2274,12 @@ function dame_nombre_pluginid ($id_plugin) { * * @return id Id of the given operating system. */ -function get_os_id ($os_name) { - return (string) db_get_value ('id_os', 'tconfig_os', 'name', $os_name); +function get_os_id($os_name) +{ + return (string) db_get_value('id_os', 'tconfig_os', 'name', $os_name); } + /** * Get the operating system name. * @@ -2038,10 +2287,12 @@ function get_os_id ($os_name) { * * @return string Name of the given operating system. */ -function get_os_name ($id_os) { - return (string) db_get_value ('name', 'tconfig_os', 'id_os', (int) $id_os); +function get_os_name($id_os) +{ + return (string) db_get_value('name', 'tconfig_os', 'id_os', (int) $id_os); } + /** * Get user's dashboards * @@ -2049,325 +2300,376 @@ function get_os_name ($id_os) { * * @return array Dashboard name of the given user. */ -function get_user_dashboards ($id_user) { - if (users_is_admin($id_user)) { - $sql = "SELECT name - FROM tdashboard WHERE id_user = '" . $id_user ."' OR id_user = ''"; - } - else { - $user_can_manage_all = users_can_manage_group_all('RR'); - if ($user_can_manage_all) { - $sql = "SELECT name - FROM tdashboard WHERE id_user = '" . $id_user ."' OR id_user = ''"; - } - else { - $user_groups = users_get_groups($id_user, "RR", false); - if (empty($user_groups)) { - return false; - } +function get_user_dashboards($id_user) +{ + if (users_is_admin($id_user)) { + $sql = "SELECT name + FROM tdashboard WHERE id_user = '".$id_user."' OR id_user = ''"; + } else { + $user_can_manage_all = users_can_manage_group_all('RR'); + if ($user_can_manage_all) { + $sql = "SELECT name + FROM tdashboard WHERE id_user = '".$id_user."' OR id_user = ''"; + } else { + $user_groups = users_get_groups($id_user, 'RR', false); + if (empty($user_groups)) { + return false; + } - $u_groups = array(); - foreach ($user_groups as $id => $group_name) { - $u_groups[] = $id; - } + $u_groups = []; + foreach ($user_groups as $id => $group_name) { + $u_groups[] = $id; + } - $sql = "SELECT name + $sql = 'SELECT name FROM tdashboard - WHERE id_group IN (" . implode(",", $u_groups) . ") AND (id_user = '" . $id_user ."' OR id_user = '')"; - } - } - - return db_get_all_rows_sql ($sql); + WHERE id_group IN ('.implode(',', $u_groups).") AND (id_user = '".$id_user."' OR id_user = '')"; + } + } + + return db_get_all_rows_sql($sql); } + /** * Get all the possible periods in seconds. * * @param bool Flag to show or not custom fist option * @param bool Show the periods by default if it is empty - * + * * @return The possible periods in an associative array. */ -function get_periods ($custom = true, $show_default = true) { - global $config; - - - $periods = array (); - - if ($custom) { - $periods[-1] = __('custom'); - } - - if (empty($config['interval_values'])) { - if ($show_default) { - $periods[SECONDS_5MINUTES] = sprintf(__('%s minutes'), '5'); - $periods[SECONDS_30MINUTES] = sprintf(__('%s minutes'), '30 '); - $periods[SECONDS_1HOUR] = __('1 hour'); - $periods[SECONDS_6HOURS] = sprintf(__('%s hours'), '6 '); - $periods[SECONDS_12HOURS] = sprintf(__('%s hours'), '12 '); - $periods[SECONDS_1DAY] = __('1 day'); - $periods[SECONDS_1WEEK] = __('1 week'); - $periods[SECONDS_15DAYS] = __('15 days'); - $periods[SECONDS_1MONTH] = __('1 month'); - $periods[SECONDS_3MONTHS] = sprintf(__('%s months'), '3 '); - $periods[SECONDS_6MONTHS] = sprintf(__('%s months'), '6 '); - $periods[SECONDS_1YEAR] = __('1 year'); - $periods[SECONDS_2YEARS] = sprintf(__('%s years'), '2 '); - $periods[SECONDS_3YEARS] = sprintf(__('%s years'), '3 '); - } - else { - $periods[-1] = __('Empty').': '.__('Default values will be used'); - } - } - else { - $values = explode(',',$config['interval_values']); - foreach($values as $v) { - $periods[$v] = human_time_description_raw ($v, true); - } - } - - return $periods; +function get_periods($custom=true, $show_default=true) +{ + global $config; + + $periods = []; + + if ($custom) { + $periods[-1] = __('custom'); + } + + if (empty($config['interval_values'])) { + if ($show_default) { + $periods[SECONDS_5MINUTES] = sprintf(__('%s minutes'), '5'); + $periods[SECONDS_30MINUTES] = sprintf(__('%s minutes'), '30 '); + $periods[SECONDS_1HOUR] = __('1 hour'); + $periods[SECONDS_6HOURS] = sprintf(__('%s hours'), '6 '); + $periods[SECONDS_12HOURS] = sprintf(__('%s hours'), '12 '); + $periods[SECONDS_1DAY] = __('1 day'); + $periods[SECONDS_1WEEK] = __('1 week'); + $periods[SECONDS_15DAYS] = __('15 days'); + $periods[SECONDS_1MONTH] = __('1 month'); + $periods[SECONDS_3MONTHS] = sprintf(__('%s months'), '3 '); + $periods[SECONDS_6MONTHS] = sprintf(__('%s months'), '6 '); + $periods[SECONDS_1YEAR] = __('1 year'); + $periods[SECONDS_2YEARS] = sprintf(__('%s years'), '2 '); + $periods[SECONDS_3YEARS] = sprintf(__('%s years'), '3 '); + } else { + $periods[-1] = __('Empty').': '.__('Default values will be used'); + } + } else { + $values = explode(',', $config['interval_values']); + foreach ($values as $v) { + $periods[$v] = human_time_description_raw($v, true); + } + } + + return $periods; } /** * Recursive copy directory */ -function copy_dir($src, $dst) { - $dir = opendir($src); - $return = true; - - if (!$dir) - return false; - - @mkdir($dst); - while (false !== ( $file = readdir($dir)) ) { - if (( $file != '.' ) && ( $file != '..' )) { - if ( is_dir($src . '/' . $file) ) { - $return = copy_dir($src . '/' . $file, $dst . '/' . $file); - - if (!$return) { - break; - } - } - else { - $r = copy($src . '/' . $file, $dst . '/' . $file); - } - } - } - - closedir($dir); - - return $return; +function copy_dir($src, $dst) +{ + $dir = opendir($src); + $return = true; + + if (!$dir) { + return false; + } + + @mkdir($dst); + while (false !== ( $file = readdir($dir))) { + if (( $file != '.' ) && ( $file != '..' )) { + if (is_dir($src.'/'.$file)) { + $return = copy_dir($src.'/'.$file, $dst.'/'.$file); + + if (!$return) { + break; + } + } else { + $r = copy($src.'/'.$file, $dst.'/'.$file); + } + } + } + + closedir($dir); + + return $return; } -function delete_dir($dir) { - if (!file_exists($dir)) - return true; - - if (!is_dir($dir)) - return unlink($dir); - - foreach (scandir($dir) as $item) { - if ($item == '.' || $item == '..') - continue; - - if (!delete_dir($dir . "/" . $item)) - return false; - } - - return rmdir($dir); + +function delete_dir($dir) +{ + if (!file_exists($dir)) { + return true; + } + + if (!is_dir($dir)) { + return unlink($dir); + } + + foreach (scandir($dir) as $item) { + if ($item == '.' || $item == '..') { + continue; + } + + if (!delete_dir($dir.'/'.$item)) { + return false; + } + } + + return rmdir($dir); } + /** * Returns 1 if the data contains a codified image (base64) */ -function is_image_data ($data) { - return (substr($data,0,10) == "data:image"); +function is_image_data($data) +{ + return (substr($data, 0, 10) == 'data:image'); } + /** -* Returns 1 if this is Snapshot data, 0 otherwise -* Looks for two or more carriage returns. -*/ -function is_snapshot_data ($data) { - return is_image_data($data); + * Returns 1 if this is Snapshot data, 0 otherwise + * Looks for two or more carriage returns. + */ +function is_snapshot_data($data) +{ + return is_image_data($data); } + /** * Check if text is too long to put it into a black screen * - * @param string Data value - * @return bool True if black window should be displayed + * @param string Data value + * @return boolean True if black window should be displayed */ -function is_text_to_black_string ($data) { - if (is_image_data($data)) return false; - // Consider large text if data is greater than 200 characters - return ((int)strlen($data)) > 200; +function is_text_to_black_string($data) +{ + if (is_image_data($data)) { + return false; + } + + // Consider large text if data is greater than 200 characters + return ((int) strlen($data)) > 200; } + /** -* Create an invisible div with a provided ID and value to -* can retrieve it from javascript with function get_php_value(name) -*/ -function set_js_value($name, $value) { - html_print_div(array('id' => 'php_to_js_value_' . $name, - 'content' => json_encode($value), 'hidden' => true)); + * Create an invisible div with a provided ID and value to + * can retrieve it from javascript with function get_php_value(name) + */ +function set_js_value($name, $value) +{ + html_print_div( + [ + 'id' => 'php_to_js_value_'.$name, + 'content' => json_encode($value), + 'hidden' => true, + ] + ); } function is_array_empty($InputVariable) { - $Result = true; - - if (is_array($InputVariable) && count($InputVariable) > 0) { - foreach ($InputVariable as $Value) { - $Result = $Result && is_array_empty($Value); - } - } - else { - $Result = empty($InputVariable); - } - - return $Result; + $Result = true; + + if (is_array($InputVariable) && count($InputVariable) > 0) { + foreach ($InputVariable as $Value) { + $Result = $Result && is_array_empty($Value); + } + } else { + $Result = empty($InputVariable); + } + + return $Result; } -// This function is used to give or not access to nodes in -// Metaconsole. Sometimes is used in common code between + +// This function is used to give or not access to nodes in +// Metaconsole. Sometimes is used in common code between // Meta and normal console, so if Meta is not activated, it // will return 1 always - // Return 0 if the user hasnt access to node/detail 1 otherwise -function can_user_access_node () { - global $config; - - $userinfo = get_user_info ($config['id_user']); - - if (defined('METACONSOLE')) { - return $userinfo["is_admin"] == 1 ? 1 : - $userinfo["metaconsole_access_node"]; - } - else { - return 1; - } +function can_user_access_node() +{ + global $config; + + $userinfo = get_user_info($config['id_user']); + + if (defined('METACONSOLE')) { + return $userinfo['is_admin'] == 1 ? 1 : $userinfo['metaconsole_access_node']; + } else { + return 1; + } } + /** * Get the upload status code */ -function get_file_upload_status ($file_input_name) { - if (!isset($_FILES[$file_input_name])) - return -1; +function get_file_upload_status($file_input_name) +{ + if (!isset($_FILES[$file_input_name])) { + return -1; + } - return $_FILES[$file_input_name]['error']; + return $_FILES[$file_input_name]['error']; } + /** * Get a human readable message with the upload status code */ -function translate_file_upload_status ($status_code) { - switch ($status_code) { - case UPLOAD_ERR_OK: - $message = true; - break; - case UPLOAD_ERR_INI_SIZE: - $message = __('The file exceeds the maximum size'); - break; - case UPLOAD_ERR_FORM_SIZE: - $message = __('The file exceeds the maximum size'); - break; - case UPLOAD_ERR_PARTIAL: - $message = __('The uploaded file was only partially uploaded'); - break; - case UPLOAD_ERR_NO_FILE: - $message = __('No file was uploaded'); - break; - case UPLOAD_ERR_NO_TMP_DIR: - $message = __('Missing a temporary folder'); - break; - case UPLOAD_ERR_CANT_WRITE: - $message = __('Failed to write file to disk'); - break; - case UPLOAD_ERR_EXTENSION: - $message = __('File upload stopped by extension'); - break; - - default: - $message = __('Unknown upload error'); - break; - } - - return $message; +function translate_file_upload_status($status_code) +{ + switch ($status_code) { + case UPLOAD_ERR_OK: + $message = true; + break; + + case UPLOAD_ERR_INI_SIZE: + $message = __('The file exceeds the maximum size'); + break; + + case UPLOAD_ERR_FORM_SIZE: + $message = __('The file exceeds the maximum size'); + break; + + case UPLOAD_ERR_PARTIAL: + $message = __('The uploaded file was only partially uploaded'); + break; + + case UPLOAD_ERR_NO_FILE: + $message = __('No file was uploaded'); + break; + + case UPLOAD_ERR_NO_TMP_DIR: + $message = __('Missing a temporary folder'); + break; + + case UPLOAD_ERR_CANT_WRITE: + $message = __('Failed to write file to disk'); + break; + + case UPLOAD_ERR_EXTENSION: + $message = __('File upload stopped by extension'); + break; + + default: + $message = __('Unknown upload error'); + break; + } + + return $message; } + /** * Get the arguments given in a function returning default value if not defined - * @param string name of the argument - * @param mixed array with arguments - * @param string defualt value for this argument - * - * @return string value for the argument + * + * @param string name of the argument + * @param mixed array with arguments + * @param string defualt value for this argument + * + * @return string value for the argument */ -function get_argument ($argument, $arguments, $default) { - if (isset($arguments[$argument])) { - return $arguments[$argument]; - } - else { - return $default; - } +function get_argument($argument, $arguments, $default) +{ + if (isset($arguments[$argument])) { + return $arguments[$argument]; + } else { + return $default; + } } + /** * Get the arguments given in a function returning default value if not defined - * @param mixed arguments - * - id_user: user who can see the news - * - modal: true if want to get modal news. false to return not modal news - * - limit: number of max news returned - * @return mixed list of news + * + * @param mixed arguments + * - id_user: user who can see the news + * - modal: true if want to get modal news. false to return not modal news + * - limit: number of max news returned + * @return mixed list of news */ -function get_news($arguments) { - global $config; - - $id_user = get_argument ('id_user', $arguments, $config['id_user']); - $modal = get_argument ('modal', $arguments, false); - $limit = get_argument ('limit', $arguments, 99999999); - - $id_group = array_keys(users_get_groups($id_user, false, true)); +function get_news($arguments) +{ + global $config; - // Empty groups - if (empty($id_group)) return array(); + $id_user = get_argument('id_user', $arguments, $config['id_user']); + $modal = get_argument('modal', $arguments, false); + $limit = get_argument('limit', $arguments, 99999999); - $id_group = implode(',',$id_group); - $current_datetime = date('Y-m-d H:i:s', time()); - $modal = (int) $modal; - - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $sql = sprintf("SELECT subject,timestamp,text,author + $id_group = array_keys(users_get_groups($id_user, false, true)); + + // Empty groups + if (empty($id_group)) { + return []; + } + + $id_group = implode(',', $id_group); + $current_datetime = date('Y-m-d H:i:s', time()); + $modal = (int) $modal; + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $sql = sprintf( + "SELECT subject,timestamp,text,author FROM tnews WHERE id_group IN (%s) AND modal = %s AND (expire = 0 OR (expire = 1 AND expire_timestamp > '%s')) ORDER BY timestamp DESC - LIMIT %s", $id_group, $modal, $current_datetime, $limit); - break; - case "oracle": - $sql = sprintf("SELECT subject,timestamp,text,author + LIMIT %s", + $id_group, + $modal, + $current_datetime, + $limit + ); + break; + + case 'oracle': + $sql = sprintf( + "SELECT subject,timestamp,text,author FROM tnews WHERE rownum <= %s AND id_group IN (%s) AND modal = %s AND (expire = 0 OR (expire = 1 AND expire_timestamp > '%s')) - ORDER BY timestamp DESC", $limit, $id_group, $modal, $current_datetime); - break; - } - - $news = db_get_all_rows_sql ($sql); - - if (empty($news)) { - $news = array(); - } - - return $news; + ORDER BY timestamp DESC", + $limit, + $id_group, + $modal, + $current_datetime + ); + break; + } + + $news = db_get_all_rows_sql($sql); + + if (empty($news)) { + $news = []; + } + + return $news; } @@ -2375,84 +2677,77 @@ function get_news($arguments) { * Print audit data in CSV format. * * @param array Audit data. - * */ -function print_audit_csv ($data) { - global $config; - global $graphic_type; +function print_audit_csv($data) +{ + global $config; + global $graphic_type; - if (!$data) { - echo __('No data found to export'); - return 0; - } + if (!$data) { + echo __('No data found to export'); + return 0; + } - $config['ignore_callback'] = true; - while (@ob_end_clean ()); - - header("Content-type: application/octet-stream"); - header("Content-Disposition: attachment; filename=audit_log".date("Y-m-d_His").".csv"); - header("Pragma: no-cache"); - header("Expires: 0"); + $config['ignore_callback'] = true; + while (@ob_end_clean()) { + } - // BOM - print pack('C*',0xEF,0xBB,0xBF); - - echo __('User') . ';' . - __('Action') . ';' . - __('Date') . ';' . - __('Source IP') . ';' . - __('Comments') ."\n"; - foreach ($data as $line) { - echo io_safe_output($line['id_usuario']) . ';' - . io_safe_output($line['accion']) . ';' - . date($config["date_format"], $line['utimestamp']) . ';' - . $line['ip_origen'] . ';' - . io_safe_output($line['descripcion']). "\n"; - } + header('Content-type: application/octet-stream'); + header('Content-Disposition: attachment; filename=audit_log'.date('Y-m-d_His').'.csv'); + header('Pragma: no-cache'); + header('Expires: 0'); - exit; + // BOM + print pack('C*', 0xEF, 0xBB, 0xBF); + + echo __('User').';'.__('Action').';'.__('Date').';'.__('Source IP').';'.__('Comments')."\n"; + foreach ($data as $line) { + echo io_safe_output($line['id_usuario']).';'.io_safe_output($line['accion']).';'.date($config['date_format'], $line['utimestamp']).';'.$line['ip_origen'].';'.io_safe_output($line['descripcion'])."\n"; + } + + exit; } + /** * Validate the code given to surpass the 2 step authentication * * @param string User name * @param string Code given by the authenticator app * - * @return -1 if the parameters introduced are incorrect, - * there is a problem accessing the user secret or - * if an exception are launched. - * true if the code is valid. - * false if the code is invalid. + * @return -1 if the parameters introduced are incorrect, + * there is a problem accessing the user secret or + * if an exception are launched. + * true if the code is valid. + * false if the code is invalid. */ -function validate_double_auth_code ($user, $code) { - global $config; - require_once ($config['homedir'].'/include/auth/GAuth/Auth.php'); - $result = false; - - if (empty($user) || empty($code)) { - $result = -1; - } - else { - $secret = db_get_value('secret', 'tuser_double_auth', 'id_user', $user); - - if ($secret === false) { - $result = -1; - } - else if (!empty($secret)) { - try { - $gAuth = new \GAuth\Auth($secret); - $result = $gAuth->validateCode($code); - } - catch (Exception $e) { - $result = -1; - } - } - } - - return $result; +function validate_double_auth_code($user, $code) +{ + global $config; + include_once $config['homedir'].'/include/auth/GAuth/Auth.php'; + $result = false; + + if (empty($user) || empty($code)) { + $result = -1; + } else { + $secret = db_get_value('secret', 'tuser_double_auth', 'id_user', $user); + + if ($secret === false) { + $result = -1; + } else if (!empty($secret)) { + try { + $gAuth = new \GAuth\Auth($secret); + $result = $gAuth->validateCode($code); + } catch (Exception $e) { + $result = -1; + } + } + } + + return $result; } + /** * Get if the 2 step authentication is enabled for the user given * @@ -2460,135 +2755,162 @@ function validate_double_auth_code ($user, $code) { * * @return true if the user has the double auth enabled or false otherwise. */ -function is_double_auth_enabled ($user) { - $result = (bool) db_get_value('id', 'tuser_double_auth', 'id_user', $user); - - return $result; +function is_double_auth_enabled($user) +{ + $result = (bool) db_get_value('id', 'tuser_double_auth', 'id_user', $user); + + return $result; } -function clear_pandora_error_for_header() { - global $config; - $config["alert_cnt"] = 0; - $_SESSION["alert_msg"] = array(); +function clear_pandora_error_for_header() +{ + global $config; + + $config['alert_cnt'] = 0; + $_SESSION['alert_msg'] = []; } -function set_pandora_error_for_header($message, $title = null) { - global $config; - if (!isset($config['alert_cnt'])) - $config['alert_cnt'] = 0; +function set_pandora_error_for_header($message, $title=null) +{ + global $config; - if ( ( !isset($_SESSION['alert_msg']) && (!is_array($_SESSION['alert_msg'])) ) ) - $_SESSION['alert_msg'] = array(); + if (!isset($config['alert_cnt'])) { + $config['alert_cnt'] = 0; + } - $message_config = array(); - if (isset($title)) - $message_config['title'] = $title; - $message_config['message'] = $message; - $message_config['no_close'] = true; + if (( !isset($_SESSION['alert_msg']) && (!is_array($_SESSION['alert_msg'])) )) { + $_SESSION['alert_msg'] = []; + } - $config['alert_cnt']++; - $_SESSION['alert_msg'][] = array('type' => 'error', 'message' => $message_config); + $message_config = []; + if (isset($title)) { + $message_config['title'] = $title; + } + + $message_config['message'] = $message; + $message_config['no_close'] = true; + + $config['alert_cnt']++; + $_SESSION['alert_msg'][] = [ + 'type' => 'error', + 'message' => $message_config, + ]; } -function get_pandora_error_for_header() { - $result = ''; - - if (isset($_SESSION['alert_msg']) && is_array($_SESSION['alert_msg'])) { - foreach ($_SESSION['alert_msg'] as $key => $value) { - if (!isset($value['type']) || !isset($value['message'])) - continue; - - switch ($value['type']) { - case 'error': - $result .= ui_print_error_message($value['message'], '', true); - break; - case 'info': - $result .= ui_print_info_message($value['message'], '', true); - break; - default: - break; - } - } - } - - return $result; + +function get_pandora_error_for_header() +{ + $result = ''; + + if (isset($_SESSION['alert_msg']) && is_array($_SESSION['alert_msg'])) { + foreach ($_SESSION['alert_msg'] as $key => $value) { + if (!isset($value['type']) || !isset($value['message'])) { + continue; + } + + switch ($value['type']) { + case 'error': + $result .= ui_print_error_message($value['message'], '', true); + break; + + case 'info': + $result .= ui_print_info_message($value['message'], '', true); + break; + + default: + break; + } + } + } + + return $result; } -function set_if_defined (&$var, $test) { - if (isset($test)) { - $var = $test; - - return true; - } - else { - return false; - } + +function set_if_defined(&$var, $test) +{ + if (isset($test)) { + $var = $test; + + return true; + } else { + return false; + } } -function set_unless_defined (&$var, $default) { - if (! isset($var)) { - $var = $default; - - return true; - } - else { - return false; - } + +function set_unless_defined(&$var, $default) +{ + if (! isset($var)) { + $var = $default; + + return true; + } else { + return false; + } } -function set_when_empty (&$var, $default) { - if (empty($var)) { - $var = $default; - - return true; - } - else { - return false; - } + +function set_when_empty(&$var, $default) +{ + if (empty($var)) { + $var = $default; + + return true; + } else { + return false; + } } -function sort_by_column (&$array_ref, $column) { - if (!empty($column)) { - usort($array_ref, function ($a, $b) use ($column) { - return strcmp($a[$column], $b[$column]); - }); - } + +function sort_by_column(&$array_ref, $column) +{ + if (!empty($column)) { + usort( + $array_ref, + function ($a, $b) use ($column) { + return strcmp($a[$column], $b[$column]); + } + ); + } } -function array2XML($data, $root = null, $xml = NULL) { - if ($xml == null) { - $xml = simplexml_load_string( - "\n<" . $root . " />"); - } - - foreach($data as $key => $value) { - if (is_numeric($key)) { - $key = "item_" . $key; - } - - if (is_array($value)) { - $node = $xml->addChild($key); - array2XML($value, $root, $node); - } - else { - $value = htmlentities($value); - - if (!is_numeric($value) && !is_bool($value)) { - if (!empty($value)) { - $xml->addChild($key, $value); - } - } - else { - $xml->addChild($key, $value); - } - } - } - - return $xml->asXML(); + +function array2XML($data, $root=null, $xml=null) +{ + if ($xml == null) { + $xml = simplexml_load_string( + "\n<".$root.' />' + ); + } + + foreach ($data as $key => $value) { + if (is_numeric($key)) { + $key = 'item_'.$key; + } + + if (is_array($value)) { + $node = $xml->addChild($key); + array2XML($value, $root, $node); + } else { + $value = htmlentities($value); + + if (!is_numeric($value) && !is_bool($value)) { + if (!empty($value)) { + $xml->addChild($key, $value); + } + } else { + $xml->addChild($key, $value); + } + } + } + + return $xml->asXML(); } + /** * Returns an array by extracting a column or columns. * @@ -2597,290 +2919,335 @@ function array2XML($data, $root = null, $xml = NULL) { * * @return array Array formed by the extracted columns of every array iteration. */ -function extract_column ($array, $column) { - $column_is_arr = is_array($column); - - return array_map(function($item) use ($column_is_arr, $column) { - if ($column_is_arr) { - return array_reduce($column, function($carry, $col) use ($item) { - $carry[$col] = $item[$col]; - return $item[$col]; - }, array()); - } - else { - return $item[$column]; - } - }, $array); +function extract_column($array, $column) +{ + $column_is_arr = is_array($column); + + return array_map( + function ($item) use ($column_is_arr, $column) { + if ($column_is_arr) { + return array_reduce( + $column, + function ($carry, $col) use ($item) { + $carry[$col] = $item[$col]; + return $item[$col]; + }, + [] + ); + } else { + return $item[$column]; + } + }, + $array + ); } -function get_percentile($percentile, $array) { - sort($array); - $index = ($percentile / 100) * count($array); - - if (floor($index) == $index) { - $result = ($array[$index-1] + $array[$index]) / 2; - } - else { - $result = $array[floor($index)]; - } - - return $result; +function get_percentile($percentile, $array) +{ + sort($array); + $index = (($percentile / 100) * count($array)); + + if (floor($index) == $index) { + $result = (($array[($index - 1)] + $array[$index]) / 2); + } else { + $result = $array[floor($index)]; + } + + return $result; } + if (!function_exists('hex2bin')) { - function hex2bin($data) { - static $old; - if ($old === null) { - $old = version_compare(PHP_VERSION, '5.2', '<'); - } - $isobj = false; - if (is_scalar($data) || (($isobj = is_object($data)) && method_exists($data, '__toString'))) { - if ($isobj && $old) { - ob_start(); - echo $data; - $data = ob_get_clean(); - } - else { - $data = (string) $data; - } - } - else { - trigger_error(__FUNCTION__.'() expects parameter 1 to be string, ' . gettype($data) . ' given', E_USER_WARNING); - return;//null in this case - } - $len = strlen($data); - if ($len % 2) { - trigger_error(__FUNCTION__.'(): Hexadecimal input string must have an even length', E_USER_WARNING); - return false; - } - if (strspn($data, '0123456789abcdefABCDEF') != $len) { - trigger_error(__FUNCTION__.'(): Input string must be hexadecimal string', E_USER_WARNING); - return false; - } - return pack('H*', $data); - } + + + function hex2bin($data) + { + static $old; + if ($old === null) { + $old = version_compare(PHP_VERSION, '5.2', '<'); + } + + $isobj = false; + if (is_scalar($data) || (($isobj = is_object($data)) && method_exists($data, '__toString'))) { + if ($isobj && $old) { + ob_start(); + echo $data; + $data = ob_get_clean(); + } else { + $data = (string) $data; + } + } else { + trigger_error(__FUNCTION__.'() expects parameter 1 to be string, '.gettype($data).' given', E_USER_WARNING); + return; + // null in this case + } + + $len = strlen($data); + if (($len % 2)) { + trigger_error(__FUNCTION__.'(): Hexadecimal input string must have an even length', E_USER_WARNING); + return false; + } + + if (strspn($data, '0123456789abcdefABCDEF') != $len) { + trigger_error(__FUNCTION__.'(): Input string must be hexadecimal string', E_USER_WARNING); + return false; + } + + return pack('H*', $data); + } + + } -function get_refresh_time_array() { - return array ( - '0' => __('Disable'), - '5' => __('5 seconds'), - '10' => __('10 seconds'), - '15' => __('15 seconds'), - '30' => __('30 seconds'), - (string)SECONDS_1MINUTE => __('1 minute'), - (string)SECONDS_2MINUTES => __('2 minutes'), - (string)SECONDS_5MINUTES => __('5 minutes'), - (string)SECONDS_15MINUTES => __('15 minutes'), - (string)SECONDS_30MINUTES => __('30 minutes'), - (string)SECONDS_1HOUR => __('1 hour')); +function get_refresh_time_array() +{ + return [ + '0' => __('Disable'), + '5' => __('5 seconds'), + '10' => __('10 seconds'), + '15' => __('15 seconds'), + '30' => __('30 seconds'), + (string) SECONDS_1MINUTE => __('1 minute'), + (string) SECONDS_2MINUTES => __('2 minutes'), + (string) SECONDS_5MINUTES => __('5 minutes'), + (string) SECONDS_15MINUTES => __('15 minutes'), + (string) SECONDS_30MINUTES => __('30 minutes'), + (string) SECONDS_1HOUR => __('1 hour'), + ]; } -function date2strftime_format($date_format) { - $replaces_list = array( - 'D' => '%a', - 'l' => '%A', - 'd' => '%d', - 'j' => '%e', - 'N' => '%u', - 'w' => '%w', - 'W' => '%W', - 'M' => '%b', - 'F' => '%B', - 'm' => '%m', - 'o' => '%G', - 'y' => '%y', - 'Y' => '%Y', - 'H' => '%H', - 'h' => '%I', - 'g' => '%l', - 'a' => '%P', - 'A' => '%p', - 'i' => '%M', - 's' => '%S', - 'u' => '%s', - 'O' => '%z', - 'T' => '%Z', - '%' => '%%', - 'G' => '%k', - ); - - $return = ""; - - //character to character because - // Replacement order gotcha - // http://php.net/manual/en/function.str-replace.php - $chars = str_split($date_format); - foreach ($chars as $c) { - if (isset($replaces_list[$c])) { - $return .= $replaces_list[$c]; - } - else { - $return .= $c; - } - } - - return $return; + +function date2strftime_format($date_format) +{ + $replaces_list = [ + 'D' => '%a', + 'l' => '%A', + 'd' => '%d', + 'j' => '%e', + 'N' => '%u', + 'w' => '%w', + 'W' => '%W', + 'M' => '%b', + 'F' => '%B', + 'm' => '%m', + 'o' => '%G', + 'y' => '%y', + 'Y' => '%Y', + 'H' => '%H', + 'h' => '%I', + 'g' => '%l', + 'a' => '%P', + 'A' => '%p', + 'i' => '%M', + 's' => '%S', + 'u' => '%s', + 'O' => '%z', + 'T' => '%Z', + '%' => '%%', + 'G' => '%k', + ]; + + $return = ''; + + // character to character because + // Replacement order gotcha + // http://php.net/manual/en/function.str-replace.php + $chars = str_split($date_format); + foreach ($chars as $c) { + if (isset($replaces_list[$c])) { + $return .= $replaces_list[$c]; + } else { + $return .= $c; + } + } + + return $return; } -function pandora_setlocale() { - global $config; - - $replace_locale = array( - 'ca' => 'ca_ES', - 'de' => 'de_DE', - 'en_GB' => 'de', - 'es' => 'es_ES', - 'fr' => 'fr_FR', - 'it' => 'it_IT', - 'nl' => 'nl_BE', - 'pl' => 'pl_PL', - 'pt' => 'pt_PT', - 'pt_BR' => 'pt_BR', - 'sk' => 'sk_SK', - 'tr' => 'tr_TR', - 'cs' => 'cs_CZ', - 'el' => 'el_GR', - 'ru' => 'ru_RU', - 'ar' => 'ar_MA', - 'ja' => 'ja_JP.UTF-8', - 'zh_CN' => 'zh_CN', - ); - - $user_language = get_user_language($config['id_user']); - - setlocale(LC_ALL, - str_replace(array_keys($replace_locale), $replace_locale, $user_language)); + +function pandora_setlocale() +{ + global $config; + + $replace_locale = [ + 'ca' => 'ca_ES', + 'de' => 'de_DE', + 'en_GB' => 'de', + 'es' => 'es_ES', + 'fr' => 'fr_FR', + 'it' => 'it_IT', + 'nl' => 'nl_BE', + 'pl' => 'pl_PL', + 'pt' => 'pt_PT', + 'pt_BR' => 'pt_BR', + 'sk' => 'sk_SK', + 'tr' => 'tr_TR', + 'cs' => 'cs_CZ', + 'el' => 'el_GR', + 'ru' => 'ru_RU', + 'ar' => 'ar_MA', + 'ja' => 'ja_JP.UTF-8', + 'zh_CN' => 'zh_CN', + ]; + + $user_language = get_user_language($config['id_user']); + + setlocale( + LC_ALL, + str_replace(array_keys($replace_locale), $replace_locale, $user_language) + ); } -function update_config_token ($cfgtoken, $cfgvalue) { - global $config; - - $delete = db_process_sql ("DELETE FROM tconfig WHERE token = '$cfgtoken'"); - $insert = db_process_sql ("INSERT INTO tconfig (token, value) VALUES ('$cfgtoken', '$cfgvalue')"); - - if ($delete && $insert) { - return true; - } - else { - return false; - } + +function update_config_token($cfgtoken, $cfgvalue) +{ + global $config; + + $delete = db_process_sql("DELETE FROM tconfig WHERE token = '$cfgtoken'"); + $insert = db_process_sql("INSERT INTO tconfig (token, value) VALUES ('$cfgtoken', '$cfgvalue')"); + + if ($delete && $insert) { + return true; + } else { + return false; + } } -function get_number_of_mr($package, $ent, $offline) { - global $config; - - if (!$ent) { - $dir = $config['attachment_store'] . "/downloads/pandora_console/extras/mr"; - } - else { - if ($offline) { - $dir = $package . "/extras/mr"; - } - else { - $dir = sys_get_temp_dir() . "/pandora_oum/" . $package . "/extras/mr"; - } - } - - $mr_size = array(); - - if (file_exists($dir) && is_dir($dir)) { - if (is_readable($dir)) { - $files = scandir($dir); // Get all the files from the directory ordered by asc - - if ($files !== false) { - $pattern = "/^\d+\.sql$/"; - $sqlfiles = preg_grep($pattern, $files); // Get the name of the correct files - $pattern = "/\.sql$/"; - $replacement = ""; - $sqlfiles_num = preg_replace($pattern, $replacement, $sqlfiles); - - foreach ($sqlfiles_num as $num) { - $mr_size[] = $num; - } - } - } - } - return $mr_size; + +function get_number_of_mr($package, $ent, $offline) +{ + global $config; + + if (!$ent) { + $dir = $config['attachment_store'].'/downloads/pandora_console/extras/mr'; + } else { + if ($offline) { + $dir = $package.'/extras/mr'; + } else { + $dir = sys_get_temp_dir().'/pandora_oum/'.$package.'/extras/mr'; + } + } + + $mr_size = []; + + if (file_exists($dir) && is_dir($dir)) { + if (is_readable($dir)) { + $files = scandir($dir); + // Get all the files from the directory ordered by asc + if ($files !== false) { + $pattern = '/^\d+\.sql$/'; + $sqlfiles = preg_grep($pattern, $files); + // Get the name of the correct files + $pattern = '/\.sql$/'; + $replacement = ''; + $sqlfiles_num = preg_replace($pattern, $replacement, $sqlfiles); + + foreach ($sqlfiles_num as $num) { + $mr_size[] = $num; + } + } + } + } + + return $mr_size; } -function remove_right_zeros ($value) { - $is_decimal = explode(".", $value); - if (isset($is_decimal[1])) { - $value_to_return = rtrim($value, "0"); - return rtrim($value_to_return, "."); - } - else { - return $value; - } + +function remove_right_zeros($value) +{ + $is_decimal = explode('.', $value); + if (isset($is_decimal[1])) { + $value_to_return = rtrim($value, '0'); + return rtrim($value_to_return, '.'); + } else { + return $value; + } } -function register_pass_change_try ($id_user, $success) { - $values = array(); - $values['id_user'] = $id_user; - $reset_pass_moment = new DateTime('now'); - $reset_pass_moment = $reset_pass_moment->format("Y-m-d H:i:s"); - $values['reset_moment'] = $reset_pass_moment; - $values['success'] = $success; - db_process_sql_insert('treset_pass_history', $values); + +function register_pass_change_try($id_user, $success) +{ + $values = []; + $values['id_user'] = $id_user; + $reset_pass_moment = new DateTime('now'); + $reset_pass_moment = $reset_pass_moment->format('Y-m-d H:i:s'); + $values['reset_moment'] = $reset_pass_moment; + $values['success'] = $success; + db_process_sql_insert('treset_pass_history', $values); } -function isJson($string) { - json_decode($string); - return (json_last_error() == JSON_ERROR_NONE); + +function isJson($string) +{ + json_decode($string); + return (json_last_error() == JSON_ERROR_NONE); } + /** * returns true or false if it is a valid ip * checking ipv4 and ipv6 or resolves the name dns - * @param string address * -*/ -function validate_address($address){ - if($address){ - if(!filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { - if(!filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { - $ip_address_dns = gethostbyname($address); - if(!filter_var($ip_address_dns, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { - if(!filter_var($ip_address_dns, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { - return false; - } - } - } - } - } - return true; + * @param string address + */ +function validate_address($address) +{ + if ($address) { + if (!filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + if (!filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + $ip_address_dns = gethostbyname($address); + if (!filter_var($ip_address_dns, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + if (!filter_var($ip_address_dns, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + return false; + } + } + } + } + } + + return true; } + /** * Used to get the offset in seconds to the UTC date. * * @param string Timezone identifier. */ -function get_utc_offset ($timezone) { - if (empty($timezone)) return 0; +function get_utc_offset($timezone) +{ + if (empty($timezone)) { + return 0; + } - $dtz = new DateTimeZone($timezone); - $dt = new DateTime("now", $dtz); + $dtz = new DateTimeZone($timezone); + $dt = new DateTime('now', $dtz); - return $dtz->getOffset($dt); + return $dtz->getOffset($dt); } -function get_system_utc_offset () { - global $config; - return get_utc_offset($config["timezone"]); + +function get_system_utc_offset() +{ + global $config; + return get_utc_offset($config['timezone']); } -function get_current_utc_offset () { - return get_utc_offset(date_default_timezone_get()); + +function get_current_utc_offset() +{ + return get_utc_offset(date_default_timezone_get()); } -function get_fixed_offset () { - return get_current_utc_offset() - get_system_utc_offset(); + +function get_fixed_offset() +{ + return (get_current_utc_offset() - get_system_utc_offset()); } + /** * Used to transform the dates without timezone information (like '2018/05/23 10:10:10') * to a unix timestamp compatible with the user custom timezone. @@ -2888,12 +3255,16 @@ function get_fixed_offset () { * @param string Date without timezone information. * @param number Offset between the date timezone and the user's default timezone. */ -function time_w_fixed_tz ($date, $timezone_offset = null) { - if ($timezone_offset === null) $timezone_offset = get_fixed_offset(); +function time_w_fixed_tz($date, $timezone_offset=null) +{ + if ($timezone_offset === null) { + $timezone_offset = get_fixed_offset(); + } - return strtotime($date) + $timezone_offset; + return (strtotime($date) + $timezone_offset); } + /** * Used to transform the dates without timezone information (like '2018/05/23 10:10:10') * to a date compatible with the user custom timezone. @@ -2902,492 +3273,636 @@ function time_w_fixed_tz ($date, $timezone_offset = null) { * @param string Date format. * @param number Offset between the date timezone and the user's default timezone. */ -function date_w_fixed_tz ($date, $format = null, $timezone_offset = null) { - global $config; +function date_w_fixed_tz($date, $format=null, $timezone_offset=null) +{ + global $config; - if ($format === null) $format = $config["date_format"]; + if ($format === null) { + $format = $config['date_format']; + } - return date($format, time_w_fixed_tz($date, $timezone_offset)); + return date($format, time_w_fixed_tz($date, $timezone_offset)); } -function color_graph_array(){ - global $config; - $color_series = array(); +function color_graph_array() +{ + global $config; - $color_series[0] = array( - 'border' => '#000000', - 'color' => $config['graph_color1'], - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series = []; - $color_series[1] = array( - 'border' => '#000000', - 'color' => $config['graph_color2'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[2] = array( - 'border' => '#000000', - 'color' => $config['graph_color3'], - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series[0] = [ + 'border' => '#000000', + 'color' => $config['graph_color1'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series[3] = array( - 'border' => '#000000', - 'color' => $config['graph_color4'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[4] = array( - 'border' => '#000000', - 'color' => $config['graph_color5'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[5] = array( - 'border' => '#000000', - 'color' => $config['graph_color6'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[6] = array( - 'border' => '#000000', - 'color' => $config['graph_color7'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[7] = array( - 'border' => '#000000', - 'color' => $config['graph_color8'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[8] = array( - 'border' => '#000000', - 'color' => $config['graph_color9'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[9] = array( - 'border' => '#000000', - 'color' => $config['graph_color10'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[10] = array( - 'border' => '#000000', - 'color' => COL_GRAPH9, - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[11] = array( - 'border' => '#000000', - 'color' => COL_GRAPH10, - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[12] = array( - 'border' => '#000000', - 'color' => COL_GRAPH11, - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[13] = array( - 'border' => '#000000', - 'color' => COL_GRAPH12, - 'alpha' => CHART_DEFAULT_ALPHA - ); - $color_series[14] = array( - 'border' => '#000000', - 'color' => COL_GRAPH13, - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series[1] = [ + 'border' => '#000000', + 'color' => $config['graph_color2'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[2] = [ + 'border' => '#000000', + 'color' => $config['graph_color3'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['event'] = array( - 'border' => '#ff0000', - 'color' => '#FF5733', - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series[3] = [ + 'border' => '#000000', + 'color' => $config['graph_color4'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[4] = [ + 'border' => '#000000', + 'color' => $config['graph_color5'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[5] = [ + 'border' => '#000000', + 'color' => $config['graph_color6'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[6] = [ + 'border' => '#000000', + 'color' => $config['graph_color7'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[7] = [ + 'border' => '#000000', + 'color' => $config['graph_color8'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[8] = [ + 'border' => '#000000', + 'color' => $config['graph_color9'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[9] = [ + 'border' => '#000000', + 'color' => $config['graph_color10'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[10] = [ + 'border' => '#000000', + 'color' => COL_GRAPH9, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[11] = [ + 'border' => '#000000', + 'color' => COL_GRAPH10, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[12] = [ + 'border' => '#000000', + 'color' => COL_GRAPH11, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[13] = [ + 'border' => '#000000', + 'color' => COL_GRAPH12, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color_series[14] = [ + 'border' => '#000000', + 'color' => COL_GRAPH13, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['alert'] = array( - 'border' => '#ffff00', - 'color' => '#ffff00', - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series['event'] = [ + 'border' => '#ff0000', + 'color' => '#FF5733', + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['unknown'] = array( - 'border' => '#999999', - 'color' => '#E1E1E1', - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series['alert'] = [ + 'border' => '#ffff00', + 'color' => '#ffff00', + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['percentil'] = array( - 'border' => '#000000', - 'color' => '#003333', - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series['unknown'] = [ + 'border' => '#999999', + 'color' => '#E1E1E1', + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['projection'] = array( - 'border' => '#000000', - 'color' => $config['graph_color8'], - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series['percentil'] = [ + 'border' => '#000000', + 'color' => '#003333', + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['overlapped'] = array( - 'border' => '#000000', - 'color' => $config['graph_color9'], - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series['projection'] = [ + 'border' => '#000000', + 'color' => $config['graph_color8'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['summatory'] = array( - 'border' => '#000000', - 'color' => $config['graph_color7'], - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series['overlapped'] = [ + 'border' => '#000000', + 'color' => $config['graph_color9'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['average'] = array( - 'border' => '#000000', - 'color' => $config['graph_color10'], - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series['summatory'] = [ + 'border' => '#000000', + 'color' => $config['graph_color7'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['no_data'] = array( - 'border' => '#000000', - 'color' => '#f2c40e', - 'alpha' => CHART_DEFAULT_ALPHA - ); + $color_series['average'] = [ + 'border' => '#000000', + 'color' => $config['graph_color10'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - $color_series['unit'] = array( - 'border' => null, - 'color' => '#0097BC', - 'alpha' => 10 - ); + $color_series['no_data'] = [ + 'border' => '#000000', + 'color' => '#f2c40e', + 'alpha' => CHART_DEFAULT_ALPHA, + ]; - return $color_series; + $color_series['unit'] = [ + 'border' => null, + 'color' => '#0097BC', + 'alpha' => 10, + ]; + + return $color_series; } -function series_type_graph_array($data, $show_elements_graph){ - global $config; - if(isset($show_elements_graph['stacked'])){ - switch ($show_elements_graph['stacked']) { - case 2: - case 4: - $type_graph = 'line'; - break; - default: - $type_graph = 'area'; - break; - } - } - else{ - $type_graph = $show_elements_graph['type_graph']; - } +function series_type_graph_array($data, $show_elements_graph) +{ + global $config; - $color_series = color_graph_array(); + if (isset($show_elements_graph['stacked'])) { + switch ($show_elements_graph['stacked']) { + case 2: + case 4: + $type_graph = 'line'; + break; - if($show_elements_graph['id_widget_dashboard']){ - $opcion = unserialize(db_get_value_filter('options','twidget_dashboard',array('id' => $show_elements_graph['id_widget_dashboard']))); - if($show_elements_graph['graph_combined']){ + default: + $type_graph = 'area'; + break; + } + } else { + $type_graph = $show_elements_graph['type_graph']; + } - foreach ($show_elements_graph['modules_id'] as $key => $value) { - $color_series[$key] = array( - 'border' => '#000000', - 'color' => $opcion[$value], - 'alpha' => CHART_DEFAULT_ALPHA - ); - } - } - else{ - $color_series[0] = array( - 'border' => '#000000', - 'color' => $opcion['max'], - 'alpha' => CHART_DEFAULT_ALPHA - ); - } - } + $color_series = color_graph_array(); - $i = 0; - if(isset($data) && is_array($data)){ - foreach ($data as $key => $value) { - if($show_elements_graph['compare'] == 'overlapped'){ - if($key == 'sum2'){ - $str = ' (' . __('Previous') . ')'; - } - } + if ($show_elements_graph['id_widget_dashboard']) { + $opcion = unserialize(db_get_value_filter('options', 'twidget_dashboard', ['id' => $show_elements_graph['id_widget_dashboard']])); + if ($show_elements_graph['graph_combined']) { + foreach ($show_elements_graph['modules_id'] as $key => $value) { + $color_series[$key] = [ + 'border' => '#000000', + 'color' => $opcion[$value], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + } + } else { + $color_series[0] = [ + 'border' => '#000000', + 'color' => $opcion['max'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + } + } - if(strpos($key, 'summatory') !== false){ - $data_return['series_type'][$key] = $type_graph; - $data_return['legend'][$key] = __('Summatory series') . ' ' . $str; - $data_return['color'][$key] = $color_series['summatory']; - } - elseif(strpos($key, 'average') !== false){ - $data_return['series_type'][$key] = $type_graph; - $data_return['legend'][$key] = __('Average series') . ' ' . $str; - $data_return['color'][$key] = $color_series['average']; - } - elseif(strpos($key, 'sum') !== false || strpos($key, 'baseline') !== false){ - switch ($value['id_module_type']) { - case 21: case 2: case 6: - case 18: case 9: case 31: case 100: - $data_return['series_type'][$key] = 'boolean'; - break; - default: - $data_return['series_type'][$key] = $type_graph; - break; - } + $i = 0; + if (isset($data) && is_array($data)) { + foreach ($data as $key => $value) { + if ($show_elements_graph['compare'] == 'overlapped') { + if ($key == 'sum2') { + $str = ' ('.__('Previous').')'; + } + } - if (isset($show_elements_graph['labels']) && - is_array($show_elements_graph['labels']) && - (count($show_elements_graph['labels']) > 0)){ - if ($show_elements_graph['unit']) - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . ' / ' . __('Unit ') . ' ' . $show_elements_graph['unit'] .': '; - else - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . ': '; - } - else{ - if(strpos($key, 'baseline') !== false){ - if ($show_elements_graph['unit']) - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . ' / ' . __('Unit ') . ' ' . $show_elements_graph['unit'] .'Baseline '; - else - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . 'Baseline '; - } - else{ - if ($show_elements_graph['unit']) - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . ' / ' . __('Unit ') . ' ' . $show_elements_graph['unit'] .': '; - else - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . ': '; - } - } + if (strpos($key, 'summatory') !== false) { + $data_return['series_type'][$key] = $type_graph; + $data_return['legend'][$key] = __('Summatory series').' '.$str; + $data_return['color'][$key] = $color_series['summatory']; + } else if (strpos($key, 'average') !== false) { + $data_return['series_type'][$key] = $type_graph; + $data_return['legend'][$key] = __('Average series').' '.$str; + $data_return['color'][$key] = $color_series['average']; + } else if (strpos($key, 'sum') !== false || strpos($key, 'baseline') !== false) { + switch ($value['id_module_type']) { + case 21: + case 2: + case 6: + case 18: + case 9: + case 31: + case 100: + $data_return['series_type'][$key] = 'boolean'; + break; - $data_return['legend'][$key] .= - __('Min:') . remove_right_zeros( - number_format( - $value['min'], - $config['graph_precision'] - ) - ) . ' ' . - __('Max:') . remove_right_zeros( - number_format( - $value['max'], - $config['graph_precision'] - ) - ) . ' ' . - _('Avg:') . remove_right_zeros( - number_format( - $value['avg'], - $config['graph_precision'] - ) - ) . ' ' . $str; + default: + $data_return['series_type'][$key] = $type_graph; + break; + } - if($show_elements_graph['compare'] == 'overlapped' && $key == 'sum2'){ - $data_return['color'][$key] = $color_series['overlapped']; - } - else{ - $data_return['color'][$key] = $color_series[$i]; - $i++; - } - } - elseif(!$show_elements_graph['fullscale'] && strpos($key, 'min') !== false || - !$show_elements_graph['fullscale'] && strpos($key, 'max') !== false){ - $data_return['series_type'][$key] = $type_graph; + if (isset($show_elements_graph['labels']) + && is_array($show_elements_graph['labels']) + && (count($show_elements_graph['labels']) > 0) + ) { + if ($show_elements_graph['unit']) { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].' / '.__('Unit ').' '.$show_elements_graph['unit'].': '; + } else { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].': '; + } + } else { + if (strpos($key, 'baseline') !== false) { + if ($show_elements_graph['unit']) { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].' / '.__('Unit ').' '.$show_elements_graph['unit'].'Baseline '; + } else { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].'Baseline '; + } + } else { + if ($show_elements_graph['unit']) { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].' / '.__('Unit ').' '.$show_elements_graph['unit'].': '; + } else { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].': '; + } + } + } - if ($show_elements_graph['unit']) - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . ' / ' . __('Unit ') . ' ' . $show_elements_graph['unit'] .': '; - else - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . ': '; + $data_return['legend'][$key] .= __('Min:').remove_right_zeros( + number_format( + $value['min'], + $config['graph_precision'] + ) + ).' '.__('Max:').remove_right_zeros( + number_format( + $value['max'], + $config['graph_precision'] + ) + ).' '._('Avg:').remove_right_zeros( + number_format( + $value['avg'], + $config['graph_precision'] + ) + ).' '.$str; - $data_return['legend'][$key] = $name_legend; - if($show_elements_graph['type_mode_graph']){ - $data_return['legend'][$key] .= - __('Min:') . remove_right_zeros( - number_format( - $value['min'], - $config['graph_precision'] - ) - ) . ' ' . - __('Max:') . remove_right_zeros( - number_format( - $value['max'], - $config['graph_precision'] - ) - ) . ' ' . - _('Avg:') . remove_right_zeros( - number_format( - $value['avg'], - $config['graph_precision'] - ) - ) . ' ' . $str; - } + if ($show_elements_graph['compare'] == 'overlapped' && $key == 'sum2') { + $data_return['color'][$key] = $color_series['overlapped']; + } else { + $data_return['color'][$key] = $color_series[$i]; + $i++; + } + } else if (!$show_elements_graph['fullscale'] && strpos($key, 'min') !== false + || !$show_elements_graph['fullscale'] && strpos($key, 'max') !== false + ) { + $data_return['series_type'][$key] = $type_graph; - if($show_elements_graph['compare'] == 'overlapped' && $key == 'sum2'){ - $data_return['color'][$key] = $color_series['overlapped']; - } - else{ - $data_return['color'][$key] = $color_series[$i]; - $i++; - } - } - elseif(strpos($key, 'event') !== false){ - $data_return['series_type'][$key] = 'points'; - if($show_elements_graph['show_events']){ - $data_return['legend'][$key] = __('Events') . ' ' . $str; - } + if ($show_elements_graph['unit']) { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].' / '.__('Unit ').' '.$show_elements_graph['unit'].': '; + } else { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].': '; + } - $data_return['color'][$key] = $color_series['event']; - } - elseif(strpos($key, 'alert') !== false){ - $data_return['series_type'][$key] = 'points'; - if($show_elements_graph['show_alerts']){ - $data_return['legend'][$key] = __('Alert') . ' ' . $str; - } + $data_return['legend'][$key] = $name_legend; + if ($show_elements_graph['type_mode_graph']) { + $data_return['legend'][$key] .= __('Min:').remove_right_zeros( + number_format( + $value['min'], + $config['graph_precision'] + ) + ).' '.__('Max:').remove_right_zeros( + number_format( + $value['max'], + $config['graph_precision'] + ) + ).' '._('Avg:').remove_right_zeros( + number_format( + $value['avg'], + $config['graph_precision'] + ) + ).' '.$str; + } - $data_return['color'][$key] = $color_series['alert']; - } - elseif(strpos($key, 'unknown') !== false){ - $data_return['series_type'][$key] = 'unknown'; - if($show_elements_graph['show_unknown']){ - $data_return['legend'][$key] = __('Unknown') . ' ' . $str; - } - $data_return['color'][$key] =$color_series['unknown']; - } - elseif(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'] .': '; - else - $name_legend = $data_return['legend'][$key] = $value['agent_alias'] . ' / ' . $value['module_name'] . ': '; - $data_return['legend'][$key] .= $name_legend; - $data_return['legend'][$key] .= remove_right_zeros( - number_format( - $value['data'][0][1], - $config['graph_precision'] - ) - ) . ' ' . $str; - } - $data_return['color'][$key] =$color_series['percentil']; - } - elseif(strpos($key, 'projection') !== false){ - $data_return['series_type'][$key] = $type_graph; - $data_return['legend'][$key] = __('Projection') . ' ' . $str; - $data_return['color'][$key] = $color_series['projection']; - } - else{ - $data_return['series_type'][$key] = $type_graph; - $data_return['legend'][$key] = $key; - $data_return['color'][$key] = $color_series[$i]; - $i++; - } - if($i > 14){ - $i = 0; - } - } - return $data_return; - } - return false; + if ($show_elements_graph['compare'] == 'overlapped' && $key == 'sum2') { + $data_return['color'][$key] = $color_series['overlapped']; + } else { + $data_return['color'][$key] = $color_series[$i]; + $i++; + } + } else if (strpos($key, 'event') !== false) { + $data_return['series_type'][$key] = 'points'; + if ($show_elements_graph['show_events']) { + $data_return['legend'][$key] = __('Events').' '.$str; + } + + $data_return['color'][$key] = $color_series['event']; + } else if (strpos($key, 'alert') !== false) { + $data_return['series_type'][$key] = 'points'; + if ($show_elements_graph['show_alerts']) { + $data_return['legend'][$key] = __('Alert').' '.$str; + } + + $data_return['color'][$key] = $color_series['alert']; + } else if (strpos($key, 'unknown') !== false) { + $data_return['series_type'][$key] = 'unknown'; + if ($show_elements_graph['show_unknown']) { + $data_return['legend'][$key] = __('Unknown').' '.$str; + } + + $data_return['color'][$key] = $color_series['unknown']; + } 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'].': '; + } else { + $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].': '; + } + + $data_return['legend'][$key] .= $name_legend; + $data_return['legend'][$key] .= remove_right_zeros( + number_format( + $value['data'][0][1], + $config['graph_precision'] + ) + ).' '.$str; + } + + $data_return['color'][$key] = $color_series['percentil']; + } else if (strpos($key, 'projection') !== false) { + $data_return['series_type'][$key] = $type_graph; + $data_return['legend'][$key] = __('Projection').' '.$str; + $data_return['color'][$key] = $color_series['projection']; + } else { + $data_return['series_type'][$key] = $type_graph; + $data_return['legend'][$key] = $key; + $data_return['color'][$key] = $color_series[$i]; + $i++; + } + + if ($i > 14) { + $i = 0; + } + } + + return $data_return; + } + + return false; } -function generator_chart_to_pdf($type_graph_pdf, $params, $params_combined = false, $module_list = false){ - global $config; - $file_js = $config["homedir"] . "/include/web2image.js"; - $url = $config["homeurl"] . "include/chart_generator.php"; - $img_file = "img_". uniqid() .".png"; - $img_path = $config["homedir"] . "/attachment/" . $img_file; - $img_url = $config["homeurl"] . "attachment/" . $img_file; +function generator_chart_to_pdf($type_graph_pdf, $params, $params_combined=false, $module_list=false) +{ + global $config; - $width_img = 500; - $height_img = (isset($config['graph_image_height'])) ? $config['graph_image_height'] : 280; + if (is_metaconsole()) { + $hack_metaconsole = '../..'; + } else { + $hack_metaconsole = ''; + } - $params['height'] = $height_img; + $file_js = $config['homedir'].'/include/web2image.js'; + $url = ui_get_full_url(false).$hack_metaconsole.'/include/chart_generator.php'; - $params_encode_json = urlencode(json_encode($params)); + $img_file = 'img_'.uniqid().'.png'; + $img_path = $config['homedir'].'/attachment/'.$img_file; + $img_url = ui_get_full_url(false).$hack_metaconsole.'/attachment/'.$img_file; - if($params_combined){ - $params_combined = urlencode(json_encode($params_combined)); - } + $width_img = 500; + $height_img = (isset($config['graph_image_height'])) ? $config['graph_image_height'] : 280; - if($module_list){ - $module_list = urlencode(json_encode($module_list)); - } + $params['height'] = $height_img; - $session_id = session_id(); + $params_encode_json = urlencode(json_encode($params)); - $cmd = '"' . io_safe_output($config['phantomjs_bin']) . DIRECTORY_SEPARATOR . 'phantomjs" --ssl-protocol=any --ignore-ssl-errors=true "' . $file_js . '" ' - . ' "' . $url . '"' - . ' "' . $type_graph_pdf . '"' - . ' "' . $params_encode_json . '"' - . ' "' . $params_combined . '"' - . ' "' . $module_list . '"' - . ' "' . $img_path . '"' - . ' "' . $width_img . '"' - . ' "' . $height_img . '"' - . ' "' . $session_id . '"' - . ' "' . $params['return_img_base_64'] . '"'; + if ($params_combined) { + $params_combined = urlencode(json_encode($params_combined)); + } - exec($cmd, $result); - $img_content = join("\n", $result); + if ($module_list) { + $module_list = urlencode(json_encode($module_list)); + } - if($params['return_img_base_64']){ - // To be used in alerts - $width_img = 500; - return $img_content; - } - else{ - // to be used in PDF files - $config["temp_images"][] = $img_path; - return ''; - } + $session_id = session_id(); + + $cmd = '"'.io_safe_output($config['phantomjs_bin']).DIRECTORY_SEPARATOR.'phantomjs" --ssl-protocol=any --ignore-ssl-errors=true "'.$file_js.'" '.' "'.$url.'"'.' "'.$type_graph_pdf.'"'.' "'.$params_encode_json.'"'.' "'.$params_combined.'"'.' "'.$module_list.'"'.' "'.$img_path.'"'.' "'.$width_img.'"'.' "'.$height_img.'"'.' "'.$session_id.'"'.' "'.$params['return_img_base_64'].'"'; + + $result = null; + $retcode = null; + exec($cmd, $result, $retcode); + + $img_content = join("\n", $result); + + if ($params['return_img_base_64']) { + // To be used in alerts + $width_img = 500; + return $img_content; + } else { + // to be used in PDF files + $config['temp_images'][] = $img_path; + return ''; + } } + /** * Get the product name. * * @return string If the installation is open, it will be 'Pandora FMS'. - * If the product name stored is empty, it returns 'Pandora FMS' too. + * If the product name stored is empty, it returns 'Pandora FMS' too. */ -function get_product_name () { - $stored_name = enterprise_hook('enterprise_get_product_name'); - if (empty($stored_name) || $stored_name == ENTERPRISE_NOT_HOOK) { - return "Pandora FMS"; - } - return $stored_name; +function get_product_name() +{ + $stored_name = enterprise_hook('enterprise_get_product_name'); + if (empty($stored_name) || $stored_name == ENTERPRISE_NOT_HOOK) { + return 'Pandora FMS'; + } + + return $stored_name; } + /** * Get the copyright notice. * * @return string If the installation is open, it will be 'Artica ST'. - * If the product name stored is empty, it returns 'Artica ST' too. + * If the product name stored is empty, it returns 'Artica ST' too. */ -function get_copyright_notice () { - $stored_name = enterprise_hook('enterprise_get_copyright_notice'); - if (empty($stored_name) || $stored_name == ENTERPRISE_NOT_HOOK) { - return "Ártica ST"; - } - return $stored_name; +function get_copyright_notice() +{ + $stored_name = enterprise_hook('enterprise_get_copyright_notice'); + if (empty($stored_name) || $stored_name == ENTERPRISE_NOT_HOOK) { + return 'Ártica ST'; + } + + return $stored_name; } + /** * Generate a random code to prevent cross site request fogery attacks * * @return string Generated code */ -function generate_csrf_code() { - // Start session to make this var permanent - if (session_status() === PHP_SESSION_NONE) session_start(); - $_SESSION['csrf_code'] = md5(uniqid(mt_rand(), true)); - session_write_close(); - return $_SESSION['csrf_code']; +function generate_csrf_code() +{ + // Start session to make this var permanent + if (session_status() === PHP_SESSION_NONE) { + session_start(); + } + + $_SESSION['csrf_code'] = md5(uniqid(mt_rand(), true)); + session_write_close(); + return $_SESSION['csrf_code']; } + /** * Validate the CSRF code * - * @return bool True if code is valid + * @return boolean True if code is valid */ -function validate_csrf_code() { - $code = get_parameter('csrf_code'); - return isset($code) && isset($_SESSION['csrf_code']) - && $_SESSION['csrf_code'] == $code; +function validate_csrf_code() +{ + $code = get_parameter('csrf_code'); + return isset($code) && isset($_SESSION['csrf_code']) + && $_SESSION['csrf_code'] == $code; } -function generate_hash_to_api(){ - hash('sha256', db_get_value ('value', 'tupdate_settings', '`key`', 'customer_key')); - } -?> + +function generate_hash_to_api() +{ + return (string) hash('sha256', db_get_value('value', 'tupdate_settings', '`key`', 'customer_key')); +} + + +/** + * Disable the profiller and display de result + * + * @param string Key to identify the profiler run. + * @param string Way to display the result + * "link" (default): Click into word "Performance" to display the profilling info. + * "console": Display with a message in pandora_console.log. + */ +function pandora_xhprof_display_result($key='', $method='link') +{ + // Check if function exists + if (!function_exists('tideways_xhprof_disable')) { + error_log('Cannot find tideways_xhprof_disable function'); + return; + } + + $run_id = uniqid(); + $data = tideways_xhprof_disable(); + $source = "pandora_$key"; + file_put_contents( + sys_get_temp_dir().'/'.$run_id.".$source.xhprof", + serialize($data) + ); + $new_url = "http://{$_SERVER['HTTP_HOST']}/profiler/index.php?run={$run_id}&source={$source}"; + switch ($method) { + case 'console': + error_log("'{$new_url}'"); + case 'link': + default: + echo "Performance\n"; + break; + } +} + + +/** + * From a network with a mask remove the smallest ip and the highest + * + * @param string address to identify the network. + * @param string mask to identify the mask network + * @return array or false with smallest ip and highest ip + */ +function range_ips_for_network($address, $mask) +{ + if (!isset($address) || !isset($mask)) { + return false; + } + + // convert ip addresses to long form + $address_long = ip2long($address); + $mask_long = ip2long($mask); + + // caculate first usable address + $ip_host_first = ((~$mask_long) & $address_long); + $ip_first = (($address_long ^ $ip_host_first) + 1); + + // caculate last usable address + $ip_broadcast_invert = ~$mask_long; + $ip_last = (($address_long | $ip_broadcast_invert) - 1); + + $range = [ + 'first' => long2ip($ip_first), + 'last' => long2ip($ip_last), + ]; + + return $range; +} + + +/** + * from two ips find out if there is such an ip + * + * @param string ip ip wont validate + * @param string ip_lower + * @param string ip_upper + * @return boolean true or false if the ip is between the two ips + */ +function is_in_network($ip, $ip_lower, $ip_upper) +{ + if (!isset($ip) || !isset($ip_lower) || !isset($ip_upper)) { + return false; + } + + $ip = (float) sprintf('%u', ip2long($ip)); + $ip_lower = (float) sprintf('%u', ip2long($ip_lower)); + $ip_upper = (float) sprintf('%u', ip2long($ip_upper)); + + if ($ip >= $ip_lower && $ip <= $ip_upper) { + return true; + } else { + return false; + } +} + + +/** + * + */ +function ip_belongs_to_network($ip, $network, $mask) +{ + if ($ip == $network) { + return true; + } + + $ranges = range_ips_for_network($network, $mask); + return is_in_network($ip, $ranges['first'], $ranges['last']); +} + + +/** + * convert the mask to cird format + * + * @param string mask + * @return string true or false if the ip is between the two ips + */ +function mask2cidr($mask) +{ + if (!isset($mask)) { + return 0; + } + + $long = ip2long($mask); + $base = ip2long('255.255.255.255'); + return (32 - log((($long ^ $base) + 1), 2)); +} diff --git a/pandora_console/include/functions_agents.php b/pandora_console/include/functions_agents.php index d69a27d8fe..9aa9cf7dfd 100644 --- a/pandora_console/include/functions_agents.php +++ b/pandora_console/include/functions_agents.php @@ -4,72 +4,83 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. /** - * @package Include + * @package Include * @subpackage Agents */ -require_once($config['homedir'] . '/include/functions.php'); -require_once($config['homedir'] . "/include/functions_modules.php"); -require_once($config['homedir'] . '/include/functions_users.php'); +require_once $config['homedir'].'/include/functions.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_users.php'; + /** * Check the agent exists in the DB. * - * @param int $id_agent The agent id. + * @param integer $id_agent The agent id. * @param boolean $show_disabled Show the agent found althought it is disabled. By default false. - * @param boolean $force_meta + * @param boolean $force_meta * * @return boolean The result to check if the agent is in the DB. */ -function agents_check_agent_exists($id_agent, $show_disabled = true, $force_meta = false) { - $agent = db_get_value_filter( - 'id_agente', - $force_meta ? 'tmetaconsole_agent' : 'tagente', - array('id_agente' => $id_agent, 'disabled' => !$show_disabled) - ); +function agents_check_agent_exists($id_agent, $show_disabled=true, $force_meta=false) +{ + $agent = db_get_value_filter( + 'id_agente', + $force_meta ? 'tmetaconsole_agent' : 'tagente', + [ + 'id_agente' => $id_agent, + 'disabled' => !$show_disabled, + ] + ); - if (!empty($agent)) { - return true; - } - else { - return false; - } + if (!empty($agent)) { + return true; + } else { + return false; + } } + /** * Get agent id from a module id that it has. * - * @param int $id_module Id module is list modules this agent. + * @param integer $id_module Id module is list modules this agent. * - * @return int Id from the agent of the given id module. + * @return integer Id from the agent of the given id module. */ -function agents_get_agent_id_by_module_id ($id_agente_modulo) { - return (int) db_get_value ('id_agente', 'tagente_modulo', - 'id_agente_modulo', $id_agente_modulo); +function agents_get_agent_id_by_module_id($id_agente_modulo) +{ + return (int) db_get_value( + 'id_agente', + 'tagente_modulo', + 'id_agente_modulo', + $id_agente_modulo + ); } + /** * Get agent id from an agent alias. * * @param string $alias Agent alias. * - * @return int Id from the agent. + * @return integer Id from the agent. */ -function agents_get_agent_id_by_alias ($alias) { - return db_get_all_rows_sql ("SELECT id_agente FROM tagente WHERE upper(alias) LIKE upper('%$alias%')"); +function agents_get_agent_id_by_alias($alias) +{ + return db_get_all_rows_sql("SELECT id_agente FROM tagente WHERE upper(alias) LIKE upper('%$alias%')"); } + /** * Creates an agent * @@ -78,47 +89,56 @@ function agents_get_agent_id_by_alias ($alias) { * @param int Agent interval * @param string Agent IP * - * @return int New agent id if created. False if it could not be created. + * @return integer New agent id if created. False if it could not be created. */ -function agents_create_agent ($name, $id_group, $interval, $ip_address, $values = false) { - if (empty ($name)) - return false; - - if (empty ($id_group) && (int)$id_group != 0) - return false; - - // Check interval greater than zero - if ($interval < 0) - $interval = false; - if (empty ($interval)) - return false; - - if (! is_array ($values)) - $values = array (); - $values['alias'] = $name; - $values['nombre'] = hash("sha256",$name . "|" .$ip_address ."|". time() ."|". sprintf("%04d", rand(0,10000))); - $values['id_grupo'] = $id_group; - $values['intervalo'] = $interval; - - if (!empty ($ip_address)){ - $values['direccion'] = $ip_address; - } - - $id_agent = db_process_sql_insert ('tagente', $values); - if ($id_agent === false) { - return false; - } - - // Create address for this agent in taddress - if (!empty ($ip_address)){ - agents_add_address ($id_agent, $ip_address); - } - - db_pandora_audit ("Agent management", "New agent '$name' created"); - - return $id_agent; +function agents_create_agent($name, $id_group, $interval, $ip_address, $values=false) +{ + if (empty($name)) { + return false; + } + + if (empty($id_group) && (int) $id_group != 0) { + return false; + } + + // Check interval greater than zero + if ($interval < 0) { + $interval = false; + } + + if (empty($interval)) { + return false; + } + + if (! is_array($values)) { + $values = []; + } + + $values['alias'] = $name; + $values['nombre'] = hash('sha256', $name.'|'.$ip_address.'|'.time().'|'.sprintf('%04d', rand(0, 10000))); + $values['id_grupo'] = $id_group; + $values['intervalo'] = $interval; + + if (!empty($ip_address)) { + $values['direccion'] = $ip_address; + } + + $id_agent = db_process_sql_insert('tagente', $values); + if ($id_agent === false) { + return false; + } + + // Create address for this agent in taddress + if (!empty($ip_address)) { + agents_add_address($id_agent, $ip_address); + } + + db_pandora_audit('Agent management', "New agent '$name' created"); + + return $id_agent; } + /** * Get all the simple alerts of an agent. * @@ -127,111 +147,113 @@ function agents_create_agent ($name, $id_group, $interval, $ip_address, $values * will not do any filter. * @param array Extra filter options in an indexed array. See * db_format_array_where_clause_sql() - * @param boolean $allModules + * @param boolean $allModules * * @return array All simple alerts defined for an agent. Empty array if no * alerts found. */ -function agents_get_alerts_simple ($id_agent = false, $filter = '', $options = false, $where = '', $allModules = false, $orderby = false, $idGroup = false, $count = false, $strict_user = false, $tag = false) { - global $config; - - if (is_array($filter)) { - $disabled = $filter['disabled']; - if (isset($filter['standby'])) { - $filter = ' AND talert_template_modules.standby = "'.$filter['standby'].'"'; - } - else { - $filter = ''; - } - } - else { - $filter = ''; - $disabled = $filter; - } - - switch ($disabled) { - case "notfired": - $filter .= ' AND times_fired = 0 AND talert_template_modules.disabled = 0'; - break; - case "fired": - $filter .= ' AND times_fired > 0 AND talert_template_modules.disabled = 0'; - break; - case "disabled": - $filter .= ' AND talert_template_modules.disabled = 1'; - break; - case "all_enabled": - $filter .= ' AND talert_template_modules.disabled = 0'; - break; - default: - $filter .= ''; - break; - } +function agents_get_alerts_simple($id_agent=false, $filter='', $options=false, $where='', $allModules=false, $orderby=false, $idGroup=false, $count=false, $strict_user=false, $tag=false) +{ + global $config; - if ($tag) { - $filter .= ' AND (id_agent_module IN (SELECT id_agente_modulo FROM ttag_module WHERE id_tag IN ('.$tag.')))'; - } - - if (isset($options['offset'])) { - $offset = $options['offset']; - unset($options['offset']); - } - - if (isset($options['limit'])) { - $limit = $options['limit']; - unset($options['limit']); - } - - if (is_array ($options)) { - $filter .= db_format_array_where_clause_sql ($options); - } - - if (($id_agent !== false) && ($idGroup !== false)) { - if ($idGroup != 0) { //All group - $subQuery = 'SELECT id_agente_modulo + if (is_array($filter)) { + $disabled = $filter['disabled']; + if (isset($filter['standby'])) { + $filter = ' AND talert_template_modules.standby = "'.$filter['standby'].'"'; + } else { + $filter = ''; + } + } else { + $filter = ''; + $disabled = $filter; + } + + switch ($disabled) { + case 'notfired': + $filter .= ' AND times_fired = 0 AND talert_template_modules.disabled = 0'; + break; + + case 'fired': + $filter .= ' AND times_fired > 0 AND talert_template_modules.disabled = 0'; + break; + + case 'disabled': + $filter .= ' AND talert_template_modules.disabled = 1'; + break; + + case 'all_enabled': + $filter .= ' AND talert_template_modules.disabled = 0'; + break; + + default: + $filter .= ''; + break; + } + + if ($tag) { + $filter .= ' AND (id_agent_module IN (SELECT id_agente_modulo FROM ttag_module WHERE id_tag IN ('.$tag.')))'; + } + + if (isset($options['offset'])) { + $offset = $options['offset']; + unset($options['offset']); + } + + if (isset($options['limit'])) { + $limit = $options['limit']; + unset($options['limit']); + } + + if (is_array($options)) { + $filter .= db_format_array_where_clause_sql($options); + } + + if (($id_agent !== false) && ($idGroup !== false)) { + if ($idGroup != 0) { + // All group + $subQuery = 'SELECT id_agente_modulo FROM tagente_modulo - WHERE delete_pending = 0 AND id_agente IN (SELECT id_agente FROM tagente WHERE id_grupo = ' . $idGroup . ')'; - } - else { - $subQuery = 'SELECT id_agente_modulo + WHERE delete_pending = 0 AND id_agente IN (SELECT id_agente FROM tagente WHERE id_grupo = '.$idGroup.')'; + } else { + $subQuery = 'SELECT id_agente_modulo FROM tagente_modulo WHERE delete_pending = 0'; - } - } - else if ($id_agent === false || empty($id_agent)) { - if ($allModules) - $disabled = ''; - else - $disabled = 'WHERE disabled = 0'; - - $subQuery = 'SELECT id_agente_modulo - FROM tagente_modulo ' . $disabled; - } - else { - $id_agent = (array) $id_agent; - $id_modules = array_keys (agents_get_modules ($id_agent, false, array('delete_pending' => 0))); - - if (empty ($id_modules)) - return array (); - - $subQuery = implode (",", $id_modules); - } - - $orderbyText = ''; - if ($orderby !== false) { - if (is_array($orderby)) { - $orderbyText = sprintf("ORDER BY %s", $orderby['field'], $orderby['order']); - } - else { - $orderbyText = sprintf("ORDER BY %s", $orderby); - } - } - - $selectText = 'talert_template_modules.*, t2.nombre AS agent_module_name, t3.alias AS agent_name, t4.name AS template_name'; - if ($count !== false) { - $selectText = 'COUNT(talert_template_modules.id) AS count'; - } - - - $sql = sprintf ("SELECT %s + } + } else if ($id_agent === false || empty($id_agent)) { + if ($allModules) { + $disabled = ''; + } else { + $disabled = 'WHERE disabled = 0'; + } + + $subQuery = 'SELECT id_agente_modulo + FROM tagente_modulo '.$disabled; + } else { + $id_agent = (array) $id_agent; + $id_modules = array_keys(agents_get_modules($id_agent, false, ['delete_pending' => 0])); + + if (empty($id_modules)) { + return []; + } + + $subQuery = implode(',', $id_modules); + } + + $orderbyText = ''; + if ($orderby !== false) { + if (is_array($orderby)) { + $orderbyText = sprintf('ORDER BY %s', $orderby['field'], $orderby['order']); + } else { + $orderbyText = sprintf('ORDER BY %s', $orderby); + } + } + + $selectText = 'talert_template_modules.*, t2.nombre AS agent_module_name, t3.alias AS agent_name, t4.name AS template_name'; + if ($count !== false) { + $selectText = 'COUNT(talert_template_modules.id) AS count'; + } + + $sql = sprintf( + 'SELECT %s FROM talert_template_modules INNER JOIN tagente_modulo t2 ON talert_template_modules.id_agent_module = t2.id_agente_modulo @@ -239,288 +261,343 @@ function agents_get_alerts_simple ($id_agent = false, $filter = '', $options = f ON t2.id_agente = t3.id_agente INNER JOIN talert_templates t4 ON talert_template_modules.id_alert_template = t4.id - WHERE id_agent_module in (%s) %s %s %s", - $selectText, $subQuery, $where, $filter, $orderbyText); - - switch ($config["dbtype"]) { - case "mysql": - $limit_sql = ''; - if (isset($offset) && isset($limit)) { - $limit_sql = " LIMIT $offset, $limit "; - } - $sql = sprintf("%s %s", $sql, $limit_sql); - $alerts = db_get_all_rows_sql($sql); - break; - case "postgresql": - $limit_sql = ''; - if (isset($offset) && isset($limit)) { - $limit_sql = " OFFSET $offset LIMIT $limit "; - } - $sql = sprintf("%s %s", $sql, $limit_sql); - - $alerts = db_get_all_rows_sql($sql); - - break; - case "oracle": - $set = array(); - if (isset($offset) && isset($limit)) { - $set['limit'] = $limit; - $set['offset'] = $offset; - } - - $alerts = oracle_recode_query ($sql, $set, 'AND', false); - break; - } - - if ($alerts === false) - return array (); - - if ($count !== false) { - return $alerts[0]['count']; - } - else { - return $alerts; - } + WHERE id_agent_module in (%s) %s %s %s', + $selectText, + $subQuery, + $where, + $filter, + $orderbyText + ); + + switch ($config['dbtype']) { + case 'mysql': + $limit_sql = ''; + if (isset($offset) && isset($limit)) { + $limit_sql = " LIMIT $offset, $limit "; + } + + $sql = sprintf('%s %s', $sql, $limit_sql); + $alerts = db_get_all_rows_sql($sql); + break; + + case 'postgresql': + $limit_sql = ''; + if (isset($offset) && isset($limit)) { + $limit_sql = " OFFSET $offset LIMIT $limit "; + } + + $sql = sprintf('%s %s', $sql, $limit_sql); + + $alerts = db_get_all_rows_sql($sql); + + break; + + case 'oracle': + $set = []; + if (isset($offset) && isset($limit)) { + $set['limit'] = $limit; + $set['offset'] = $offset; + } + + $alerts = oracle_recode_query($sql, $set, 'AND', false); + break; + } + + if ($alerts === false) { + return []; + } + + if ($count !== false) { + return $alerts[0]['count']; + } else { + return $alerts; + } } + /** * Get a list of agents. * * By default, it will return all the agents where the user has reading access. - * + * * @param array filter options in an indexed array. See * db_format_array_where_clause_sql() * @param array Fields to get. * @param string Access needed in the agents groups. - * @param array $order The order of agents, by default is upward for field nombre. - * @param bool $return Whether to return array with agents or false, or sql string statement - * + * @param array $order The order of agents, by default is upward for field nombre. + * @param boolean $return Whether to return array with agents or false, or sql string statement + * * @return mixed An array with all alerts defined for an agent or false in case no allowed groups are specified. */ -function agents_get_agents ($filter = false, $fields = false, - $access = 'AR', - $order = array('field' => 'nombre', 'order' => 'ASC'), - $return = false, - $disabled_agent = 0) { - - global $config; - - if (! is_array ($filter)) { - $filter = array (); - } - - if (isset($filter['search'])) { - $search = $filter['search']; - unset($filter['search']); - } - else { - $search = ''; - } - - if (isset($filter['search_custom'])) { - $search_custom = $filter['search_custom']; - unset($filter['search_custom']); - } else { - $search_custom = ''; - } - - if (isset($filter['offset'])) { - $offset = $filter['offset']; - unset($filter['offset']); - } - - if (isset($filter['limit'])) { - $limit = $filter['limit']; - unset($filter['limit']); - } - - $status_sql = ' 1 = 1'; - if (isset($filter['status'])) { - switch ($filter['status']) { - case AGENT_STATUS_NORMAL: - $status_sql = "( +function agents_get_agents( + $filter=false, + $fields=false, + $access='AR', + $order=[ + 'field' => 'nombre', + 'order' => 'ASC', + ], + $return=false, + $disabled_agent=0 +) { + global $config; + + if (! is_array($filter)) { + $filter = []; + } + + if (isset($filter['search'])) { + $search = $filter['search']; + unset($filter['search']); + } else { + $search = ''; + } + + if (isset($filter['search_custom'])) { + $search_custom = $filter['search_custom']; + unset($filter['search_custom']); + } else { + $search_custom = ''; + } + + if (isset($filter['offset'])) { + $offset = $filter['offset']; + unset($filter['offset']); + } + + if (isset($filter['limit'])) { + $limit = $filter['limit']; + unset($filter['limit']); + } + + $status_sql = ' 1 = 1'; + if (isset($filter['status'])) { + switch ($filter['status']) { + case AGENT_STATUS_NORMAL: + $status_sql = '( critical_count = 0 AND warning_count = 0 AND unknown_count = 0 - AND normal_count > 0)"; - break; - case AGENT_STATUS_WARNING: - $status_sql = "( + AND normal_count > 0)'; + break; + + case AGENT_STATUS_WARNING: + $status_sql = '( critical_count = 0 AND warning_count > 0 - AND total_count > 0)"; - break; - case AGENT_STATUS_CRITICAL: - $status_sql = "critical_count > 0"; - break; - case AGENT_STATUS_UNKNOWN: - $status_sql = "( + AND total_count > 0)'; + break; + + case AGENT_STATUS_CRITICAL: + $status_sql = 'critical_count > 0'; + break; + + case AGENT_STATUS_UNKNOWN: + $status_sql = '( critical_count = 0 AND warning_count = 0 - AND unknown_count > 0)"; - break; - case AGENT_STATUS_NOT_NORMAL: - $status_sql = "( + AND unknown_count > 0)'; + break; + + case AGENT_STATUS_NOT_NORMAL: + $status_sql = '( normal_count <> total_count - OR total_count = notinit_count)"; - //The AGENT_STATUS_NOT_NORMAL filter must show all agents that are not in normal status - /*"( - normal_count <> total_count - AND - (normal_count + notinit_count) <> total_count)";*/ - break; - case AGENT_STATUS_NOT_INIT: - $status_sql = "( + OR total_count = notinit_count)'; + // The AGENT_STATUS_NOT_NORMAL filter must show all agents that are not in normal status + /* + "( + normal_count <> total_count + AND + (normal_count + notinit_count) <> total_count)";*/ + break; + + case AGENT_STATUS_NOT_INIT: + $status_sql = '( total_count = 0 - OR total_count = notinit_count)"; - break; - } - unset($filter['status']); - } - - - unset($filter['order']); - - $filter_nogroup = $filter; - - //Get user groups - $groups = array_keys (users_get_groups ($config["id_user"], $access, false)); - - //If no group specified, get all user groups - if (empty ($filter['id_grupo'])) { - $all_groups = true; - $filter['id_grupo'] = $groups; - } - elseif (! is_array ($filter['id_grupo'])) { - $all_groups = false; - //If group is specified but not allowed, return false - if (! in_array ($filter['id_grupo'], $groups)) { - return false; - } - $filter['id_grupo'] = (array) $filter['id_grupo']; //Make an array - } - else { - $all_groups = true; - //Check each group specified to the user groups, remove unwanted groups - foreach ($filter['id_grupo'] as $key => $id_group) { - if (! in_array ($id_group, $groups)) { - unset ($filter['id_grupo'][$key]); - } - } - //If no allowed groups are specified return false - if (count ($filter['id_grupo']) == 0) { - return false; - } - } - $filter['id_group'] = $filter['id_grupo']; - - if (in_array (0, $filter['id_grupo'])) { - unset ($filter['id_grupo']); - unset ($filter['id_group']); - } - - if (!is_array ($fields)) { - $fields = array (); - $fields[0] = "id_agente"; - $fields[1] = "nombre"; - } - - if (isset($order['field'])) { - if(!isset($order['order'])) { - $order['order'] = 'ASC'; - } - if (!isset($order['field2'])) { - $order = 'ORDER BY '.$order['field'] . ' ' . $order['order']; - } - else { - $order = 'ORDER BY '.$order['field'] . ' ' . $order['order'] . ', ' . $order['field2']; - } - } - - //Fix for postgresql - if (empty($filter['id_agente'])) { - unset($filter['id_agente']); - } + OR total_count = notinit_count)'; + break; + } - // Group filter with secondary groups - $where_secondary = ''; - if (isset($filter['id_group']) && isset($filter['id_grupo'])) { - $where_secondary .= db_format_array_where_clause_sql (array( - 'tagent_secondary_group.id_group' => $filter['id_group'], - 'id_grupo' => $filter['id_grupo'] - ) , 'OR', ''); - unset($filter['id_group']); - unset($filter['id_grupo']); - unset($filter_nogroup['id_grupo']); - unset($filter_nogroup['id_group']); - } - // Add the group filter to - $where = db_format_array_where_clause_sql ($filter, 'AND', "(" . $where_secondary . ") AND "); - if ($where == '' && $where_secondary != '') { - $where = $where_secondary; - } - - $where_nogroup = db_format_array_where_clause_sql( - $filter_nogroup, 'AND', ''); - - if ($where_nogroup == '') { - $where_nogroup = '1 = 1'; - } + unset($filter['status']); + } - if ($disabled_agent == 1){ - $disabled = 'disabled = 0'; - } - else{ - $disabled = '1 = 1'; - } - - $extra = false; - - // TODO: CLEAN extra_sql - $sql_extra = ''; - if ($all_groups) { - $where_nogroup = '1 = 1'; - } - - if ($extra) { - $where = sprintf('(%s OR (%s)) AND (%s) AND (%s) %s AND %s', - $sql_extra, $where, $where_nogroup, $status_sql, $search, $disabled); - } - else { - $where = sprintf('%s AND %s AND (%s) %s AND %s %s', - $where, $where_nogroup, $status_sql, $search, $disabled, $search_custom); - } - $sql = sprintf('SELECT DISTINCT %s + unset($filter['order']); + + $filter_nogroup = $filter; + + // Get user groups + $groups = array_keys(users_get_groups($config['id_user'], $access, false)); + + // If no group specified, get all user groups + if (empty($filter['id_grupo'])) { + $all_groups = true; + $filter['id_grupo'] = $groups; + } else if (! is_array($filter['id_grupo'])) { + $all_groups = false; + // If group is specified but not allowed, return false + if (! in_array($filter['id_grupo'], $groups)) { + return false; + } + + $filter['id_grupo'] = (array) $filter['id_grupo']; + // Make an array + } else { + $all_groups = true; + // Check each group specified to the user groups, remove unwanted groups + foreach ($filter['id_grupo'] as $key => $id_group) { + if (! in_array($id_group, $groups)) { + unset($filter['id_grupo'][$key]); + } + } + + // If no allowed groups are specified return false + if (count($filter['id_grupo']) == 0) { + return false; + } + } + + $filter['id_group'] = $filter['id_grupo']; + + if (in_array(0, $filter['id_grupo'])) { + unset($filter['id_grupo']); + unset($filter['id_group']); + } + + if (!is_array($fields)) { + $fields = []; + $fields[0] = 'id_agente'; + $fields[1] = 'nombre'; + } + + if (isset($order['field'])) { + if (!isset($order['order'])) { + $order['order'] = 'ASC'; + } + + if (!isset($order['field2'])) { + $order = 'ORDER BY '.$order['field'].' '.$order['order']; + } else { + $order = 'ORDER BY '.$order['field'].' '.$order['order'].', '.$order['field2']; + } + } + + // Fix for postgresql + if (empty($filter['id_agente'])) { + unset($filter['id_agente']); + } + + // Group filter with secondary groups + $where_secondary = ''; + if (isset($filter['id_group']) && isset($filter['id_grupo'])) { + $where_secondary .= db_format_array_where_clause_sql( + [ + 'tagent_secondary_group.id_group' => $filter['id_group'], + 'id_grupo' => $filter['id_grupo'], + ], + 'OR', + '' + ); + unset($filter['id_group']); + unset($filter['id_grupo']); + unset($filter_nogroup['id_grupo']); + unset($filter_nogroup['id_group']); + } + + // Add the group filter to + $where = db_format_array_where_clause_sql($filter, 'AND', '('.$where_secondary.') AND '); + if ($where == '' && $where_secondary != '') { + $where = $where_secondary; + } + + $where_nogroup = db_format_array_where_clause_sql( + $filter_nogroup, + 'AND', + '' + ); + + if ($where_nogroup == '') { + $where_nogroup = '1 = 1'; + } + + if ($disabled_agent == 1) { + $disabled = 'disabled = 0'; + } else { + $disabled = '1 = 1'; + } + + $extra = false; + + // TODO: CLEAN extra_sql + $sql_extra = ''; + if ($all_groups) { + $where_nogroup = '1 = 1'; + } + + if ($extra) { + $where = sprintf( + '(%s OR (%s)) AND (%s) AND (%s) %s AND %s', + $sql_extra, + $where, + $where_nogroup, + $status_sql, + $search, + $disabled + ); + } else { + $where = sprintf( + '%s AND %s AND (%s) %s AND %s %s', + $where, + $where_nogroup, + $status_sql, + $search, + $disabled, + $search_custom + ); + } + + $sql = sprintf( + 'SELECT DISTINCT %s FROM tagente LEFT JOIN tagent_secondary_group ON tagent_secondary_group.id_agent=tagente.id_agente - WHERE %s %s', implode(',',$fields), $where, $order); + WHERE %s %s', + implode(',', $fields), + $where, + $order + ); - $limit_sql = ''; - if (isset($offset) && isset($limit)) { - $limit_sql = " LIMIT $offset, $limit "; - } - $sql = sprintf("%s %s", $sql, $limit_sql); - if ($return) return $sql; - else $agents = db_get_all_rows_sql($sql); + $limit_sql = ''; + if (isset($offset) && isset($limit)) { + $limit_sql = " LIMIT $offset, $limit "; + } - return $agents; + $sql = sprintf('%s %s', $sql, $limit_sql); + if ($return) { + return $sql; + } else { + $agents = db_get_all_rows_sql($sql); + } + + return $agents; } + /** * Get all the alerts of an agent, simple and combined. * - * @param int $id_agent Agent id + * @param integer $id_agent Agent id * @param string Special filter. Can be: "notfired", "fired" or "disabled". * @param array Extra filter options in an indexed array. See * db_format_array_where_clause_sql() * * @return array An array with all alerts defined for an agent. */ -function agents_get_alerts ($id_agent = false, $filter = false, $options = false) { - $simple_alerts = agents_get_alerts_simple ($id_agent, $filter, $options); - - return array ('simple' => $simple_alerts); +function agents_get_alerts($id_agent=false, $filter=false, $options=false) +{ + $simple_alerts = agents_get_alerts_simple($id_agent, $filter, $options); + + return ['simple' => $simple_alerts]; } + /** * Copy the agents config from one agent to the other * @@ -531,194 +608,229 @@ function agents_get_alerts ($id_agent = false, $filter = false, $options = false * @param array Which modules to copy. * @param array Which alerts to copy. Only will be used if target_modules is empty. * - * @return bool True in case of good, false in case of bad + * @return boolean True in case of good, false in case of bad */ -function agents_process_manage_config ($source_id_agent, $destiny_id_agents, $copy_modules = false, $copy_alerts = false, $target_modules = false, $target_alerts = false) { - global $config; - - if (empty ($source_id_agent)) { - ui_print_error_message(__('No source agent to copy')); - return false; - } - - if (empty ($destiny_id_agents)) { - ui_print_error_message(__('No destiny agent(s) to copy')); - return false; - } - - if ($copy_modules == false) { - $copy_modules = (bool) get_parameter ('copy_modules', $copy_modules); - } - - if ($copy_alerts == false) { - $copy_alerts = (bool) get_parameter ('copy_alerts', $copy_alerts); - } - - if (! $copy_modules && ! $copy_alerts) - return false; - - if (empty ($target_modules)) { - $target_modules = (array) get_parameter ('target_modules', array ()); - } - - if (empty ($target_alerts)) { - $target_alerts = (array) get_parameter ('target_alerts', array ()); - } - - if (empty ($target_modules)) { - if (! $copy_alerts) { - ui_print_error_message(__('No modules have been selected')); - return false; - } - $target_modules = array (); - - foreach ($target_alerts as $id_alert) { - $alert = alerts_get_alert_agent_module ($id_alert); - if ($alert === false) - continue; - /* Check if some alerts which doesn't belong to the agent was given */ - if (modules_get_agentmodule_agent ($alert['id_agent_module']) != $source_id_agent) - continue; - array_push ($target_modules, $alert['id_agent_module']); - } - } - - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - db_process_sql ('SET AUTOCOMMIT = 0'); - db_process_sql ('START TRANSACTION'); - break; - case "oracle": - db_process_sql_begin(); - break; - } - $error = false; - - $repeated_modules = array(); - foreach ($destiny_id_agents as $id_destiny_agent) { - foreach ($target_modules as $id_agent_module) { - - // Check the module name exists in target - $module = modules_get_agentmodule ($id_agent_module); - if ($module === false) - return false; - $modules = agents_get_modules ($id_destiny_agent, false, - array ('nombre' => $module['nombre'], 'disabled' => false)); - - // Keep all modules repeated - if (! empty ($modules)) { - $modules_repeated = array_pop (array_keys ($modules)); - $result = $modules_repeated; - $repeated_modules[] = $modules_repeated; - } - else { - - $result = modules_copy_agent_module_to_agent ($id_agent_module, - $id_destiny_agent); - - if ($result === false) { - $error = true; - break; - } - } - - // Check if all modules are repeated and no alerts are copied, if YES then error - if (empty($target_alerts) and count($repeated_modules) == count($target_modules)) { - $error = true; - break; - } - - $id_destiny_module = $result; - - if (! $copy_alerts) - continue; - - /* If the alerts were given, copy afterwards. Otherwise, all the - alerts for the module will be copied */ - if (! empty ($target_alerts)) { - foreach ($target_alerts as $id_alert) { - $alert = alerts_get_alert_agent_module ($id_alert); - if ($alert === false) - continue; - if ($alert['id_agent_module'] != $id_agent_module) - continue; - $result = alerts_copy_alert_module_to_module ($alert['id'], - $id_destiny_module); - if ($result === false) { - $error = true; - break; - } - } - continue; - } - - $alerts = alerts_get_alerts_agent_module ($id_agent_module, true); - - if ($alerts === false) - continue; - - foreach ($alerts as $alert) { - $result = alerts_copy_alert_module_to_module ($alert['id'], - $id_destiny_module); - if ($result === false) { - $error = true; - break; - } - } - } - if ($error) - break; - } - - if ($error) { - ui_print_error_message( - __('There was an error copying the agent configuration, the copy has been cancelled')); - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - db_process_sql ('ROLLBACK'); - break; - case "oracle": - db_process_sql_rollback(); - break; - } - } - else { - ui_print_success_message(__('Successfully copied')); - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - db_process_sql ('COMMIT'); - break; - case "oracle": - db_process_sql_commit(); - break; - } - } - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - db_process_sql ('SET AUTOCOMMIT = 1'); - break; - } +function agents_process_manage_config($source_id_agent, $destiny_id_agents, $copy_modules=false, $copy_alerts=false, $target_modules=false, $target_alerts=false) +{ + global $config; - if ($error) - return false; - else - return true; + if (empty($source_id_agent)) { + ui_print_error_message(__('No source agent to copy')); + return false; + } + + if (empty($destiny_id_agents)) { + ui_print_error_message(__('No destiny agent(s) to copy')); + return false; + } + + if ($copy_modules == false) { + $copy_modules = (bool) get_parameter('copy_modules', $copy_modules); + } + + if ($copy_alerts == false) { + $copy_alerts = (bool) get_parameter('copy_alerts', $copy_alerts); + } + + if (! $copy_modules && ! $copy_alerts) { + return false; + } + + if (empty($target_modules)) { + $target_modules = (array) get_parameter('target_modules', []); + } + + if (empty($target_alerts)) { + $target_alerts = (array) get_parameter('target_alerts', []); + } + + if (empty($target_modules)) { + if (! $copy_alerts) { + ui_print_error_message(__('No modules have been selected')); + return false; + } + + $target_modules = []; + + foreach ($target_alerts as $id_alert) { + $alert = alerts_get_alert_agent_module($id_alert); + if ($alert === false) { + continue; + } + + // Check if some alerts which doesn't belong to the agent was given + if (modules_get_agentmodule_agent($alert['id_agent_module']) != $source_id_agent) { + continue; + } + + array_push($target_modules, $alert['id_agent_module']); + } + } + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + db_process_sql('SET AUTOCOMMIT = 0'); + db_process_sql('START TRANSACTION'); + break; + + case 'oracle': + db_process_sql_begin(); + break; + } + + $error = false; + + $repeated_modules = []; + foreach ($destiny_id_agents as $id_destiny_agent) { + foreach ($target_modules as $id_agent_module) { + // Check the module name exists in target + $module = modules_get_agentmodule($id_agent_module); + if ($module === false) { + return false; + } + + $modules = agents_get_modules( + $id_destiny_agent, + false, + [ + 'nombre' => $module['nombre'], + 'disabled' => false, + ] + ); + + // Keep all modules repeated + if (! empty($modules)) { + $modules_repeated = array_pop(array_keys($modules)); + $result = $modules_repeated; + $repeated_modules[] = $modules_repeated; + } else { + $result = modules_copy_agent_module_to_agent( + $id_agent_module, + $id_destiny_agent + ); + + if ($result === false) { + $error = true; + break; + } + } + + // Check if all modules are repeated and no alerts are copied, if YES then error + if (empty($target_alerts) and count($repeated_modules) == count($target_modules)) { + $error = true; + break; + } + + $id_destiny_module = $result; + + if (! $copy_alerts) { + continue; + } + + /* + If the alerts were given, copy afterwards. Otherwise, all the + alerts for the module will be copied */ + if (! empty($target_alerts)) { + foreach ($target_alerts as $id_alert) { + $alert = alerts_get_alert_agent_module($id_alert); + if ($alert === false) { + continue; + } + + if ($alert['id_agent_module'] != $id_agent_module) { + continue; + } + + $result = alerts_copy_alert_module_to_module( + $alert['id'], + $id_destiny_module + ); + if ($result === false) { + $error = true; + break; + } + } + + continue; + } + + $alerts = alerts_get_alerts_agent_module($id_agent_module, true); + + if ($alerts === false) { + continue; + } + + foreach ($alerts as $alert) { + $result = alerts_copy_alert_module_to_module( + $alert['id'], + $id_destiny_module + ); + if ($result === false) { + $error = true; + break; + } + } + } + + if ($error) { + break; + } + } + + if ($error) { + ui_print_error_message( + __('There was an error copying the agent configuration, the copy has been cancelled') + ); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + db_process_sql('ROLLBACK'); + break; + + case 'oracle': + db_process_sql_rollback(); + break; + } + } else { + ui_print_success_message(__('Successfully copied')); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + db_process_sql('COMMIT'); + break; + + case 'oracle': + db_process_sql_commit(); + break; + } + } + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + db_process_sql('SET AUTOCOMMIT = 1'); + break; + } + + if ($error) { + return false; + } else { + return true; + } } -function agents_get_next_contact($idAgent, $maxModules = false) { - $agent = db_get_row("tagente", "id_agente", $idAgent); - $last_contact = time_w_fixed_tz($agent["ultimo_contacto"]); - $difference = time() - $last_contact; - - return ($agent["intervalo"] > 0 && $last_contact > 0) - ? round ($difference / ($agent["intervalo"] / 100)) - : 0; + +function agents_get_next_contact($idAgent, $maxModules=false) +{ + $agent = db_get_row('tagente', 'id_agente', $idAgent); + $last_contact = time_w_fixed_tz($agent['ultimo_contacto']); + $difference = (time() - $last_contact); + + return ($agent['intervalo'] > 0 && $last_contact > 0) ? round($difference / ($agent['intervalo'] / 100)) : 0; } + /** * Get all the modules common in various agents. If an empty list is passed it will select all * @@ -746,308 +858,336 @@ function agents_get_next_contact($idAgent, $maxModules = false) { * @return array An array with all modules in the agent. * If multiple rows are selected, they will be in an array */ -function agents_common_modules ($id_agent, $filter = false, $indexed = true, $get_not_init_modules = true) { - $id_agent = safe_int ($id_agent, 1); - - $where = ''; - if (! empty ($id_agent)) { - $where = sprintf (' WHERE delete_pending = 0 AND id_agente IN (%s) +function agents_common_modules($id_agent, $filter=false, $indexed=true, $get_not_init_modules=true) +{ + $id_agent = safe_int($id_agent, 1); + + $where = ''; + if (! empty($id_agent)) { + $where = sprintf( + ' WHERE delete_pending = 0 AND id_agente IN (%s) AND ( SELECT count(nombre) FROM tagente_modulo t2 WHERE delete_pending = 0 AND t1.nombre = t2.nombre - AND id_agente IN (%s)) = (%s)', implode (",", (array) $id_agent), implode (",", (array) $id_agent), count($id_agent)); - } - - if (! empty ($filter)) { - $where .= ' AND '; - if (is_array ($filter)) { - $fields = array (); - foreach ($filter as $field => $value) { - array_push ($fields, $field.'="'.$value.'"'); - } - $where .= implode (' AND ', $fields); - } - else { - $where .= $filter; - } - } - - $sql = sprintf ('SELECT DISTINCT(t1.id_agente_modulo) as id_agente_modulo + AND id_agente IN (%s)) = (%s)', + implode(',', (array) $id_agent), + implode(',', (array) $id_agent), + count($id_agent) + ); + } + + if (! empty($filter)) { + $where .= ' AND '; + if (is_array($filter)) { + $fields = []; + foreach ($filter as $field => $value) { + array_push($fields, $field.'="'.$value.'"'); + } + + $where .= implode(' AND ', $fields); + } else { + $where .= $filter; + } + } + + $sql = sprintf( + 'SELECT DISTINCT(t1.id_agente_modulo) as id_agente_modulo FROM tagente_modulo t1, talert_template_modules t2 %s ORDER BY nombre', - $where); - $result = db_get_all_rows_sql ($sql); - - if (empty ($result)) { - return array (); - } - - if (! $indexed) - return $result; - - $modules = array (); - foreach ($result as $module) { - if ($get_not_init_modules || modules_get_agentmodule_is_init($module['id_agente_modulo'])) { - $modules[$module['id_agente_modulo']] = $module['id_agente_modulo']; - } - } - return $modules; + $where + ); + $result = db_get_all_rows_sql($sql); + + if (empty($result)) { + return []; + } + + if (! $indexed) { + return $result; + } + + $modules = []; + foreach ($result as $module) { + if ($get_not_init_modules || modules_get_agentmodule_is_init($module['id_agente_modulo'])) { + $modules[$module['id_agente_modulo']] = $module['id_agente_modulo']; + } + } + + return $modules; } + /** * Get all the agents within a group(s). * - * @param mixed $id_group Group id or an array of ID's. If nothing is selected, it will select all - * @param mixed $search to add Default: False. If True will return disabled agents as well. If searching array (disabled => (bool), string => (string)) - * @param string $case Which case to return the agentname as (lower, upper, none) - * @param boolean $noACL jump the ACL test. - * @param boolean $childGroups The flag to get agents in the child group of group parent passed. By default false. - * @param boolean $serialized Only in metaconsole. Return the key as . By default false. - * @param string $separator Only in metaconsole. Separator for the serialized data. By default |. - * @param bool $add_alert_bulk_op //TODO documentation - * @param bool $force_serialized. If the agent has not id_server (typically in node) put 0 as . + * @param mixed $id_group Group id or an array of ID's. If nothing is selected, it will select all + * @param mixed $search to add Default: False. If True will return disabled agents as well. If searching array (disabled => (bool), string => (string)) + * @param string $case Which case to return the agentname as (lower, upper, none) + * @param boolean $noACL jump the ACL test. + * @param boolean $childGroups The flag to get agents in the child group of group parent passed. By default false. + * @param boolean $serialized Only in metaconsole. Return the key as . By default false. + * @param string $separator Only in metaconsole. Separator for the serialized data. By default |. + * @param boolean $add_alert_bulk_op //TODO documentation + * @param boolean $force_serialized. If the agent has not id_server (typically in node) put 0 as . * * @return array An array with all agents in the group or an empty array */ -function agents_get_group_agents ( - $id_group = 0, - $search = false, - $case = "lower", - $noACL = false, - $childGroups = false, - $serialized = false, - $separator = '|', - $add_alert_bulk_op = false, - $force_serialized = false +function agents_get_group_agents( + $id_group=0, + $search=false, + $case='lower', + $noACL=false, + $childGroups=false, + $serialized=false, + $separator='|', + $add_alert_bulk_op=false, + $force_serialized=false ) { + global $config; - global $config; - - $filter = array(); - - if (!$noACL) { - $id_group = $id_group == 0 - ? array_keys(users_get_groups(false, "AR", false)) - : groups_safe_acl($config["id_user"], $id_group, "AR"); - if (empty ($id_group)) { - //An empty array means the user doesn't have access - return array (); - } - } - - if ($childGroups) { - if (is_array($id_group)) { - foreach ($id_group as $parent) { - $id_group = array_merge($id_group, - groups_get_id_recursive($parent, true)); - } - } - else { - $id_group = groups_get_id_recursive($id_group, true); - } - - if (!$noACL) { - $id_group = array_keys( - users_get_groups(false, "AR", true, false, (array)$id_group)); - } - } + $filter = []; - // Search for primary and secondary groups - if (!empty($id_group)) { - $filter[] = '(' . db_format_array_where_clause_sql( - array( - 'id_group' => $id_group, - 'id_grupo' => $id_group - ), - 'OR' - ) . ')'; - } + // check available groups for target user only if asking for 'All' group + if (!$noACL && $id_group == 0) { + $id_group = $id_group == 0 ? array_keys(users_get_groups(false, 'AR', false)) : groups_safe_acl($config['id_user'], $id_group, 'AR'); + if (empty($id_group)) { + // An empty array means the user doesn't have access + return []; + } + } - if ($search === true) { - //No added search. Show both disabled and non-disabled - } - else if (is_array ($search)) { - if (!$search['all_agents']) { - $filter['disabled'] = 0; - if (isset ($search["disabled"])) { - $filter['disabled'] = (int) $search["disabled"]; - - unset ($search["disabled"]); - } - } - - if (isset ($search["string"])) { - $string = io_safe_input ($search["string"]); - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $filter[] = "(nombre COLLATE utf8_general_ci LIKE '%$string%' OR direccion LIKE '%$string%')"; - break; - case "oracle": - $filter[] = "(UPPER(nombre) LIKE UPPER('%$string%') OR direccion LIKE upper('%$string%'))"; - break; - } - - unset ($search["string"]); - } - - if (isset ($search["name"])) { - $name = io_safe_input ($search["name"]); - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $filter[] = "nombre COLLATE utf8_general_ci LIKE '$name'"; - break; - case "oracle": - $filter[] = "UPPER(nombre) LIKE UPPER('$name')"; - break; - } - - unset ($search["name"]); - } - - if (isset ($search["alias"])) { - $name = io_safe_input ($search["alias"]); - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $filter[] = "alias COLLATE utf8_general_ci LIKE '$name'"; - break; - case "oracle": - $filter[] = "UPPER(alias) LIKE UPPER('$name')"; - break; - } - - unset ($search["alias"]); - } - - if (isset($search['id_os'])) { - $filter['id_os'] = $search['id_os']; - } - - if (isset($search['status'])) { - switch ($search['status']) { - case AGENT_STATUS_NORMAL: - $filter[] = "( + if ($childGroups) { + if (is_array($id_group)) { + foreach ($id_group as $parent) { + $id_group = array_merge( + $id_group, + groups_get_id_recursive($parent, true) + ); + } + } else { + $id_group = groups_get_id_recursive($id_group, true); + } + + // check available groups for target user only if asking for 'All' group + if (!$noACL && $id_group == 0) { + $id_group = array_keys( + users_get_groups(false, 'AR', true, false, (array) $id_group) + ); + } + } + + // Search for primary and secondary groups + if (!empty($id_group)) { + $filter[] = '('.db_format_array_where_clause_sql( + [ + 'id_group' => $id_group, + 'id_grupo' => $id_group, + ], + 'OR' + ).')'; + } + + if ($search === true) { + // No added search. Show both disabled and non-disabled + } else if (is_array($search)) { + if (!$search['all_agents']) { + $filter['disabled'] = 0; + if (isset($search['disabled'])) { + $filter['disabled'] = (int) $search['disabled']; + + unset($search['disabled']); + } + } + + if (isset($search['string'])) { + $string = io_safe_input($search['string']); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $filter[] = "(nombre COLLATE utf8_general_ci LIKE '%$string%' OR direccion LIKE '%$string%')"; + break; + + case 'oracle': + $filter[] = "(UPPER(nombre) LIKE UPPER('%$string%') OR direccion LIKE upper('%$string%'))"; + break; + } + + unset($search['string']); + } + + if (isset($search['name'])) { + $name = io_safe_input($search['name']); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $filter[] = "nombre COLLATE utf8_general_ci LIKE '$name'"; + break; + + case 'oracle': + $filter[] = "UPPER(nombre) LIKE UPPER('$name')"; + break; + } + + unset($search['name']); + } + + if (isset($search['alias'])) { + $name = io_safe_input($search['alias']); + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $filter[] = "alias COLLATE utf8_general_ci LIKE '$name'"; + break; + + case 'oracle': + $filter[] = "UPPER(alias) LIKE UPPER('$name')"; + break; + } + + unset($search['alias']); + } + + if (isset($search['id_os'])) { + $filter['id_os'] = $search['id_os']; + } + + if (isset($search['status'])) { + switch ($search['status']) { + case AGENT_STATUS_NORMAL: + $filter[] = '( critical_count = 0 AND warning_count = 0 AND unknown_count = 0 - AND normal_count > 0)"; - break; - case AGENT_STATUS_WARNING: - $filter[] = "( + AND normal_count > 0)'; + break; + + case AGENT_STATUS_WARNING: + $filter[] = '( critical_count = 0 AND warning_count > 0 - AND total_count > 0)"; - break; - case AGENT_STATUS_CRITICAL: - $filter[] = "critical_count > 0"; - break; - case AGENT_STATUS_UNKNOWN: - $filter[] = "( + AND total_count > 0)'; + break; + + case AGENT_STATUS_CRITICAL: + $filter[] = 'critical_count > 0'; + break; + + case AGENT_STATUS_UNKNOWN: + $filter[] = '( critical_count = 0 AND warning_count = 0 - AND unknown_count > 0)"; - break; - case AGENT_STATUS_NOT_NORMAL: - $filter[] = "( + AND unknown_count > 0)'; + break; + + case AGENT_STATUS_NOT_NORMAL: + $filter[] = '( critical_count > 0 OR warning_count > 0 OR unknown_count > 0 OR total_count = 0 - OR total_count = notinit_count)"; - break; - case AGENT_STATUS_NOT_INIT: - $filter[] = "( + OR total_count = notinit_count)'; + break; + + case AGENT_STATUS_NOT_INIT: + $filter[] = '( total_count = 0 - OR total_count = notinit_count)"; - break; - } - unset($search['status']); - } - if ($add_alert_bulk_op) { - if (isset($search['id_agente'])) { - $filter['id_agente'] = $search['id_agente']; - } - } + OR total_count = notinit_count)'; + break; + } - if (is_metaconsole() && isset($search['id_server'])) { - $filter['id_tmetaconsole_setup'] = $search['id_server']; - - if ($filter['id_tmetaconsole_setup'] == 0) { - // All nodes - unset ($filter['id_tmetaconsole_setup']); - } - - unset ($search["id_server"]); - } - if (!$add_alert_bulk_op) { - // Add the rest of the filter from the search array - foreach ($search as $key => $value) { - $filter[] = $value; - } - } - } - else { - $filter['disabled'] = 0; - } - - $filter['order'] = 'alias'; - - if (is_metaconsole()) { - $table_name = 'tmetaconsole_agent ta LEFT JOIN tmetaconsole_agent_secondary_group tasg ON ta.id_agente = tasg.id_agent'; + unset($search['status']); + } - $fields = array( - 'ta.id_tagente AS id_agente', - 'alias', - 'ta.id_tmetaconsole_setup AS id_server' - ); - } - else { - $table_name = 'tagente LEFT JOIN tagent_secondary_group ON id_agente=id_agent'; + if ($add_alert_bulk_op) { + if (isset($search['id_agente'])) { + $filter['id_agente'] = $search['id_agente']; + } + } - $fields = array( - 'id_agente', - 'alias' - ); - } + if (is_metaconsole() && isset($search['id_server'])) { + $filter['id_tmetaconsole_setup'] = $search['id_server']; - $result = db_get_all_rows_filter($table_name, $filter, $fields); + if ($filter['id_tmetaconsole_setup'] == 0) { + // All nodes + unset($filter['id_tmetaconsole_setup']); + } - if ($result === false) - return array (); //Return an empty array - - $agents = array (); - foreach ($result as $row) { - if (!isset($row["id_agente"]) || !isset($row["alias"])) - continue; - if ($serialized && isset($row["id_server"])) { - $key = $row["id_server"] . $separator . $row["id_agente"]; - } elseif ($force_serialized) { - $key = "0" . $separator . $row["id_agente"]; - } else { - $key = $row["id_agente"]; - } + unset($search['id_server']); + } - switch ($case) { - case "lower": - $value = mb_strtolower ($row["alias"], "UTF-8"); - break; - case "upper": - $value = mb_strtoupper ($row["alias"], "UTF-8"); - break; - default: - $value = $row["alias"]; - break; - } - - $agents[$key] = $value; - } - return ($agents); + if (!$add_alert_bulk_op) { + // Add the rest of the filter from the search array + foreach ($search as $key => $value) { + $filter[] = $value; + } + } + } else { + $filter['disabled'] = 0; + } + + $filter['order'] = 'alias'; + + if (is_metaconsole()) { + $table_name = 'tmetaconsole_agent ta LEFT JOIN tmetaconsole_agent_secondary_group tasg ON ta.id_agente = tasg.id_agent'; + + $fields = [ + 'ta.id_tagente AS id_agente', + 'alias', + 'ta.id_tmetaconsole_setup AS id_server', + ]; + } else { + $table_name = 'tagente LEFT JOIN tagent_secondary_group ON id_agente=id_agent'; + + $fields = [ + 'id_agente', + 'alias', + ]; + } + + $result = db_get_all_rows_filter($table_name, $filter, $fields); + + if ($result === false) { + return []; + // Return an empty array + } + + $agents = []; + foreach ($result as $row) { + if (!isset($row['id_agente']) || !isset($row['alias'])) { + continue; + } + + if ($serialized && isset($row['id_server'])) { + $key = $row['id_server'].$separator.$row['id_agente']; + } else if ($force_serialized) { + $key = '0'.$separator.$row['id_agente']; + } else { + $key = $row['id_agente']; + } + + switch ($case) { + case 'lower': + $value = mb_strtolower($row['alias'], 'UTF-8'); + break; + + case 'upper': + $value = mb_strtoupper($row['alias'], 'UTF-8'); + break; + + default: + $value = $row['alias']; + break; + } + + $agents[$key] = $value; + } + + return ($agents); } + /** * Get all the modules in an agent. If an empty list is passed it will select all * @@ -1075,154 +1215,170 @@ function agents_get_group_agents ( * @return array An array with all modules in the agent. * If multiple rows are selected, they will be in an array */ -function agents_get_modules ($id_agent = null, $details = false, - $filter = false, $indexed = true, $get_not_init_modules = true, - $force_tags = false) { - - global $config; - - $userGroups = users_get_groups($config['id_user'], 'AR', false); - if (empty($userGroups)) { - return array(); - } - $id_groups = array_keys($userGroups); - $id_groups_sql = implode(',', $id_groups); - - // ================================================================= - // When there is not a agent id. Get a agents of groups that the - // user can read the agents. - // ================================================================= - if ($id_agent === null) { - - $sql = "SELECT id_agente - FROM tagente - WHERE id_grupo IN (" . implode(',', $id_groups) . ")"; - $id_agent = db_get_all_rows_sql($sql); - - if ($id_agent == false) { - $id_agent = array(); - } - - $temp = array(); - foreach ($id_agent as $item) { - $temp[] = $item['id_agente']; - } - $id_agent = $temp; - } - - // ================================================================= - // Fixed strange values. Only array of ids or id as int - // ================================================================= - if (!is_array($id_agent)) { - $id_agent = safe_int ($id_agent, 1); - } +function agents_get_modules( + $id_agent=null, + $details=false, + $filter=false, + $indexed=true, + $get_not_init_modules=true, + $force_tags=false +) { + global $config; - $where = "1 = 1 "; - // Groups ACL only when user is not empty - if (!users_can_manage_group_all("AR")) { - $where = "( + $userGroups = users_get_groups($config['id_user'], 'AR', false); + if (empty($userGroups)) { + return []; + } + + $id_groups = array_keys($userGroups); + $id_groups_sql = implode(',', $id_groups); + + // ================================================================= + // When there is not a agent id. Get a agents of groups that the + // user can read the agents. + // ================================================================= + if ($id_agent === null) { + $sql = 'SELECT id_agente + FROM tagente + WHERE id_grupo IN ('.implode(',', $id_groups).')'; + $id_agent = db_get_all_rows_sql($sql); + + if ($id_agent == false) { + $id_agent = []; + } + + $temp = []; + foreach ($id_agent as $item) { + $temp[] = $item['id_agente']; + } + + $id_agent = $temp; + } + + // ================================================================= + // Fixed strange values. Only array of ids or id as int + // ================================================================= + if (!is_array($id_agent)) { + $id_agent = safe_int($id_agent, 1); + } + + $where = '1 = 1 '; + // Groups ACL only when user is not empty + if (!users_can_manage_group_all('AR')) { + $where = "( tagente.id_grupo IN ($id_groups_sql) OR tasg.id_group IN ($id_groups_sql) )"; - } + } - if (! empty ($id_agent)) { - $id_agent_sql = implode (",", (array)$id_agent); - $where .= " AND tagente.id_agente IN ($id_agent_sql) "; - } + if (! empty($id_agent)) { + $id_agent_sql = implode(',', (array) $id_agent); + $where .= " AND tagente.id_agente IN ($id_agent_sql) "; + } - if (! empty ($filter)) { - $where .= ' AND '; - if (is_array ($filter)) { - $fields = array (); + if (! empty($filter)) { + $where .= ' AND '; + if (is_array($filter)) { + $fields = []; - //---------------------------------------------------------- - // Code for filters as array of arrays - // for example: - // $filter = array( - // 'id_modulo' => 2, // networkmap type - // 'id_tipo_modulo' => array( - // '<>2', // != generic_proc - // '<>6', // != remote_icmp_proc - // '<>9')); - //---------------------------------------------------------- - $list_filter = array(); - foreach ($filter as $field => $value) { - if (is_array($value)) { - foreach ($value as $v) { - $list_filter[] = array('field' => $field, - 'value' => $v); - } - } - else { - $list_filter[] = array('field' => $field, - 'value' => $value); - } - } - //---------------------------------------------------------- - foreach ($list_filter as $item) { - $field = $item['field']; - $value = $item['value']; + // ---------------------------------------------------------- + // Code for filters as array of arrays + // for example: + // $filter = array( + // 'id_modulo' => 2, // networkmap type + // 'id_tipo_modulo' => array( + // '<>2', // != generic_proc + // '<>6', // != remote_icmp_proc + // '<>9')); + // ---------------------------------------------------------- + $list_filter = []; + foreach ($filter as $field => $value) { + if (is_array($value)) { + foreach ($value as $v) { + $list_filter[] = [ + 'field' => $field, + 'value' => $v, + ]; + } + } else { + $list_filter[] = [ + 'field' => $field, + 'value' => $value, + ]; + } + } - //Check <> operator - $operatorDistin = false; - if (strlen($value) > 2) { - if ($value[0] . $value[1] == '<>') { - $operatorDistin = true; - } - } + // ---------------------------------------------------------- + foreach ($list_filter as $item) { + $field = $item['field']; + $value = $item['value']; - if ($value[0] == '%') { - array_push ($fields, - $field . ' LIKE "' . $value . '"'); - } - else if ($operatorDistin) { - array_push($fields, $field.' <> ' . substr($value, 2)); - } - else if (substr($value, -1) == '%') { - array_push ($fields, $field.' LIKE "'.$value.'"'); - } - else if (strncmp($value, '666=666', 7) == 0) { - array_push ($fields, ' '.$value); - } - else if (preg_match('/\bin\b/i',$field)) { - array_push ($fields, $field.' '.$value); - } - else { - array_push ($fields, 'tagente_modulo.' . $field.' = "'.$value.'"'); - } - } - $where .= implode (' AND ', $fields); - } - else { - $where .= $filter; - } - } + // Check <> operator + $operatorDistin = false; + if (strlen($value) > 2) { + if ($value[0].$value[1] == '<>') { + $operatorDistin = true; + } + } - $stored_details = $details; - if (empty ($details)) { - $details = "tagente_modulo.nombre"; - $stored_details = "nombre"; - } - else { - $details = (array)$details; - $details = io_safe_input ($details); - $details = array_map(function ($a) { - return preg_match('/tagente_modulo./i', $a) ? $a : 'tagente_modulo.' . $a; - },$details - ); - } + if ($value[0] == '%') { + array_push( + $fields, + $field.' LIKE "'.$value.'"' + ); + } else if ($operatorDistin) { + array_push($fields, $field.' <> '.substr($value, 2)); + } else if (substr($value, -1) == '%') { + array_push($fields, $field.' LIKE "'.$value.'"'); + } else if (strncmp($value, '666=666', 7) == 0) { + array_push($fields, ' '.$value); + } else if (preg_match('/\bin\b/i', $field)) { + array_push($fields, $field.' '.$value); + } else { + array_push($fields, 'tagente_modulo.'.$field.' = "'.$value.'"'); + } + } - $sql_tags_join = ""; - if (tags_has_user_acl_tags($config['id_user']) || $force_tags){ - $where_tags = tags_get_acl_tags($config['id_user'], $id_groups, 'AR', - 'module_condition', 'AND', 'tagente_modulo', false, array(), - true); - $where .= "\n\n" . $where_tags; - $sql_tags_join = "INNER JOIN ttag_module - ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo"; - } + $where .= implode(' AND ', $fields); + } else { + $where .= $filter; + } + } - $sql = sprintf ('SELECT %s%s + $stored_details = $details; + if (empty($details)) { + $details = 'tagente_modulo.nombre'; + $stored_details = 'nombre'; + } else { + $details = (array) $details; + $details = io_safe_input($details); + $details = array_map( + function ($a) { + return preg_match('/tagente_modulo./i', $a) ? $a : 'tagente_modulo.'.$a; + }, + $details + ); + } + + $sql_tags_join = ''; + if (tags_has_user_acl_tags($config['id_user']) || $force_tags) { + $where_tags = tags_get_acl_tags( + $config['id_user'], + $id_groups, + 'AR', + 'module_condition', + 'AND', + 'tagente_modulo', + false, + [], + true + ); + $where .= "\n\n".$where_tags; + $sql_tags_join = 'INNER JOIN ttag_module + ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo'; + } + + $sql = sprintf( + 'SELECT %s%s FROM tagente_modulo %s INNER JOIN tagente @@ -1231,172 +1387,207 @@ function agents_get_modules ($id_agent = null, $details = false, ON tagente.id_agente = tasg.id_agent WHERE tagente_modulo.delete_pending = 0 AND %s - GROUP BY tagente_modulo.id_agente_modulo - ORDER BY tagente_modulo.nombre', - ($details != 'tagente_modulo.*' && $indexed) ? 'tagente_modulo.id_agente_modulo,' : '', - io_safe_output(implode (",", (array) $details)), - $sql_tags_join, - $where); - $result = db_get_all_rows_sql ($sql); + GROUP BY 1 + ORDER BY 1', + ($details != 'tagente_modulo.*' && $indexed) ? 'tagente_modulo.id_agente_modulo,' : '', + io_safe_output(implode(',', (array) $details)), + $sql_tags_join, + $where + ); + $result = db_get_all_rows_sql($sql); - if (empty ($result)) { - return array (); - } + if (empty($result)) { + return []; + } - if (! $indexed) - return $result; + if (! $indexed) { + return $result; + } - $modules = array (); - foreach ($result as $module) { - if ($get_not_init_modules || modules_get_agentmodule_is_init($module['id_agente_modulo'])) { - if (is_array ($stored_details) || $stored_details == '*') { - //Just stack the information in array by ID - $modules[$module['id_agente_modulo']] = $module; - } - else { - $modules[$module['id_agente_modulo']] = $module[$stored_details]; - } - } - } - return $modules; + $modules = []; + foreach ($result as $module) { + if ($get_not_init_modules || modules_get_agentmodule_is_init($module['id_agente_modulo'])) { + if (is_array($stored_details) || $stored_details == '*') { + // Just stack the information in array by ID + $modules[$module['id_agente_modulo']] = $module; + } else { + $modules[$module['id_agente_modulo']] = $module[$stored_details]; + } + } + } + + return $modules; } + /** * Get agent id from a module id that it has. * - * @param int $id_module Id module is list modules this agent. + * @param integer $id_module Id module is list modules this agent. * - * @return int Id from the agent of the given id module. + * @return integer Id from the agent of the given id module. */ -function agents_get_module_id ($id_agente_modulo) { - return (int) db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_agente_modulo); +function agents_get_module_id($id_agente_modulo) +{ + return (int) db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_agente_modulo); } + /** * Get agent id from an agent name. * - * @param string $agent_name Agent name to get its id. + * @param string $agent_name Agent name to get its id. * @param boolean $io_safe_input If it is true transform to safe string, by default false. * - * @return int Id from the agent of the given name. + * @return integer Id from the agent of the given name. */ -function agents_get_agent_id ($agent_name, $io_safe_input = false) { - if ($io_safe_input) { - $agent_name = io_safe_input($agent_name); - } - return (int) db_get_value ('id_agente', 'tagente', 'nombre', $agent_name); +function agents_get_agent_id($agent_name, $io_safe_input=false) +{ + if ($io_safe_input) { + $agent_name = io_safe_input($agent_name); + } + + return (int) db_get_value('id_agente', 'tagente', 'nombre', $agent_name); } + /** * Get name of an agent. * - * @param int $id_agent Agent id. - * @param string $case Case (upper, lower, none) + * @param integer $id_agent Agent id. + * @param string $case Case (upper, lower, none) * * @return string Name of the given agent. */ -function agents_get_name ($id_agent, $case = "none") { - $agent = (string) db_get_value ('nombre', - 'tagente', 'id_agente', (int) $id_agent); - - // Version 3.0 has enforced case sensitive agent names - // so we always should show real case names. - switch ($case) { - case "upper": - return mb_strtoupper ($agent,"UTF-8"); - break; - case "lower": - return mb_strtolower ($agent,"UTF-8"); - break; - case "none": - default: - return ($agent); - break; - } +function agents_get_name($id_agent, $case='none') +{ + $agent = (string) db_get_value( + 'nombre', + 'tagente', + 'id_agente', + (int) $id_agent + ); + + // Version 3.0 has enforced case sensitive agent names + // so we always should show real case names. + switch ($case) { + case 'upper': + return mb_strtoupper($agent, 'UTF-8'); + + break; + case 'lower': + return mb_strtolower($agent, 'UTF-8'); + + break; + case 'none': + default: + return ($agent); + + break; + } } + /** * Get alias of an agent (cached function). * - * @param int $id_agent Agent id. - * @param string $case Case (upper, lower, none) + * @param integer $id_agent Agent id. + * @param string $case Case (upper, lower, none) * * @return string Alias of the given agent. */ -function agents_get_alias ($id_agent, $case = 'none') { - global $config; - // Prepare cache - static $cache = array(); - if (empty($case)) $case = 'none'; +function agents_get_alias($id_agent, $case='none') +{ + global $config; + // Prepare cache + static $cache = []; + if (empty($case)) { + $case = 'none'; + } - // Check cache - if (isset($cache[$case][$id_agent])) return $cache[$case][$id_agent]; + // Check cache + if (isset($cache[$case][$id_agent])) { + return $cache[$case][$id_agent]; + } - if($config['dbconnection_cache'] == null && is_metaconsole()){ - $alias = (string) db_get_value ('alias', 'tmetaconsole_agent', 'id_tagente', (int) $id_agent); - } else { - $alias = (string) db_get_value ('alias', 'tagente', 'id_agente', (int) $id_agent); - } + if ($config['dbconnection_cache'] == null && is_metaconsole()) { + $alias = (string) db_get_value('alias', 'tmetaconsole_agent', 'id_tagente', (int) $id_agent); + } else { + $alias = (string) db_get_value('alias', 'tagente', 'id_agente', (int) $id_agent); + } - switch ($case) { - case 'upper': - $alias = mb_strtoupper($alias, 'UTF-8'); - break; - case 'lower': - $alias = mb_strtolower($alias, 'UTF-8'); - break; - } + switch ($case) { + case 'upper': + $alias = mb_strtoupper($alias, 'UTF-8'); + break; - $cache[$case][$id_agent] = $alias; - return $alias; + case 'lower': + $alias = mb_strtolower($alias, 'UTF-8'); + break; + } + + $cache[$case][$id_agent] = $alias; + return $alias; } -function agents_get_alias_by_name ($name, $case = 'none') { - $alias = (string) db_get_value ('alias', 'tagente', 'nombre', $name); - - switch ($case) { - case 'upper': - return mb_strtoupper($alias, 'UTF-8'); - case 'lower': - return mb_strtolower($alias, 'UTF-8'); - case 'none': - default: - return ($alias); - } + +function agents_get_alias_by_name($name, $case='none') +{ + $alias = (string) db_get_value('alias', 'tagente', 'nombre', $name); + + switch ($case) { + case 'upper': + return mb_strtoupper($alias, 'UTF-8'); + + case 'lower': + return mb_strtolower($alias, 'UTF-8'); + + case 'none': + default: + return ($alias); + } } + /** * Check if an agent has alerts fired. * * @param int Agent id. * - * @return bool True if the agent has fired alerts. + * @return boolean True if the agent has fired alerts. */ -function agents_check_alert_fired ($id_agent) { - $sql = sprintf ("SELECT COUNT(*) +function agents_check_alert_fired($id_agent) +{ + $sql = sprintf( + 'SELECT COUNT(*) FROM talert_template_modules, tagente_modulo WHERE talert_template_modules.id_agent_module = tagente_modulo.id_agente_modulo - AND times_fired > 0 AND id_agente = %d", - $id_agent); - - $value = db_get_sql ($sql); - if ($value > 0) - return true; - - return false; + AND times_fired > 0 AND id_agente = %d', + $id_agent + ); + + $value = db_get_sql($sql); + if ($value > 0) { + return true; + } + + return false; } + /** * Get the interval of an agent. * * @param int Agent id. * - * @return int The interval value of a given agent + * @return integer The interval value of a given agent */ -function agents_get_interval ($id_agent) { - return (int) db_get_value ('intervalo', 'tagente', 'id_agente', $id_agent); +function agents_get_interval($id_agent) +{ + return (int) db_get_value('intervalo', 'tagente', 'id_agente', $id_agent); } + /** * Get all data of agent. * @@ -1404,128 +1595,158 @@ function agents_get_interval ($id_agent) { * * @return The interval value and status of last contact */ -function agents_get_interval_status ($agent) { - - $return = ''; - $last_time = time_w_fixed_tz($agent["ultimo_contacto"]); - $now = time (); - $diferencia = $now - $last_time; - $time = ui_print_timestamp ($last_time, true, array('style' => 'font-size:6.5pt')); - $min_interval = modules_get_agentmodule_mininterval_no_async($agent['id_agente']); - $return = $time; - if ($diferencia > ($min_interval["min_interval"] * 2) && $min_interval['num_interval'] > 0) - $return = ''.$time.''; - - return $return; +function agents_get_interval_status($agent) +{ + $return = ''; + $last_time = time_w_fixed_tz($agent['ultimo_contacto']); + $now = time(); + $diferencia = ($now - $last_time); + $time = ui_print_timestamp($last_time, true, ['style' => 'font-size:6.5pt']); + $min_interval = modules_get_agentmodule_mininterval_no_async($agent['id_agente']); + $return = $time; + if ($diferencia > ($min_interval['min_interval'] * 2) && $min_interval['num_interval'] > 0) { + $return = ''.$time.''; + } + + return $return; } + /** * Get the operating system of an agent. * * @param int Agent id. * - * @return int The interval value of a given agent + * @return integer The interval value of a given agent */ -function agents_get_os ($id_agent) { - return (int) db_get_value ('id_os', 'tagente', 'id_agente', $id_agent); +function agents_get_os($id_agent) +{ + return (int) db_get_value('id_os', 'tagente', 'id_agente', $id_agent); } + /** * Get the flag value of an agent module. * * @param int Agent module id. * - * @return bool The flag value of an agent module. + * @return boolean The flag value of an agent module. */ -function agents_give_agentmodule_flag ($id_agent_module) { - return db_get_value ('flag', 'tagente_modulo', 'id_agente_modulo', $id_agent_module); +function agents_give_agentmodule_flag($id_agent_module) +{ + return db_get_value('flag', 'tagente_modulo', 'id_agente_modulo', $id_agent_module); } + /** * Assign an IP address to an agent. * * @param int Agent id * @param string IP address to assign */ -function agents_add_address ($id_agent, $ip_address) { - global $config; - - // Check if already is attached to agent - switch ($config["dbtype"]) { - case "mysql": - $sql = sprintf ("SELECT COUNT(`ip`) +function agents_add_address($id_agent, $ip_address) +{ + global $config; + + // Check if already is attached to agent + switch ($config['dbtype']) { + case 'mysql': + $sql = sprintf( + "SELECT COUNT(`ip`) FROM taddress_agent, taddress WHERE taddress_agent.id_a = taddress.id_a - AND ip = '%s' AND id_agent = %d",$ip_address,$id_agent); - break; - case "postgresql": - case "oracle": - $sql = sprintf ("SELECT COUNT(ip) + AND ip = '%s' AND id_agent = %d", + $ip_address, + $id_agent + ); + break; + + case 'postgresql': + case 'oracle': + $sql = sprintf( + "SELECT COUNT(ip) FROM taddress_agent, taddress WHERE taddress_agent.id_a = taddress.id_a - AND ip = '%s' AND id_agent = %d", $ip_address, $id_agent); - break; - } - $current_address = db_get_sql ($sql); - if ($current_address > 0) - return; - - // Look for a record with this IP Address - $id_address = (int) db_get_value ('id_a', 'taddress', 'ip', $ip_address); - - if ($id_address === 0) { - // Create IP address in tadress table - $id_address = db_process_sql_insert('taddress', array('ip' => $ip_address)); - } - - // Add address to agent - $values = array('id_a' => $id_address, 'id_agent' => $id_agent); - db_process_sql_insert('taddress_agent', $values); + AND ip = '%s' AND id_agent = %d", + $ip_address, + $id_agent + ); + break; + } + + $current_address = db_get_sql($sql); + if ($current_address > 0) { + return; + } + + // Look for a record with this IP Address + $id_address = (int) db_get_value('id_a', 'taddress', 'ip', $ip_address); + + if ($id_address === 0) { + // Create IP address in tadress table + $id_address = db_process_sql_insert('taddress', ['ip' => $ip_address]); + } + + // Add address to agent + $values = [ + 'id_a' => $id_address, + 'id_agent' => $id_agent, + ]; + db_process_sql_insert('taddress_agent', $values); } + /** * Unassign an IP address from an agent. * * @param int Agent id * @param string IP address to unassign */ -function agents_delete_address ($id_agent, $ip_address) { - global $config; - - $sql = sprintf ("SELECT id_ag +function agents_delete_address($id_agent, $ip_address) +{ + global $config; + + $sql = sprintf( + "SELECT id_ag FROM taddress_agent, taddress WHERE taddress_agent.id_a = taddress.id_a AND ip = '%s' - AND id_agent = %d", $ip_address, $id_agent); - $id_ag = db_get_sql ($sql); - if ($id_ag !== false) { - db_process_sql_delete('taddress_agent', array('id_ag' => $id_ag)); - } - - $agent_name = agents_get_name($id_agent, ""); - db_pandora_audit("Agent management", - "Deleted IP $ip_address from agent '$agent_name'"); - - // Need to change main address? - if (agents_get_address($id_agent) == $ip_address) { - $new_ips = agents_get_addresses ($id_agent); - if (empty($new_ips)) { - $new_ip = ''; - } - else { - $new_ip = reset($new_ips); - } - - // Change main address in agent to first one in the list - - db_process_sql_update('tagente', - array('direccion' => $new_ip), - array('id_agente' => $id_agent)); - - return $new_ip; - } + AND id_agent = %d", + $ip_address, + $id_agent + ); + $id_ag = db_get_sql($sql); + if ($id_ag !== false) { + db_process_sql_delete('taddress_agent', ['id_ag' => $id_ag]); + } + + $agent_name = agents_get_name($id_agent, ''); + db_pandora_audit( + 'Agent management', + "Deleted IP $ip_address from agent '$agent_name'" + ); + + // Need to change main address? + if (agents_get_address($id_agent) == $ip_address) { + $new_ips = agents_get_addresses($id_agent); + if (empty($new_ips)) { + $new_ip = ''; + } else { + $new_ip = reset($new_ips); + } + + // Change main address in agent to first one in the list + db_process_sql_update( + 'tagente', + ['direccion' => $new_ip], + ['id_agente' => $id_agent] + ); + + return $new_ip; + } } + /** * Get address of an agent. * @@ -1533,10 +1754,12 @@ function agents_delete_address ($id_agent, $ip_address) { * * @return string The address of the given agent */ -function agents_get_address ($id_agent) { - return (string) db_get_value ('direccion', 'tagente', 'id_agente', (int) $id_agent); +function agents_get_address($id_agent) +{ + return (string) db_get_value('direccion', 'tagente', 'id_agente', (int) $id_agent); } + /** * Get description of an agent. * @@ -1544,10 +1767,12 @@ function agents_get_address ($id_agent) { * * @return string The address of the given agent */ -function agents_get_description ($id_agent) { - return (string) db_get_value ('comentarios', 'tagente', 'id_agente', (int) $id_agent); +function agents_get_description($id_agent) +{ + return (string) db_get_value('comentarios', 'tagente', 'id_agente', (int) $id_agent); } + /** * Get the agent that matches an IP address * @@ -1555,30 +1780,39 @@ function agents_get_description ($id_agent) { * * @return mixed The agent that has the IP address given. False if none were found. */ -function agents_get_agent_with_ip ($ip_address) { - global $config; - - switch ($config["dbtype"]) { - case "mysql": - $sql = sprintf ('SELECT tagente.* +function agents_get_agent_with_ip($ip_address) +{ + global $config; + + switch ($config['dbtype']) { + case 'mysql': + $sql = sprintf( + 'SELECT tagente.* FROM tagente, taddress, taddress_agent WHERE tagente.id_agente = taddress_agent.id_agent AND taddress_agent.id_a = taddress.id_a - AND ip = "%s"', $ip_address); - break; - case "postgresql": - case "oracle": - $sql = sprintf ('SELECT tagente.* + AND ip = "%s"', + $ip_address + ); + break; + + case 'postgresql': + case 'oracle': + $sql = sprintf( + 'SELECT tagente.* FROM tagente, taddress, taddress_agent WHERE tagente.id_agente = taddress_agent.id_agent AND taddress_agent.id_a = taddress.id_a - AND ip = \'%s\'', $ip_address); - break; - } - - return db_get_row_sql ($sql); + AND ip = \'%s\'', + $ip_address + ); + break; + } + + return db_get_row_sql($sql); } + /** * Get all IP addresses of an agent * @@ -1586,397 +1820,478 @@ function agents_get_agent_with_ip ($ip_address) { * * @return array Array with the IP address of the given agent or an empty array. */ -function agents_get_addresses ($id_agent) { - if (is_array($id_agent)) { - $sql = sprintf ("SELECT ip +function agents_get_addresses($id_agent) +{ + if (is_array($id_agent)) { + $sql = sprintf( + 'SELECT ip FROM taddress_agent, taddress WHERE taddress_agent.id_a = taddress.id_a - AND id_agent IN (%s)", implode(",", $id_agent)); - } - else { - $sql = sprintf ("SELECT ip + AND id_agent IN (%s)', + implode(',', $id_agent) + ); + } else { + $sql = sprintf( + 'SELECT ip FROM taddress_agent, taddress WHERE taddress_agent.id_a = taddress.id_a - AND id_agent = %d", $id_agent); - } - - $ips = db_get_all_rows_sql ($sql); - - if ($ips === false) { - $ips = array (); - } - - $ret_arr = array (); - foreach ($ips as $row) { - $ret_arr[$row["ip"]] = $row["ip"]; - } - - return $ret_arr; + AND id_agent = %d', + $id_agent + ); + } + + $ips = db_get_all_rows_sql($sql); + + if ($ips === false) { + $ips = []; + } + + $ret_arr = []; + foreach ($ips as $row) { + $ret_arr[$row['ip']] = $row['ip']; + } + + return $ret_arr; } + /** * Get the worst status of all modules of a given agent from the counts. * * @param array agent to check. * - * @return int Worst status of an agent for all of its modules. + * @return integer Worst status of an agent for all of its modules. * return -1 if the data are wrong */ -function agents_get_status_from_counts($agent) { - - - // Check if in the data there are all the necessary values - if (!isset($agent['normal_count']) && - !isset($agent['warning_count']) && - !isset($agent['critical_count']) && - !isset($agent['unknown_count']) && - !isset($agent['notinit_count']) && - !isset($agent['total_count'])) { - return -1; - } - - # Juanma (05/05/2014) Fix: This status is not init! 0 modules or all not init - if ($agent['notinit_count'] == $agent['total_count']) { - return AGENT_MODULE_STATUS_NOT_INIT; - } - if ($agent['critical_count'] > 0) { - return AGENT_MODULE_STATUS_CRITICAL_BAD; - } - else if ($agent['warning_count'] > 0) { - return AGENT_MODULE_STATUS_WARNING; - } - else if ($agent['unknown_count'] > 0) { - return AGENT_MODULE_STATUS_UNKNOWN; - } - else if ($agent['normal_count'] == $agent['total_count']) { - return AGENT_MODULE_STATUS_NORMAL; - } - else if ($agent['normal_count'] + $agent['notinit_count'] == $agent['total_count']) { - return AGENT_MODULE_STATUS_NORMAL; - } - //~ else if($agent['notinit_count'] == $agent['total_count']) { - //~ return AGENT_MODULE_STATUS_NORMAL; - //~ } - - return -1; +function agents_get_status_from_counts($agent) +{ + // Check if in the data there are all the necessary values + if (!isset($agent['normal_count']) + && !isset($agent['warning_count']) + && !isset($agent['critical_count']) + && !isset($agent['unknown_count']) + && !isset($agent['notinit_count']) + && !isset($agent['total_count']) + ) { + return -1; + } + + // Juanma (05/05/2014) Fix: This status is not init! 0 modules or all not init + if ($agent['notinit_count'] == $agent['total_count']) { + return AGENT_MODULE_STATUS_NOT_INIT; + } + + if ($agent['critical_count'] > 0) { + return AGENT_MODULE_STATUS_CRITICAL_BAD; + } else if ($agent['warning_count'] > 0) { + return AGENT_MODULE_STATUS_WARNING; + } else if ($agent['unknown_count'] > 0) { + return AGENT_MODULE_STATUS_UNKNOWN; + } else if ($agent['normal_count'] == $agent['total_count']) { + return AGENT_MODULE_STATUS_NORMAL; + } else if (($agent['normal_count'] + $agent['notinit_count']) == $agent['total_count']) { + return AGENT_MODULE_STATUS_NORMAL; + } + + // ~ else if($agent['notinit_count'] == $agent['total_count']) { + // ~ return AGENT_MODULE_STATUS_NORMAL; + // ~ } + return -1; } + /** * Get the worst status of all modules of a given agent. * * @param int Id agent to check. - * @param bool Whether the call check ACLs or not + * @param bool Whether the call check ACLs or not * - * @return int Worst status of an agent for all of its modules. + * @return integer Worst status of an agent for all of its modules. * The value -1 is returned in case the agent has exceed its interval. */ -function agents_get_status($id_agent = 0, $noACLs = false) { - global $config; - - if (!$noACLs) { - $modules = agents_get_modules ($id_agent, 'id_agente_modulo', - array('disabled' => 0), true, false); - } - else { - $filter_modules['id_agente'] = $id_agent; - $filter_modules['disabled'] = 0; - $filter_modules['delete_pending'] = 0; - // Get all non disabled modules of the agent - $all_modules = db_get_all_rows_filter('tagente_modulo', - $filter_modules, 'id_agente_modulo'); - if ($all_modules === false) $all_modules = array(); +function agents_get_status($id_agent=0, $noACLs=false) +{ + global $config; - $result_modules = array(); - // Skip non init modules - foreach ($all_modules as $module) { - if (modules_get_agentmodule_is_init($module['id_agente_modulo'])) { - $modules[] = $module['id_agente_modulo']; - } - } - } - - if (!isset($modules) || empty($modules) || count($modules) == 0) { - return AGENT_MODULE_STATUS_NOT_INIT; - } - - $modules_status = array(); - $modules_async = 0; - foreach ($modules as $module) { - $modules_status[] = modules_get_agentmodule_status($module); - - $module_type = modules_get_agentmodule_type($module); - if (($module_type >= 21 && $module_type <= 23) || - $module_type == 100) { - $modules_async++; - } - } - - // If all the modules are asynchronous or keep alive, the group cannot be unknown - if ($modules_async < count($modules)) { - $time = get_system_time (); - - switch ($config["dbtype"]) { - case "mysql": - $status = db_get_value_filter ('COUNT(*)', - 'tagente', - array ('id_agente' => (int) $id_agent, - 'UNIX_TIMESTAMP(ultimo_contacto) + intervalo * 2 > '.$time)); - break; - case "postgresql": - $status = db_get_value_filter ('COUNT(*)', - 'tagente', - array ('id_agente' => (int) $id_agent, - 'ceil(date_part(\'epoch\', ultimo_contacto)) + intervalo * 2 > '.$time)); - break; - case "oracle": - $status = db_get_value_filter ('count(*)', - 'tagente', - array ('id_agente' => (int) $id_agent, - 'ceil((to_date(ultimo_contacto, \'YYYY-MM-DD HH24:MI:SS\') - to_date(\'19700101000000\',\'YYYYMMDDHH24MISS\')) * (' . SECONDS_1DAY . ')) > ' . $time)); - break; - } - - if (! $status) - return AGENT_MODULE_STATUS_UNKNOWN; - } - - // Checking if any module has alert fired - if (is_int(array_search(AGENT_MODULE_STATUS_CRITICAL_ALERT, $modules_status))) { - return AGENT_MODULE_STATUS_CRITICAL_ALERT; - } - // Checking if any module has alert fired - elseif (is_int(array_search(AGENT_MODULE_STATUS_WARNING_ALERT, $modules_status))) { - return AGENT_MODULE_STATUS_WARNING_ALERT; - } - // Checking if any module has critical status - elseif (is_int(array_search(AGENT_MODULE_STATUS_CRITICAL_BAD, $modules_status))) { - return AGENT_MODULE_STATUS_CRITICAL_BAD; - } - // Checking if any module has critical status - elseif (is_int(array_search(AGENT_MODULE_STATUS_NORMAL_ALERT, $modules_status))) { - return AGENT_STATUS_ALERT_FIRED; - } - // Checking if any module has warning status - elseif (is_int(array_search(AGENT_MODULE_STATUS_WARNING,$modules_status))) { - return AGENT_MODULE_STATUS_WARNING; - } - // Checking if any module has unknown status - elseif (is_int(array_search(AGENT_MODULE_STATUS_UNKNOWN, $modules_status))) { - return AGENT_MODULE_STATUS_UNKNOWN; - } - else { - return AGENT_MODULE_STATUS_NORMAL; - } + if (!$noACLs) { + $modules = agents_get_modules( + $id_agent, + 'id_agente_modulo', + ['disabled' => 0], + true, + false + ); + } else { + $filter_modules['id_agente'] = $id_agent; + $filter_modules['disabled'] = 0; + $filter_modules['delete_pending'] = 0; + // Get all non disabled modules of the agent + $all_modules = db_get_all_rows_filter( + 'tagente_modulo', + $filter_modules, + 'id_agente_modulo' + ); + if ($all_modules === false) { + $all_modules = []; + } + + $result_modules = []; + // Skip non init modules + foreach ($all_modules as $module) { + if (modules_get_agentmodule_is_init($module['id_agente_modulo'])) { + $modules[] = $module['id_agente_modulo']; + } + } + } + + if (!isset($modules) || empty($modules) || count($modules) == 0) { + return AGENT_MODULE_STATUS_NOT_INIT; + } + + $modules_status = []; + $modules_async = 0; + foreach ($modules as $module) { + $modules_status[] = modules_get_agentmodule_status($module); + + $module_type = modules_get_agentmodule_type($module); + if (($module_type >= 21 && $module_type <= 23) + || $module_type == 100 + ) { + $modules_async++; + } + } + + // If all the modules are asynchronous or keep alive, the group cannot be unknown + if ($modules_async < count($modules)) { + $time = get_system_time(); + + switch ($config['dbtype']) { + case 'mysql': + $status = db_get_value_filter( + 'COUNT(*)', + 'tagente', + [ + 'id_agente' => (int) $id_agent, + 'UNIX_TIMESTAMP(ultimo_contacto) + intervalo * 2 > '.$time + ] + ); + break; + + case 'postgresql': + $status = db_get_value_filter( + 'COUNT(*)', + 'tagente', + [ + 'id_agente' => (int) $id_agent, + 'ceil(date_part(\'epoch\', ultimo_contacto)) + intervalo * 2 > '.$time + ] + ); + break; + + case 'oracle': + $status = db_get_value_filter( + 'count(*)', + 'tagente', + [ + 'id_agente' => (int) $id_agent, + 'ceil((to_date(ultimo_contacto, \'YYYY-MM-DD HH24:MI:SS\') - to_date(\'19700101000000\',\'YYYYMMDDHH24MISS\')) * ('.SECONDS_1DAY.')) > '.$time + ] + ); + break; + } + + if (! $status) { + return AGENT_MODULE_STATUS_UNKNOWN; + } + } + + // Checking if any module has alert fired + if (is_int(array_search(AGENT_MODULE_STATUS_CRITICAL_ALERT, $modules_status))) { + return AGENT_MODULE_STATUS_CRITICAL_ALERT; + } + // Checking if any module has alert fired + else if (is_int(array_search(AGENT_MODULE_STATUS_WARNING_ALERT, $modules_status))) { + return AGENT_MODULE_STATUS_WARNING_ALERT; + } + // Checking if any module has critical status + else if (is_int(array_search(AGENT_MODULE_STATUS_CRITICAL_BAD, $modules_status))) { + return AGENT_MODULE_STATUS_CRITICAL_BAD; + } + // Checking if any module has critical status + else if (is_int(array_search(AGENT_MODULE_STATUS_NORMAL_ALERT, $modules_status))) { + return AGENT_STATUS_ALERT_FIRED; + } + // Checking if any module has warning status + else if (is_int(array_search(AGENT_MODULE_STATUS_WARNING, $modules_status))) { + return AGENT_MODULE_STATUS_WARNING; + } + // Checking if any module has unknown status + else if (is_int(array_search(AGENT_MODULE_STATUS_UNKNOWN, $modules_status))) { + return AGENT_MODULE_STATUS_UNKNOWN; + } else { + return AGENT_MODULE_STATUS_NORMAL; + } } + /** * Delete an agent from the database. * * @param mixed An array of agents ids or a single integer id to be erased * @param bool Disable the ACL checking, for default false. * - * @return bool False if error, true if success. + * @return boolean False if error, true if success. */ -function agents_delete_agent ($id_agents, $disableACL = false) { - global $config; - - $error = false; - - //Convert single values to an array - if (! is_array ($id_agents)) - $id_agents = (array) $id_agents; - - foreach ($id_agents as $id_agent) { - $id_agent = (int) $id_agent; //Cast as integer - if ($id_agent < 1) - continue; - - $agent_name = agents_get_name($id_agent, ""); - $agent_alias = io_safe_output(agents_get_alias($id_agent)); - - /* Check for deletion permissions */ - $all_groups = agents_get_all_groups_agent ($id_agent); - if ((! check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) && !$disableACL) { - return false; - } - - //A variable where we store that long subquery thing for - //modules - $where_modules = "ANY(SELECT id_agente_modulo FROM tagente_modulo WHERE id_agente = ".$id_agent.")"; - - //IP address - $sql = sprintf ("SELECT id_ag +function agents_delete_agent($id_agents, $disableACL=false) +{ + global $config; + + $error = false; + + // Convert single values to an array + if (! is_array($id_agents)) { + $id_agents = (array) $id_agents; + } + + foreach ($id_agents as $id_agent) { + $id_agent = (int) $id_agent; + // Cast as integer + if ($id_agent < 1) { + continue; + } + + $agent_name = agents_get_name($id_agent, ''); + $agent_alias = io_safe_output(agents_get_alias($id_agent)); + + // Check for deletion permissions + $all_groups = agents_get_all_groups_agent($id_agent); + if ((! check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) && !$disableACL) { + return false; + } + + // A variable where we store that long subquery thing for + // modules + $where_modules = 'ANY(SELECT id_agente_modulo FROM tagente_modulo WHERE id_agente = '.$id_agent.')'; + + // IP address + $sql = sprintf( + 'SELECT id_ag FROM taddress_agent, taddress WHERE taddress_agent.id_a = taddress.id_a - AND id_agent = %d", - $id_agent); - $addresses = db_get_all_rows_sql ($sql); - - if ($addresses === false) { - $addresses = array (); - } - foreach ($addresses as $address) { - db_process_delete_temp ("taddress_agent", - "id_ag", $address["id_ag"]); - } - - // We cannot delete tagente_datos and tagente_datos_string here - // because it's a huge ammount of time. tagente_module has a special - // field to mark for delete each module of agent deleted and in - // daily maintance process, all data for that modules are deleted - - //Alert - db_process_delete_temp ("talert_template_modules", - "id_agent_module", $where_modules, true); - - //Events (up/down monitors) - // Dont delete here, could be very time-exausting, let the daily script - // delete them after XXX days - // db_process_delete_temp ("tevento", "id_agente", $id_agent); - - //Graphs, layouts, reports & networkmapenterprise - db_process_delete_temp ("tgraph_source", - "id_agent_module", $where_modules, true); - db_process_delete_temp ("tlayout_data", - "id_agente_modulo", $where_modules, true); - db_process_delete_temp ("treport_content", - "id_agent_module", $where_modules, true); - if (enterprise_installed()) { - $nodes = db_get_all_rows_filter( - "titem", - array("source_data" => $id_agent, "type" => 0)); - if (empty($nodes)) { - $nodes = array(); - } - - foreach ($nodes as $node) { - db_process_delete_temp ("tnetworkmap_ent_rel_nodes", - "parent", $node['id']); - db_process_delete_temp ("tnetworkmap_ent_rel_nodes", - "child", $node['id']); - } - - db_process_delete_temp ("titem", - "source_data", $id_agent); - } - - //Planned Downtime - db_process_delete_temp ("tplanned_downtime_agents", "id_agent", - $id_agent); - - //The status of the module - db_process_delete_temp ("tagente_estado", "id_agente", $id_agent); - - //The actual modules, don't put anything based on - // DONT Delete this, just mark for deletion - // db_process_delete_temp ("tagente_modulo", "id_agente", $id_agent); - - db_process_sql_update ('tagente_modulo', - array ('delete_pending' => 1, 'disabled' => 1, 'nombre' => 'pendingdelete'), - 'id_agente = '. $id_agent); - - // Access entries - // Dont delete here, this records are deleted in daily script - // db_process_delete_temp ("tagent_access", "id_agent", $id_agent); - - // Delete agent policies - enterprise_include_once('include/functions_policies.php'); - enterprise_hook('policies_delete_agent', array($id_agent)); - - // Delete agent in networkmap enterprise - if (enterprise_installed()) { - enterprise_include_once("include/functions_pandora_networkmap.php"); - networkmap_delete_nodes_by_agent(array($id_agent)); - } - - // tagente_datos_inc - // Dont delete here, this records are deleted later, in database script - // db_process_delete_temp ("tagente_datos_inc", "id_agente_modulo", $where_modules, true); - - // Delete remote configuration - if (enterprise_installed()) { - if (isset ($config["remote_config"])) { - enterprise_include_once('include/functions_config_agents.php'); - if (enterprise_hook('config_agents_has_remote_configuration', array($id_agent))) { - $agent_name = agents_get_name($id_agent); - $agent_name = io_safe_output($agent_name); - $agent_alias = io_safe_output(agents_get_alias($id_agent)); - $agent_md5 = md5 ($agent_name, false); - - // Agent remote configuration editor - $file_name = $config["remote_config"] . "/conf/" . $agent_md5 . ".conf"; - - $error = !@unlink ($file_name); - - if (!$error) { - $file_name = $config["remote_config"] . "/md5/" . $agent_md5 . ".md5"; - $error = !@unlink ($file_name); - } - - if ($error) { - db_pandora_audit( "Agent management", - "Error: Deleted agent $agent_alias, the error is in the delete conf or md5."); - } - } - } - } - - //And at long last, the agent - db_process_delete_temp ("tagente", "id_agente", $id_agent); - - db_process_sql ("delete from ttag_module where id_agente_modulo in (select id_agente_modulo from tagente_modulo where id_agente = ".$id_agent.")"); - - db_pandora_audit( "Agent management", - "Deleted agent $agent_alias"); - - // Delete the agent from the metaconsole cache - enterprise_include_once('include/functions_agents.php'); - enterprise_hook('agent_delete_from_cache', array($id_agent)); + AND id_agent = %d', + $id_agent + ); + $addresses = db_get_all_rows_sql($sql); - /* Break the loop on error */ - if ($error) - break; - } - - - - if ($error) { - return false; - } - else { - return true; - } + if ($addresses === false) { + $addresses = []; + } + + foreach ($addresses as $address) { + db_process_delete_temp( + 'taddress_agent', + 'id_ag', + $address['id_ag'] + ); + } + + // We cannot delete tagente_datos and tagente_datos_string here + // because it's a huge ammount of time. tagente_module has a special + // field to mark for delete each module of agent deleted and in + // daily maintance process, all data for that modules are deleted + // Alert + db_process_delete_temp( + 'talert_template_modules', + 'id_agent_module', + $where_modules, + true + ); + + // Events (up/down monitors) + // Dont delete here, could be very time-exausting, let the daily script + // delete them after XXX days + // db_process_delete_temp ("tevento", "id_agente", $id_agent); + // Graphs, layouts, reports & networkmapenterprise + db_process_delete_temp( + 'tgraph_source', + 'id_agent_module', + $where_modules, + true + ); + db_process_delete_temp( + 'tlayout_data', + 'id_agente_modulo', + $where_modules, + true + ); + db_process_delete_temp( + 'treport_content', + 'id_agent_module', + $where_modules, + true + ); + if (enterprise_installed()) { + $nodes = db_get_all_rows_filter( + 'titem', + [ + 'source_data' => $id_agent, + 'type' => 0, + ] + ); + if (empty($nodes)) { + $nodes = []; + } + + foreach ($nodes as $node) { + db_process_delete_temp( + 'tnetworkmap_ent_rel_nodes', + 'parent', + $node['id'] + ); + db_process_delete_temp( + 'tnetworkmap_ent_rel_nodes', + 'child', + $node['id'] + ); + } + + db_process_delete_temp( + 'titem', + 'source_data', + $id_agent + ); + } + + // Planned Downtime + db_process_delete_temp( + 'tplanned_downtime_agents', + 'id_agent', + $id_agent + ); + + // The status of the module + db_process_delete_temp('tagente_estado', 'id_agente', $id_agent); + + // The actual modules, don't put anything based on + // DONT Delete this, just mark for deletion + // db_process_delete_temp ("tagente_modulo", "id_agente", $id_agent); + db_process_sql_update( + 'tagente_modulo', + [ + 'delete_pending' => 1, + 'disabled' => 1, + 'nombre' => 'pendingdelete', + ], + 'id_agente = '.$id_agent + ); + + // Access entries + // Dont delete here, this records are deleted in daily script + // db_process_delete_temp ("tagent_access", "id_agent", $id_agent); + // Delete agent policies + enterprise_include_once('include/functions_policies.php'); + enterprise_hook('policies_delete_agent', [$id_agent]); + + // Delete agent in networkmap enterprise + if (enterprise_installed()) { + enterprise_include_once('include/functions_pandora_networkmap.php'); + networkmap_delete_nodes_by_agent([$id_agent]); + } + + // tagente_datos_inc + // Dont delete here, this records are deleted later, in database script + // db_process_delete_temp ("tagente_datos_inc", "id_agente_modulo", $where_modules, true); + // Delete remote configuration + if (enterprise_installed()) { + if (isset($config['remote_config'])) { + enterprise_include_once('include/functions_config_agents.php'); + if (enterprise_hook('config_agents_has_remote_configuration', [$id_agent])) { + $agent_name = agents_get_name($id_agent); + $agent_name = io_safe_output($agent_name); + $agent_alias = io_safe_output(agents_get_alias($id_agent)); + $agent_md5 = md5($agent_name, false); + + // Agent remote configuration editor + $file_name = $config['remote_config'].'/conf/'.$agent_md5.'.conf'; + + $error = !@unlink($file_name); + + if (!$error) { + $file_name = $config['remote_config'].'/md5/'.$agent_md5.'.md5'; + $error = !@unlink($file_name); + } + + if ($error) { + db_pandora_audit( + 'Agent management', + "Error: Deleted agent $agent_alias, the error is in the delete conf or md5." + ); + } + } + } + } + + // And at long last, the agent + db_process_delete_temp('tagente', 'id_agente', $id_agent); + + db_process_sql('delete from ttag_module where id_agente_modulo in (select id_agente_modulo from tagente_modulo where id_agente = '.$id_agent.')'); + + db_pandora_audit( + 'Agent management', + "Deleted agent $agent_alias" + ); + + // Delete the agent from the metaconsole cache + enterprise_include_once('include/functions_agents.php'); + enterprise_hook('agent_delete_from_cache', [$id_agent]); + + // Break the loop on error + if ($error) { + break; + } + } + + if ($error) { + return false; + } else { + return true; + } } + /** * This function gets the agent group for a given agent module * * @param int The agent module id * - * @return int The group id + * @return integer The group id */ -function agents_get_agentmodule_group ($id_module) { - $agent = (int) modules_get_agentmodule_agent ((int) $id_module); - return (int) agents_get_agent_group ($agent); +function agents_get_agentmodule_group($id_module) +{ + $agent = (int) modules_get_agentmodule_agent((int) $id_module); + return (int) agents_get_agent_group($agent); } + /** * This function gets the group for a given agent * * @param int The agent id * @param bool True to use the metaconsole tables * - * @return int The group id + * @return integer The group id */ -function agents_get_agent_group ($id_agent, $force_meta = false) { - return (int) db_get_value ( - 'id_grupo', - $force_meta ? "tmetaconsole_agent" : "tagente", - 'id_agente', - (int) $id_agent - ); +function agents_get_agent_group($id_agent, $force_meta=false) +{ + return (int) db_get_value( + 'id_grupo', + $force_meta ? 'tmetaconsole_agent' : 'tagente', + 'id_agente', + (int) $id_agent + ); } + /** * This function gets the count of incidents attached to the agent * @@ -1984,15 +2299,21 @@ function agents_get_agent_group ($id_agent, $force_meta = false) { * * @return mixed The incidents attached or false */ -function agents_get_count_incidents ($id_agent) { - if (empty($id_agent)) { - return false; - } - - return db_get_value('count(*)', 'tincidencia', 'id_agent', - $id_agent); +function agents_get_count_incidents($id_agent) +{ + if (empty($id_agent)) { + return false; + } + + return db_get_value( + 'count(*)', + 'tincidencia', + 'id_agent', + $id_agent + ); } + /** * Get critical monitors by using the status code in modules. * @@ -2001,55 +2322,65 @@ function agents_get_count_incidents ($id_agent) { * * @return mixed The incidents attached or false */ -function agents_monitor_critical ($id_agent, $filter="") { - - if ($filter) { - $filter = " AND ".$filter; - } - - return db_get_sql ("SELECT critical_count +function agents_monitor_critical($id_agent, $filter='') +{ + if ($filter) { + $filter = ' AND '.$filter; + } + + return db_get_sql( + "SELECT critical_count FROM tagente - WHERE id_agente = $id_agent" . $filter); + WHERE id_agente = $id_agent".$filter + ); } + // Get warning monitors by using the status code in modules. +function agents_monitor_warning($id_agent, $filter='') +{ + if ($filter) { + $filter = ' AND '.$filter; + } -function agents_monitor_warning ($id_agent, $filter="") { - - if ($filter) { - $filter = " AND ".$filter; - } - - return db_get_sql ("SELECT warning_count + return db_get_sql( + "SELECT warning_count FROM tagente - WHERE id_agente = $id_agent" . $filter); + WHERE id_agente = $id_agent".$filter + ); } + // Get unknown monitors by using the status code in modules. +function agents_monitor_unknown($id_agent, $filter='') +{ + if ($filter) { + $filter = ' AND '.$filter; + } -function agents_monitor_unknown ($id_agent, $filter="") { - - if ($filter) { - $filter = " AND ".$filter; - } - - return db_get_sql ("SELECT unknown_count + return db_get_sql( + "SELECT unknown_count FROM tagente - WHERE id_agente = $id_agent" . $filter); + WHERE id_agente = $id_agent".$filter + ); } + // Get ok monitors by using the status code in modules. -function agents_monitor_ok ($id_agent, $filter="") { - - if ($filter) { - $filter = " AND ".$filter; - } - - return db_get_sql ("SELECT normal_count +function agents_monitor_ok($id_agent, $filter='') +{ + if ($filter) { + $filter = ' AND '.$filter; + } + + return db_get_sql( + "SELECT normal_count FROM tagente - WHERE id_agente = $id_agent" . $filter); + WHERE id_agente = $id_agent".$filter + ); } + /** * Get all monitors disabled of an specific agent. * @@ -2058,20 +2389,23 @@ function agents_monitor_ok ($id_agent, $filter="") { * * @return mixed Total module count or false */ -function agents_monitor_disabled ($id_agent, $filter="") { - - if ($filter) { - $filter = " AND ".$filter; - } - - return db_get_sql(" +function agents_monitor_disabled($id_agent, $filter='') +{ + if ($filter) { + $filter = ' AND '.$filter; + } + + return db_get_sql( + " SELECT COUNT( DISTINCT tagente_modulo.id_agente_modulo) FROM tagente, tagente_modulo WHERE tagente_modulo.id_agente = tagente.id_agente AND tagente_modulo.disabled = 1 - AND tagente.id_agente = $id_agent".$filter); + AND tagente.id_agente = $id_agent".$filter + ); } + /** * Get all monitors notinit of an specific agent. * @@ -2080,17 +2414,20 @@ function agents_monitor_disabled ($id_agent, $filter="") { * * @return mixed Total module count or false */ -function agents_monitor_notinit ($id_agent, $filter="") { - - if (!empty($filter)) { - $filter = " AND ".$filter; - } - - return db_get_sql ("SELECT notinit_count +function agents_monitor_notinit($id_agent, $filter='') +{ + if (!empty($filter)) { + $filter = ' AND '.$filter; + } + + return db_get_sql( + "SELECT notinit_count FROM tagente - WHERE id_agente = $id_agent" . $filter); + WHERE id_agente = $id_agent".$filter + ); } + /** * Get all monitors of an specific agent. * @@ -2100,198 +2437,269 @@ function agents_monitor_notinit ($id_agent, $filter="") { * * @return mixed Total module count or false */ -function agents_monitor_total ($id_agent, $filter = '', $disabled = false) { - - if ($filter) { - $filter = " AND ".$filter; - } - - $sql = "SELECT COUNT( DISTINCT tagente_modulo.id_agente_modulo) +function agents_monitor_total($id_agent, $filter='', $disabled=false) +{ + if ($filter) { + $filter = ' AND '.$filter; + } + + $sql = "SELECT COUNT( DISTINCT tagente_modulo.id_agente_modulo) FROM tagente_estado, tagente, tagente_modulo WHERE tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo AND tagente_estado.id_agente = tagente.id_agente AND tagente.id_agente = $id_agent".$filter; - - if (!$disabled) - $sql .= " AND tagente.disabled = 0 AND tagente_modulo.disabled = 0"; - - return db_get_sql ($sql); + + if (!$disabled) { + $sql .= ' AND tagente.disabled = 0 AND tagente_modulo.disabled = 0'; + } + + return db_get_sql($sql); } -//Returns the alert image to display tree view -function agents_tree_view_alert_img ($alert_fired) { - - if ($alert_fired) { - return ui_print_status_image (STATUS_ALERT_FIRED, __('Alert fired'), true); - } - else { - return ui_print_status_image (STATUS_ALERT_NOT_FIRED, __('Alert not fired'), true); - } +// Returns the alert image to display tree view +function agents_tree_view_alert_img($alert_fired) +{ + if ($alert_fired) { + return ui_print_status_image(STATUS_ALERT_FIRED, __('Alert fired'), true); + } else { + return ui_print_status_image(STATUS_ALERT_NOT_FIRED, __('Alert not fired'), true); + } } -//Returns the alert ball image to display tree view -function agents_tree_view_alert_img_ball ($alert_fired) { - - if ($alert_fired) { - return ui_print_status_image (STATUS_ALERT_FIRED_BALL, __('Alert fired'), true); - } - else { - return ui_print_status_image (STATUS_ALERT_NOT_FIRED_BALL, __('Alert not fired'), true); - } +// Returns the alert ball image to display tree view +function agents_tree_view_alert_img_ball($alert_fired) +{ + if ($alert_fired) { + return ui_print_status_image(STATUS_ALERT_FIRED_BALL, __('Alert fired'), true); + } else { + return ui_print_status_image(STATUS_ALERT_NOT_FIRED_BALL, __('Alert not fired'), true); + } } -//Returns the status image to display tree view -function agents_tree_view_status_img ($critical, $warning, $unknown, $total, $notinit) { - if ($total == 0 || $total == $notinit) { - return ui_print_status_image (STATUS_AGENT_NO_MONITORS, - __('No Monitors'), true); - } - if ($critical > 0) { - return ui_print_status_image (STATUS_AGENT_CRITICAL, - __('At least one module in CRITICAL status'), true); - } - else if ($warning > 0) { - return ui_print_status_image (STATUS_AGENT_WARNING, - __('At least one module in WARNING status'), true); - } - else if ($unknown > 0) { - return ui_print_status_image (STATUS_AGENT_DOWN, - __('At least one module is in UKNOWN status'), true); - } - else { - return ui_print_status_image (STATUS_AGENT_OK, - __('All Monitors OK'), true); - } +// Returns the status image to display tree view +function agents_tree_view_status_img($critical, $warning, $unknown, $total, $notinit) +{ + if ($total == 0 || $total == $notinit) { + return ui_print_status_image( + STATUS_AGENT_NO_MONITORS, + __('No Monitors'), + true + ); + } + + if ($critical > 0) { + return ui_print_status_image( + STATUS_AGENT_CRITICAL, + __('At least one module in CRITICAL status'), + true + ); + } else if ($warning > 0) { + return ui_print_status_image( + STATUS_AGENT_WARNING, + __('At least one module in WARNING status'), + true + ); + } else if ($unknown > 0) { + return ui_print_status_image( + STATUS_AGENT_DOWN, + __('At least one module is in UKNOWN status'), + true + ); + } else { + return ui_print_status_image( + STATUS_AGENT_OK, + __('All Monitors OK'), + true + ); + } } -//Returns the status ball image to display tree view -function agents_tree_view_status_img_ball ($critical, $warning, $unknown, $total, $notinit) { - if ($total == 0 || $total == $notinit) { - return ui_print_status_image (STATUS_AGENT_NO_MONITORS_BALL, - __('No Monitors'), true); - } - if ($critical > 0) { - return ui_print_status_image (STATUS_AGENT_CRITICAL_BALL, - __('At least one module in CRITICAL status'), true); - } - else if ($warning > 0) { - return ui_print_status_image (STATUS_AGENT_WARNING_BALL, - __('At least one module in WARNING status'), true); - } - else if ($unknown > 0) { - return ui_print_status_image (STATUS_AGENT_DOWN_BALL, - __('At least one module is in UKNOWN status'), true); - } - else { - return ui_print_status_image (STATUS_AGENT_OK_BALL, - __('All Monitors OK'), true); - } +// Returns the status ball image to display tree view +function agents_tree_view_status_img_ball($critical, $warning, $unknown, $total, $notinit) +{ + if ($total == 0 || $total == $notinit) { + return ui_print_status_image( + STATUS_AGENT_NO_MONITORS_BALL, + __('No Monitors'), + true + ); + } + + if ($critical > 0) { + return ui_print_status_image( + STATUS_AGENT_CRITICAL_BALL, + __('At least one module in CRITICAL status'), + true + ); + } else if ($warning > 0) { + return ui_print_status_image( + STATUS_AGENT_WARNING_BALL, + __('At least one module in WARNING status'), + true + ); + } else if ($unknown > 0) { + return ui_print_status_image( + STATUS_AGENT_DOWN_BALL, + __('At least one module is in UKNOWN status'), + true + ); + } else { + return ui_print_status_image( + STATUS_AGENT_OK_BALL, + __('All Monitors OK'), + true + ); + } } -//Returns the status image to display agent detail view -function agents_detail_view_status_img ($critical, $warning, $unknown, $total, $notinit) { - if ($total == 0 || $total == $notinit) { - return ui_print_status_image (STATUS_AGENT_NOT_INIT, - __('No Monitors'), true, false, 'images'); - } - else if ($critical > 0) { - return ui_print_status_image (STATUS_AGENT_CRITICAL, - __('At least one module in CRITICAL status'), true, false, 'images'); - } - else if ($warning > 0) { - return ui_print_status_image (STATUS_AGENT_WARNING, - __('At least one module in WARNING status'), true, false, 'images'); - } - else if ($unknown > 0) { - return ui_print_status_image (STATUS_AGENT_UNKNOWN, - __('At least one module is in UKNOWN status'), true, false, 'images'); - } - else { - return ui_print_status_image (STATUS_AGENT_OK, - __('All Monitors OK'), true, false, 'images'); - } +// Returns the status image to display agent detail view +function agents_detail_view_status_img($critical, $warning, $unknown, $total, $notinit) +{ + if ($total == 0 || $total == $notinit) { + return ui_print_status_image( + STATUS_AGENT_NOT_INIT, + __('No Monitors'), + true, + false, + 'images' + ); + } else if ($critical > 0) { + return ui_print_status_image( + STATUS_AGENT_CRITICAL, + __('At least one module in CRITICAL status'), + true, + false, + 'images' + ); + } else if ($warning > 0) { + return ui_print_status_image( + STATUS_AGENT_WARNING, + __('At least one module in WARNING status'), + true, + false, + 'images' + ); + } else if ($unknown > 0) { + return ui_print_status_image( + STATUS_AGENT_UNKNOWN, + __('At least one module is in UKNOWN status'), + true, + false, + 'images' + ); + } else { + return ui_print_status_image( + STATUS_AGENT_OK, + __('All Monitors OK'), + true, + false, + 'images' + ); + } } -function agents_update_gis($idAgente, $latitude, $longitude, $altitude, - $ignore_new_gis_data, $manual_placement, $start_timestamp, - $end_timestamp, $number_of_packages, $description_save_history, - $description_update_gis, $description_first_insert) { - - $previusAgentGISData = db_get_row_sql(" + +function agents_update_gis( + $idAgente, + $latitude, + $longitude, + $altitude, + $ignore_new_gis_data, + $manual_placement, + $start_timestamp, + $end_timestamp, + $number_of_packages, + $description_save_history, + $description_update_gis, + $description_first_insert +) { + $previusAgentGISData = db_get_row_sql( + ' SELECT * FROM tgis_data_status - WHERE tagente_id_agente = " . $idAgente); - - db_process_sql_update('tagente', - array('update_gis_data' => $updateGisData), - array('id_agente' => $idAgente)); - - $return = false; - - if ($previusAgentGISData !== false) { - $return = db_process_sql_insert('tgis_data_history', array( - "longitude" => $previusAgentGISData['stored_longitude'], - "latitude" => $previusAgentGISData['stored_latitude'], - "altitude" => $previusAgentGISData['stored_altitude'], - "start_timestamp" => $previusAgentGISData['start_timestamp'], - "end_timestamp" => $end_timestamp, - "description" => $description_save_history, - "manual_placement" => $previusAgentGISData['manual_placement'], - "number_of_packages" => $previusAgentGISData['number_of_packages'], - "tagente_id_agente" => $previusAgentGISData['tagente_id_agente'] - )); - $return = db_process_sql_update('tgis_data_status', array( - "tagente_id_agente" => $idAgente, - "current_longitude" => $longitude, - "current_latitude" => $latitude, - "current_altitude" => $altitude, - "stored_longitude" => $longitude, - "stored_latitude" => $latitude, - "stored_altitude" => $altitude, - "start_timestamp" => $start_timestamp, - "manual_placement" => $manual_placement, - "description" => $description_update_gis, - "number_of_packages" => $number_of_packages), - array("tagente_id_agente" => $idAgente)); - } - else { - //The table "tgis_data_status" have not a autonumeric - //then the mysql_insert_id function return 0 - - $prev_count = db_get_num_rows("SELECT * FROM tgis_data_status"); - - $return = db_process_sql_insert('tgis_data_status', array( - "tagente_id_agente" => $idAgente, - "current_longitude" => $longitude, - "current_latitude" => $latitude, - "current_altitude" => $altitude, - "stored_longitude" => $longitude, - "stored_latitude" => $latitude, - "stored_altitude" => $altitude, - "start_timestamp" => $start_timestamp, - "manual_placement" => $manual_placement, - "description" => $description_first_insert, - "number_of_packages" => $number_of_packages - )); - - - $count = db_get_num_rows("SELECT * FROM tgis_data_status"); - - if ($return === 0) { - if ($prev_count < $count) { - $return = true; - } - } - } - - return (bool)$return; + WHERE tagente_id_agente = '.$idAgente + ); + + db_process_sql_update( + 'tagente', + ['update_gis_data' => $updateGisData], + ['id_agente' => $idAgente] + ); + + $return = false; + + if ($previusAgentGISData !== false) { + $return = db_process_sql_insert( + 'tgis_data_history', + [ + 'longitude' => $previusAgentGISData['stored_longitude'], + 'latitude' => $previusAgentGISData['stored_latitude'], + 'altitude' => $previusAgentGISData['stored_altitude'], + 'start_timestamp' => $previusAgentGISData['start_timestamp'], + 'end_timestamp' => $end_timestamp, + 'description' => $description_save_history, + 'manual_placement' => $previusAgentGISData['manual_placement'], + 'number_of_packages' => $previusAgentGISData['number_of_packages'], + 'tagente_id_agente' => $previusAgentGISData['tagente_id_agente'], + ] + ); + $return = db_process_sql_update( + 'tgis_data_status', + [ + 'tagente_id_agente' => $idAgente, + 'current_longitude' => $longitude, + 'current_latitude' => $latitude, + 'current_altitude' => $altitude, + 'stored_longitude' => $longitude, + 'stored_latitude' => $latitude, + 'stored_altitude' => $altitude, + 'start_timestamp' => $start_timestamp, + 'manual_placement' => $manual_placement, + 'description' => $description_update_gis, + 'number_of_packages' => $number_of_packages, + ], + ['tagente_id_agente' => $idAgente] + ); + } else { + // The table "tgis_data_status" have not a autonumeric + // then the mysql_insert_id function return 0 + $prev_count = db_get_num_rows('SELECT * FROM tgis_data_status'); + + $return = db_process_sql_insert( + 'tgis_data_status', + [ + 'tagente_id_agente' => $idAgente, + 'current_longitude' => $longitude, + 'current_latitude' => $latitude, + 'current_altitude' => $altitude, + 'stored_longitude' => $longitude, + 'stored_latitude' => $latitude, + 'stored_altitude' => $altitude, + 'start_timestamp' => $start_timestamp, + 'manual_placement' => $manual_placement, + 'description' => $description_first_insert, + 'number_of_packages' => $number_of_packages, + ] + ); + + $count = db_get_num_rows('SELECT * FROM tgis_data_status'); + + if ($return === 0) { + if ($prev_count < $count) { + $return = true; + } + } + } + + return (bool) $return; } + /** * Returns a list with network interfaces data by agent * @@ -2300,192 +2708,208 @@ function agents_update_gis($idAgente, $latitude, $longitude, $altitude, * * @return array A list of network interfaces information by agents. */ -function agents_get_network_interfaces ($agents = false, $agents_filter = false) { - global $config; +function agents_get_network_interfaces($agents=false, $agents_filter=false) +{ + global $config; - if ($agents === false) { - $filter = false; - if ($agents_filter !== false) { - $filter = $agents_filter; - } - $fields = array( - 'id_agente', - 'alias', - 'id_grupo' - ); - $agents = agents_get_agents($filter, $fields); - } - - $ni_by_agents = array(); - - foreach ($agents as $agent) { - $agent_id = $agent['id_agente']; - $agent_group_id = $agent['id_grupo']; - $agent_name = $agent['alias']; - $agent_interfaces = array(); - - $accepted_module_types = array(); - $remote_snmp_proc = (int) db_get_value("id_tipo", "ttipo_modulo", "nombre", "remote_snmp_proc"); - if ($remote_snmp_proc) - $accepted_module_types[] = $remote_snmp_proc; - $remote_icmp_proc = (int) db_get_value("id_tipo", "ttipo_modulo", "nombre", "remote_icmp_proc"); - if ($remote_icmp_proc) - $accepted_module_types[] = $remote_icmp_proc; - $remote_tcp_proc = (int) db_get_value("id_tipo", "ttipo_modulo", "nombre", "remote_tcp_proc"); - if ($remote_tcp_proc) - $accepted_module_types[] = $remote_tcp_proc; - $generic_proc = (int) db_get_value("id_tipo", "ttipo_modulo", "nombre", "generic_proc"); - if ($generic_proc) - $accepted_module_types[] = $generic_proc; - - if (empty($accepted_module_types)) - $accepted_module_types[] = 0; // No modules will be returned - - $columns = array( - "id_agente_modulo", - "nombre", - "ip_target" - ); + if ($agents === false) { + $filter = false; + if ($agents_filter !== false) { + $filter = $agents_filter; + } - if ($config['dbtype'] == 'oracle') - $columns[] = 'TO_CHAR(descripcion) AS descripcion'; - else - $columns[] = 'descripcion'; + $fields = [ + 'id_agente', + 'alias', + 'id_grupo', + ]; + $agents = agents_get_agents($filter, $fields); + } - $filter = " tagente_modulo.id_agente = $agent_id AND tagente_modulo.disabled = 0 AND tagente_modulo.id_tipo_modulo IN (".implode(",", $accepted_module_types).") AND (tagente_modulo.nombre LIKE '%_ifOperStatus' OR tagente_modulo.nombre LIKE 'ifOperStatus_%')"; - $modules = agents_get_modules($agent_id, $columns, $filter, true, false); + $ni_by_agents = []; - if (!empty($modules)) { - $interfaces = array(); + foreach ($agents as $agent) { + $agent_id = $agent['id_agente']; + $agent_group_id = $agent['id_grupo']; + $agent_name = $agent['alias']; + $agent_interfaces = []; - foreach ($modules as $module) { - $module_name = (string) $module['nombre']; + $accepted_module_types = []; + $remote_snmp_proc = (int) db_get_value('id_tipo', 'ttipo_modulo', 'nombre', 'remote_snmp_proc'); + if ($remote_snmp_proc) { + $accepted_module_types[] = $remote_snmp_proc; + } - // Trying to get the interface name from the module name - if (preg_match ("/^(.+)_if.+/", $module_name, $matches)) { - if ($matches[1]) { - $interface_name = $matches[1]; - $interface_name_escaped = str_replace("/", "\/", $interface_name); - $interfaces[$interface_name] = $module; - $type_interface=1; - } - } - elseif( preg_match ("/^if.+_(.+)$/", $module_name, $matches) ){ - if ($matches[1]) { - $interface_name = $matches[1]; - $interface_name_escaped = str_replace("/", "\/", $interface_name); - $interfaces[$interface_name] = $module; - $type_interface=0; - } - } - } - unset($modules); + $remote_icmp_proc = (int) db_get_value('id_tipo', 'ttipo_modulo', 'nombre', 'remote_icmp_proc'); + if ($remote_icmp_proc) { + $accepted_module_types[] = $remote_icmp_proc; + } - foreach ($interfaces as $interface_name => $module) { - $interface_name_escaped = str_replace("/", "\/", $interface_name); - - $module_id = $module['id_agente_modulo']; - $module_name = $module['nombre']; - $module_description = $module['descripcion']; - $db_status = modules_get_agentmodule_status($module_id); - $module_value = modules_get_last_value ($module_id); - modules_get_status($module_id, $db_status, $module_value, $status, $title); - $status_image = ui_print_status_image($status, $title, true); - - $ip_target = "--"; - // Trying to get something like an IP from the description - if (preg_match ("/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/", $module_description, $matches) - || preg_match ("/(((?=(?>.*?(::))(?!.+\3)))\3?|([\dA-F]{1,4}(\3|:?)|\2))(?4){5}((?4){2}|(25[0-5]| - (2[0-4]|1\d|[1-9])?\d)(\.(?7)){3})/i", $module_description, $matches) && $matches[0]) { - - $ip_target = $matches[0]; - } - // else if (isset($module['ip_target']) && !empty($module['ip_target'])) { - // $ip_target = $module['ip_target']; - // } - $mac = "--"; - // Trying to get something like a mac from the description - if (preg_match ("/([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})/i", $module_description, $matches)) { - if ($matches[0]) { - $mac = $matches[0]; - } - } + $remote_tcp_proc = (int) db_get_value('id_tipo', 'ttipo_modulo', 'nombre', 'remote_tcp_proc'); + if ($remote_tcp_proc) { + $accepted_module_types[] = $remote_tcp_proc; + } - // Get the ifInOctets and ifOutOctets modules of the interface - $columns = array( - "id_agente_modulo", - "nombre" - ); - - if($type_interface){ - $interface_traffic_modules = agents_get_modules($agent_id, $columns, "tagente_modulo.nombre LIKE '". $interface_name . "_if%Octets'"); - } - else{ - $interface_traffic_modules = agents_get_modules($agent_id, $columns, "tagente_modulo.nombre LIKE 'if%Octets_$interface_name'"); - } - - if (!empty($interface_traffic_modules) && count($interface_traffic_modules) >= 2) { - $interface_traffic_modules_aux = array('in' => '', 'out' => ''); - foreach ($interface_traffic_modules as $interface_traffic_module) { - $interface_name_escaped = str_replace("/", "\/", $interface_name); - if ($type_interface) { - if (preg_match ("/^" . $interface_name_escaped . "_if(.+)Octets$/i", $interface_traffic_module['nombre'], $matches)) { - if (strtolower($matches[1]) == 'in' || strtolower($matches[1]) == 'hcin') { - $interface_traffic_modules_aux['in'] = $interface_traffic_module['id_agente_modulo']; - } - elseif (strtolower($matches[1]) == 'out' || strtolower($matches[1]) == 'hcout') { - $interface_traffic_modules_aux['out'] = $interface_traffic_module['id_agente_modulo']; - } - } - } - else{ - if (preg_match ("/^if(.+)Octets_$interface_name_escaped$/i", $interface_traffic_module['nombre'], $matches)) { - if (strtolower($matches[1]) == 'in' || strtolower($matches[1]) == 'hcin') { - $interface_traffic_modules_aux['in'] = $interface_traffic_module['id_agente_modulo']; - } - elseif (strtolower($matches[1]) == 'out' || strtolower($matches[1]) == 'hcout') { - $interface_traffic_modules_aux['out'] = $interface_traffic_module['id_agente_modulo']; - } - } - } - } - if (!empty($interface_traffic_modules_aux['in']) && !empty($interface_traffic_modules_aux['out'])) { - $interface_traffic_modules = $interface_traffic_modules_aux; - } - else { - $interface_traffic_modules = false; - } - } - else { - $interface_traffic_modules = false; - } + $generic_proc = (int) db_get_value('id_tipo', 'ttipo_modulo', 'nombre', 'generic_proc'); + if ($generic_proc) { + $accepted_module_types[] = $generic_proc; + } - $agent_interfaces[$interface_name] = array(); - $agent_interfaces[$interface_name]['status_image'] = $status_image; - $agent_interfaces[$interface_name]['status_module_id'] = $module_id; - $agent_interfaces[$interface_name]['status_module_name'] = $module_name; - $agent_interfaces[$interface_name]['ip'] = $ip_target; - $agent_interfaces[$interface_name]['mac'] = $mac; + if (empty($accepted_module_types)) { + $accepted_module_types[] = 0; + // No modules will be returned + } - if ($interface_traffic_modules !== false) { - $agent_interfaces[$interface_name]['traffic'] = array(); - $agent_interfaces[$interface_name]['traffic']['in'] = $interface_traffic_modules['in']; - $agent_interfaces[$interface_name]['traffic']['out'] = $interface_traffic_modules['out']; - } - } - } + $columns = [ + 'id_agente_modulo', + 'nombre', + 'ip_target', + ]; - if (!empty($agent_interfaces)) { - $ni_by_agents[$agent_id] = array(); - $ni_by_agents[$agent_id]['name'] = $agent_name; - $ni_by_agents[$agent_id]['group'] = $agent_group_id; - $ni_by_agents[$agent_id]['interfaces'] = $agent_interfaces; - } - } + if ($config['dbtype'] == 'oracle') { + $columns[] = 'TO_CHAR(descripcion) AS descripcion'; + } else { + $columns[] = 'descripcion'; + } - return $ni_by_agents; + $filter = " tagente_modulo.id_agente = $agent_id AND tagente_modulo.disabled = 0 AND tagente_modulo.id_tipo_modulo IN (".implode(',', $accepted_module_types).") AND (tagente_modulo.nombre LIKE '%_ifOperStatus' OR tagente_modulo.nombre LIKE 'ifOperStatus_%')"; + $modules = agents_get_modules($agent_id, $columns, $filter, true, false); + + if (!empty($modules)) { + $interfaces = []; + + foreach ($modules as $module) { + $module_name = (string) $module['nombre']; + + // Trying to get the interface name from the module name + if (preg_match('/^(.+)_if.+/', $module_name, $matches)) { + if ($matches[1]) { + $interface_name = $matches[1]; + $interface_name_escaped = str_replace('/', '\/', $interface_name); + $interfaces[$interface_name] = $module; + $type_interface = 1; + } + } else if (preg_match('/^if.+_(.+)$/', $module_name, $matches)) { + if ($matches[1]) { + $interface_name = $matches[1]; + $interface_name_escaped = str_replace('/', '\/', $interface_name); + $interfaces[$interface_name] = $module; + $type_interface = 0; + } + } + } + + unset($modules); + + foreach ($interfaces as $interface_name => $module) { + $interface_name_escaped = str_replace('/', '\/', $interface_name); + + $module_id = $module['id_agente_modulo']; + $module_name = $module['nombre']; + $module_description = $module['descripcion']; + $db_status = modules_get_agentmodule_status($module_id); + $module_value = modules_get_last_value($module_id); + modules_get_status($module_id, $db_status, $module_value, $status, $title); + $status_image = ui_print_status_image($status, $title, true); + + $ip_target = '--'; + // Trying to get something like an IP from the description + if (preg_match('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/', $module_description, $matches) + || preg_match( + "/(((?=(?>.*?(::))(?!.+\3)))\3?|([\dA-F]{1,4}(\3|:?)|\2))(?4){5}((?4){2}|(25[0-5]| + (2[0-4]|1\d|[1-9])?\d)(\.(?7)){3})/i", + $module_description, + $matches + ) && $matches[0] + ) { + $ip_target = $matches[0]; + } + + // else if (isset($module['ip_target']) && !empty($module['ip_target'])) { + // $ip_target = $module['ip_target']; + // } + $mac = '--'; + // Trying to get something like a mac from the description + if (preg_match('/([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})/i', $module_description, $matches)) { + if ($matches[0]) { + $mac = $matches[0]; + } + } + + // Get the ifInOctets and ifOutOctets modules of the interface + $columns = [ + 'id_agente_modulo', + 'nombre', + ]; + + if ($type_interface) { + $interface_traffic_modules = agents_get_modules($agent_id, $columns, "tagente_modulo.nombre LIKE '".$interface_name."_if%Octets'"); + } else { + $interface_traffic_modules = agents_get_modules($agent_id, $columns, "tagente_modulo.nombre LIKE 'if%Octets_$interface_name'"); + } + + if (!empty($interface_traffic_modules) && count($interface_traffic_modules) >= 2) { + $interface_traffic_modules_aux = [ + 'in' => '', + 'out' => '', + ]; + foreach ($interface_traffic_modules as $interface_traffic_module) { + $interface_name_escaped = str_replace('/', '\/', $interface_name); + if ($type_interface) { + if (preg_match('/^'.$interface_name_escaped.'_if(.+)Octets$/i', $interface_traffic_module['nombre'], $matches)) { + if (strtolower($matches[1]) == 'in' || strtolower($matches[1]) == 'hcin') { + $interface_traffic_modules_aux['in'] = $interface_traffic_module['id_agente_modulo']; + } else if (strtolower($matches[1]) == 'out' || strtolower($matches[1]) == 'hcout') { + $interface_traffic_modules_aux['out'] = $interface_traffic_module['id_agente_modulo']; + } + } + } else { + if (preg_match("/^if(.+)Octets_$interface_name_escaped$/i", $interface_traffic_module['nombre'], $matches)) { + if (strtolower($matches[1]) == 'in' || strtolower($matches[1]) == 'hcin') { + $interface_traffic_modules_aux['in'] = $interface_traffic_module['id_agente_modulo']; + } else if (strtolower($matches[1]) == 'out' || strtolower($matches[1]) == 'hcout') { + $interface_traffic_modules_aux['out'] = $interface_traffic_module['id_agente_modulo']; + } + } + } + } + + if (!empty($interface_traffic_modules_aux['in']) && !empty($interface_traffic_modules_aux['out'])) { + $interface_traffic_modules = $interface_traffic_modules_aux; + } else { + $interface_traffic_modules = false; + } + } else { + $interface_traffic_modules = false; + } + + $agent_interfaces[$interface_name] = []; + $agent_interfaces[$interface_name]['status_image'] = $status_image; + $agent_interfaces[$interface_name]['status_module_id'] = $module_id; + $agent_interfaces[$interface_name]['status_module_name'] = $module_name; + $agent_interfaces[$interface_name]['ip'] = $ip_target; + $agent_interfaces[$interface_name]['mac'] = $mac; + + if ($interface_traffic_modules !== false) { + $agent_interfaces[$interface_name]['traffic'] = []; + $agent_interfaces[$interface_name]['traffic']['in'] = $interface_traffic_modules['in']; + $agent_interfaces[$interface_name]['traffic']['out'] = $interface_traffic_modules['out']; + } + } + } + + if (!empty($agent_interfaces)) { + $ni_by_agents[$agent_id] = []; + $ni_by_agents[$agent_id]['name'] = $agent_name; + $ni_by_agents[$agent_id]['group'] = $agent_group_id; + $ni_by_agents[$agent_id]['interfaces'] = $agent_interfaces; + } + } + + return $ni_by_agents; } + /** * Returns the value of the custom field for the selected agent. * @@ -2494,64 +2918,83 @@ function agents_get_network_interfaces ($agents = false, $agents_filter = false) * * @return mixed The custom field value or false on error. */ -function agents_get_agent_custom_field ($agent_id, $custom_field_name) { - if (empty($agent_id) && empty($custom_field_name)) { - return false; - } - - $sql = sprintf("SELECT tacd.description AS value +function agents_get_agent_custom_field($agent_id, $custom_field_name) +{ + if (empty($agent_id) && empty($custom_field_name)) { + return false; + } + + $sql = sprintf( + "SELECT tacd.description AS value FROM tagent_custom_data tacd INNER JOIN tagent_custom_fields tacf ON tacd.id_field = tacf.id_field AND tacf.name LIKE '%s' WHERE tacd.id_agent = %d", - $custom_field_name, $agent_id); - return db_get_value_sql($sql); + $custom_field_name, + $agent_id + ); + return db_get_value_sql($sql); } + function select_modules_for_agent_group( - $id_group, $id_agents, $selection, $return = true, $index_by_name = false + $id_group, + $id_agents, + $selection, + $return=true, + $index_by_name=false ) { - global $config; - $agents = (empty($id_agents)) ? array() : implode(",", $id_agents); - - $filter_agent_group = ""; - $filter_group = ""; - $filter_agent = ""; - $selection_filter = ""; - $sql_conditions_tags = ""; - $sql_tags_inner = ""; + global $config; + $agents = (empty($id_agents)) ? [] : implode(',', $id_agents); - $groups = array_keys(users_get_groups(false, "AR", false)); + $filter_agent_group = ''; + $filter_group = ''; + $filter_agent = ''; + $selection_filter = ''; + $sql_conditions_tags = ''; + $sql_tags_inner = ''; - if ($id_group != 0) { - $filter_group = " AND tagente_modulo.id_module_group = ". $id_group; - } - if ($agents != null) { - $filter_agent = " AND tagente.id_agente IN (" . $agents . ")"; - } - if (!users_can_manage_group_all("AR")) { - $group_string = implode(',', $groups); - $filter_agent_group = " AND ( + $groups = array_keys(users_get_groups(false, 'AR', false)); + + if ($id_group != 0) { + $filter_group = ' AND tagente_modulo.id_module_group = '.$id_group; + } + + if ($agents != null) { + $filter_agent = ' AND tagente.id_agente IN ('.$agents.')'; + } + + if (!users_can_manage_group_all('AR')) { + $group_string = implode(',', $groups); + $filter_agent_group = " AND ( tagente.id_grupo IN ($group_string) OR tasg.id_group IN ($group_string) )"; - } - if (!$selection && $agents != null) { - $number_agents = count($id_agents); - $selection_filter = "HAVING COUNT(id_agente_modulo) = $number_agents"; - } + } - if (tags_has_user_acl_tags(false)){ - $sql_conditions_tags = tags_get_acl_tags( - $config['id_user'], $groups, 'AR', - 'module_condition', 'AND', 'tagente_modulo', true, array(), - false); - $sql_tags_inner = "INNER JOIN ttag_module - ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo"; - } + if (!$selection && $agents != null) { + $number_agents = count($id_agents); + $selection_filter = "HAVING COUNT(id_agente_modulo) = $number_agents"; + } - $sql = "SELECT * FROM + if (tags_has_user_acl_tags(false)) { + $sql_conditions_tags = tags_get_acl_tags( + $config['id_user'], + $groups, + 'AR', + 'module_condition', + 'AND', + 'tagente_modulo', + true, + [], + false + ); + $sql_tags_inner = 'INNER JOIN ttag_module + ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo'; + } + + $sql = "SELECT * FROM ( SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.nombre FROM tagente_modulo @@ -2570,88 +3013,103 @@ function select_modules_for_agent_group( GROUP BY nombre $selection_filter"; - $modules = db_get_all_rows_sql($sql); - if ($modules === false) $modules = array(); + $modules = db_get_all_rows_sql($sql); + if ($modules === false) { + $modules = []; + } - if ($return) { - echo json_encode($modules); - return; - } + if ($return) { + echo json_encode($modules); + return; + } - $modules_array = array(); - foreach ($modules as $value) { - if($index_by_name) { - $modules_array[io_safe_output($value['nombre'])] = - ui_print_truncate_text( - io_safe_output($value['nombre']), 'module_medium', false, true - ); - } else { - $modules_array[$value['id_agente_modulo']] = $value['nombre']; - } - } - return $modules_array; + $modules_array = []; + foreach ($modules as $value) { + if ($index_by_name) { + $modules_array[io_safe_output($value['nombre'])] = ui_print_truncate_text( + io_safe_output($value['nombre']), + 'module_medium', + false, + true + ); + } else { + $modules_array[$value['id_agente_modulo']] = $value['nombre']; + } + } + + return $modules_array; } + function select_agents_for_module_group( - $module_names, $selection, $filter, $access = "AR" + $module_names, + $selection, + $filter, + $access='AR' ) { - global $config; + global $config; - $default_filter = array ( - 'status' => null - ); + $default_filter = ['status' => null]; - $filter = array_merge($default_filter, $filter); + $filter = array_merge($default_filter, $filter); - $module_names_condition = ""; - $filter_agent_group = ""; - $selection_filter = ""; - $sql_conditions_tags = ""; - $sql_tags_inner = ""; - $status_filter = ""; - $module_type_filter = ""; + $module_names_condition = ''; + $filter_agent_group = ''; + $selection_filter = ''; + $sql_conditions_tags = ''; + $sql_tags_inner = ''; + $status_filter = ''; + $module_type_filter = ''; - $groups = array_keys(users_get_groups(false, $access, false)); + $groups = array_keys(users_get_groups(false, $access, false)); - // Name - if (!users_can_manage_group_all($access)) { - $group_string = implode(',', $groups); - $filter_agent_group = " AND ( + // Name + if (!users_can_manage_group_all($access)) { + $group_string = implode(',', $groups); + $filter_agent_group = " AND ( tagente.id_grupo IN ($group_string) OR tasg.id_group IN ($group_string) )"; - } + } - // Name filter - if ($module_names) { - $module_names_sql = implode("','", $module_names); - $module_names_condition = " AND tagente_modulo.nombre IN ('$module_names_sql') "; - } + // Name filter + if ($module_names) { + $module_names_sql = implode("','", $module_names); + $module_names_condition = " AND tagente_modulo.nombre IN ('$module_names_sql') "; + } - // Common or all modules filter - if (!$selection) { - $number_modules = count($module_names); - $selection_filter = "HAVING COUNT(id_agente) = $number_modules"; - } + // Common or all modules filter + if (!$selection) { + $number_modules = count($module_names); + $selection_filter = "HAVING COUNT(id_agente) = $number_modules"; + } - // Status filter - if ($filter['status'] != null) { - $status_filter = " AND " . modules_get_state_condition( - $filter['status'], "tagente_estado" - ); - } + // Status filter + if ($filter['status'] != null) { + $status_filter = ' AND '.modules_get_state_condition( + $filter['status'], + 'tagente_estado' + ); + } - // Tags input and ACL conditions - if (tags_has_user_acl_tags(false) || $filter['tags'] != null){ - $sql_conditions_tags = tags_get_acl_tags( - $config['id_user'], $groups, $access, - 'module_condition', 'AND', 'tagente_modulo', true, array(), - false); - $sql_tags_inner = "INNER JOIN ttag_module - ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo"; - } + // Tags input and ACL conditions + if (tags_has_user_acl_tags(false) || $filter['tags'] != null) { + $sql_conditions_tags = tags_get_acl_tags( + $config['id_user'], + $groups, + $access, + 'module_condition', + 'AND', + 'tagente_modulo', + true, + [], + false + ); + $sql_tags_inner = 'INNER JOIN ttag_module + ON ttag_module.id_agente_modulo = tagente_modulo.id_agente_modulo'; + } - $sql = "SELECT * FROM + $sql = "SELECT * FROM ( SELECT tagente.id_agente, tagente.alias FROM tagente @@ -2673,11 +3131,15 @@ function select_agents_for_module_group( ) x GROUP BY id_agente $selection_filter"; - $modules = db_get_all_rows_sql($sql); - if ($modules === false) return array(); - return index_array(db_get_all_rows_sql($sql), 'id_agente', 'alias'); + $modules = db_get_all_rows_sql($sql); + if ($modules === false) { + return []; + } + + return index_array(db_get_all_rows_sql($sql), 'id_agente', 'alias'); } + /** * Returns a random name identifier for an agent. * @@ -2686,170 +3148,201 @@ function select_agents_for_module_group( * * @return string Random identifier name. */ -function agents_generate_name ($alias, $address = '') { - return hash('sha256', $alias . '|' . $address . '|' . time() . '|' . sprintf('%04d', rand(0, 10000))); +function agents_generate_name($alias, $address='') +{ + return hash('sha256', $alias.'|'.$address.'|'.time().'|'.sprintf('%04d', rand(0, 10000))); } + /** * Returns all the groups related to an agent. It includes all secondary groups. * - * @param int $id_agent - * @param int $id_group. By default it will search for it in dtabase + * @param integer $id_agent + * @param integer $id_group. By default it will search for it in dtabase * @param bool True to use the metaconsole tables * - * @return Array with the main and secondary groups + * @return array with the main and secondary groups */ -function agents_get_all_groups_agent ($id_agent, $group = false, $force_meta = false) { - // Cache the agent id groups - static $cache = array(); - if (isset($cache[$id_agent])) return $cache[$id_agent]; - // Get the group if is not defined - if ($group === false) $group = agents_get_agent_group($id_agent, $force_meta); +function agents_get_all_groups_agent($id_agent, $group=false, $force_meta=false) +{ + // Cache the agent id groups + static $cache = []; + if (isset($cache[$id_agent])) { + return $cache[$id_agent]; + } - // If cannot retrieve the group, it means that agent does not exist - if (!$group) return array(); + // Get the group if is not defined + if ($group === false) { + $group = agents_get_agent_group($id_agent, $force_meta); + } - enterprise_include_once('include/functions_agents.php'); - $secondary_groups = enterprise_hook('agents_get_secondary_groups', array($id_agent, $force_meta)); + // If cannot retrieve the group, it means that agent does not exist + if (!$group) { + return []; + } - // Return only an array with the group in open version - if ($secondary_groups == ENTERPRISE_NOT_HOOK) return array($group); + enterprise_include_once('include/functions_agents.php'); + $secondary_groups = enterprise_hook('agents_get_secondary_groups', [$id_agent, $force_meta]); - // Add a list of groups - $secondary_groups['plain'][] = $group; - $cache[$id_agent] = $secondary_groups['plain']; - return $secondary_groups['plain']; + // Return only an array with the group in open version + if ($secondary_groups == ENTERPRISE_NOT_HOOK) { + return [$group]; + } + + // Add a list of groups + $secondary_groups['plain'][] = $group; + $cache[$id_agent] = $secondary_groups['plain']; + return $secondary_groups['plain']; } + /** * @brief Get the total agents with a filter and an access bit * * @param Array filter agentes array. It is the same that agents_get_agents function * @param string ACL bit * - * @return int Total agents retrieved with the filter + * @return integer Total agents retrieved with the filter */ -function agents_count_agents_filter ($filter = array(), $access = "AR") { - $total_agents = agents_get_agents( - $filter, - array ('COUNT(DISTINCT id_agente) as total'), - $access - ); - return ($total_agents !== false) - ? $total_agents[0]['total'] - : 0; +function agents_count_agents_filter($filter=[], $access='AR') +{ + $total_agents = agents_get_agents( + $filter, + ['COUNT(DISTINCT id_agente) as total'], + $access + ); + return ($total_agents !== false) ? $total_agents[0]['total'] : 0; } + /** * @brief Check if an agent is accessible by the user * * @param int Id agent * @param string ACL access bit - * @param boolean $force_meta + * @param boolean $force_meta * * @return True if user has access, false if user has not permissions and - * null if id agent does not exist + * null if id agent does not exist */ -function agents_check_access_agent ($id_agent, $access = "AR", $force_meta = false) { - global $config; +function agents_check_access_agent($id_agent, $access='AR', $force_meta=false) +{ + global $config; - if (users_access_to_agent($id_agent, $access, false, $force_meta)) return true; + if (users_access_to_agent($id_agent, $access, false, $force_meta)) { + return true; + } - // If agent exist return false - if (agents_check_agent_exists($id_agent, true, $force_meta)) return false; - // Return null otherwise - return null; + // If agent exist return false + if (agents_check_agent_exists($id_agent, true, $force_meta)) { + return false; + } + + // Return null otherwise + return null; } -function agents_get_status_clause($state, $show_not_init = true) { - switch ($state) { - case AGENT_STATUS_CRITICAL: - return "(ta.critical_count > 0)"; - case AGENT_STATUS_WARNING: - return "(ta.warning_count > 0 AND ta.critical_count = 0)"; - case AGENT_STATUS_UNKNOWN: - return "( + +function agents_get_status_clause($state, $show_not_init=true) +{ + switch ($state) { + case AGENT_STATUS_CRITICAL: + return '(ta.critical_count > 0)'; + + case AGENT_STATUS_WARNING: + return '(ta.warning_count > 0 AND ta.critical_count = 0)'; + + case AGENT_STATUS_UNKNOWN: + return '( ta.critical_count = 0 AND ta.warning_count = 0 AND ta.unknown_count > 0 - )"; - case AGENT_STATUS_NOT_INIT: - return $show_not_init - ? "(ta.total_count = ta.notinit_count OR ta.total_count = 0)" - : "1=0"; - case AGENT_STATUS_NORMAL: - return "( + )'; + + case AGENT_STATUS_NOT_INIT: + return $show_not_init ? '(ta.total_count = ta.notinit_count OR ta.total_count = 0)' : '1=0'; + + case AGENT_STATUS_NORMAL: + return '( ta.critical_count = 0 AND ta.warning_count = 0 AND ta.unknown_count = 0 AND ta.normal_count > 0 - )"; - case AGENT_STATUS_ALL: - default: - return $show_not_init - ? "1=1" - : "(ta.total_count <> ta.notinit_count)"; - } - // If the state is not an expected state, return no condition - return "1=1"; + )'; + + case AGENT_STATUS_ALL: + default: + return $show_not_init ? '1=1' : '(ta.total_count <> ta.notinit_count)'; + } + + // If the state is not an expected state, return no condition + return '1=1'; } -function agents_get_image_status($status){ - switch ($status) { - case AGENT_STATUS_NORMAL: - $image_status = html_print_image( - 'images/status_sets/default/agent_ok.png', - true, - array( - 'title' => __('Agents ok') - ) - ); - break; - case AGENT_STATUS_CRITICAL: - $image_status = html_print_image( - 'images/status_sets/default/agent_critical.png', - true, - array( - 'title' => __('Agents critical') - ) - ); - break; - case AGENT_STATUS_WARNING: - $image_status = html_print_image( - 'images/status_sets/default/agent_warning.png', - true, - array( - 'title' => __('Agents warning') - ) - ); - break; - case AGENT_STATUS_UNKNOWN: - $image_status = html_print_image( - 'images/status_sets/default/agent_down.png', - true, - array( - 'title' => __('Agents unknown') - ) - ); - break; - case AGENT_STATUS_ALERT_FIRED: - $image_status = 'alert'; - break; - case AGENT_STATUS_NOT_INIT: - $image_status = html_print_image( - 'images/status_sets/default/agent_no_data.png', - true, - array( - 'title' => __('Agents not init') - ) - ); - break; - default: - $image_status= html_print_image( - 'images/status_sets/default/agent_ok.png', - true, - array( - 'title' => __('Agents ok') - ) - ); - break; - } - return $image_status; + +function agents_get_image_status($status) +{ + switch ($status) { + case AGENT_STATUS_NORMAL: + $image_status = html_print_image( + 'images/status_sets/default/agent_ok.png', + true, + [ + 'title' => __('Agents ok'), + ] + ); + break; + + case AGENT_STATUS_CRITICAL: + $image_status = html_print_image( + 'images/status_sets/default/agent_critical.png', + true, + [ + 'title' => __('Agents critical'), + ] + ); + break; + + case AGENT_STATUS_WARNING: + $image_status = html_print_image( + 'images/status_sets/default/agent_warning.png', + true, + [ + 'title' => __('Agents warning'), + ] + ); + break; + + case AGENT_STATUS_UNKNOWN: + $image_status = html_print_image( + 'images/status_sets/default/agent_down.png', + true, + [ + 'title' => __('Agents unknown'), + ] + ); + break; + + case AGENT_STATUS_ALERT_FIRED: + $image_status = 'alert'; + break; + + case AGENT_STATUS_NOT_INIT: + $image_status = html_print_image( + 'images/status_sets/default/agent_no_data.png', + true, + [ + 'title' => __('Agents not init'), + ] + ); + break; + + default: + $image_status = html_print_image( + 'images/status_sets/default/agent_ok.png', + true, + [ + 'title' => __('Agents ok'), + ] + ); + break; + } + + return $image_status; } -?> \ No newline at end of file diff --git a/pandora_console/include/functions_alerts.php b/pandora_console/include/functions_alerts.php index 57677b8dea..6bfe709c32 100644 --- a/pandora_console/include/functions_alerts.php +++ b/pandora_console/include/functions_alerts.php @@ -4,101 +4,101 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. /** - * @package Include + * @package Include * @subpackage Alerts */ -require_once($config['homedir'] . "/include/functions_agents.php"); -require_once($config['homedir'] . '/include/functions_modules.php'); -require_once($config['homedir'] . '/include/functions_users.php'); +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_users.php'; -function alerts_get_alerts($id_group = 0, $free_search = "", $status = "all", $standby = -1, $acl = false, $total = false, $id_agent = 0) { - $sql = ""; - $alerts = array(); - - //----------- Group ------------------------------------------------ - if ($id_group != 0) { - if ($acl !== false) { - $groups = users_get_groups (false, $acl, false); - - if (array_key_exists($id_group, $groups)) { - $group_query = " AND t3.id_grupo = " . $id_group . " "; - } - else { - //Set to fail the query - $group_query = " AND 1=0 "; - } - } - else { - $group_query = " AND t3.id_grupo = " . $id_group . " "; - } - } - else { - if ($acl !== false) { - $groups = users_get_groups (false, $acl, false); - - $id_groups = array_keys($groups); - - $group_query = " AND ( - t3.id_grupo IN (" . implode(',', $id_groups) . ") - OR tasg.id_group IN (" . implode(',', $id_groups) . ") - )"; - } - else { - $group_query = ""; - } - } - - //------------ Status ---------------------------------------------- - switch ($status) { - case "notfired": - $status_query = ' AND t0.times_fired = 0 AND t0.disabled = 0'; - break; - case "fired": - $status_query = ' AND t0.times_fired > 0 AND t0.disabled = 0'; - break; - case "disabled": - $status_query = ' AND t0.disabled = 1'; - break; - case "all_enabled": - $status_query = ' AND t0.disabled = 0'; - break; - default: - $status_query = ''; - break; - } - - //----------- Standby ---------------------------------------------- - $standby_query = ''; - if ($standby != -1) { - $status_query .= ' AND t0.standby = ' . $standby . ' '; - } - - //----------- Free search ------------------------------------------ - $free_search = io_safe_input($free_search); - - //----------- Make the query --------------------------------------- - if ($total) { - $sql = 'SELECT COUNT(*)'; - } - else { - $sql = 'SELECT *, t2.nombre AS module_name, + +function alerts_get_alerts($id_group=0, $free_search='', $status='all', $standby=-1, $acl=false, $total=false, $id_agent=0) +{ + $sql = ''; + $alerts = []; + + // ----------- Group ------------------------------------------------ + if ($id_group != 0) { + if ($acl !== false) { + $groups = users_get_groups(false, $acl, false); + + if (array_key_exists($id_group, $groups)) { + $group_query = ' AND t3.id_grupo = '.$id_group.' '; + } else { + // Set to fail the query + $group_query = ' AND 1=0 '; + } + } else { + $group_query = ' AND t3.id_grupo = '.$id_group.' '; + } + } else { + if ($acl !== false) { + $groups = users_get_groups(false, $acl, false); + + $id_groups = array_keys($groups); + + $group_query = ' AND ( + t3.id_grupo IN ('.implode(',', $id_groups).') + OR tasg.id_group IN ('.implode(',', $id_groups).') + )'; + } else { + $group_query = ''; + } + } + + // ------------ Status ---------------------------------------------- + switch ($status) { + case 'notfired': + $status_query = ' AND t0.times_fired = 0 AND t0.disabled = 0'; + break; + + case 'fired': + $status_query = ' AND t0.times_fired > 0 AND t0.disabled = 0'; + break; + + case 'disabled': + $status_query = ' AND t0.disabled = 1'; + break; + + case 'all_enabled': + $status_query = ' AND t0.disabled = 0'; + break; + + default: + $status_query = ''; + break; + } + + // ----------- Standby ---------------------------------------------- + $standby_query = ''; + if ($standby != -1) { + $status_query .= ' AND t0.standby = '.$standby.' '; + } + + // ----------- Free search ------------------------------------------ + $free_search = io_safe_input($free_search); + + // ----------- Make the query --------------------------------------- + if ($total) { + $sql = 'SELECT COUNT(*)'; + } else { + $sql = 'SELECT *, t2.nombre AS module_name, t3.nombre AS agent_name, t3.alias AS agent_alias, t1.name AS template_name, t0.disabled AS alert_disabled '; - } - $sql .= ' + } + + $sql .= ' FROM talert_template_modules AS t0 INNER JOIN talert_templates t1 ON t0.id_alert_template = t1.id @@ -109,992 +109,1173 @@ function alerts_get_alerts($id_group = 0, $free_search = "", $status = "all", $s LEFT JOIN tagent_secondary_group tasg ON tasg.id_agent = t3.id_agente WHERE 1=1 - ' . $status_query . ' ' . $standby_query . ' ' . $group_query . ' - AND (t1.name LIKE "%' . $free_search . '%" - OR t2.nombre LIKE "%' . $free_search . '%" - OR t3.nombre LIKE "%' . $free_search . '%")'; - - if ($id_agent != 0) { - $sql .= ' AND t3.id_agente = ' . $id_agent; - } - - $row_alerts = db_get_all_rows_sql($sql); - - if ($total) { - return reset($row_alerts[0]); - } - else { - - - return $row_alerts; - } + '.$status_query.' '.$standby_query.' '.$group_query.' + AND (t1.name LIKE "%'.$free_search.'%" + OR t2.nombre LIKE "%'.$free_search.'%" + OR t3.nombre LIKE "%'.$free_search.'%")'; + + if ($id_agent != 0) { + $sql .= ' AND t3.id_agente = '.$id_agent; + } + + $row_alerts = db_get_all_rows_sql($sql); + + if ($total) { + return reset($row_alerts[0]); + } else { + return $row_alerts; + } } + /** * Get fired status from any alert of agent in group. - * + * * @param integer $idGroup The ID of group. - * @param mixed $type The list of types to search or type. By default "alert_fired". - * + * @param mixed $type The list of types to search or type. By default "alert_fired". + * * @return mixed Return id if the group have any alert is fired or false is not. */ -function alerts_get_event_status_group($idGroup, $type = "alert_fired", $query = 'AND 1=1', $agents = null) { - global $config; - - $return = false; - - $typeWhere = ''; - - if (!is_array($type)) { - $typeWhere = ' AND event_type = "' . $type . '" '; - } - else { - $temp = array(); - foreach ($type as $item) { - array_push ( $temp , $item ); - } - - $typeWhere = ' AND event_type IN ('; - - foreach ($temp as $ele) { - $typeWhere .= "'".$ele."'"; - - if($ele != end($temp)){ - $typeWhere .= ","; - } - - } - - $typeWhere .= ')'; - - } - - if ($agents == null) { - $agents = agents_get_group_agents($idGroup, false, "lower", false); +function alerts_get_event_status_group($idGroup, $type='alert_fired', $query='AND 1=1', $agents=null) +{ + global $config; - $idAgents = array_keys($agents); - - } - else { - $idAgents = array_values($agents); - - } - - $result = db_get_all_rows_sql('SELECT id_evento + $return = false; + + $typeWhere = ''; + + if (!is_array($type)) { + $typeWhere = ' AND event_type = "'.$type.'" '; + } else { + $temp = []; + foreach ($type as $item) { + array_push($temp, $item); + } + + $typeWhere = ' AND event_type IN ('; + + foreach ($temp as $ele) { + $typeWhere .= "'".$ele."'"; + + if ($ele != end($temp)) { + $typeWhere .= ','; + } + } + + $typeWhere .= ')'; + } + + if ($agents == null) { + $agents = agents_get_group_agents($idGroup, false, 'lower', false); + + $idAgents = array_keys($agents); + } else { + $idAgents = array_values($agents); + } + + $result = db_get_all_rows_sql( + 'SELECT id_evento FROM tevento - WHERE estado = 0 AND id_agente IN (0,' . implode(',', $idAgents) . ') ' . $typeWhere . $query . ' - ORDER BY id_evento DESC LIMIT 1'); - - if ($result === false) { - return false; - } - - return $result[0]['id_evento']; + WHERE estado = 0 AND id_agente IN (0,'.implode(',', $idAgents).') '.$typeWhere.$query.' + ORDER BY id_evento DESC LIMIT 1' + ); + + if ($result === false) { + return false; + } + + return $result[0]['id_evento']; } + /** * Insert in talert_commands a new command. * * @param string name command name to save in DB. * @param string command String of command. * @param mixed A single value or array of values to insert (can be a multiple amount of rows). - * + * * @return mixed False in case of error or invalid values passed. Affected rows otherwise. */ -function alerts_create_alert_command ($name, $command, $values = false) { - if (empty ($name)) - return false; - if (empty ($command)) - return false; - if (! is_array ($values)) - $values = array (); - $values['name'] = $name; - $values['command'] = $command; - - return @db_process_sql_insert ('talert_commands', $values); +function alerts_create_alert_command($name, $command, $values=false) +{ + if (empty($name)) { + return false; + } + + if (empty($command)) { + return false; + } + + if (! is_array($values)) { + $values = []; + } + + $values['name'] = $name; + $values['command'] = $command; + + return @db_process_sql_insert('talert_commands', $values); } + /** * Update a command in talert_commands. * * @param int Alert command Id. * @param mixed Array of values to update. - * + * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function alerts_update_alert_command ($id_alert_command, $values) { - $id_alert_command = safe_int ($id_alert_command, 1); - if (empty ($id_alert_command)) - return false; - if (! is_array ($values)) - return false; - - return (@db_process_sql_update ('talert_commands', - $values, - array ('id' => $id_alert_command))) !== false; +function alerts_update_alert_command($id_alert_command, $values) +{ + $id_alert_command = safe_int($id_alert_command, 1); + if (empty($id_alert_command)) { + return false; + } + + if (! is_array($values)) { + return false; + } + + return (@db_process_sql_update( + 'talert_commands', + $values, + ['id' => $id_alert_command] + )) !== false; } + /** * Delete a command in talert_commands. * * @param int Alert command Id. - * + * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function alerts_delete_alert_command ($id_alert_command) { - $id_alert_command = safe_int ($id_alert_command, 1); - if (empty ($id_alert_command)) - return false; - - return (@db_process_sql_delete ('talert_commands', - array ('id' => $id_alert_command))) !== false; +function alerts_delete_alert_command($id_alert_command) +{ + $id_alert_command = safe_int($id_alert_command, 1); + if (empty($id_alert_command)) { + return false; + } + + return (@db_process_sql_delete( + 'talert_commands', + ['id' => $id_alert_command] + )) !== false; } + /** * Get a command in talert_commands. * * @param int Alert command Id. - * + * * @return mixed False in case of error or invalid values passed. All row of the selected command otherwise */ -function alerts_get_alert_command ($id_alert_command) { - $id_alert_command = safe_int ($id_alert_command, 1); - if (empty ($id_alert_command)) - return false; - - return db_get_row ('talert_commands', 'id', $id_alert_command); +function alerts_get_alert_command($id_alert_command) +{ + $id_alert_command = safe_int($id_alert_command, 1); + if (empty($id_alert_command)) { + return false; + } + + return db_get_row('talert_commands', 'id', $id_alert_command); } + /** * Get name of a command in talert_commands. * * @param int Alert command Id. - * + * * @return mixed False in case of error or invalid values passed. Command name otherwise */ -function alert_get_alert_command_name ($id_alert_command) { - $id_alert_command = safe_int ($id_alert_command, 1); - if (empty ($id_alert_command)) - return false; - - return db_get_value ('name', 'talert_commands', 'id', $id_alert_command); +function alert_get_alert_command_name($id_alert_command) +{ + $id_alert_command = safe_int($id_alert_command, 1); + if (empty($id_alert_command)) { + return false; + } + + return db_get_value('name', 'talert_commands', 'id', $id_alert_command); } + /** * Get command field of a command in talert_commands. * * @param int Alert command Id. - * + * * @return mixed False in case of error or invalid values passed. Command field otherwise */ -function alerts_get_alert_command_command ($id_alert_command) { - $id_alert_command = safe_int ($id_alert_command, 1); - if (empty ($id_alert_command)) - return false; - - return db_get_value ('command', 'talert_commands', 'id', $id_alert_command); +function alerts_get_alert_command_command($id_alert_command) +{ + $id_alert_command = safe_int($id_alert_command, 1); + if (empty($id_alert_command)) { + return false; + } + + return db_get_value('command', 'talert_commands', 'id', $id_alert_command); } + /** * Get internal field of a command in talert_commands. * * @param int Alert command Id. - * + * * @return mixed False in case of error or invalid values passed. Internal field otherwise */ -function alerts_get_alert_command_internal ($id_alert_command) { - $id_alert_command = safe_int ($id_alert_command, 1); - if (empty ($id_alert_command)) - return false; - - return (bool) db_get_value ('internal', 'talert_commands', 'id', $id_alert_command); +function alerts_get_alert_command_internal($id_alert_command) +{ + $id_alert_command = safe_int($id_alert_command, 1); + if (empty($id_alert_command)) { + return false; + } + + return (bool) db_get_value('internal', 'talert_commands', 'id', $id_alert_command); } + /** * Get description field of a command in talert_commands. * * @param int Alert command Id. - * + * * @return mixed False in case of error or invalid values passed. Description field otherwise */ -function alerts_get_alert_command_description ($id_alert_command) { - $id_alert_command = safe_int ($id_alert_command, 1); - if (empty ($id_alert_command)) - return false; - - return db_get_value ('description', 'talert_commands', 'id', $id_alert_command); +function alerts_get_alert_command_description($id_alert_command) +{ + $id_alert_command = safe_int($id_alert_command, 1); + if (empty($id_alert_command)) { + return false; + } + + return db_get_value('description', 'talert_commands', 'id', $id_alert_command); } + /** - * Creates a new alert action. + * Creates a new alert action. * - * @param string Name of the alert action + * @param string Name of the alert action * @param int Id of the alert command associated - * @param mixed Other fields of the new alert or false. - * - * @return mixed Returns the id if success or false in case of fail. + * @param mixed Other fields of the new alert or false. + * + * @return mixed Returns the id if success or false in case of fail. */ -function alerts_create_alert_action ($name, $id_alert_command, $values = false) { - $id_alert_command = safe_int ($id_alert_command, 1); - if (empty ($id_alert_command)) - return false; - if (empty ($name)) - return false; - - if (! is_array ($values)) - $values = array (); - $values['name'] = $name; - $values['id_alert_command'] = (int) $id_alert_command; - - return @db_process_sql_insert ('talert_actions', $values); +function alerts_create_alert_action($name, $id_alert_command, $values=false) +{ + $id_alert_command = safe_int($id_alert_command, 1); + if (empty($id_alert_command)) { + return false; + } + + if (empty($name)) { + return false; + } + + if (! is_array($values)) { + $values = []; + } + + $values['name'] = $name; + $values['id_alert_command'] = (int) $id_alert_command; + + return @db_process_sql_insert('talert_actions', $values); } + /** - * Updates an alert action. + * Updates an alert action. * * @param int Id of the alert action - * @param array Values to update. - * - * @return mixed Returns affected rows or false in case of fail. + * @param array Values to update. + * + * @return mixed Returns affected rows or false in case of fail. */ -function alerts_update_alert_action ($id_alert_action, $values) { - $id_alert_action = safe_int ($id_alert_action, 1); - if (empty ($id_alert_action)) - return false; - if (! is_array ($values)) - return false; - - return (@db_process_sql_update ('talert_actions', - $values, - array ('id' => $id_alert_action))) !== false; +function alerts_update_alert_action($id_alert_action, $values) +{ + $id_alert_action = safe_int($id_alert_action, 1); + if (empty($id_alert_action)) { + return false; + } + + if (! is_array($values)) { + return false; + } + + return (@db_process_sql_update( + 'talert_actions', + $values, + ['id' => $id_alert_action] + )) !== false; } + /** - * Delete an alert action. + * Delete an alert action. * * @param int Id of the alert action - * - * @return mixed Returns affected rows or false in case of fail. + * + * @return mixed Returns affected rows or false in case of fail. */ -function alerts_delete_alert_action ($id_alert_action) { - $id_alert_action = safe_int ($id_alert_action, 1); - if (empty ($id_alert_action)) - return false; - - return (@db_process_sql_delete ('talert_actions', - array ('id' => $id_alert_action))) !== false; +function alerts_delete_alert_action($id_alert_action) +{ + $id_alert_action = safe_int($id_alert_action, 1); + if (empty($id_alert_action)) { + return false; + } + + return (@db_process_sql_delete( + 'talert_actions', + ['id' => $id_alert_action] + )) !== false; } + /** - * Clone an alert action. + * Clone an alert action. * * @param int Id of the original alert action - * - * @return mixed Id of the cloned action or false in case of fail. + * + * @return mixed Id of the cloned action or false in case of fail. */ -function alerts_clone_alert_action ($id_alert_action) { - $id_alert_action = safe_int ($id_alert_action, 1); - if (empty ($id_alert_action)) - return false; - - $action = alerts_get_alert_action($id_alert_action); - - if (empty ($action)) - return false; - - unset($action['id']); - - return alerts_create_alert_action ($action['name']." ".__('copy'), $action['id_alert_command'], $action); +function alerts_clone_alert_action($id_alert_action) +{ + $id_alert_action = safe_int($id_alert_action, 1); + if (empty($id_alert_action)) { + return false; + } + + $action = alerts_get_alert_action($id_alert_action); + + if (empty($action)) { + return false; + } + + unset($action['id']); + + return alerts_create_alert_action($action['name'].' '.__('copy'), $action['id_alert_command'], $action); } + /** * Get all alert actions in Pandora DB. - * - * @param bool $only_names Return only names, by default is true. - * @param bool $acl Check the ACL, by default is false - * + * + * @param boolean $only_names Return only names, by default is true. + * @param boolean $acl Check the ACL, by default is false + * * @return array The list of actions. */ -function alerts_get_alert_actions ($only_names = true, $acl = false) { - $groups = users_get_groups(false, "AR", true); - - if ($groups === false) { - $groups = array(); - } - $id_groups = array_keys($groups); - - $all_actions = db_get_all_rows_filter('talert_actions', array('id_group' => $id_groups)); - - if ($all_actions === false) - return array (); - - if (! $only_names) - return $all_actions; - - $actions = array (); - foreach ($all_actions as $action) { - $actions[$action['id']] = $action['name']; - } - - return $actions; +function alerts_get_alert_actions($only_names=true, $acl=false) +{ + $groups = users_get_groups(false, 'AR', true); + + if ($groups === false) { + $groups = []; + } + + $id_groups = array_keys($groups); + + $all_actions = db_get_all_rows_filter('talert_actions', ['id_group' => $id_groups]); + + if ($all_actions === false) { + return []; + } + + if (! $only_names) { + return $all_actions; + } + + $actions = []; + foreach ($all_actions as $action) { + $actions[$action['id']] = $action['name']; + } + + return $actions; } + /** * Get actions alerts filtered. - * + * * @param bool Return all fields or not. * @param variant String with SQL filter or false in case you don't want to filter. * * @return mixed A matrix with all the values returned from the SQL statement or * false in case of empty result */ -function alerts_get_alert_actions_filter ($only_names = true, $filter = false) { - - if (!$filter) - $all_actions = db_get_all_rows_in_table ('talert_actions'); - elseif (is_string($filter)) - $all_actions = db_get_all_rows_filter ('talert_actions', $filter); - else - $all_actions = false; - - if ($all_actions === false) - return array (); - - if (! $only_names) - return $all_actions; - - $actions = array (); - foreach ($all_actions as $action) { - $actions[$action['id']] = $action['name']; - } - - return $actions; +function alerts_get_alert_actions_filter($only_names=true, $filter=false) +{ + if (!$filter) { + $all_actions = db_get_all_rows_in_table('talert_actions'); + } else if (is_string($filter)) { + $all_actions = db_get_all_rows_filter('talert_actions', $filter); + } else { + $all_actions = false; + } + + if ($all_actions === false) { + return []; + } + + if (! $only_names) { + return $all_actions; + } + + $actions = []; + foreach ($all_actions as $action) { + $actions[$action['id']] = $action['name']; + } + + return $actions; } + /** * Get action alert. - * + * * @param int Id of the action alert. * * @return mixed An array with the result set of the action alert or * false in case of empty result */ -function alerts_get_alert_action ($id_alert_action) { - $id_alert_action = safe_int ($id_alert_action, 1); - if (empty ($id_alert_action)) - return false; - - return db_get_row ('talert_actions', 'id', $id_alert_action); +function alerts_get_alert_action($id_alert_action) +{ + $id_alert_action = safe_int($id_alert_action, 1); + if (empty($id_alert_action)) { + return false; + } + + return db_get_row('talert_actions', 'id', $id_alert_action); } + /** * Get Id of the alert command associated with an alert action. - * + * * @param int Id of the action alert. * * @return mixed Id of the action alert or * false in case of empty result */ -function alerts_get_alert_action_alert_command_id ($id_alert_action) { - return db_get_value ('id_alert_command', 'talert_actions', - 'id', $id_alert_action); +function alerts_get_alert_action_alert_command_id($id_alert_action) +{ + return db_get_value( + 'id_alert_command', + 'talert_actions', + 'id', + $id_alert_action + ); } + /** * Get alert command associated with an alert action. - * + * * @param int Id of the action alert. * * @return mixed Result set of the action alert or * false in case of empty result */ -function alerts_get_alert_action_alert_command ($id_alert_action) { - $id_command = alerts_get_alert_action_alert_command_id ($id_alert_action); - - return alerts_get_alert_command ($id_command); +function alerts_get_alert_action_alert_command($id_alert_action) +{ + $id_command = alerts_get_alert_action_alert_command_id($id_alert_action); + + return alerts_get_alert_command($id_command); } + /** * Get field1 of an alert action. - * + * * @param int Id of the action alert. * * @return mixed Field1 of the action alert or * false in case of empty result */ -function alerts_get_alert_action_field1 ($id_alert_action) { - return db_get_value ('field1', 'talert_actions', 'id', $id_alert_action); +function alerts_get_alert_action_field1($id_alert_action) +{ + return db_get_value('field1', 'talert_actions', 'id', $id_alert_action); } + /** * Get field2 of an alert action. - * + * * @param int Id of the action alert. * * @return mixed Field2 of the action alert or * false in case of empty result */ -function alerts_get_alert_action_field2 ($id_alert_action) { - return db_get_value ('field2', 'talert_actions', 'id', $id_alert_action); +function alerts_get_alert_action_field2($id_alert_action) +{ + return db_get_value('field2', 'talert_actions', 'id', $id_alert_action); } + /** * Get field3 of an alert action. - * + * * @param int Id of the action alert. * * @return mixed Field3 of the action alert or * false in case of empty result */ -function alerts_get_alert_action_field3 ($id_alert_action) { - return db_get_value ('field3', 'talert_actions', 'id', $id_alert_action); +function alerts_get_alert_action_field3($id_alert_action) +{ + return db_get_value('field3', 'talert_actions', 'id', $id_alert_action); } + /** * Get name of an alert action. - * + * * @param int Id of the action alert. * * @return mixed Name of the action alert or * false in case of empty result */ -function alerts_get_alert_action_name ($id_alert_action) { - return db_get_value ('name', 'talert_actions', 'id', $id_alert_action); +function alerts_get_alert_action_name($id_alert_action) +{ + return db_get_value('name', 'talert_actions', 'id', $id_alert_action); } + /** * Get types of alert templates. - * + * * @return array Types of alert templates. */ -function alerts_get_alert_templates_types () { - $types = array (); - - $types['regex'] = __('Regular expression'); - $types['max_min'] = __('Max and min'); - $types['max'] = __('Max.'); - $types['min'] = __('Min.'); - $types['equal'] = __('Equal to'); - $types['not_equal'] = __('Not equal to'); - $types['warning'] = __('Warning status'); - $types['critical'] = __('Critical status'); - $types['unknown'] = __('Unknown status'); - $types['onchange'] = __('On Change'); - $types['always'] = __('Always'); - - return $types; +function alerts_get_alert_templates_types() +{ + $types = []; + + $types['regex'] = __('Regular expression'); + $types['max_min'] = __('Max and min'); + $types['max'] = __('Max.'); + $types['min'] = __('Min.'); + $types['equal'] = __('Equal to'); + $types['not_equal'] = __('Not equal to'); + $types['warning'] = __('Warning status'); + $types['critical'] = __('Critical status'); + $types['unknown'] = __('Unknown status'); + $types['onchange'] = __('On Change'); + $types['always'] = __('Always'); + + return $types; } + /** * Get type name of an alert template. - * + * * @param string alert template type. * * @return string name of the alert template. */ -function alerts_get_alert_templates_type_name ($type) { - $types = alerts_get_alert_templates_types (); - - if (! isset ($type[$type])) - return __('Unknown'); - - return $types[$type]; +function alerts_get_alert_templates_type_name($type) +{ + $types = alerts_get_alert_templates_types(); + + if (! isset($type[$type])) { + return __('Unknown'); + } + + return $types[$type]; } + /** * Creates an alert template. - * + * * @param string Name of the alert template. * @param string Type of the alert template. * @param mixed Array of alert template values or false. * * @return string name of the alert template. */ -function alerts_create_alert_template ($name, $type, $values = false) { - if (empty ($name)) - return false; - if (empty ($type)) - return false; - - if (! is_array ($values)) - $values = array (); - $values['name'] = $name; - $values['type'] = $type; - - switch ($type) { - /* TODO: Check values based on type, return false if failure */ - } - - return @db_process_sql_insert ('talert_templates', $values); +function alerts_create_alert_template($name, $type, $values=false) +{ + if (empty($name)) { + return false; + } + + if (empty($type)) { + return false; + } + + if (! is_array($values)) { + $values = []; + } + + $values['name'] = $name; + $values['type'] = $type; + + switch ($type) { + // TODO: Check values based on type, return false if failure + } + + return @db_process_sql_insert('talert_templates', $values); } + /** * Updates an alert template. - * + * * @param int Id of the alert template. * @param array Array of alert template values. * * @return mixed Number of rows affected or false if something goes wrong. */ -function alerts_update_alert_template ($id_alert_template, $values) { - $id_alert_template = safe_int ($id_alert_template, 1); - - if (empty ($id_alert_template)) - return false; - if (! is_array ($values)) - return false; - - return (@db_process_sql_update ('talert_templates', - $values, - array ('id' => $id_alert_template))) !== false; +function alerts_update_alert_template($id_alert_template, $values) +{ + $id_alert_template = safe_int($id_alert_template, 1); + + if (empty($id_alert_template)) { + return false; + } + + if (! is_array($values)) { + return false; + } + + return (@db_process_sql_update( + 'talert_templates', + $values, + ['id' => $id_alert_template] + )) !== false; } + /** * Deletes an alert template. - * + * * @param int Id of the alert template. * * @return mixed Number of rows affected or false if something goes wrong. */ -function alerts_delete_alert_template ($id_alert_template) { - $id_alert_template = safe_int ($id_alert_template, 1); - - if (empty ($id_alert_template)) - return false; - - return @db_process_sql_delete ('talert_templates', array ('id' => $id_alert_template)); +function alerts_delete_alert_template($id_alert_template) +{ + $id_alert_template = safe_int($id_alert_template, 1); + + if (empty($id_alert_template)) { + return false; + } + + return @db_process_sql_delete('talert_templates', ['id' => $id_alert_template]); } + /** * Get a set of alert templates. - * + * * @param mixed Array with filter conditions or false. * @param mixed Array with a set of fields to retrieve or false. * * @return mixed Array with selected alert templates or false if something goes wrong. */ -function alerts_get_alert_templates ($filter = false, $fields = false) { - global $config; - - if (isset($filter['offset'])) { - $offset = $filter['offset']; - unset($filter['offset']); - } - - if (isset($filter['limit'])) { - $limit = $filter['limit']; - unset($filter['limit']); - } - - $templates_sql = @db_get_all_rows_filter ('talert_templates', $filter, $fields, 'AND', false, true); - - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $limit_sql = ''; - if (isset($offset) && isset($limit)) { - $limit_sql = " LIMIT $offset, $limit "; - } - else { - $limit_sql = ""; - } - - $sql = sprintf("%s %s", $templates_sql, $limit_sql); - - $alert_templates = db_get_all_rows_sql($sql); - break; - case "oracle": - $set = array(); - if (isset($offset) && isset($limit)) { - $set['limit'] = $limit; - $set['offset'] = $offset; - } - - $alert_templates = oracle_recode_query ($templates_sql, $set, 'AND', false); - break; - } - return $alert_templates; +function alerts_get_alert_templates($filter=false, $fields=false) +{ + global $config; + + if (isset($filter['offset'])) { + $offset = $filter['offset']; + unset($filter['offset']); + } + + if (isset($filter['limit'])) { + $limit = $filter['limit']; + unset($filter['limit']); + } + + $templates_sql = @db_get_all_rows_filter('talert_templates', $filter, $fields, 'AND', false, true); + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $limit_sql = ''; + if (isset($offset) && isset($limit)) { + $limit_sql = " LIMIT $offset, $limit "; + } else { + $limit_sql = ''; + } + + $sql = sprintf('%s %s', $templates_sql, $limit_sql); + + $alert_templates = db_get_all_rows_sql($sql); + break; + + case 'oracle': + $set = []; + if (isset($offset) && isset($limit)) { + $set['limit'] = $limit; + $set['offset'] = $offset; + } + + $alert_templates = oracle_recode_query($templates_sql, $set, 'AND', false); + break; + } + + return $alert_templates; } + /** * Get one alert template. - * + * * @param int Id of an alert template. * * @return mixed Selected alert template or false if something goes wrong. */ -function alerts_get_alert_template ($id_alert_template) { - global $config; - - $alert_templates = false; - $id_alert_template = safe_int ($id_alert_template, 1); - - if (!empty ($id_alert_template)) { - switch ($config['dbtype']) { - case "mysql": - case "postgresql": - $alert_templates = db_get_row ('talert_templates', 'id', $id_alert_template); - break; - case "oracle": - $sql = "SELECT column_name +function alerts_get_alert_template($id_alert_template) +{ + global $config; + + $alert_templates = false; + $id_alert_template = safe_int($id_alert_template, 1); + + if (!empty($id_alert_template)) { + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $alert_templates = db_get_row('talert_templates', 'id', $id_alert_template); + break; + + case 'oracle': + $sql = "SELECT column_name FROM user_tab_columns WHERE table_name = 'TALERT_TEMPLATES' AND column_name NOT IN ('TIME_FROM','TIME_TO')"; - $fields_select = db_get_all_rows_sql($sql); - - $column_names = array_map(function($item) { - return $item['column_name']; - }, $fields_select); - $column_names_str = implode(',', $column_names); - - $sql = "SELECT $column_names_str, + $fields_select = db_get_all_rows_sql($sql); + + $column_names = array_map( + function ($item) { + return $item['column_name']; + }, + $fields_select + ); + $column_names_str = implode(',', $column_names); + + $sql = "SELECT $column_names_str, to_char(time_from, 'hh24:mi:ss') AS time_from, to_char(time_to, 'hh24:mi:ss') AS time_to FROM talert_templates WHERE id = $id_alert_template"; - $alert_templates = db_get_row_sql($sql); - break; - } - } - - return $alert_templates; + $alert_templates = db_get_row_sql($sql); + break; + } + } + + return $alert_templates; } + /** * Get field1 of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Field1 field or false if something goes wrong. */ -function alerts_get_alert_template_field1 ($id_alert_template) { - return db_get_value ('field1', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_field1($id_alert_template) +{ + return db_get_value('field1', 'talert_templates', 'id', $id_alert_template); } + /** * Get field2 of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Field2 field or false if something goes wrong. */ -function alerts_get_alert_template_field2 ($id_alert_template) { - return db_get_value ('field2', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_field2($id_alert_template) +{ + return db_get_value('field2', 'talert_templates', 'id', $id_alert_template); } + /** * Get field3 of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Field3 field or false if something goes wrong. */ -function alerts_get_alert_template_field3 ($id_alert_template) { - return db_get_value ('field3', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_field3($id_alert_template) +{ + return db_get_value('field3', 'talert_templates', 'id', $id_alert_template); } + /** * Get name of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Name field or false if something goes wrong. */ -function alerts_get_alert_template_name ($id_alert_template) { - return db_get_value ('name', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_name($id_alert_template) +{ + return db_get_value('name', 'talert_templates', 'id', $id_alert_template); } + /** * Get description of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Description field or false if something goes wrong. */ -function alerts_get_alert_template_description ($id_alert_template) { - return db_get_value ('description', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_description($id_alert_template) +{ + return db_get_value('description', 'talert_templates', 'id', $id_alert_template); } + /** * Get type of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Type field or false if something goes wrong. */ -function alerts_get_alert_template_type ($id_alert_template) { - return db_get_value ('type', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_type($id_alert_template) +{ + return db_get_value('type', 'talert_templates', 'id', $id_alert_template); } + /** * Get type's name of alert template. - * + * * @param int Id of an alert template. * * @return mixed Type's name of an alert template or false if something goes wrong. */ -function alerts_get_alert_template_type_name ($id_alert_template) { - $type = alerts_get_alert_template_type ($id_alert_template); - - return alerts_get_alert_templates_type_name ($type); +function alerts_get_alert_template_type_name($id_alert_template) +{ + $type = alerts_get_alert_template_type($id_alert_template); + + return alerts_get_alert_templates_type_name($type); } + /** * Get value of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Value field or false if something goes wrong. */ -function alerts_get_alert_template_value ($id_alert_template) { - return db_get_value ('value', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_value($id_alert_template) +{ + return db_get_value('value', 'talert_templates', 'id', $id_alert_template); } + /** * Get max_value of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Max_value field or false if something goes wrong. */ -function alerts_get_alert_template_max_value ($id_alert_template) { - return db_get_value ('max_value', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_max_value($id_alert_template) +{ + return db_get_value('max_value', 'talert_templates', 'id', $id_alert_template); } + /** * Get min_value of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Min_value field or false if something goes wrong. */ -function alerts_get_alert_template_min_value ($id_alert_template) { - return db_get_value ('min_value', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_min_value($id_alert_template) +{ + return db_get_value('min_value', 'talert_templates', 'id', $id_alert_template); } + /** * Get alert_text of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Alert_text field or false if something goes wrong. */ -function alerts_get_alert_template_alert_text ($id_alert_template) { - return db_get_value ('alert_text', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_alert_text($id_alert_template) +{ + return db_get_value('alert_text', 'talert_templates', 'id', $id_alert_template); } + /** * Get time_from of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Time_from field or false if something goes wrong. */ -function alerts_get_alert_template_time_from ($id_alert_template) { - return db_get_value ('time_from', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_time_from($id_alert_template) +{ + return db_get_value('time_from', 'talert_templates', 'id', $id_alert_template); } + /** * Get time_to of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Time_to field or false if something goes wrong. */ -function alerts_get_alert_template_time_to ($id_alert_template) { - return db_get_value ('time_to', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_time_to($id_alert_template) +{ + return db_get_value('time_to', 'talert_templates', 'id', $id_alert_template); } + /** * Get alert template in weekday format. - * + * * @param int Id of an alert template. * * @return mixed Alert template in weekday format or false if something goes wrong. */ -function alerts_get_alert_template_weekdays ($id_alert_template) { - $alert = alerts_get_alert_template ($id_alert_template); - - if ($alert === false) - return false; - - $retval = array (); - $days = array ('monday', 'tuesday', 'wednesday', 'thursday', - 'friday', 'saturday', 'sunday'); - foreach ($days as $day) - $retval[$day] = (bool) $alert[$day]; - - return $retval; +function alerts_get_alert_template_weekdays($id_alert_template) +{ + $alert = alerts_get_alert_template($id_alert_template); + + if ($alert === false) { + return false; + } + + $retval = []; + $days = [ + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday', + ]; + foreach ($days as $day) { + $retval[$day] = (bool) $alert[$day]; + } + + return $retval; } + /** * Get recovery_notify of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Recovery_notify field or false if something goes wrong. */ -function alerts_get_alert_template_recovery_notify ($id_alert_template) { - return db_get_value ('recovery_notify', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_recovery_notify($id_alert_template) +{ + return db_get_value('recovery_notify', 'talert_templates', 'id', $id_alert_template); } + /** * Get field2_recovery of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Field2_recovery field or false if something goes wrong. */ -function alerts_get_alert_template_field2_recovery ($id_alert_template) { - return db_get_value ('field2_recovery', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_field2_recovery($id_alert_template) +{ + return db_get_value('field2_recovery', 'talert_templates', 'id', $id_alert_template); } + /** * Get field3_recovery of talert_templates table. - * + * * @param int Id of an alert template. * * @return mixed Field3_recovery field or false if something goes wrong. */ -function alerts_get_alert_template_field3_recovery ($id_alert_template) { - return db_get_value ('field3_recovery', 'talert_templates', 'id', $id_alert_template); +function alerts_get_alert_template_field3_recovery($id_alert_template) +{ + return db_get_value('field3_recovery', 'talert_templates', 'id', $id_alert_template); } + /** * Duplicates an alert template. - * + * * @param int Id of an alert template. * * @return mixed Duplicates an alert template or false if something goes wrong. */ -function alerts_duplicate_alert_template ($id_alert_template) { - $template = alerts_get_alert_template ($id_alert_template); - - if ($template === false) - return false; - - $name = io_safe_input(__('Copy of') . ' ') . $template['name']; - $type = $template['type']; - - $size = count ($template) / 2; - for ($i = 0; $i < $size; $i++) { - unset ($template[$i]); - } - unset ($template['name']); - unset ($template['id']); - unset ($template['type']); - $template['value'] = safe_sql_string ($template['value']); - - return alerts_create_alert_template ($name, $type, $template); +function alerts_duplicate_alert_template($id_alert_template) +{ + $template = alerts_get_alert_template($id_alert_template); + + if ($template === false) { + return false; + } + + $name = io_safe_input(__('Copy of').' ').$template['name']; + $type = $template['type']; + + $size = (count($template) / 2); + for ($i = 0; $i < $size; $i++) { + unset($template[$i]); + } + + unset($template['name']); + unset($template['id']); + unset($template['type']); + $template['value'] = safe_sql_string($template['value']); + + return alerts_create_alert_template($name, $type, $template); } + /** * Creates an alert associated to a module. - * + * * @param int Id of an alert template. * * @return mixed Alert associated to a module or false if something goes wrong. */ -function alerts_create_alert_agent_module ($id_agent_module, $id_alert_template, $values = false) { - if (empty ($id_agent_module)) - return false; - if (empty ($id_alert_template)) - return false; - - if (! is_array ($values)) - $values = array (); - $values['id_agent_module'] = (int) $id_agent_module; - $values['id_alert_template'] = (int) $id_alert_template; - $values['last_reference'] = time(); - - return @db_process_sql_insert ('talert_template_modules', $values); +function alerts_create_alert_agent_module($id_agent_module, $id_alert_template, $values=false) +{ + if (empty($id_agent_module)) { + return false; + } + + if (empty($id_alert_template)) { + return false; + } + + if (! is_array($values)) { + $values = []; + } + + $values['id_agent_module'] = (int) $id_agent_module; + $values['id_alert_template'] = (int) $id_alert_template; + $values['last_reference'] = time(); + + return @db_process_sql_insert('talert_template_modules', $values); } + /** * Updates an alert associated to a module. - * + * * @param int Id of an alert template. * @param array Values of the update. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_update_alert_agent_module ($id_alert_agent_module, $values) { +function alerts_update_alert_agent_module($id_alert_agent_module, $values) +{ + if (empty($id_alert_agent_module)) { + return false; + } - if (empty ($id_alert_agent_module)) - return false; + if (! is_array($values)) { + return false; + } - if (! is_array ($values)) - return false; - - return (@db_process_sql_update ('talert_template_modules', - $values, - array ('id' => $id_alert_agent_module))) !== false; + return (@db_process_sql_update( + 'talert_template_modules', + $values, + ['id' => $id_alert_agent_module] + )) !== false; } + /** * Deletes an alert associated to a module. - * + * * @param int Id of an alert template. * @param mixed Array with filter conditions to delete. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_delete_alert_agent_module ($id_alert_agent_module, $filter = false) { - if (empty ($id_alert_agent_module) && ! is_array ($filter)) - return false; - - if (! is_array ($filter)) - $filter = array (); - if ($id_alert_agent_module) - $filter['id'] = $id_alert_agent_module; +function alerts_delete_alert_agent_module($id_alert_agent_module, $filter=false) +{ + if (empty($id_alert_agent_module) && ! is_array($filter)) { + return false; + } - // Get the id agent to update the fired alert counts - $agent_id = false; - if (isset ($filter['id_agent_module'])){ - $agent_id = modules_get_agentmodule_agent ($filter["id_agent_module"]); - } - else if (isset ($filter['id'])){ - $alert = alerts_get_alert_agent_module($id_alert_agent_module); - $agent_id = modules_get_agentmodule_agent ($alert["id_agent_module"]); - } - - /* - The deletion of actions from talert_template_module_actions, - it is automatily because the data base this table have - a foreing key and delete on cascade. - */ - if (@db_process_sql_delete ('talert_template_modules', $filter) !== false) { - // Update fired alert count on the agent - // It will only occur if is specified the alert id or the id_agent_module - if ($agent_id !== false) { - db_process_sql(sprintf('UPDATE tagente SET update_alert_count=1 WHERE id_agente = %d', $agent_id)); - } - return true; - } - - return false; + if (! is_array($filter)) { + $filter = []; + } + + if ($id_alert_agent_module) { + $filter['id'] = $id_alert_agent_module; + } + + // Get the id agent to update the fired alert counts + $agent_id = false; + if (isset($filter['id_agent_module'])) { + $agent_id = modules_get_agentmodule_agent($filter['id_agent_module']); + } else if (isset($filter['id'])) { + $alert = alerts_get_alert_agent_module($id_alert_agent_module); + $agent_id = modules_get_agentmodule_agent($alert['id_agent_module']); + } + + /* + The deletion of actions from talert_template_module_actions, + it is automatily because the data base this table have + a foreing key and delete on cascade. + */ + if (@db_process_sql_delete('talert_template_modules', $filter) !== false) { + // Update fired alert count on the agent + // It will only occur if is specified the alert id or the id_agent_module + if ($agent_id !== false) { + db_process_sql(sprintf('UPDATE tagente SET update_alert_count=1 WHERE id_agente = %d', $agent_id)); + } + + return true; + } + + return false; } + /** * Get alert associated to a module. - * + * * @param int Id of an alert template. * @param mixed Array with filter conditions to delete. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_get_alert_agent_module ($id_alert_agent_module) { - $id_alert_agent_module = safe_int ($id_alert_agent_module, 0); - - if (empty ($id_alert_agent_module)) - return false; - - return db_get_row ('talert_template_modules', 'id', $id_alert_agent_module); +function alerts_get_alert_agent_module($id_alert_agent_module) +{ + $id_alert_agent_module = safe_int($id_alert_agent_module, 0); + + if (empty($id_alert_agent_module)) { + return false; + } + + return db_get_row('talert_template_modules', 'id', $id_alert_agent_module); } + /** * Get alert associated to a module. - * + * * @param int Id of an alert template. * @param bool Disabled or not. * @param mixed Filter conditions or false. @@ -1102,260 +1283,342 @@ function alerts_get_alert_agent_module ($id_alert_agent_module) { * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_get_alerts_agent_module ($id_agent_module, $disabled = false, $filter = false, $fields = false) { - $id_alert_agent_module = safe_int ($id_agent_module, 0); - - if (! is_array ($filter)) - $filter = array (); - if (! $disabled) - $filter['disabled'] = 0; - $filter['id_agent_module'] = (int) $id_agent_module; - - return db_get_all_rows_filter ('talert_template_modules', - $filter, $fields); +function alerts_get_alerts_agent_module($id_agent_module, $disabled=false, $filter=false, $fields=false) +{ + $id_alert_agent_module = safe_int($id_agent_module, 0); + + if (! is_array($filter)) { + $filter = []; + } + + if (! $disabled) { + $filter['disabled'] = 0; + } + + $filter['id_agent_module'] = (int) $id_agent_module; + + return db_get_all_rows_filter( + 'talert_template_modules', + $filter, + $fields + ); } + /** * Get alert associated to a module (only id and name fields). - * + * * @param int Id of an alert template. * @param bool Disabled or not. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_get_alerts_module_name ($id_agent_module, $disabled = false) { - $id_alert_agent_module = safe_int ($id_agent_module, 0); - - $sql = sprintf ('SELECT a.id, b.name +function alerts_get_alerts_module_name($id_agent_module, $disabled=false) +{ + $id_alert_agent_module = safe_int($id_agent_module, 0); + + $sql = sprintf( + 'SELECT a.id, b.name FROM talert_template_modules AS a, talert_templates AS b - WHERE a.id=b.id AND a.id_agent_module = %d AND a.disabled = %d', - $id_agent_module, (int)$disabled); - - return db_process_sql($sql); + WHERE a.id=b.id AND a.id_agent_module = %d AND a.disabled = %d', + $id_agent_module, + (int) $disabled + ); + + return db_process_sql($sql); } /** * Get disabled field of talert_template_modules table. - * + * * @param int Id of an alert associated to a module. * * @return mixed Disabled field or false if something goes wrong. */ -function alerts_get_alert_agent_module_disabled ($id_alert_agent_module) { - $id_alert_agent_module = safe_int ($id_alert_agent_module, 0); - - return db_get_value ('disabled', 'talert_template_modules', 'id', - $id_alert_agent_module); +function alerts_get_alert_agent_module_disabled($id_alert_agent_module) +{ + $id_alert_agent_module = safe_int($id_alert_agent_module, 0); + + return db_get_value( + 'disabled', + 'talert_template_modules', + 'id', + $id_alert_agent_module + ); } + /** * Force execution of an alert associated to a module. - * + * * @param int Id of an alert associated to a module. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_agent_module_force_execution ($id_alert_agent_module) { - $id_alert_agent_module = safe_int ($id_alert_agent_module, 0); - - return (@db_process_sql_update ('talert_template_modules', - array ('force_execution' => 1), - array ('id' => $id_alert_agent_module))) !== false; +function alerts_agent_module_force_execution($id_alert_agent_module) +{ + $id_alert_agent_module = safe_int($id_alert_agent_module, 0); + + return (@db_process_sql_update( + 'talert_template_modules', + ['force_execution' => 1], + ['id' => $id_alert_agent_module] + )) !== false; } + /** * Disable/Enable an alert associated to a module. - * + * * @param int Id of an alert associated to a module. * @param bool Whether to enable or disable an alert. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_agent_module_disable ($id_alert_agent_module, $disabled) { - $id_alert_agent_module = safe_int ($id_alert_agent_module, 0); - - return (@db_process_sql_update ('talert_template_modules', - array ('disabled' => (bool) $disabled), - array ('id' => $id_alert_agent_module))) !== false; +function alerts_agent_module_disable($id_alert_agent_module, $disabled) +{ + $id_alert_agent_module = safe_int($id_alert_agent_module, 0); + + return (@db_process_sql_update( + 'talert_template_modules', + ['disabled' => (bool) $disabled], + ['id' => $id_alert_agent_module] + )) !== false; } + /** * Disable/Enable stanby of an alert associated to a module. - * + * * @param int Id of an alert associated to a module. * @param bool Whether to enable or disable stanby of an alert. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_agent_module_standby ($id_alert_agent_module, $standby) { - $id_alert_agent_module = safe_int ($id_alert_agent_module, 0); - - return (@db_process_sql_update ('talert_template_modules', - array ('standby' => (bool) $standby), - array ('id' => $id_alert_agent_module))) !== false; +function alerts_agent_module_standby($id_alert_agent_module, $standby) +{ + $id_alert_agent_module = safe_int($id_alert_agent_module, 0); + + return (@db_process_sql_update( + 'talert_template_modules', + ['standby' => (bool) $standby], + ['id' => $id_alert_agent_module] + )) !== false; } + /** * Get last fired of an alert associated to a module. - * + * * @param int Id of an alert associated to a module. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_get_alerts_agent_module_last_fired ($id_alert_agent_module) { - $id_alert_agent_module = safe_int ($id_alert_agent_module, 1); - - return db_get_value ('last_fired', 'talert_template_modules', 'id', - $id_alert_agent_module); +function alerts_get_alerts_agent_module_last_fired($id_alert_agent_module) +{ + $id_alert_agent_module = safe_int($id_alert_agent_module, 1); + + return db_get_value( + 'last_fired', + 'talert_template_modules', + 'id', + $id_alert_agent_module + ); } + /** * Add an action to an alert associated to a module. - * + * * @param int Id of an alert associated to a module. * @param int Id of an alert. * @param mixed Options of the action. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_add_alert_agent_module_action ($id_alert_template_module, $id_alert_action, $options = false) { - global $config; - - if (empty ($id_alert_template_module)) - return false; - if (empty ($id_alert_action)) - return false; - - $values = array (); - $values['id_alert_template_module'] = (int) $id_alert_template_module; - $values['id_alert_action'] = (int) $id_alert_action; - $values['fires_max'] = 0; - $values['fires_min'] = 0; - $values['module_action_threshold'] = 0; - if ($options) { - $max = 0; - $min = 0; - if (isset ($options['fires_max'])) - $values['fires_max'] = $options['fires_max']; - if (isset ($options['fires_min'])) - $values['fires_min'] = $options['fires_min']; - if (isset ($options['module_action_threshold'])) - $values['module_action_threshold'] = (int) $options['module_action_threshold']; - } - - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - return (@db_process_sql_insert( - 'talert_template_module_actions', $values)) !== false; - break; - case "oracle": - return (@db_process_sql_insert( - 'talert_template_module_actions', $values, false)) !== false; - break; - } +function alerts_add_alert_agent_module_action($id_alert_template_module, $id_alert_action, $options=false) +{ + global $config; + + if (empty($id_alert_template_module)) { + return false; + } + + if (empty($id_alert_action)) { + return false; + } + + $values = []; + $values['id_alert_template_module'] = (int) $id_alert_template_module; + $values['id_alert_action'] = (int) $id_alert_action; + $values['fires_max'] = 0; + $values['fires_min'] = 0; + $values['module_action_threshold'] = 0; + if ($options) { + $max = 0; + $min = 0; + if (isset($options['fires_max'])) { + $values['fires_max'] = $options['fires_max']; + } + + if (isset($options['fires_min'])) { + $values['fires_min'] = $options['fires_min']; + } + + if (isset($options['module_action_threshold'])) { + $values['module_action_threshold'] = (int) $options['module_action_threshold']; + } + } + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + return (@db_process_sql_insert( + 'talert_template_module_actions', + $values + )) !== false; + + break; + case 'oracle': + return (@db_process_sql_insert( + 'talert_template_module_actions', + $values, + false + )) !== false; + + break; + } } + /** * Update an action to an alert associated to a module. - * + * * @param int Id of register. * @param mixed Options of the action. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_update_alert_agent_module_action ($id_module_action, $options = false) { - global $config; - - $values = array (); - $values['fires_max'] = 0; - $values['fires_min'] = 0; - $values['module_action_threshold'] = 0; - if ($options) { - $max = 0; - $min = 0; - if (isset ($options['fires_max'])) - $values['fires_max'] = $options['fires_max']; - if (isset ($options['fires_min'])) - $values['fires_min'] = $options['fires_min']; - if (isset ($options['module_action_threshold'])) - $values['module_action_threshold'] = (int) $options['module_action_threshold']; - if (isset ($options['id_alert_action'])) - $values['id_alert_action'] = (int) $options['id_alert_action']; - } - - return (@db_process_sql_update ('talert_template_module_actions', - $values, - array ('id' => $id_module_action))) !== false; +function alerts_update_alert_agent_module_action($id_module_action, $options=false) +{ + global $config; + + $values = []; + $values['fires_max'] = 0; + $values['fires_min'] = 0; + $values['module_action_threshold'] = 0; + if ($options) { + $max = 0; + $min = 0; + if (isset($options['fires_max'])) { + $values['fires_max'] = $options['fires_max']; + } + + if (isset($options['fires_min'])) { + $values['fires_min'] = $options['fires_min']; + } + + if (isset($options['module_action_threshold'])) { + $values['module_action_threshold'] = (int) $options['module_action_threshold']; + } + + if (isset($options['id_alert_action'])) { + $values['id_alert_action'] = (int) $options['id_alert_action']; + } + } + + return (@db_process_sql_update( + 'talert_template_module_actions', + $values, + ['id' => $id_module_action] + )) !== false; } + /** * Delete an action to an alert associated to a module. - * + * * @param int Id of an alert associated to a module. * * @return mixed Affected rows or false if something goes wrong. */ -function alerts_delete_alert_agent_module_action ($id_alert_agent_module_action) { - if (empty ($id_alert_agent_module_action)) - return false; - - return (@db_process_sql_delete ('talert_template_module_actions', - array ('id' => $id_alert_agent_module_action))) !== false; +function alerts_delete_alert_agent_module_action($id_alert_agent_module_action) +{ + if (empty($id_alert_agent_module_action)) { + return false; + } + + return (@db_process_sql_delete( + 'talert_template_module_actions', + ['id' => $id_alert_agent_module_action] + )) !== false; } + /** * Get actions of an alert associated to a module. - * + * * @param int Id of an alert associated to a module. * @param mixed Array with fields to retrieve or false. * * @return mixed Actions associated or false if something goes wrong. */ -function alerts_get_alert_agent_module_actions ($id_alert_agent_module, $fields = false, $server_id = -1) { - if (empty ($id_alert_agent_module)) - return false; +function alerts_get_alert_agent_module_actions($id_alert_agent_module, $fields=false, $server_id=-1) +{ + if (empty($id_alert_agent_module)) { + return false; + } - if (defined('METACONSOLE')) { - $server = db_get_row ('tmetaconsole_setup', 'id', $server_id); + if (defined('METACONSOLE')) { + $server = db_get_row('tmetaconsole_setup', 'id', $server_id); - if (metaconsole_connect($server) == NOERR) { - $actions = db_get_all_rows_filter ('talert_template_module_actions', - array ('id_alert_template_module' => $id_alert_agent_module), - $fields); + if (metaconsole_connect($server) == NOERR) { + $actions = db_get_all_rows_filter( + 'talert_template_module_actions', + ['id_alert_template_module' => $id_alert_agent_module], + $fields + ); - metaconsole_restore_db (); - } - } else { - $actions = db_get_all_rows_filter ('talert_template_module_actions', - array ('id_alert_template_module' => $id_alert_agent_module), - $fields); - } - - if ($actions === false) - return array (); - if ($fields !== false) - return $actions; - - $retval = array (); - foreach ($actions as $element) { - $action = alerts_get_alert_action ($element['id_alert_action']); - $action['fires_min'] = $element['fires_min']; - $action['fires_max'] = $element['fires_max']; - $action['module_action_threshold'] = $element['module_action_threshold']; - - if (isset($element['id'])) - $retval[$element['id']] = $action; - } - - return $retval; + metaconsole_restore_db(); + } + } else { + $actions = db_get_all_rows_filter( + 'talert_template_module_actions', + ['id_alert_template_module' => $id_alert_agent_module], + $fields + ); + } + + if ($actions === false) { + return []; + } + + if ($fields !== false) { + return $actions; + } + + $retval = []; + foreach ($actions as $element) { + $action = alerts_get_alert_action($element['id_alert_action']); + $action['fires_min'] = $element['fires_min']; + $action['fires_max'] = $element['fires_max']; + $action['module_action_threshold'] = $element['module_action_threshold']; + + if (isset($element['id'])) { + $retval[$element['id']] = $action; + } + } + + return $retval; } + /** * Returns the actions applied to an alert assigned to a module in a hash. + * * @param unsigned int id_agent_module - * + * * @return hash with the actions * * hash[template1][action1] <- fired @@ -1363,191 +1626,268 @@ function alerts_get_alert_agent_module_actions ($id_alert_agent_module, $fields * hash[template1][action3] <- fired * hash[template2][action1] <- fired */ -function alerts_get_effective_alert_actions($id_agent_module) { - if (empty ($id_agent_module)) - return false; +function alerts_get_effective_alert_actions($id_agent_module) +{ + if (empty($id_agent_module)) { + return false; + } - $default_sql = 'select tm.id, t.name as template, a.name as action, tm.last_fired as last_execution from talert_templates t, talert_actions a, talert_template_modules tm where tm.id_alert_template=t.id and t.id_alert_action=a.id and tm.id_agent_module=' . $id_agent_module; - $actions = db_get_all_rows_sql ($default_sql); + $default_sql = 'select tm.id, t.name as template, a.name as action, tm.last_fired as last_execution from talert_templates t, talert_actions a, talert_template_modules tm where tm.id_alert_template=t.id and t.id_alert_action=a.id and tm.id_agent_module='.$id_agent_module; + $actions = db_get_all_rows_sql($default_sql); - $custom_sql = 'select tm.id, t.name as template, a.name as action, tma.last_execution from talert_actions a, talert_template_module_actions tma, talert_template_modules tm, talert_templates t where tma.id_alert_template_module=tm.id and tma.id_alert_action=a.id and tm.id_alert_template = t.id and tm.id_agent_module=' . $id_agent_module; - $custom_actions = db_get_all_rows_sql($custom_sql); + $custom_sql = 'select tm.id, t.name as template, a.name as action, tma.last_execution from talert_actions a, talert_template_module_actions tma, talert_template_modules tm, talert_templates t where tma.id_alert_template_module=tm.id and tma.id_alert_action=a.id and tm.id_alert_template = t.id and tm.id_agent_module='.$id_agent_module; + $custom_actions = db_get_all_rows_sql($custom_sql); - $no_actions_sql = 'select tm.id, t.name as template from talert_templates t, talert_template_modules tm where tm.id_alert_template=t.id and tm.id_agent_module=' . $id_agent_module; - $no_actions = db_get_all_rows_sql ($no_actions_sql); + $no_actions_sql = 'select tm.id, t.name as template from talert_templates t, talert_template_modules tm where tm.id_alert_template=t.id and tm.id_agent_module='.$id_agent_module; + $no_actions = db_get_all_rows_sql($no_actions_sql); - $nactions = 0; - $return = array(); + $nactions = 0; + $return = []; - if ($actions !== false) { - foreach ($actions as $a) { - if (!isset($return[$a["template"]]["id"])){ - $return[$a["template"]]["id"] = $a["id"]; - } - if (!isset($return[$a["template"]]["default"])){ - $return[$a["template"]]["default"] = array(); + if ($actions !== false) { + foreach ($actions as $a) { + if (!isset($return[$a['template']]['id'])) { + $return[$a['template']]['id'] = $a['id']; + } - } - $return[$a["template"]]["default"][$nactions]["fired"] = $a["last_execution"]; - $return[$a["template"]]["default"][$nactions]["name"] = $a["action"]; - $nactions++; - } + if (!isset($return[$a['template']]['default'])) { + $return[$a['template']]['default'] = []; + } - } + $return[$a['template']]['default'][$nactions]['fired'] = $a['last_execution']; + $return[$a['template']]['default'][$nactions]['name'] = $a['action']; + $nactions++; + } + } - if ($custom_actions !== false) { - foreach ($custom_actions as $a) { - if (!isset($return[$a["template"]]["id"])){ - $return[$a["template"]]["id"] = $a["id"]; - } - if (!isset($return[$a["template"]]["custom"])){ - $return[$a["template"]]["custom"] = array(); - } - $return[$a["template"]]["custom"][$nactions]["fired"] = $a["last_execution"]; - $return[$a["template"]]["custom"][$nactions]["name"] = $a["action"]; - $nactions++; - } - } + if ($custom_actions !== false) { + foreach ($custom_actions as $a) { + if (!isset($return[$a['template']]['id'])) { + $return[$a['template']]['id'] = $a['id']; + } - if ($no_actions !== false){ - foreach ($no_actions as $a) { - if (!isset($return[$a["template"]]["id"])){ - $return[$a["template"]]["id"] = $a["id"]; - } - if (!isset($return[$a["template"]]["unavailable"])){ - $return[$a["template"]]["unavailable"] = array(); - } - $return[$a["template"]]["unavailable"][$nactions]["fired"] = 0; - $return[$a["template"]]["unavailable"][$nactions]["name"] = __("No actions defined"); - $nactions++; - } - } + if (!isset($return[$a['template']]['custom'])) { + $return[$a['template']]['custom'] = []; + } + $return[$a['template']]['custom'][$nactions]['fired'] = $a['last_execution']; + $return[$a['template']]['custom'][$nactions]['name'] = $a['action']; + $nactions++; + } + } - if ($nactions == 0) { - return false; - } + if ($no_actions !== false) { + foreach ($no_actions as $a) { + if (!isset($return[$a['template']]['id'])) { + $return[$a['template']]['id'] = $a['id']; + } - return $return; + if (!isset($return[$a['template']]['unavailable'])) { + $return[$a['template']]['unavailable'] = []; + } + + $return[$a['template']]['unavailable'][$nactions]['fired'] = 0; + $return[$a['template']]['unavailable'][$nactions]['name'] = __('No actions defined'); + $nactions++; + } + } + + if ($nactions == 0) { + return false; + } + + return $return; } + +/** + * Validate alerts for the given module. + * + * @param int agent_module_id ID of the module + */ +function alerts_validate_alert_module($agent_module_id) +{ + db_process_sql( + sprintf( + 'UPDATE talert_template_modules + SET times_fired=0, internal_counter=0 + WHERE id_agent_module = %d', + $agent_module_id + ) + ); +} + + +/** + * Validate alerts for the given agent. + * + * @param int agent_id ID of the agent + */ +function alerts_validate_alert_agent($agent_id) +{ + db_process_sql( + sprintf( + 'UPDATE talert_template_modules tm + INNER JOIN tagente_modulo am ON tm.id_agent_module = am.id_agente_modulo + SET tm.times_fired=0, tm.internal_counter=0 + WHERE am.id_agente = %d', + $agent_id + ) + ); +} + + /** * Validates an alert id or an array of alert id's. * * @param mixed Array of alerts ids or single id. * @param bool Whether to check ACLs * - * @return bool True if it was successful, false otherwise. + * @return boolean True if it was successful, false otherwise. */ -function alerts_validate_alert_agent_module ($id_alert_agent_module, $noACLs = false) { - global $config; - - include_once ("include/functions_events.php"); - - $alerts = safe_int ($id_alert_agent_module, 1); - - if (empty ($alerts)) { - return false; - } - - $alerts = (array) $alerts; - - foreach ($alerts as $id) { - $alert = alerts_get_alert_agent_module ($id); - $agent_id = modules_get_agentmodule_agent ($alert["id_agent_module"]); - $group_id = agents_get_agent_group ($agent_id); - $critical_instructions = db_get_value('critical_instructions', 'tagente_modulo', 'id_agente_modulo', $agent_id); - $warning_instructions = db_get_value('warning_instructions', 'tagente_modulo', 'id_agente_modulo', $agent_id); - $unknown_instructions = db_get_value('unknown_instructions', 'tagente_modulo', 'id_agente_modulo', $agent_id); - - if (!$noACLs) { - if (! check_acl ($config['id_user'], $group_id, "AW")) { - continue; - } - } - $result = db_process_sql_update ('talert_template_modules', - array ('times_fired' => 0, - 'internal_counter' => 0), - array ('id' => $id)); - - - if ($result > 0) { - // Update fired alert count on the agent - db_process_sql(sprintf('UPDATE tagente SET update_alert_count=1 WHERE id_agente = %d', $agent_id)); - - events_create_event ("Manual validation of alert for ". - alerts_get_alert_template_description ($alert["id_alert_template"]), - $group_id, $agent_id, 1, $config["id_user"], - "alert_manual_validation", 1, $alert["id_agent_module"], - $id, $critical_instructions, $warning_instructions, $unknown_instructions); - } - elseif ($result === false) { - return false; - } - } - return true; +function alerts_validate_alert_agent_module($id_alert_agent_module, $noACLs=false) +{ + global $config; + + include_once 'include/functions_events.php'; + + $alerts = safe_int($id_alert_agent_module, 1); + + if (empty($alerts)) { + return false; + } + + $alerts = (array) $alerts; + + foreach ($alerts as $id) { + $alert = alerts_get_alert_agent_module($id); + $agent_id = modules_get_agentmodule_agent($alert['id_agent_module']); + $group_id = agents_get_agent_group($agent_id); + $critical_instructions = db_get_value('critical_instructions', 'tagente_modulo', 'id_agente_modulo', $agent_id); + $warning_instructions = db_get_value('warning_instructions', 'tagente_modulo', 'id_agente_modulo', $agent_id); + $unknown_instructions = db_get_value('unknown_instructions', 'tagente_modulo', 'id_agente_modulo', $agent_id); + + if (!$noACLs) { + if (! check_acl($config['id_user'], $group_id, 'AW')) { + continue; + } + } + + $result = db_process_sql_update( + 'talert_template_modules', + [ + 'times_fired' => 0, + 'internal_counter' => 0, + ], + ['id' => $id] + ); + + if ($result > 0) { + // Update fired alert count on the agent + db_process_sql(sprintf('UPDATE tagente SET update_alert_count=1 WHERE id_agente = %d', $agent_id)); + + events_create_event( + 'Manual validation of alert for '.alerts_get_alert_template_description($alert['id_alert_template']), + $group_id, + $agent_id, + 1, + $config['id_user'], + 'alert_manual_validation', + 1, + $alert['id_agent_module'], + $id, + $critical_instructions, + $warning_instructions, + $unknown_instructions + ); + } else if ($result === false) { + return false; + } + } + + return true; } + /** * Copy an alert defined in a module agent to other module agent. - * + * * This function avoid duplicated insertion. - * + * * @param int Source agent module id. * @param int Detiny agent module id. * * @return New alert id on success. Existing alert id if it already exists. * False on error. */ -function alerts_copy_alert_module_to_module ($id_agent_alert, $id_destiny_module) { - global $config; - - $alert = alerts_get_alert_agent_module ($id_agent_alert); - if ($alert === false) - return false; - - $alerts = alerts_get_alerts_agent_module ($id_destiny_module, false, - array ('id_alert_template' => $alert['id_alert_template'])); - if (! empty ($alerts)) { - return $alerts[0]['id']; - } - - /* PHP copy arrays on assignment */ - $new_alert = array (); - $new_alert['id_agent_module'] = (int) $id_destiny_module; - $new_alert['id_alert_template'] = $alert['id_alert_template']; - - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $id_new_alert = @db_process_sql_insert ( - 'talert_template_modules', $new_alert); - break; - case "oracle": - $id_new_alert = @db_process_sql_insert ( - 'talert_template_modules', $new_alert, false); - break; - } - - if ($id_new_alert === false) { - return false; - } - - $actions = alerts_get_alert_agent_module_actions ($id_agent_alert); - if (empty ($actions)) - return $id_new_alert; - - foreach ($actions as $action) { - $result = alerts_add_alert_agent_module_action ($id_new_alert, $action['id'], - array ('fires_min' => $action['fires_min'], - 'fires_max' => $action['fires_max'])); - if ($result === false) - return false; - } - - return $id_new_alert; +function alerts_copy_alert_module_to_module($id_agent_alert, $id_destiny_module) +{ + global $config; + + $alert = alerts_get_alert_agent_module($id_agent_alert); + if ($alert === false) { + return false; + } + + $alerts = alerts_get_alerts_agent_module( + $id_destiny_module, + false, + ['id_alert_template' => $alert['id_alert_template']] + ); + if (! empty($alerts)) { + return $alerts[0]['id']; + } + + // PHP copy arrays on assignment + $new_alert = []; + $new_alert['id_agent_module'] = (int) $id_destiny_module; + $new_alert['id_alert_template'] = $alert['id_alert_template']; + + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $id_new_alert = @db_process_sql_insert( + 'talert_template_modules', + $new_alert + ); + break; + + case 'oracle': + $id_new_alert = @db_process_sql_insert( + 'talert_template_modules', + $new_alert, + false + ); + break; + } + + if ($id_new_alert === false) { + return false; + } + + $actions = alerts_get_alert_agent_module_actions($id_agent_alert); + if (empty($actions)) { + return $id_new_alert; + } + + foreach ($actions as $action) { + $result = alerts_add_alert_agent_module_action( + $id_new_alert, + $action['id'], + [ + 'fires_min' => $action['fires_min'], + 'fires_max' => $action['fires_max'], + ] + ); + if ($result === false) { + return false; + } + } + + return $id_new_alert; } + /** * Get agents with an specific alert template. * @@ -1558,47 +1898,56 @@ function alerts_copy_alert_module_to_module ($id_agent_alert, $id_destiny_module * * @return mixed Affected rows or false is something goes wrong. */ -function alerts_get_agents_with_alert_template ($id_alert_template, $id_group, $filter = false, $fields = false, $id_agents = false) { - global $config; - - if (empty ($id_alert_template)) - return false; - - if (! is_array ($filter)) - $filter = array (); - $filter[] = 'tagente_modulo.id_agente_modulo = talert_template_modules.id_agent_module'; - $filter[] = 'tagente_modulo.id_agente = tagente.id_agente'; - $filter['id_alert_template'] = $id_alert_template; - $filter['tagente_modulo.disabled'] = '<> 1'; - $filter['delete_pending'] = '<> 1'; - - if (empty ($id_agents)) { - switch ($config["dbtype"]) { - case "mysql": - $filter['`tagente`.id_agente'] = array_keys (agents_get_group_agents ($id_group, false, "none")); - break; - case "postgresql": - case "oracle": - $filter['tagente.id_agente'] = array_keys (agents_get_group_agents ($id_group, false, "none")); - break; - } - } - else { - switch ($config["dbtype"]) { - case "mysql": - $filter['`tagente`.id_agente'] = $id_agents; - break; - case "postgresql": - case "oracle": - $filter['tagente.id_agente'] = $id_agents; - break; - } - } - - return db_get_all_rows_filter ('tagente, tagente_modulo, talert_template_modules', - $filter, $fields); +function alerts_get_agents_with_alert_template($id_alert_template, $id_group, $filter=false, $fields=false, $id_agents=false) +{ + global $config; + + if (empty($id_alert_template)) { + return false; + } + + if (! is_array($filter)) { + $filter = []; + } + + $filter[] = 'tagente_modulo.id_agente_modulo = talert_template_modules.id_agent_module'; + $filter[] = 'tagente_modulo.id_agente = tagente.id_agente'; + $filter['id_alert_template'] = $id_alert_template; + $filter['tagente_modulo.disabled'] = '<> 1'; + $filter['delete_pending'] = '<> 1'; + + if (empty($id_agents)) { + switch ($config['dbtype']) { + case 'mysql': + $filter['`tagente`.id_agente'] = array_keys(agents_get_group_agents($id_group, false, 'none')); + break; + + case 'postgresql': + case 'oracle': + $filter['tagente.id_agente'] = array_keys(agents_get_group_agents($id_group, false, 'none')); + break; + } + } else { + switch ($config['dbtype']) { + case 'mysql': + $filter['`tagente`.id_agente'] = $id_agents; + break; + + case 'postgresql': + case 'oracle': + $filter['tagente.id_agente'] = $id_agents; + break; + } + } + + return db_get_all_rows_filter( + 'tagente, tagente_modulo, talert_template_modules', + $filter, + $fields + ); } + /** * Get type name for alerts (e-mail, text, internal, ...) based on type number * @@ -1606,63 +1955,79 @@ function alerts_get_agents_with_alert_template ($id_alert_template, $id_group, $ * * @return string Type name of the alert. */ -function get_alert_type ($id_type) { - return (string) db_get_value ('name', 'talert_templates', 'id', (int) $id_type); +function get_alert_type($id_type) +{ + return (string) db_get_value('name', 'talert_templates', 'id', (int) $id_type); } + /** * Get all the fired of alerts happened in an Agent during a period of time. * * The returned alerts will be in the time interval ($date - $period, $date] * - * @param int $id_agent Agent id to get events. - * @param int $period Period of time in seconds to get events. - * @param int $date Beginning date to get events. + * @param integer $id_agent Agent id to get events. + * @param integer $period Period of time in seconds to get events. + * @param integer $date Beginning date to get events. * * @return array An array with all the events happened. */ -function get_agent_alert_fired ($id_agent, $id_alert, $period, $date = 0) { - if (!is_numeric ($date)) { - $date = time_w_fixed_tz($date); - } - if (empty ($date)) { - $date = get_system_time(); - } - - $datelimit = $date - $period; - - $sql = sprintf ('SELECT timestamp +function get_agent_alert_fired($id_agent, $id_alert, $period, $date=0) +{ + if (!is_numeric($date)) { + $date = time_w_fixed_tz($date); + } + + if (empty($date)) { + $date = get_system_time(); + } + + $datelimit = ($date - $period); + + $sql = sprintf( + 'SELECT timestamp FROM tevento WHERE id_agente = %d AND utimestamp > %d AND utimestamp <= %d AND id_alert_am = %d - ORDER BY timestamp DESC', $id_agent, $datelimit, $date, $id_alert); - - return db_get_all_rows_sql ($sql); + ORDER BY timestamp DESC', + $id_agent, + $datelimit, + $date, + $id_alert + ); + + return db_get_all_rows_sql($sql); } + /** * Get all the fired of alerts happened in an Agent module during a period of time. * * The returned alerts will be in the time interval ($date - $period, $date] * - * @param int $id_agent_module Agent module id to get events. - * @param int $period Period of time in seconds to get events. - * @param int $date Beginning date to get events. + * @param integer $id_agent_module Agent module id to get events. + * @param integer $period Period of time in seconds to get events. + * @param integer $date Beginning date to get events. * * @return array An array with all the events happened. */ -function get_module_alert_fired ($id_agent_module, $id_alert) { - - $sql = sprintf ('SELECT * +function get_module_alert_fired($id_agent_module, $id_alert) +{ + $sql = sprintf( + 'SELECT * FROM tevento WHERE id_agentmodule = %d AND id_alert_am = %d - ORDER BY timestamp DESC', $id_agent_module, $id_alert); - - return db_get_all_rows_sql ($sql); + ORDER BY timestamp DESC', + $id_agent_module, + $id_alert + ); + + return db_get_all_rows_sql($sql); } + /** * Get all the times an alerts fired during a period. * @@ -1670,134 +2035,153 @@ function get_module_alert_fired ($id_agent_module, $id_alert) { * @param int Period timed to check from date * @param int Date to check (current time by default) * - * @return int The number of times an alert fired. + * @return integer The number of times an alert fired. */ -function get_alert_fires_in_period ($id_alert_module, $period, $date = 0) { - global $config; - - if (!$date) - $date = get_system_time (); - - $datelimit = $date - $period; - - switch ($config["dbtype"]) { - case "mysql": - $sql = sprintf ("SELECT COUNT(`id_agentmodule`) +function get_alert_fires_in_period($id_alert_module, $period, $date=0) +{ + global $config; + + if (!$date) { + $date = get_system_time(); + } + + $datelimit = ($date - $period); + + switch ($config['dbtype']) { + case 'mysql': + $sql = sprintf( + "SELECT COUNT(`id_agentmodule`) FROM `tevento` WHERE `event_type` = 'alert_fired' AND `id_alert_am` = %d AND `utimestamp` > %d AND `utimestamp` <= %d", - $id_alert_module, $datelimit, $date); - break; - case "postgresql": - case "oracle": - $sql = sprintf ("SELECT COUNT(id_agentmodule) + $id_alert_module, + $datelimit, + $date + ); + break; + + case 'postgresql': + case 'oracle': + $sql = sprintf( + "SELECT COUNT(id_agentmodule) FROM tevento WHERE event_type = 'alert_fired' AND id_alert_am = %d AND utimestamp > %d AND utimestamp <= %d", - $id_alert_module, $datelimit, $date); - break; - } - - return (int) db_get_sql ($sql); + $id_alert_module, + $datelimit, + $date + ); + break; + } + + return (int) db_get_sql($sql); } + /** * Get all the alerts defined in a group. * * It gets all the alerts of all the agents on a given group. * - * @param int $id_group Group id to check. + * @param integer $id_group Group id to check. * * @return array An array with alerts dictionaries defined in a group. */ -function get_group_alerts($id_group, $filter = '', $options = false, - $where = '', $allModules = false, $orderby = false, - $idGroup = false, $count = false, $strict_user = false, $tag = false, $action_filter = false) { +function get_group_alerts( + $id_group, + $filter='', + $options=false, + $where='', + $allModules=false, + $orderby=false, + $idGroup=false, + $count=false, + $strict_user=false, + $tag=false, + $action_filter=false +) { + global $config; - global $config; - - $group_query = ''; - if (!empty($idGroup)) { - $group_query = ' AND id_grupo = ' . $idGroup; - } - - if (is_array($filter)) { - $disabled = $filter['disabled']; - if (isset($filter['standby'])) { - $filter = $group_query . ' AND talert_template_modules.standby = "'.$filter['standby'].'"'; - } - else { - $filter = $group_query; - } - } - else { - $filter = $group_query; - $disabled = $filter; - } - - switch ($disabled) { - case "notfired": - $filter .= ' AND times_fired = 0 AND talert_template_modules.disabled = 0'; - break; - case "fired": - $filter .= ' AND times_fired > 0 AND talert_template_modules.disabled = 0'; - break; - case "disabled": - $filter .= ' AND talert_template_modules.disabled = 1'; - break; - case "all_enabled": - $filter .= ' AND talert_template_modules.disabled = 0'; - break; - default: - $filter .= ''; - break; - } - - //WHEN SELECT ALL TAGS TO FILTER ALERTS - - $modules_tags = count(db_process_sql('select * from ttag')); - - $modules_user_tags = count(explode(",", $tag)); - - if($modules_tags != $modules_user_tags){ - if ($tag) { - $filter .= ' AND (id_agent_module IN (SELECT id_agente_modulo FROM ttag_module WHERE id_tag IN ('.$tag.')))'; - } + $group_query = ''; + if (!empty($idGroup)) { + $group_query = ' AND id_grupo = '.$idGroup; + } - } - - //WHEN SELECT ALL TAGS TO FILTER ALERTS - - if($action_filter){ - $filter .= ' AND (talert_template_modules.id IN (SELECT id_alert_template_module FROM talert_template_module_actions where id_alert_action = '.$action_filter.'))'; - } - if (is_array ($options)) { - $filter .= db_format_array_where_clause_sql ($options); - } - - - if ($id_group !== false) { - $groups = users_get_groups($config["id_user"], "AR"); + if (is_array($filter)) { + $disabled = $filter['disabled']; + if (isset($filter['standby'])) { + $filter = $group_query.' AND talert_template_modules.standby = "'.$filter['standby'].'"'; + } else { + $filter = $group_query; + } + } else { + $filter = $group_query; + $disabled = $filter; + } - if ($id_group != 0) { - if (is_array($id_group)) { - if (in_array(0, $id_group)) { - $id_group = 0; - } - } - - if (is_array($id_group)) { - if (empty($id_group)) { - $subQuery = 'SELECT id_agente_modulo + switch ($disabled) { + case 'notfired': + $filter .= ' AND times_fired = 0 AND talert_template_modules.disabled = 0'; + break; + + case 'fired': + $filter .= ' AND times_fired > 0 AND talert_template_modules.disabled = 0'; + break; + + case 'disabled': + $filter .= ' AND talert_template_modules.disabled = 1'; + break; + + case 'all_enabled': + $filter .= ' AND talert_template_modules.disabled = 0'; + break; + + default: + $filter .= ''; + break; + } + + // WHEN SELECT ALL TAGS TO FILTER ALERTS + $modules_tags = count(db_process_sql('select * from ttag')); + + $modules_user_tags = count(explode(',', $tag)); + + if ($modules_tags != $modules_user_tags) { + if ($tag) { + $filter .= ' AND (id_agent_module IN (SELECT id_agente_modulo FROM ttag_module WHERE id_tag IN ('.$tag.')))'; + } + } + + // WHEN SELECT ALL TAGS TO FILTER ALERTS + if ($action_filter) { + $filter .= ' AND (talert_template_modules.id IN (SELECT id_alert_template_module FROM talert_template_module_actions where id_alert_action = '.$action_filter.'))'; + } + + if (is_array($options)) { + $filter .= db_format_array_where_clause_sql($options); + } + + if ($id_group !== false) { + $groups = users_get_groups($config['id_user'], 'AR'); + + if ($id_group != 0) { + if (is_array($id_group)) { + if (in_array(0, $id_group)) { + $id_group = 0; + } + } + + if (is_array($id_group)) { + if (empty($id_group)) { + $subQuery = 'SELECT id_agente_modulo FROM tagente_modulo WHERE 1 = 0'; - } - else { - $subQuery = 'SELECT id_agente_modulo + } else { + $subQuery = 'SELECT id_agente_modulo FROM tagente_modulo WHERE delete_pending = 0 AND id_agente IN (SELECT id_agente @@ -1805,52 +2189,48 @@ function get_group_alerts($id_group, $filter = '', $options = false, LEFT JOIN tagent_secondary_group tasg ON ta.id_agente = tasg.id_agent WHERE - id_grupo IN (' . implode(',', $id_group) . ') - OR id_group IN (' . implode(',', $id_group) . '))'; - - } - } - else { - $subQuery = 'SELECT id_agente_modulo + id_grupo IN ('.implode(',', $id_group).') + OR id_group IN ('.implode(',', $id_group).'))'; + } + } else { + $subQuery = 'SELECT id_agente_modulo FROM tagente_modulo WHERE delete_pending = 0 AND id_agente IN (SELECT id_agente - FROM tagente WHERE id_grupo = ' . $idGroup . ')'; - } - } - else { - //ALL GROUP - $subQuery = 'SELECT id_agente_modulo + FROM tagente WHERE id_grupo = '.$idGroup.')'; + } + } else { + // ALL GROUP + $subQuery = 'SELECT id_agente_modulo FROM tagente_modulo WHERE delete_pending = 0'; - } + } + } else { + if ($allModules) { + $disabled = ''; + } else { + $disabled = 'WHERE disabled = 0'; + } - } - else { - if ($allModules) - $disabled = ''; - else - $disabled = 'WHERE disabled = 0'; - - $subQuery = 'SELECT id_agente_modulo - FROM tagente_modulo ' . $disabled; - } - - $orderbyText = ''; - if ($orderby !== false) { - if (is_array($orderby)) { - $orderbyText = sprintf("ORDER BY %s", $orderby['field'], $orderby['order']); - } - else { - $orderbyText = sprintf("ORDER BY %s", $orderby); - } - } - - $selectText = 'DISTINCT talert_template_modules.*, t2.nombre AS agent_module_name, t3.alias AS agent_name, t4.name AS template_name'; - if ($count !== false) { - $selectText = 'COUNT(DISTINCT talert_template_modules.id) AS count'; - } - - $sql = sprintf ("SELECT %s + $subQuery = 'SELECT id_agente_modulo + FROM tagente_modulo '.$disabled; + } + + $orderbyText = ''; + if ($orderby !== false) { + if (is_array($orderby)) { + $orderbyText = sprintf('ORDER BY %s', $orderby['field'], $orderby['order']); + } else { + $orderbyText = sprintf('ORDER BY %s', $orderby); + } + } + + $selectText = 'DISTINCT talert_template_modules.*, t2.nombre AS agent_module_name, t3.alias AS agent_name, t4.name AS template_name'; + if ($count !== false) { + $selectText = 'COUNT(DISTINCT talert_template_modules.id) AS count'; + } + + $sql = sprintf( + 'SELECT %s FROM talert_template_modules INNER JOIN tagente_modulo t2 ON talert_template_modules.id_agent_module = t2.id_agente_modulo @@ -1860,21 +2240,27 @@ function get_group_alerts($id_group, $filter = '', $options = false, ON tasg.id_agent = t2.id_agente INNER JOIN talert_templates t4 ON talert_template_modules.id_alert_template = t4.id - WHERE id_agent_module in (%s) %s %s %s", - $selectText, $subQuery, $where, $filter, $orderbyText); - $alerts = db_get_all_rows_sql ($sql); + WHERE id_agent_module in (%s) %s %s %s', + $selectText, + $subQuery, + $where, + $filter, + $orderbyText + ); + $alerts = db_get_all_rows_sql($sql); - if ($alerts === false) - return array (); - - if ($count !== false) { - return $alerts[0]['count']; - } - else { - return $alerts; - } + if ($alerts === false) { + return []; + } + + if ($count !== false) { + return $alerts[0]['count']; + } else { + return $alerts; + } } + /** * Get all the alerts fired during a period, given a list of alerts. * @@ -1885,29 +2271,36 @@ function get_group_alerts($id_group, $filter = '', $options = false, * @return array An array with the alert id as key and the number of times * the alert was fired (only included if it was fired). */ -function get_alerts_fired ($alerts, $period = 0, $date = 0) { - if (! $date) - $date = get_system_time (); - - $datelimit = $date - $period; - - $alerts_fired = array (); - $agents = array (); - - foreach ($alerts as $alert) { - if (isset($alert['id'])) { - $fires = get_alert_fires_in_period($alert['id'], - $period, $date); - if (! $fires) { - continue; - } - $alerts_fired[$alert['id']] = $fires; - } - } - - return $alerts_fired; +function get_alerts_fired($alerts, $period=0, $date=0) +{ + if (! $date) { + $date = get_system_time(); + } + + $datelimit = ($date - $period); + + $alerts_fired = []; + $agents = []; + + foreach ($alerts as $alert) { + if (isset($alert['id'])) { + $fires = get_alert_fires_in_period( + $alert['id'], + $period, + $date + ); + if (! $fires) { + continue; + } + + $alerts_fired[$alert['id']] = $fires; + } + } + + return $alerts_fired; } + /** * Get the last time an alert fired during a period. * @@ -1915,98 +2308,124 @@ function get_alerts_fired ($alerts, $period = 0, $date = 0) { * @param int Period timed to check from date * @param int Date to check (current date by default) * - * @return int The last time an alert fired. It's an UNIX timestamp. + * @return integer The last time an alert fired. It's an UNIX timestamp. */ -function get_alert_last_fire_timestamp_in_period ($id_alert_module, $period, $date = 0) { - global $config; - - if ($date == 0) { - $date = get_system_time (); - } - $datelimit = $date - $period; - - switch ($config["dbtype"]) { - case "mysql": - $sql = sprintf ("SELECT MAX(`utimestamp`) +function get_alert_last_fire_timestamp_in_period($id_alert_module, $period, $date=0) +{ + global $config; + + if ($date == 0) { + $date = get_system_time(); + } + + $datelimit = ($date - $period); + + switch ($config['dbtype']) { + case 'mysql': + $sql = sprintf( + "SELECT MAX(`utimestamp`) FROM `tevento` WHERE `event_type` = 'alert_fired' AND `id_alert_am` = %d AND `utimestamp` > %d AND `utimestamp` <= %d", - $id_alert_module, $datelimit, $date); - break; - case "postgresql": - case "oracle": - $sql = sprintf ("SELECT MAX(utimestamp) + $id_alert_module, + $datelimit, + $date + ); + break; + + case 'postgresql': + case 'oracle': + $sql = sprintf( + "SELECT MAX(utimestamp) FROM tevento WHERE event_type = 'alert_fired' AND id_alert_am = %d AND utimestamp > %d AND utimestamp <= %d", - $id_alert_module, $datelimit, $date); - break; - } - - return db_get_sql ($sql); + $id_alert_module, + $datelimit, + $date + ); + break; + } + + return db_get_sql($sql); } + /** * Insert in talert_special_days a new special day. * * @param date of special day. * @param same day of the week. * @param mixed A single value or array of values to insert (can be a multiple a mount of rows). - * + * * @return mixed False in case of error or invalid values passed. Affected rows otherwise. */ -function alerts_create_alert_special_day ($date, $same_day, $values = false) { - if (empty ($date)) - return false; - if (empty ($same_day)) - return false; - - if (! is_array ($values)) - $values = array (); +function alerts_create_alert_special_day($date, $same_day, $values=false) +{ + if (empty($date)) { + return false; + } - global $config; - $date_db = ''; + if (empty($same_day)) { + return false; + } - switch ($config['dbtype']) { - case "mysql": - $date_db = 'date'; - break; - case "oracle": - $date_db = '"date"'; - break; - } + if (! is_array($values)) { + $values = []; + } + + global $config; + $date_db = ''; + + switch ($config['dbtype']) { + case 'mysql': + $date_db = 'date'; + break; + + case 'oracle': + $date_db = '"date"'; + break; + } + + $values[$date_db] = $date; + $values['same_day'] = $same_day; + + return @db_process_sql_insert('talert_special_days', $values); +} - $values[$date_db] = $date; - $values['same_day'] = $same_day; - - return @db_process_sql_insert ('talert_special_days', $values); -} /** * Update a special day in talert_special_days. * * @param int special day Id. * @param mixed Array of values to update. - * + * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function alerts_update_alert_special_day ($id_special_day, $values) { - $id_special_day = safe_int ($id_special_day, 1); - - if (empty ($id_special_day)) - return false; - if (! is_array ($values)) - return false; - - return (@db_process_sql_update ('talert_special_days', - $values, - array ('id' => $id_special_day))) !== false; +function alerts_update_alert_special_day($id_special_day, $values) +{ + $id_special_day = safe_int($id_special_day, 1); + + if (empty($id_special_day)) { + return false; + } + + if (! is_array($values)) { + return false; + } + + return (@db_process_sql_update( + 'talert_special_days', + $values, + ['id' => $id_special_day] + )) !== false; } + /** * Delete a special day in talert_special_days. * @@ -2014,260 +2433,268 @@ function alerts_update_alert_special_day ($id_special_day, $values) { * * @return mixed False in case of error or invalid values passed. Affected rows otherwise */ -function alerts_delete_alert_special_day ($id_special_day) { - $id_special_day = safe_int ($id_special_day, 1); - - if (empty ($id_special_day)) - return false; - - return (@db_process_sql_delete ('talert_special_days', - array ('id' => $id_special_day))) !== false; +function alerts_delete_alert_special_day($id_special_day) +{ + $id_special_day = safe_int($id_special_day, 1); + + if (empty($id_special_day)) { + return false; + } + + return (@db_process_sql_delete( + 'talert_special_days', + ['id' => $id_special_day] + )) !== false; } + /** * Get a special day in talert_special_days. * * @param int special day Id. - * + * * @return mixed False in case of error or invalid values passed. All row of the selected command otherwise */ -function alerts_get_alert_special_day ($id_special_day) { - $id_special_day = safe_int ($id_special_day, 1); - - if (empty ($id_special_day)) - return false; - - return db_get_row ('talert_special_days', 'id', $id_special_day); +function alerts_get_alert_special_day($id_special_day) +{ + $id_special_day = safe_int($id_special_day, 1); + + if (empty($id_special_day)) { + return false; + } + + return db_get_row('talert_special_days', 'id', $id_special_day); } + /** * Get number of alert fired that an action is executed. Only fot non default alerts - * + * * @param mixed action - * - * @return mixed array with numeric indexes and 0|1 values for not executing or executing. + * + * @return mixed array with numeric indexes and 0|1 values for not executing or executing. * Returned 'everytime' for always situations * Returned $escalation['greater_than'] = VALUE for 'min - infinite' situations */ -function alerts_get_action_escalation($action) { - $escalation = array(); - - if ($action['fires_min'] == 0 && $action['fires_max'] == 0) { - $escalation = 'everytime'; - } - else if($action['fires_min'] == $action['fires_max']) { - for($i=1;$i<$action['fires_min'];$i++) { - $escalation[$i] = 0; - } - $escalation[$action['fires_max']] = 1; - } - else if($action['fires_min'] < $action['fires_max']) { - for($i=1;$i<=$action['fires_max'];$i++) { - if ($i <= $action['fires_min']) { - $escalation[$i] = 0; - } - else { - $escalation[$i] = 1; - } - } - } - else if($action['fires_min'] > $action['fires_max']) { - $escalation['greater_than'] = $action['fires_min']; - } - - return $escalation; +function alerts_get_action_escalation($action) +{ + $escalation = []; + + if ($action['fires_min'] == 0 && $action['fires_max'] == 0) { + $escalation = 'everytime'; + } else if ($action['fires_min'] == $action['fires_max']) { + for ($i = 1; $i < $action['fires_min']; $i++) { + $escalation[$i] = 0; + } + + $escalation[$action['fires_max']] = 1; + } else if ($action['fires_min'] < $action['fires_max']) { + for ($i = 1; $i <= $action['fires_max']; $i++) { + if ($i <= $action['fires_min']) { + $escalation[$i] = 0; + } else { + $escalation[$i] = 1; + } + } + } else if ($action['fires_min'] > $action['fires_max']) { + $escalation['greater_than'] = $action['fires_min']; + } + + return $escalation; } /** * Get escalation of all the actions - * + * * @param mixed Actions of an alert * @param mixed Default action of an alert - * + * * @return mixed Actions array including the default action and the escalation of each action */ -function alerts_get_actions_escalation($actions, $default_action = 0) { - $escalation = array(); - foreach($actions as $kaction => $action) { - $escalation[$kaction] = alerts_get_action_escalation($action); - } - - $default_escalation = alerts_get_default_action_escalation($default_action, $escalation); - $escalation = array(0 => $default_escalation) + $escalation; - - $escalation = alerts_normalize_actions_escalation($escalation); +function alerts_get_actions_escalation($actions, $default_action=0) +{ + $escalation = []; + foreach ($actions as $kaction => $action) { + $escalation[$kaction] = alerts_get_action_escalation($action); + } - // Join the actions with the default action - $actions = array(0 => $default_action) + $actions; - - // Add the escalation values to the actions array - foreach(array_keys($actions) as $kaction) { - $actions[$kaction]['escalation'] = $escalation[$kaction]; - } - - return $actions; + $default_escalation = alerts_get_default_action_escalation($default_action, $escalation); + $escalation = ([0 => $default_escalation] + $escalation); + + $escalation = alerts_normalize_actions_escalation($escalation); + + // Join the actions with the default action + $actions = ([0 => $default_action] + $actions); + + // Add the escalation values to the actions array + foreach (array_keys($actions) as $kaction) { + $actions[$kaction]['escalation'] = $escalation[$kaction]; + } + + return $actions; } + /** * Get escalation of default action. A default action will be executed when the alert is fired and * no other action is executed - * + * * @param mixed Default action of the alert * @param mixed Escalation of all the other actions - * + * * @return mixed Array with the escalation of the default alert */ -function alerts_get_default_action_escalation($default_action, $escalation) { - if ($default_action === 0) { - return array(); - } - - $busy_times = array(); - $busy_greater_than = -1; - foreach($escalation as $action_escalation) { - if ($action_escalation == 'everytime') { - return 'never'; - } - else if (isset($action_escalation['greater_than'])) { - if ($busy_greater_than == -1 || $action_escalation['greater_than'] < $busy_greater_than) { - $busy_greater_than = $action_escalation['greater_than']; - } - } - else { - foreach($action_escalation as $k => $v) { - if (!isset($busy_times[$k])) { - $busy_times[$k] = 0; - } - - $busy_times[$k] += $v; - } - } - } - - // Set to 1 the busy executions - // Set to 2 the min - infinite situations - foreach($busy_times as $k => $v) { - if ($busy_greater_than != -1) { - if ($k == ($busy_greater_than + 1)) { - $busy_times[$k] = 2; - } - else if ($k > ($busy_greater_than + 1)) { - unset($busy_times[$k]); - } - } - else if ($v > 1) { - $busy_times[$k] = 1; - } - } - - // Fill gaps from last busy to greater than - if ($busy_greater_than != -1) { - for($i=(count($busy_times)+1);$i<=$busy_greater_than;$i++) { - $busy_times[$i] = 0; - } - $busy_times[$i] = 2; - } +function alerts_get_default_action_escalation($default_action, $escalation) +{ + if ($default_action === 0) { + return []; + } - // Set as default execution the not busy times - $default_escalation = array(); - foreach($busy_times as $k => $v) { - switch($v) { - case 0: - $default_escalation[$k] = 1; - break; - default: - $default_escalation[$k] = 0; - break; - } - - // Last element - if ($k == count($busy_times)) { - switch($v) { - case 2: - if ($default_escalation[$k] == 0) { - unset($default_escalation[$k]); - } - break; - default: - $default_escalation[$k+1] = 1; - break; - } - } - } - - if (empty($busy_times)) { - if ($busy_greater_than == -1) { - $default_escalation = 'everytime'; - } - else { - for($i=1;$i<=$busy_greater_than;$i++) { - $default_escalation[$i] = 1; - } - } - } - - return $default_escalation; + $busy_times = []; + $busy_greater_than = -1; + foreach ($escalation as $action_escalation) { + if ($action_escalation == 'everytime') { + return 'never'; + } else if (isset($action_escalation['greater_than'])) { + if ($busy_greater_than == -1 || $action_escalation['greater_than'] < $busy_greater_than) { + $busy_greater_than = $action_escalation['greater_than']; + } + } else { + foreach ($action_escalation as $k => $v) { + if (!isset($busy_times[$k])) { + $busy_times[$k] = 0; + } + + $busy_times[$k] += $v; + } + } + } + + // Set to 1 the busy executions + // Set to 2 the min - infinite situations + foreach ($busy_times as $k => $v) { + if ($busy_greater_than != -1) { + if ($k == ($busy_greater_than + 1)) { + $busy_times[$k] = 2; + } else if ($k > ($busy_greater_than + 1)) { + unset($busy_times[$k]); + } + } else if ($v > 1) { + $busy_times[$k] = 1; + } + } + + // Fill gaps from last busy to greater than + if ($busy_greater_than != -1) { + for ($i = (count($busy_times) + 1); $i <= $busy_greater_than; $i++) { + $busy_times[$i] = 0; + } + + $busy_times[$i] = 2; + } + + // Set as default execution the not busy times + $default_escalation = []; + foreach ($busy_times as $k => $v) { + switch ($v) { + case 0: + $default_escalation[$k] = 1; + break; + + default: + $default_escalation[$k] = 0; + break; + } + + // Last element + if ($k == count($busy_times)) { + switch ($v) { + case 2: + if ($default_escalation[$k] == 0) { + unset($default_escalation[$k]); + } + break; + + default: + $default_escalation[($k + 1)] = 1; + break; + } + } + } + + if (empty($busy_times)) { + if ($busy_greater_than == -1) { + $default_escalation = 'everytime'; + } else { + for ($i = 1; $i <= $busy_greater_than; $i++) { + $default_escalation[$i] = 1; + } + } + } + + return $default_escalation; } + /** - * Normalize escalation to have same number of elements setting all + * Normalize escalation to have same number of elements setting all * of them the same number of elements - * + * * @param mixed Escalation of the alerts - * + * * @return mixed Escalation of the alerts with same number of elements * */ -function alerts_normalize_actions_escalation($escalation) { - $max_elements = 0; - $any_greater_than = false; - foreach($escalation as $k => $v) { - if (is_array($v) && isset($v['greater_than'])) { - $escalation[$k] = array(); - for($i=1;$i<$v['greater_than'];$i++) { - $escalation[$k][$i] = 0; - } - $escalation[$k][$v['greater_than']] = 2; - $any_greater_than = true; - } - - $n = count($escalation[$k]); - if ($n > $max_elements) { - $max_elements = $n; - } - } +function alerts_normalize_actions_escalation($escalation) +{ + $max_elements = 0; + $any_greater_than = false; + foreach ($escalation as $k => $v) { + if (is_array($v) && isset($v['greater_than'])) { + $escalation[$k] = []; + for ($i = 1; $i < $v['greater_than']; $i++) { + $escalation[$k][$i] = 0; + } - if ($max_elements == 1 || !$any_greater_than) { - $nelements = $max_elements; - } - else { - $nelements = $max_elements+1; - } - - foreach($escalation as $k => $v) { - if ($v == 'everytime') { - $escalation[$k] = array_fill(1, $nelements, 1); - $escalation[$k][$max_elements] = 2; - } - else if ($v == 'never') { - $escalation[$k] = array_fill(1, $nelements, 0); - } - else { - $fill_value = 0; - for($i=1;$i<=$nelements;$i++) { - if (!isset($escalation[$k][$i])) { - $escalation[$k][$i] = $fill_value; - } - else if ($escalation[$k][$i] == 2) { - $fill_value = 1; - $escalation[$k][$i] = 0; - } - } - } - } - - return $escalation; + $escalation[$k][$v['greater_than']] = 2; + $any_greater_than = true; + } + + $n = count($escalation[$k]); + if ($n > $max_elements) { + $max_elements = $n; + } + } + + if ($max_elements == 1 || !$any_greater_than) { + $nelements = $max_elements; + } else { + $nelements = ($max_elements + 1); + } + + foreach ($escalation as $k => $v) { + if ($v == 'everytime') { + $escalation[$k] = array_fill(1, $nelements, 1); + $escalation[$k][$max_elements] = 2; + } else if ($v == 'never') { + $escalation[$k] = array_fill(1, $nelements, 0); + } else { + $fill_value = 0; + for ($i = 1; $i <= $nelements; $i++) { + if (!isset($escalation[$k][$i])) { + $escalation[$k][$i] = $fill_value; + } else if ($escalation[$k][$i] == 2) { + $fill_value = 1; + $escalation[$k][$i] = 0; + } + } + } + } + + return $escalation; } + + /** * Check if a command can be added to an action. * @@ -2276,113 +2703,123 @@ function alerts_normalize_actions_escalation($escalation) { * * @return False if command group and alert group are distint of 0 and they are not equal */ -function alerts_validate_command_to_action($action_group, $command_group) { - // If action group or command group is All, all commands can be applicated. - if ($action_group == 0 || $command_group == 0) return true; - return $action_group == $command_group; +function alerts_validate_command_to_action($action_group, $command_group) +{ + // If action group or command group is All, all commands can be applicated. + if ($action_group == 0 || $command_group == 0) { + return true; + } + + return $action_group == $command_group; } + /** * Print the UI update actions * * @param bool Update or create */ -function alerts_ui_update_or_create_actions($update = true) { - global $config; - $id = (string) get_parameter ('id'); +function alerts_ui_update_or_create_actions($update=true) +{ + global $config; + $id = (string) get_parameter('id'); - // Check ACL of existing aler action - if($update) { - $al_action = alerts_get_alert_action ($id); - if ($al_action !== false) { - if ($al_action['id_group'] == 0) { - if (! check_acl ($config['id_user'], 0, "PM")) { - db_pandora_audit("ACL Violation", - "Trying to access Alert Management"); - require ("general/noaccess.php"); - exit; - } - } - } - } + // Check ACL of existing aler action + if ($update) { + $al_action = alerts_get_alert_action($id); + if ($al_action !== false) { + if ($al_action['id_group'] == 0) { + if (! check_acl($config['id_user'], 0, 'PM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Alert Management' + ); + include 'general/noaccess.php'; + exit; + } + } + } + } - $name = (string) get_parameter ('name'); - $id_alert_command = (int) get_parameter ('id_command'); - $group = get_parameter ('group'); - $action_threshold = (int) get_parameter ('action_threshold'); + $name = (string) get_parameter('name'); + $id_alert_command = (int) get_parameter('id_command'); + $group = get_parameter('group'); + $action_threshold = (int) get_parameter('action_threshold'); - // Validate some values - if (!$id_alert_command) { - ui_print_error_message(__('No command specified')); - return; - } - if (!$name) { - ui_print_error_message(__('No name specified')); - return; - } - $comamnd_group = db_get_value('id_group', 'talert_commands', 'id', $id_alert_command); - if(!alerts_validate_command_to_action($group, $comamnd_group)) { - ui_print_error_message(__("Alert and command group does not match")); - return; - } + // Validate some values + if (!$id_alert_command) { + ui_print_error_message(__('No command specified')); + return; + } - // Fill fields info - $info_fields = ''; - $values = array(); - for ($i = 1; $i <= $config['max_macro_fields']; $i++) { - $values['field'.$i] = (string) get_parameter ('field'.$i.'_value'); - $info_fields .= ' Field'.$i.': ' . $values['field'.$i]; - $values['field'.$i.'_recovery'] = (string) get_parameter ('field'.$i.'_recovery_value'); - $info_fields .= ' Field'.$i.'Recovery: ' . $values['field'.$i.'_recovery']; - } + if (!$name) { + ui_print_error_message(__('No name specified')); + return; + } - $values['id_group'] = $group; - $values['action_threshold'] = $action_threshold; - if ($update) { - $values['name'] = $name; - $values['id_alert_command'] = $id_alert_command; - $result = (!$name) ? '' : alerts_update_alert_action ($id, $values); - } else { - $name_check = db_get_value ('name', 'talert_actions', 'name', $name); - if ($name_check) { - $result = ''; - } - else { - $result = alerts_create_alert_action ($name, $id_alert_command, - $values); - $values = array( - "Name" => $name, - "ID alert Command" => $id_alert_command, - "Field information" => $info_fields, - "Group" => $values['id_group'], - "Action threshold" => $values['action_threshold'] - ); - } - } + $comamnd_group = db_get_value('id_group', 'talert_commands', 'id', $id_alert_command); + if (!alerts_validate_command_to_action($group, $comamnd_group)) { + ui_print_error_message(__('Alert and command group does not match')); + return; + } - if ($result) { - db_pandora_audit( - "Command management", - $update ? "Update alert action #" . $id : "Create alert action #" . $result, - false, - false, - json_encode($values) - ); - } - else { - db_pandora_audit( - "Command management", - $update ? "Fail try to update alert action #" . $id : "Fail try to create alert action", - false, - false, - $update ? json_encode($values) : '' - ); - } + // Fill fields info + $info_fields = ''; + $values = []; + for ($i = 1; $i <= $config['max_macro_fields']; $i++) { + $values['field'.$i] = (string) get_parameter('field'.$i.'_value'); + $info_fields .= ' Field'.$i.': '.$values['field'.$i]; + $values['field'.$i.'_recovery'] = (string) get_parameter('field'.$i.'_recovery_value'); + $info_fields .= ' Field'.$i.'Recovery: '.$values['field'.$i.'_recovery']; + } - ui_print_result_message ($result, - $update ? __('Successfully updated') : __('Successfully created'), - $update ? __('Could not be updated') : __('Could not be created') - ); + $values['id_group'] = $group; + $values['action_threshold'] = $action_threshold; + if ($update) { + $values['name'] = $name; + $values['id_alert_command'] = $id_alert_command; + $result = (!$name) ? '' : alerts_update_alert_action($id, $values); + } else { + $name_check = db_get_value('name', 'talert_actions', 'name', $name); + if ($name_check) { + $result = ''; + } else { + $result = alerts_create_alert_action( + $name, + $id_alert_command, + $values + ); + $values = [ + 'Name' => $name, + 'ID alert Command' => $id_alert_command, + 'Field information' => $info_fields, + 'Group' => $values['id_group'], + 'Action threshold' => $values['action_threshold'], + ]; + } + } + + if ($result) { + db_pandora_audit( + 'Command management', + $update ? 'Update alert action #'.$id : 'Create alert action #'.$result, + false, + false, + json_encode($values) + ); + } else { + db_pandora_audit( + 'Command management', + $update ? 'Fail try to update alert action #'.$id : 'Fail try to create alert action', + false, + false, + $update ? json_encode($values) : '' + ); + } + + ui_print_result_message( + $result, + $update ? __('Successfully updated') : __('Successfully created'), + $update ? __('Could not be updated') : __('Could not be created') + ); } - -?> diff --git a/pandora_console/include/functions_api.php b/pandora_console/include/functions_api.php index 53479ae7ed..545d84d640 100644 --- a/pandora_console/include/functions_api.php +++ b/pandora_console/include/functions_api.php @@ -1,820 +1,952 @@ 'string', 'data' => urldecode($other)); - break; - default: - if (strpos($otherType, 'url_encode_separator_') !== false) { - $separator = str_replace('url_encode_separator_', '', $otherType); - $returnVar = array('type' => 'array', 'data' => explode($separator, $other)); - foreach ($returnVar['data'] as $index => $element) - $returnVar['data'][$index] = urldecode($element); - } - else { - $returnVar = array('type' => 'string', 'data' => urldecode($other)); - } - break; - } - - return $returnVar; +function parseOtherParameter($other, $otherType) +{ + switch ($otherType) { + case 'url_encode': + $returnVar = [ + 'type' => 'string', + 'data' => urldecode($other), + ]; + break; + + default: + if (strpos($otherType, 'url_encode_separator_') !== false) { + $separator = str_replace('url_encode_separator_', '', $otherType); + $returnVar = [ + 'type' => 'array', + 'data' => explode($separator, $other), + ]; + foreach ($returnVar['data'] as $index => $element) { + $returnVar['data'][$index] = urldecode($element); + } + } else { + $returnVar = [ + 'type' => 'string', + 'data' => urldecode($other), + ]; + } + break; + } + + return $returnVar; } + /** - * - * @param $typeError - * @param $returnType + * + * @param $typeError + * @param $returnType * @return unknown_type */ -function returnError($typeError, $returnType = 'string') { - switch ($typeError) { - case 'no_set_no_get_no_help': - returnData($returnType, - array('type' => 'string', 'data' => __('No set or get or help operation.'))); - break; - case 'no_exist_operation': - returnData($returnType, - array('type' => 'string', 'data' => __('This operation does not exist.'))); - break; - case 'id_not_found': - returnData($returnType, - array('type' => 'string', 'data' => __('Id does not exist in BD.'))); - break; - case 'not_allowed_operation_cluster': - returnData($returnType, - array('type' => 'string', 'data' => __('This operation can not be used in cluster elements.'))); - break; - case 'forbidden': - returnData($returnType, - array('type' => 'string', 'data' => __('The user has not enough permission to make this action.'))); - break; - case 'no_data_to_show': - returnData($returnType, - array('type' => 'string', 'data' => __('No data to show.'))); - break; - default: - returnData("string", - array('type' => 'string', 'data' => __($returnType))); - break; - } +function returnError($typeError, $returnType='string') +{ + switch ($typeError) { + case 'no_set_no_get_no_help': + returnData( + $returnType, + [ + 'type' => 'string', + 'data' => __('No set or get or help operation.'), + ] + ); + break; + + case 'no_exist_operation': + returnData( + $returnType, + [ + 'type' => 'string', + 'data' => __('This operation does not exist.'), + ] + ); + break; + + case 'id_not_found': + returnData( + $returnType, + [ + 'type' => 'string', + 'data' => __('Id does not exist in BD.'), + ] + ); + break; + + case 'not_allowed_operation_cluster': + returnData( + $returnType, + [ + 'type' => 'string', + 'data' => __('This operation can not be used in cluster elements.'), + ] + ); + break; + + case 'forbidden': + returnData( + $returnType, + [ + 'type' => 'string', + 'data' => __('The user has not enough permission to make this action.'), + ] + ); + break; + + case 'no_data_to_show': + returnData( + $returnType, + [ + 'type' => 'string', + 'data' => __('No data to show.'), + ] + ); + break; + + case 'centralized': + returnData( + $returnType, + [ + 'type' => 'string', + 'data' => __('This console is not manager of this environment, please manage this feature from centralized manager console (Metaconsole).'), + ] + ); + break; + + default: + returnData( + 'string', + [ + 'type' => 'string', + 'data' => __($returnType), + ] + ); + break; + } } + /** - * @param $returnType - * @param $data - * @param $separator + * @param $returnType + * @param $data + * @param $separator * @return */ -function returnData($returnType, $data, $separator = ';') { - switch ($returnType) { - case 'string': - if( is_array($data['data']) ){ - echo convert_array_multi($data['data'], $separator); - } - else{ - echo $data['data']; - } - break; - case 'csv': - case 'csv_head': - if( is_array($data['data']) ){ - if (array_key_exists('list_index', $data)) { - if ($returnType == 'csv_head') { - foreach($data['list_index'] as $index) { - echo $index; - if (end($data['list_index']) == $index) - echo "\n"; - else - echo $separator; - } - } - foreach($data['data'] as $dataContent) { - foreach($data['list_index'] as $index) { - if (array_key_exists($index, $dataContent)) - echo str_replace("\n", " ", $dataContent[$index]); - if (end($data['list_index']) == $index) - echo "\n"; - else - echo $separator; - } - } - } - else { - if (!empty($data['data'])) { - foreach ($data['data'] as $dataContent) { - $clean = array_map("array_apply_io_safe_output", $dataContent); - foreach ($clean as $k => $v) { - $clean[$k] = str_replace("\r", "\n", $clean[$k]); - $clean[$k] = str_replace("\n", " ", $clean[$k]); - $clean[$k] = strip_tags($clean[$k]); - $clean[$k] = str_replace(';',' ',$clean[$k]); - } - $row = implode($separator, $clean); - echo $row . "\n"; - } - } - } - } - else{ - echo $data['data']; - } - break; - case 'json': - $data = array_apply_io_safe_output($data); - header('Content-type: application/json'); - // Allows extra parameters to json_encode, like JSON_FORCE_OBJECT - if ($separator == ";") { - $separator = null; - } +function returnData($returnType, $data, $separator=';') +{ + switch ($returnType) { + case 'string': + if (is_array($data['data'])) { + echo convert_array_multi($data['data'], $separator); + } else { + echo $data['data']; + } + break; - if(empty($separator)){ - echo json_encode ($data); - } else { - echo json_encode ($data, $separator); - } + case 'csv': + case 'csv_head': + if (is_array($data['data'])) { + if (array_key_exists('list_index', $data)) { + if ($returnType == 'csv_head') { + foreach ($data['list_index'] as $index) { + echo $index; + if (end($data['list_index']) == $index) { + echo "\n"; + } else { + echo $separator; + } + } + } - break; - } + foreach ($data['data'] as $dataContent) { + foreach ($data['list_index'] as $index) { + if (array_key_exists($index, $dataContent)) { + echo str_replace("\n", ' ', $dataContent[$index]); + } + + if (end($data['list_index']) == $index) { + echo "\n"; + } else { + echo $separator; + } + } + } + } else { + if (!empty($data['data'])) { + foreach ($data['data'] as $dataContent) { + $clean = array_map('array_apply_io_safe_output', (array) $dataContent); + foreach ($clean as $k => $v) { + $clean[$k] = str_replace("\r", "\n", $clean[$k]); + $clean[$k] = str_replace("\n", ' ', $clean[$k]); + $clean[$k] = strip_tags($clean[$k]); + $clean[$k] = str_replace(';', ' ', $clean[$k]); + } + + $row = implode($separator, $clean); + echo $row."\n"; + } + } + } + } else { + echo $data['data']; + } + break; + + case 'json': + $data = array_apply_io_safe_output($data); + header('Content-type: application/json'); + // Allows extra parameters to json_encode, like JSON_FORCE_OBJECT + if ($separator == ';') { + $separator = null; + } + + if (empty($separator)) { + echo json_encode($data); + } else { + echo json_encode($data, $separator); + } + break; + } } -function array_apply_io_safe_output($item) { - return io_safe_output($item); + +function array_apply_io_safe_output($item) +{ + return io_safe_output($item); } + /** - * - * @param $ip + * + * @param $ip * @return unknown_type */ -function isInACL($ip) { - global $config; - - if (in_array($ip, $config['list_ACL_IPs_for_API'])) - return true; - - // If the IP is not in the list, we check one by one, all the wildcard registers - foreach($config['list_ACL_IPs_for_API'] as $acl_ip) { - if (preg_match('/\*/', $acl_ip)) { +function isInACL($ip) +{ + global $config; - if($acl_ip[0]=='*' && strlen($acl_ip)>1){ - //example *.lab.artica.es == 151.80.15.* - $acl_ip = str_replace('*.','',$acl_ip); - $name = array(); - $name = gethostbyname($acl_ip); - $names = explode('.',$name); - $names[3] = ""; - $names = implode('.',$names); - if (preg_match('/'.$names.'/', $ip)) { - return true; - } + if (in_array($ip, $config['list_ACL_IPs_for_API'])) { + return true; + } - }else{ - //example 192.168.70.* or * - $acl_ip = str_replace('.','\.',$acl_ip); - // Replace wilcard by .* to do efective in regular expression - $acl_ip = str_replace('*','.*',$acl_ip); - // If the string match with the beginning of the IP give it access - if (preg_match('/'.$acl_ip.'/', $ip)) { - return true; - } - } - // Scape for protection + // If the IP is not in the list, we check one by one, all the wildcard registers + foreach ($config['list_ACL_IPs_for_API'] as $acl_ip) { + if (preg_match('/\*/', $acl_ip)) { + if ($acl_ip[0] == '*' && strlen($acl_ip) > 1) { + // example *.lab.artica.es == 151.80.15.* + $acl_ip = str_replace('*.', '', $acl_ip); + $name = []; + $name = gethostbyname($acl_ip); + $names = explode('.', $name); + $names[3] = ''; + $names = implode('.', $names); + if (preg_match('/'.$names.'/', $ip)) { + return true; + } + } else { + // example 192.168.70.* or * + $acl_ip = str_replace('.', '\.', $acl_ip); + // Replace wilcard by .* to do efective in regular expression + $acl_ip = str_replace('*', '.*', $acl_ip); + // If the string match with the beginning of the IP give it access + if (preg_match('/'.$acl_ip.'/', $ip)) { + return true; + } + } - }else{ - //example lab.artica.es without '*' - $name = array(); - $name = gethostbyname($acl_ip); - if (preg_match('/'.$name.'/', $ip)) { - return true; - } - } - } - - return false; + // Scape for protection + } else { + // example lab.artica.es without '*' + $name = []; + $name = gethostbyname($acl_ip); + if (preg_match('/'.$name.'/', $ip)) { + return true; + } + } + } + + return false; } + // Return string OK,[version],[build] -function api_get_test() { - global $pandora_version; - global $build_version; - - echo "OK,$pandora_version,$build_version"; - - if (defined ('METACONSOLE')) { - echo ",meta"; - } +function api_get_test() +{ + global $pandora_version; + global $build_version; + + echo "OK,$pandora_version,$build_version"; + + if (defined('METACONSOLE')) { + echo ',meta'; + } } -//Return OK if agent cache is activated -function api_get_test_agent_cache(){ - if (defined ('METACONSOLE')) { - return; - } - $status = enterprise_hook('test_agent_cache', array()); - if ($status === ENTERPRISE_NOT_HOOK) { - echo 'ERR'; - return; - } - echo $status; +// Return OK if agent cache is activated +function api_get_test_agent_cache() +{ + if (defined('METACONSOLE')) { + return; + } + + $status = enterprise_hook('test_agent_cache', []); + if ($status === ENTERPRISE_NOT_HOOK) { + echo 'ERR'; + return; + } + + echo $status; } + // Returs the string OK if a connection to the event replication DB can be established. -function api_get_test_event_replication_db() { - if (defined ('METACONSOLE')) { - return; - } - - $status = enterprise_hook('events_test_replication_db', array()); - if ($status === ENTERPRISE_NOT_HOOK) { - echo 'ERR'; - return; - } - echo $status; +function api_get_test_event_replication_db() +{ + if (defined('METACONSOLE')) { + return; + } + + $status = enterprise_hook('events_test_replication_db', []); + if ($status === ENTERPRISE_NOT_HOOK) { + echo 'ERR'; + return; + } + + echo $status; } -//-------------------------DEFINED OPERATIONS FUNCTIONS----------------- -function api_get_groups($thrash1, $thrash2, $other, $returnType, $user_in_db) { - if (defined ('METACONSOLE')) { - return; - } - - if ($other['type'] == 'string') { - if ($other['data'] != '') { - returnError('error_parameter', 'Error in the parameters.'); - return; - } - else {//Default values - $separator = ';'; - } - } - else if ($other['type'] == 'array') { - $separator = $other['data'][0]; - } - - $groups = users_get_groups ($user_in_db, "IR"); - - $data_groups = array(); - foreach ($groups as $id => $group) { - $data_groups[] = array($id, $group); - } - - $data['type'] = 'array'; - $data['data'] = $data_groups; - - returnData($returnType, $data, $separator); + +// -------------------------DEFINED OPERATIONS FUNCTIONS----------------- +function api_get_groups($thrash1, $thrash2, $other, $returnType, $user_in_db) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($other['type'] == 'string') { + if ($other['data'] != '') { + returnError('error_parameter', 'Error in the parameters.'); + return; + } else { + // Default values + $separator = ';'; + } + } else if ($other['type'] == 'array') { + $separator = $other['data'][0]; + } + + $groups = users_get_groups($user_in_db, 'IR'); + + $data_groups = []; + foreach ($groups as $id => $group) { + $data_groups[] = [ + $id, + $group, + ]; + } + + $data['type'] = 'array'; + $data['data'] = $data_groups; + + returnData($returnType, $data, $separator); } -function api_get_agent_module_name_last_value($agentName, $moduleName, $other = ';', $returnType){ - $idAgent = agents_get_agent_id($agentName); - $sql = sprintf('SELECT id_agente_modulo + +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"', $idAgent, $moduleName); - $idModuleAgent = db_get_value_sql($sql); + WHERE id_agente = %d AND nombre LIKE "%s"', + $idAgent, + $moduleName + ); + $idModuleAgent = db_get_value_sql($sql); - api_get_module_last_value($idModuleAgent, null, $other, $returnType); + api_get_module_last_value($idModuleAgent, null, $other, $returnType); } -function api_get_agent_module_name_last_value_alias($alias, $moduleName, $other = ';', $returnType) { - $sql = sprintf('SELECT tagente_modulo.id_agente_modulo FROM tagente_modulo +function api_get_agent_module_name_last_value_alias($alias, $moduleName, $other=';', $returnType) +{ + $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"', $alias, $moduleName); - $idModuleAgent = db_get_value_sql($sql); + WHERE tagente.alias LIKE "%s" AND tagente_modulo.nombre LIKE "%s"', + $alias, + $moduleName + ); + $idModuleAgent = db_get_value_sql($sql); - api_get_module_last_value($idModuleAgent, null, $other, $returnType); + api_get_module_last_value($idModuleAgent, null, $other, $returnType); } -function api_get_module_last_value($idAgentModule, $trash1, $other = ';', $returnType) { - global $config; - if (defined ('METACONSOLE')) { - return; - } +function api_get_module_last_value($idAgentModule, $trash1, $other=';', $returnType) +{ + global $config; + if (defined('METACONSOLE')) { + return; + } - $check_access = agents_check_access_agent(modules_get_agentmodule_agent($idAgentModule)); - if ($check_access === false || !check_acl($config['id_user'], 0, "AR")) { - returnError('forbidden', $returnType); - return; - } + $check_access = agents_check_access_agent(modules_get_agentmodule_agent($idAgentModule)); + if ($check_access === false || !check_acl($config['id_user'], 0, 'AR')) { + returnError('forbidden', $returnType); + return; + } - $sql = sprintf('SELECT datos + $sql = sprintf( + 'SELECT datos FROM tagente_estado - WHERE id_agente_modulo = %d', $idAgentModule); - $value = db_get_value_sql($sql); + WHERE id_agente_modulo = %d', + $idAgentModule + ); + $value = db_get_value_sql($sql); - if ($value === false) { - if (isset($other['data'][1]) && $other['data'][0] == 'error_value') { - returnData($returnType, array('type' => 'string', 'data' => $other['data'][1])); - } elseif ($check_access) { - returnError('no_data_to_show', $returnType); - } else { - returnError('id_not_found', $returnType); - } - return; - } + if ($value === false) { + if (isset($other['data'][1]) && $other['data'][0] == 'error_value') { + returnData($returnType, ['type' => 'string', 'data' => $other['data'][1]]); + } else if ($check_access) { + returnError('no_data_to_show', $returnType); + } else { + returnError('id_not_found', $returnType); + } - $data = array('type' => 'string', 'data' => $value); - returnData($returnType, $data); + return; + } + + $data = [ + 'type' => 'string', + 'data' => $value, + ]; + returnData($returnType, $data); } -/*** DB column mapping table used by tree_agents (and get module_properties) ***/ -/* agent related field mappings (output field => column designation for 'tagente') */ -$agent_field_column_mapping = array( - /* agent_id is not in this list (because it is mandatory) */ - /* agent_id_group is not in this list */ - 'agent_name' => 'nombre as agent_name', - 'agent_direction' => 'direccion as agent_direction', - 'agent_comentary' => 'comentarios as agent_comentary', - 'agent_last_contant' => 'ultimo_contacto as agent_last_contant', - 'agent_mode' => 'modo as agent_mode', - 'agent_interval' => 'intervalo as agent_interval', - 'agent_id_os' => 'id_os as agent_id_os', - 'agent_os_version' => 'os_version as agent_os_version', - 'agent_version' => 'agent_version as agent_version', - 'agent_last_remote_contact' => 'ultimo_contacto_remoto as agent_last_remote_contact', - 'agent_disabled' => 'disabled as agent_disabled', - 'agent_id_parent' => 'id_parent as agent_id_parent', - 'agent_custom_id' => 'custom_id as agent_custom_id', - 'agent_server_name' => 'server_name as agent_server_name', - 'agent_cascade_protection' => 'cascade_protection as agent_cascade_protection', - 'agent_cascade_protection_module' => 'cascade_protection_module as agent_cascade_protection_module',); +/* + DB column mapping table used by tree_agents (and get module_properties) +*/ -/* module related field mappings 1/2 (output field => column for 'tagente_modulo') */ -$module_field_column_mampping = array( - /* module_id_agent_modulo is not in this list */ - 'module_id_agent' => 'id_agente as module_id_agent', - 'module_id_module_type' => 'id_tipo_modulo as module_id_module_type', - 'module_description' => 'descripcion as module_description', - 'module_name' => 'nombre as module_name', - 'module_max' => 'max as module_max', - 'module_min' => 'min as module_min', - 'module_interval' => 'module_interval', - 'module_tcp_port' => 'tcp_port as module_tcp_port', - 'module_tcp_send' => 'tcp_send as module_tcp_send', - 'module_tcp_rcv' => 'tcp_rcv as module_tcp_rcv', - 'module_snmp_community' => 'snmp_community as module_snmp_community', - 'module_snmp_oid' => 'snmp_oid as module_snmp_oid', - 'module_ip_target' => 'ip_target as module_ip_target', - 'module_id_module_group' => 'id_module_group as module_id_module_group', - 'module_flag' => 'flag as module_flag', - 'module_id_module' => 'id_modulo as module_id_module', - 'module_disabled' => 'disabled as module_disabled', - 'module_id_export' => 'id_export as module_id_export', - 'module_plugin_user' => 'plugin_user as module_plugin_user', - 'module_plugin_pass' => 'plugin_pass as module_plugin_pass', - 'module_plugin_parameter' => 'plugin_parameter as module_plugin_parameter', - 'module_id_plugin' => 'id_plugin as module_id_plugin', - 'module_post_process' => 'post_process as module_post_process', - 'module_prediction_module' => 'prediction_module as module_prediction_module', - 'module_max_timeout' => 'max_timeout as module_max_timeout', - 'module_max_retries' => 'max_retries as module_max_retries', - 'module_custom_id' => 'custom_id as module_custom_id', - 'module_history_data' => 'history_data as module_history_data', - 'module_min_warning' => 'min_warning as module_min_warning', - 'module_max_warning' => 'max_warning as module_max_warning', - 'module_str_warning' => 'str_warning as module_str_warning', - 'module_min_critical' => 'min_critical as module_min_critical', - 'module_max_critical' => 'max_critical as module_max_critical', - 'module_str_critical' => 'str_critical as module_str_critical', - 'module_min_ff_event' => 'min_ff_event as module_min_ff_event', - 'module_delete_pending' => 'delete_pending as module_delete_pending', - 'module_plugin_macros' => 'macros as module_plugin_macros', - 'module_macros' => 'module_macros as module_macros', - 'module_critical_inverse' => 'critical_inverse as module_critical_inverse', - 'module_warning_inverse' => 'warning_inverse as module_warning_inverse'); +/* + * Agent related field mappings (output field => column designation for 'tagente'). + * agent_id is not in this list (because it is mandatory). + * agent_id_group is not in this list. + */ +$agent_field_column_mapping = [ + 'agent_name' => 'nombre as agent_name', + 'agent_direction' => 'direccion as agent_direction', + 'agent_comentary' => 'comentarios as agent_comentary', + 'agent_last_contant' => 'ultimo_contacto as agent_last_contant', + 'agent_mode' => 'modo as agent_mode', + 'agent_interval' => 'intervalo as agent_interval', + 'agent_id_os' => 'id_os as agent_id_os', + 'agent_os_version' => 'os_version as agent_os_version', + 'agent_version' => 'agent_version as agent_version', + 'agent_last_remote_contact' => 'ultimo_contacto_remoto as agent_last_remote_contact', + 'agent_disabled' => 'disabled as agent_disabled', + 'agent_id_parent' => 'id_parent as agent_id_parent', + 'agent_custom_id' => 'custom_id as agent_custom_id', + 'agent_server_name' => 'server_name as agent_server_name', + 'agent_cascade_protection' => 'cascade_protection as agent_cascade_protection', + 'agent_cascade_protection_module' => 'cascade_protection_module as agent_cascade_protection_module', +]; -/* module related field mappings 2/2 (output field => column for 'tagente_estado') */ -$estado_fields_to_columns_mapping = array( - /* module_id_agent_modulo is not in this list */ - 'module_id_agent_state' => 'id_agente_estado as module_id_agent_state', - 'module_data' => 'datos as module_data', - 'module_timestamp' => 'timestamp as module_timestamp', - 'module_state' => 'estado as module_state', - 'module_last_try' => 'last_try as module_last_try', - 'module_utimestamp' => 'utimestamp as module_utimestamp', - 'module_current_interval' => 'current_interval as module_current_interval', - 'module_running_by' => 'running_by as module_running_by', - 'module_last_execution_try' => 'last_execution_try as module_last_execution_try', - 'module_status_changes' => 'status_changes as module_status_changes', - 'module_last_status' => 'last_status as module_last_status'); +// module related field mappings 1/2 (output field => column for 'tagente_modulo') +// module_id_agent_modulo is not in this list +$module_field_column_mampping = [ + 'module_id_agent' => 'id_agente as module_id_agent', + 'module_id_module_type' => 'id_tipo_modulo as module_id_module_type', + 'module_description' => 'descripcion as module_description', + 'module_name' => 'nombre as module_name', + 'module_max' => 'max as module_max', + 'module_min' => 'min as module_min', + 'module_interval' => 'module_interval', + 'module_tcp_port' => 'tcp_port as module_tcp_port', + 'module_tcp_send' => 'tcp_send as module_tcp_send', + 'module_tcp_rcv' => 'tcp_rcv as module_tcp_rcv', + 'module_snmp_community' => 'snmp_community as module_snmp_community', + 'module_snmp_oid' => 'snmp_oid as module_snmp_oid', + 'module_ip_target' => 'ip_target as module_ip_target', + 'module_id_module_group' => 'id_module_group as module_id_module_group', + 'module_flag' => 'flag as module_flag', + 'module_id_module' => 'id_modulo as module_id_module', + 'module_disabled' => 'disabled as module_disabled', + 'module_id_export' => 'id_export as module_id_export', + 'module_plugin_user' => 'plugin_user as module_plugin_user', + 'module_plugin_pass' => 'plugin_pass as module_plugin_pass', + 'module_plugin_parameter' => 'plugin_parameter as module_plugin_parameter', + 'module_id_plugin' => 'id_plugin as module_id_plugin', + 'module_post_process' => 'post_process as module_post_process', + 'module_prediction_module' => 'prediction_module as module_prediction_module', + 'module_max_timeout' => 'max_timeout as module_max_timeout', + 'module_max_retries' => 'max_retries as module_max_retries', + 'module_custom_id' => 'custom_id as module_custom_id', + 'module_history_data' => 'history_data as module_history_data', + 'module_min_warning' => 'min_warning as module_min_warning', + 'module_max_warning' => 'max_warning as module_max_warning', + 'module_str_warning' => 'str_warning as module_str_warning', + 'module_min_critical' => 'min_critical as module_min_critical', + 'module_max_critical' => 'max_critical as module_max_critical', + 'module_str_critical' => 'str_critical as module_str_critical', + 'module_min_ff_event' => 'min_ff_event as module_min_ff_event', + 'module_delete_pending' => 'delete_pending as module_delete_pending', + 'module_plugin_macros' => 'macros as module_plugin_macros', + 'module_macros' => 'module_macros as module_macros', + 'module_critical_inverse' => 'critical_inverse as module_critical_inverse', + 'module_warning_inverse' => 'warning_inverse as module_warning_inverse', +]; + +// module related field mappings 2/2 (output field => column for 'tagente_estado') +// module_id_agent_modulo is not in this list +$estado_fields_to_columns_mapping = [ + 'module_id_agent_state' => 'id_agente_estado as module_id_agent_state', + 'module_data' => 'datos as module_data', + 'module_timestamp' => 'timestamp as module_timestamp', + 'module_state' => 'estado as module_state', + 'module_last_try' => 'last_try as module_last_try', + 'module_utimestamp' => 'utimestamp as module_utimestamp', + 'module_current_interval' => 'current_interval as module_current_interval', + 'module_running_by' => 'running_by as module_running_by', + 'module_last_execution_try' => 'last_execution_try as module_last_execution_try', + 'module_status_changes' => 'status_changes as module_status_changes', + 'module_last_status' => 'last_status as module_last_status', +]; + +/*** + * end of DB column mapping table + ***/ -/*** end of DB column mapping table ***/ /** - * + * * @param $trash1 * @param $trahs2 - * @param mixed $other If $other is string is only the separator, - * but if it's array, $other as param is ;;(,...) in this order - * and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " " - * api.php?op=get&op2=tree_agents&return_type=csv&other=;| |type_row,group_id,agent_name&other_mode=url_encode_separator_| - * - * - * @param $returnType + * @param mixed $other If $other is string is only the separator, + * but if it's array, $other as param is ;;(,...) in this order + * and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " " + * api.php?op=get&op2=tree_agents&return_type=csv&other=;| |type_row,group_id,agent_name&other_mode=url_encode_separator_| + * + * @param $returnType * @return unknown_type */ -function api_get_tree_agents($trash1, $trahs2, $other, $returnType) { - global $config; +function api_get_tree_agents($trash1, $trahs2, $other, $returnType) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } - - if ($other['type'] == 'array') { - $separator = $other['data'][0]; - $returnReplace = $other['data'][1]; - if (trim($other['data'][2]) == '') - $fields = false; - else { - $fields = explode(',', $other['data'][2]); - foreach($fields as $index => $field) - $fields[$index] = trim($field); - } - - } - else { - if (strlen($other['data']) == 0) - $separator = ';'; //by default - else - $separator = $other['data']; - $returnReplace = ' '; - $fields = false; - } - - /** NOTE: if you want to add an output field, you have to add it to; - 1. $master_fields (field name) - 2. one of following field_column_mapping array (a pair of field name and corresponding column designation) - - e.g. To add a new field named 'agent_NEWFIELD' that comes from tagente's COLUMN_X , you have to add; - 1. "agent_NEW_FIELD" to $master_fields - 2. "'agent_NEW_FIELD' => 'agent_NEWFIELD as COLUMN_X'" to $agent_field_column_mapping - **/ - - /* all of output field names */ - $master_fields = array( - 'type_row', - - 'group_id', - 'group_name', - 'group_parent', - 'disabled', - 'custom_id', - 'group_description', - 'group_contact', - 'group_other', - - 'agent_id', - 'alias', - 'agent_direction', - 'agent_comentary', - 'agent_id_group', - 'agent_last_contant', - 'agent_mode', - 'agent_interval', - 'agent_id_os', - 'agent_os_version', - 'agent_version', - 'agent_last_remote_contact', - 'agent_disabled', - 'agent_id_parent', - 'agent_custom_id', - 'agent_server_name', - 'agent_cascade_protection', - 'agent_cascade_protection_module', - 'agent_name', - - 'module_id_agent_modulo', - 'module_id_agent', - 'module_id_module_type', - 'module_description', - 'module_name', - 'module_max', - 'module_min', - 'module_interval', - 'module_tcp_port', - 'module_tcp_send', - 'module_tcp_rcv', - 'module_snmp_community', - 'module_snmp_oid', - 'module_ip_target', - 'module_id_module_group', - 'module_flag', - 'module_id_module', - 'module_disabled', - 'module_id_export', - 'module_plugin_user', - 'module_plugin_pass', - 'module_plugin_parameter', - 'module_id_plugin', - 'module_post_process', - 'module_prediction_module', - 'module_max_timeout', - 'module_max_retries', - 'module_custom_id', - 'module_history_data', - 'module_min_warning', - 'module_max_warning', - 'module_str_warning', - 'module_min_critical', - 'module_max_critical', - 'module_str_critical', - 'module_min_ff_event', - 'module_delete_pending', - 'module_id_agent_state', - 'module_data', - 'module_timestamp', - 'module_state', - 'module_last_try', - 'module_utimestamp', - 'module_current_interval', - 'module_running_by', - 'module_last_execution_try', - 'module_status_changes', - 'module_last_status', - 'module_plugin_macros', - 'module_macros', - 'module_critical_inverse', - 'module_warning_inverse', - - 'alert_id_agent_module', - 'alert_id_alert_template', - 'alert_internal_counter', - 'alert_last_fired', - 'alert_last_reference', - 'alert_times_fired', - 'alert_disabled', - 'alert_force_execution', - 'alert_id_alert_action', - 'alert_type', - 'alert_value', - 'alert_matches_value', - 'alert_max_value', - 'alert_min_value', - 'alert_time_threshold', - 'alert_max_alerts', - 'alert_min_alerts', - 'alert_time_from', - 'alert_time_to', - 'alert_monday', - 'alert_tuesday', - 'alert_wednesday', - 'alert_thursday', - 'alert_friday', - 'alert_saturday', - 'alert_sunday', - 'alert_recovery_notify', - 'alert_field2_recovery', - 'alert_field3_recovery', - 'alert_id_alert_template_module', - 'alert_fires_min', - 'alert_fires_max', - 'alert_id_alert_command', - 'alert_command', - 'alert_internal', - 'alert_template_modules_id', - 'alert_templates_id', - 'alert_template_module_actions_id', - 'alert_actions_id', - 'alert_commands_id', - 'alert_templates_name', - 'alert_actions_name', - 'alert_commands_name', - 'alert_templates_description', - 'alert_commands_description', - 'alert_template_modules_priority', - 'alert_templates_priority', - 'alert_templates_field1', - 'alert_actions_field1', - 'alert_templates_field2', - 'alert_actions_field2', - 'alert_templates_field3', - 'alert_actions_field3', - 'alert_templates_id_group', - 'alert_actions_id_group'); - - /* agent related field mappings (output field => column designation for 'tagente') */ - - global $agent_field_column_mapping; - - /* module related field mappings 1/2 (output field => column for 'tagente_modulo') */ - - global $module_field_column_mampping; - - /* module related field mappings 2/2 (output field => column for 'tagente_estado') */ + if (defined('METACONSOLE')) { + return; + } - global $estado_fields_to_columns_mapping; - - /* alert related field mappings (output field => column for 'talert_template_modules', ... ) */ + if ($other['type'] == 'array') { + $separator = $other['data'][0]; + $returnReplace = $other['data'][1]; + if (trim($other['data'][2]) == '') { + $fields = false; + } else { + $fields = explode(',', $other['data'][2]); + foreach ($fields as $index => $field) { + $fields[$index] = trim($field); + } + } + } else { + if (strlen($other['data']) == 0) { + $separator = ';'; + // by default + } else { + $separator = $other['data']; + } - $alert_fields_to_columns_mapping = array( - /*** 'alert_id_agent_module (id_agent_module) is not in this list ***/ - 'alert_template_modules_id' => 't1.id as alert_template_modules_id', - 'alert_id_alert_template' => 't1.id_alert_template as alert_id_alert_template', - 'alert_internal_counter' => 't1.internal_counter as alert_internal_counter', - 'alert_last_fired' => 't1.last_fired as alert_last_fired', - 'alert_last_reference' => 't1.last_reference as alert_last_reference', - 'alert_times_fired' => 't1.times_fired as alert_times_fired', - 'alert_disabled' => 't1.disabled as alert_disabled', - 'alert_force_execution' => 't1.force_execution as alert_force_execution', - 'alert_template_modules_priority' => 't1.priority as alert_template_modules_priority', - - 'alert_templates_id' => 't2.id as alert_templates_id', - 'alert_type' => 't2.type as alert_type', - 'alert_value' => 't2.value as alert_value', - 'alert_matches_value' => 't2.matches_value as alert_matches_value', - 'alert_max_value' => 't2.max_value as alert_max_value', - 'alert_min_value' => 't2.min_value as alert_min_value', - 'alert_time_threshold' => 't2.time_threshold as alert_time_threshold', - 'alert_max_alerts' => 't2.max_alerts as alert_max_alerts', - 'alert_min_alerts' => 't2.min_alerts as alert_min_alerts', - 'alert_time_from' => 't2.time_from as alert_time_from', - 'alert_time_to' => 't2.time_to as alert_time_to', - 'alert_monday' => 't2.monday as alert_monday', - 'alert_tuesday' => 't2.tuesday as alert_tuesday', - 'alert_wednesday' => 't2.wednesday as alert_wednesday', - 'alert_thursday' => 't2.thursday as alert_thursday', - 'alert_friday' => 't2.friday as alert_friday', - 'alert_saturday' => 't2.saturday as alert_saturday', - 'alert_sunday' => 't2.sunday as alert_sunday', - 'alert_templates_name' => 't2.name as alert_templates_name', - 'alert_templates_description' => 't2.description as alert_templates_description', - 'alert_templates_priority' => 't2.priority as alert_templates_priority', - 'alert_templates_id_group' => 't2.id_group as alert_templates_id_group', - 'alert_recovery_notify' => 't2.recovery_notify as alert_recovery_notify', - 'alert_field2_recovery' => 't2.field2_recovery as alert_field2_recovery', - 'alert_field3_recovery' => 't2.field3_recovery as alert_field3_recovery', - 'alert_templates_field1' => 't2.field1 as alert_templates_field1', - 'alert_templates_field2' => 't2.field2 as alert_templates_field2', - 'alert_templates_field3' => 't2.field3 as alert_templates_field3', - - 'alert_template_module_actions_id' => 't3.id as alert_template_module_actions_id', - 'alert_id_alert_action' => 't3.id_alert_action as alert_id_alert_action', - 'alert_id_alert_template_module' => 't3.id_alert_template_module as alert_id_alert_template_module', - 'alert_fires_min' => 't3.fires_min as alert_fires_min', - 'alert_fires_max' => 't3.fires_max as alert_fires_max', - - 'alert_actions_id' => 't4.id as alert_actions_id', - 'alert_actions_name' => 't4.name as alert_actions_name', - 'alert_id_alert_command' => 't4.id_alert_command as alert_id_alert_command', - 'alert_actions_id_group' => 't4.id_group as alert_actions_id_group', - 'alert_actions_field1' => 't4.field1 as alert_actions_field1', - 'alert_actions_field2' => 't4.field2 as alert_actions_field2', - 'alert_actions_field3' => 't4.field3 as alert_actions_field3', - - 'alert_command' => 't5.command as alert_command', - 'alert_internal' => 't5.internal as alert_internal', - 'alert_commands_id' => 't5.id as alert_commands_id', - 'alert_commands_name' => 't5.name as alert_commands_name', - 'alert_commands_description' => 't5.description as alert_commands_description'); - - if ($fields == false) { - $fields = $master_fields; - } + $returnReplace = ' '; + $fields = false; + } - /** construct column list to query for tagente, tagente_modulo, tagente_estado and alert-related tables **/ - { - $agent_additional_columns = ""; - $module_additional_columns = ""; - $estado_additional_columns = ""; - $alert_additional_columns = ""; - - foreach ($fields as $fld ) { - if (array_key_exists ($fld, $agent_field_column_mapping ) ) { - $agent_additional_columns .= (", " . $agent_field_column_mapping[$fld] ); - } - if (array_key_exists ($fld, $module_field_column_mampping ) ) { - $module_additional_columns .= (", " . $module_field_column_mampping[$fld]); - } - if (array_key_exists ($fld, $estado_fields_to_columns_mapping ) ) { - $estado_additional_columns .= (", " . $estado_fields_to_columns_mapping[$fld]); - } - if (array_key_exists ($fld, $alert_fields_to_columns_mapping ) ) { - $alert_additional_columns .= (", " . $alert_fields_to_columns_mapping[$fld]); - } - } - } - - $returnVar = array(); + /* + NOTE: if you want to add an output field, you have to add it to; + 1. $master_fields (field name) + 2. one of following field_column_mapping array (a pair of field name and corresponding column designation) - // Get only the user groups - $filter_groups = "1 = 1"; - if (!users_is_admin($config['id_user'])) { - $user_groups = implode (',', array_keys(users_get_groups())); - $filter_groups = "id_grupo IN ($user_groups)"; - } + e.g. To add a new field named 'agent_NEWFIELD' that comes from tagente's COLUMN_X , you have to add; + 1. "agent_NEW_FIELD" to $master_fields + 2. "'agent_NEW_FIELD' => 'agent_NEWFIELD as COLUMN_X'" to $agent_field_column_mapping + */ - $groups = db_get_all_rows_sql('SELECT id_grupo as group_id, ' . - 'nombre as group_name, parent as group_parent, disabled, custom_id, ' . - 'description as group_description, contact as group_contact, ' . - 'other as group_other FROM tgrupo WHERE ' . $filter_groups); - if ($groups === false) $groups = array(); - $groups = str_replace('\n', $returnReplace, $groups); + // all of output field names + $master_fields = [ + 'type_row', - foreach ($groups as &$group) { - $group['type_row'] = 'group'; - $returnVar[] = $group; + 'group_id', + 'group_name', + 'group_parent', + 'disabled', + 'custom_id', + 'group_description', + 'group_contact', + 'group_other', - // Get the agents for this group - $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 + 'agent_id', + 'alias', + 'agent_direction', + 'agent_comentary', + 'agent_id_group', + 'agent_last_contant', + 'agent_mode', + 'agent_interval', + 'agent_id_os', + 'agent_os_version', + 'agent_version', + 'agent_last_remote_contact', + 'agent_disabled', + 'agent_id_parent', + 'agent_custom_id', + 'agent_server_name', + 'agent_cascade_protection', + 'agent_cascade_protection_module', + 'agent_name', + + 'module_id_agent_modulo', + 'module_id_agent', + 'module_id_module_type', + 'module_description', + 'module_name', + 'module_max', + 'module_min', + 'module_interval', + 'module_tcp_port', + 'module_tcp_send', + 'module_tcp_rcv', + 'module_snmp_community', + 'module_snmp_oid', + 'module_ip_target', + 'module_id_module_group', + 'module_flag', + 'module_id_module', + 'module_disabled', + 'module_id_export', + 'module_plugin_user', + 'module_plugin_pass', + 'module_plugin_parameter', + 'module_id_plugin', + 'module_post_process', + 'module_prediction_module', + 'module_max_timeout', + 'module_max_retries', + 'module_custom_id', + 'module_history_data', + 'module_min_warning', + 'module_max_warning', + 'module_str_warning', + 'module_min_critical', + 'module_max_critical', + 'module_str_critical', + 'module_min_ff_event', + 'module_delete_pending', + 'module_id_agent_state', + 'module_data', + 'module_timestamp', + 'module_state', + 'module_last_try', + 'module_utimestamp', + 'module_current_interval', + 'module_running_by', + 'module_last_execution_try', + 'module_status_changes', + 'module_last_status', + 'module_plugin_macros', + 'module_macros', + 'module_critical_inverse', + 'module_warning_inverse', + + 'alert_id_agent_module', + 'alert_id_alert_template', + 'alert_internal_counter', + 'alert_last_fired', + 'alert_last_reference', + 'alert_times_fired', + 'alert_disabled', + 'alert_force_execution', + 'alert_id_alert_action', + 'alert_type', + 'alert_value', + 'alert_matches_value', + 'alert_max_value', + 'alert_min_value', + 'alert_time_threshold', + 'alert_max_alerts', + 'alert_min_alerts', + 'alert_time_from', + 'alert_time_to', + 'alert_monday', + 'alert_tuesday', + 'alert_wednesday', + 'alert_thursday', + 'alert_friday', + 'alert_saturday', + 'alert_sunday', + 'alert_recovery_notify', + 'alert_field2_recovery', + 'alert_field3_recovery', + 'alert_id_alert_template_module', + 'alert_fires_min', + 'alert_fires_max', + 'alert_id_alert_command', + 'alert_command', + 'alert_internal', + 'alert_template_modules_id', + 'alert_templates_id', + 'alert_template_module_actions_id', + 'alert_actions_id', + 'alert_commands_id', + 'alert_templates_name', + 'alert_actions_name', + 'alert_commands_name', + 'alert_templates_description', + 'alert_commands_description', + 'alert_template_modules_priority', + 'alert_templates_priority', + 'alert_templates_field1', + 'alert_actions_field1', + 'alert_templates_field2', + 'alert_actions_field2', + 'alert_templates_field3', + 'alert_actions_field3', + 'alert_templates_id_group', + 'alert_actions_id_group', + ]; + + // agent related field mappings (output field => column designation for 'tagente') + global $agent_field_column_mapping; + + // module related field mappings 1/2 (output field => column for 'tagente_modulo') + global $module_field_column_mampping; + + // module related field mappings 2/2 (output field => column for 'tagente_estado') + global $estado_fields_to_columns_mapping; + + // alert related field mappings (output field => column for 'talert_template_modules', ... ) + $alert_fields_to_columns_mapping = [ + // 'alert_id_agent_module (id_agent_module) is not in this list + 'alert_template_modules_id' => 't1.id as alert_template_modules_id', + 'alert_id_alert_template' => 't1.id_alert_template as alert_id_alert_template', + 'alert_internal_counter' => 't1.internal_counter as alert_internal_counter', + 'alert_last_fired' => 't1.last_fired as alert_last_fired', + 'alert_last_reference' => 't1.last_reference as alert_last_reference', + 'alert_times_fired' => 't1.times_fired as alert_times_fired', + 'alert_disabled' => 't1.disabled as alert_disabled', + 'alert_force_execution' => 't1.force_execution as alert_force_execution', + 'alert_template_modules_priority' => 't1.priority as alert_template_modules_priority', + + 'alert_templates_id' => 't2.id as alert_templates_id', + 'alert_type' => 't2.type as alert_type', + 'alert_value' => 't2.value as alert_value', + 'alert_matches_value' => 't2.matches_value as alert_matches_value', + 'alert_max_value' => 't2.max_value as alert_max_value', + 'alert_min_value' => 't2.min_value as alert_min_value', + 'alert_time_threshold' => 't2.time_threshold as alert_time_threshold', + 'alert_max_alerts' => 't2.max_alerts as alert_max_alerts', + 'alert_min_alerts' => 't2.min_alerts as alert_min_alerts', + 'alert_time_from' => 't2.time_from as alert_time_from', + 'alert_time_to' => 't2.time_to as alert_time_to', + 'alert_monday' => 't2.monday as alert_monday', + 'alert_tuesday' => 't2.tuesday as alert_tuesday', + 'alert_wednesday' => 't2.wednesday as alert_wednesday', + 'alert_thursday' => 't2.thursday as alert_thursday', + 'alert_friday' => 't2.friday as alert_friday', + 'alert_saturday' => 't2.saturday as alert_saturday', + 'alert_sunday' => 't2.sunday as alert_sunday', + 'alert_templates_name' => 't2.name as alert_templates_name', + 'alert_templates_description' => 't2.description as alert_templates_description', + 'alert_templates_priority' => 't2.priority as alert_templates_priority', + 'alert_templates_id_group' => 't2.id_group as alert_templates_id_group', + 'alert_recovery_notify' => 't2.recovery_notify as alert_recovery_notify', + 'alert_field2_recovery' => 't2.field2_recovery as alert_field2_recovery', + 'alert_field3_recovery' => 't2.field3_recovery as alert_field3_recovery', + 'alert_templates_field1' => 't2.field1 as alert_templates_field1', + 'alert_templates_field2' => 't2.field2 as alert_templates_field2', + 'alert_templates_field3' => 't2.field3 as alert_templates_field3', + + 'alert_template_module_actions_id' => 't3.id as alert_template_module_actions_id', + 'alert_id_alert_action' => 't3.id_alert_action as alert_id_alert_action', + 'alert_id_alert_template_module' => 't3.id_alert_template_module as alert_id_alert_template_module', + 'alert_fires_min' => 't3.fires_min as alert_fires_min', + 'alert_fires_max' => 't3.fires_max as alert_fires_max', + + 'alert_actions_id' => 't4.id as alert_actions_id', + 'alert_actions_name' => 't4.name as alert_actions_name', + 'alert_id_alert_command' => 't4.id_alert_command as alert_id_alert_command', + 'alert_actions_id_group' => 't4.id_group as alert_actions_id_group', + 'alert_actions_field1' => 't4.field1 as alert_actions_field1', + 'alert_actions_field2' => 't4.field2 as alert_actions_field2', + 'alert_actions_field3' => 't4.field3 as alert_actions_field3', + + 'alert_command' => 't5.command as alert_command', + 'alert_internal' => 't5.internal as alert_internal', + 'alert_commands_id' => 't5.id as alert_commands_id', + 'alert_commands_name' => 't5.name as alert_commands_name', + 'alert_commands_description' => 't5.description as alert_commands_description', + ]; + + if ($fields == false) { + $fields = $master_fields; + } + + // construct column list to query for tagente, tagente_modulo, tagente_estado and alert-related tables + { + $agent_additional_columns = ''; + $module_additional_columns = ''; + $estado_additional_columns = ''; + $alert_additional_columns = ''; + + foreach ($fields as $fld) { + if (array_key_exists($fld, $agent_field_column_mapping)) { + $agent_additional_columns .= (', '.$agent_field_column_mapping[$fld] ); + } + + if (array_key_exists($fld, $module_field_column_mampping)) { + $module_additional_columns .= (', '.$module_field_column_mampping[$fld]); + } + + if (array_key_exists($fld, $estado_fields_to_columns_mapping)) { + $estado_additional_columns .= (', '.$estado_fields_to_columns_mapping[$fld]); + } + + if (array_key_exists($fld, $alert_fields_to_columns_mapping)) { + $alert_additional_columns .= (', '.$alert_fields_to_columns_mapping[$fld]); + } + } + + } + + $returnVar = []; + + // Get only the user groups + $filter_groups = '1 = 1'; + if (!users_is_admin($config['id_user'])) { + $user_groups = implode(',', array_keys(users_get_groups())); + $filter_groups = "id_grupo IN ($user_groups)"; + } + + $groups = db_get_all_rows_sql( + 'SELECT id_grupo as group_id, '.'nombre as group_name, parent as group_parent, disabled, custom_id, '.'description as group_description, contact as group_contact, '.'other as group_other FROM tgrupo WHERE '.$filter_groups + ); + if ($groups === false) { + $groups = []; + } + + $groups = str_replace('\n', $returnReplace, $groups); + + foreach ($groups as &$group) { + $group['type_row'] = 'group'; + $returnVar[] = $group; + + // Get the agents for this group + $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" - ); - if ($agents === false) $agents = array(); - $agents = str_replace('\n', $returnReplace, $agents); + ); + if ($agents === false) { + $agents = []; + } - foreach ($agents as $index => &$agent) { - $agent['type_row'] = 'agent'; - $returnVar[] = $agent; - - if ( strlen($module_additional_columns) <= 0 - && strlen($estado_additional_columns) <= 0 - && strlen($alert_additional_columns) <= 0 ) { - continue; /** SKIP collecting MODULES and ALERTS **/ - } - - $modules = db_get_all_rows_sql('SELECT * - FROM (SELECT id_agente_modulo as module_id_agent_modulo ' . $module_additional_columns . ' + $agents = str_replace('\n', $returnReplace, $agents); + + foreach ($agents as $index => &$agent) { + $agent['type_row'] = 'agent'; + $returnVar[] = $agent; + + if (strlen($module_additional_columns) <= 0 + && strlen($estado_additional_columns) <= 0 + && strlen($alert_additional_columns) <= 0 + ) { + continue; + // SKIP collecting MODULES and ALERTS + } + + $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 . ' + 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) $modules = array(); - $modules = str_replace('\n', $returnReplace, $modules); - - foreach ($modules as &$module) { - $module['type_row'] = 'module'; + WHERE id_agente = '.$agent['agent_id'].') t2 + ON t1.module_id_agent_modulo = t2.module_id_agent_modulo' + ); - if( $module['module_macros'] ) { - $module['module_macros'] = base64_decode( $module['module_macros']); - } + if ($modules === false) { + $modules = []; + } - $returnVar[] = $module; - - if ( strlen($alert_additional_columns) <= 0 ) { - continue; /** SKIP collecting ALERTS info **/ - } - - $alerts = db_get_all_rows_sql('SELECT t1.id_agent_module as alert_id_agent_module ' . $alert_additional_columns . ' + $modules = str_replace('\n', $returnReplace, $modules); + + foreach ($modules as &$module) { + $module['type_row'] = 'module'; + + if ($module['module_macros']) { + $module['module_macros'] = base64_decode($module['module_macros']); + } + + $returnVar[] = $module; + + if (strlen($alert_additional_columns) <= 0) { + continue; + // SKIP collecting ALERTS info + } + + $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 + 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 @@ -822,1298 +954,1441 @@ function api_get_tree_agents($trash1, $trahs2, $other, $returnType) { 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) $alerts = array(); - $alerts = str_replace('\n', $returnReplace, $alerts); - - foreach ($alerts as &$alert) { - $alert['type_row'] = 'alert'; - $returnVar[] = $alert; - } - } - } - } - $data = array('type' => 'array', 'data' => $returnVar); - - $data['list_index'] = $fields; - - returnData($returnType, $data, $separator); + ON t4.id_alert_command = t5.id' + ); + + if ($alerts === false) { + $alerts = []; + } + + $alerts = str_replace('\n', $returnReplace, $alerts); + + foreach ($alerts as &$alert) { + $alert['type_row'] = 'alert'; + $returnVar[] = $alert; + } + } + } + } + + $data = [ + 'type' => 'array', + 'data' => $returnVar, + ]; + + $data['list_index'] = $fields; + + returnData($returnType, $data, $separator); } + /** - * + * * @param $id_module * @param $trahs2 - * @param mixed $other If $other is string is only the separator, - * but if it's array, $other as param is ;;(,...) in this order - * and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " " - * api.php?op=get&op2=module_properties&id=1116&return_type=csv&other=;| |module_id_agent,module_name,module_description,module_last_try,module_data&other_mode=url_encode_separator_| - * - * @param $returnType + * @param mixed $other If $other is string is only the separator, + * but if it's array, $other as param is ;;(,...) in this order + * and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " " + * api.php?op=get&op2=module_properties&id=1116&return_type=csv&other=;| |module_id_agent,module_name,module_description,module_last_try,module_data&other_mode=url_encode_separator_| + * + * @param $returnType * @return unknown_type */ function api_get_module_properties($id_module, $trahs2, $other, $returnType) { - if (!util_api_check_agent_and_print_error(modules_get_agentmodule_agent($id_module), $returnType)) return; + if (!util_api_check_agent_and_print_error(modules_get_agentmodule_agent($id_module), $returnType)) { + return; + } - if ($other['type'] == 'array') { - $separator = $other['data'][0]; - $returnReplace = $other['data'][1]; - if (trim($other['data'][2]) == '') - $fields = false; - else { - $fields = explode(',', $other['data'][2]); - foreach($fields as $index => $field) - $fields[$index] = trim($field); - } - - } - else { - if (strlen($other['data']) == 0) - $separator = ';'; //by default - else - $separator = $other['data']; - $returnReplace = ' '; - $fields = false; - } - get_module_properties($id_module, $fields, $separator, $returnType, $returnReplace); + if ($other['type'] == 'array') { + $separator = $other['data'][0]; + $returnReplace = $other['data'][1]; + if (trim($other['data'][2]) == '') { + $fields = false; + } else { + $fields = explode(',', $other['data'][2]); + foreach ($fields as $index => $field) { + $fields[$index] = trim($field); + } + } + } else { + if (strlen($other['data']) == 0) { + $separator = ';'; + // by default + } else { + $separator = $other['data']; + } + + $returnReplace = ' '; + $fields = false; + } + + get_module_properties($id_module, $fields, $separator, $returnType, $returnReplace); } + + /** - * + * * @param $agent_name * @param $module_name - * @param mixed $other If $other is string is only the separator, - * but if it's array, $other as param is ;;(,...) in this order - * and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " " - * api.php?op=get&op2=module_properties_by_name&id=sample_agent&id2=sample_module&return_type=csv&other=;| |module_id_agent,module_name,module_str_critical,module_str_warning&other_mode=url_encode_separator_| - * - * @param $returnType + * @param mixed $other If $other is string is only the separator, + * but if it's array, $other as param is ;;(,...) in this order + * and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " " + * api.php?op=get&op2=module_properties_by_name&id=sample_agent&id2=sample_module&return_type=csv&other=;| |module_id_agent,module_name,module_str_critical,module_str_warning&other_mode=url_encode_separator_| + * + * @param $returnType * @return unknown_type */ function api_get_module_properties_by_name($agent_name, $module_name, $other, $returnType) { - if ($other['type'] == 'array') { - $separator = $other['data'][0]; - $returnReplace = $other['data'][1]; - if (trim($other['data'][2]) == '') - $fields = false; - else { - $fields = explode(',', $other['data'][2]); - foreach($fields as $index => $field) - $fields[$index] = trim($field); - } - - } - else { - if (strlen($other['data']) == 0) - $separator = ';'; //by default - else - $separator = $other['data']; - $returnReplace = ' '; - $fields = false; - } + if ($other['type'] == 'array') { + $separator = $other['data'][0]; + $returnReplace = $other['data'][1]; + if (trim($other['data'][2]) == '') { + $fields = false; + } else { + $fields = explode(',', $other['data'][2]); + foreach ($fields as $index => $field) { + $fields[$index] = trim($field); + } + } + } else { + if (strlen($other['data']) == 0) { + $separator = ';'; + // by default + } else { + $separator = $other['data']; + } - $agent_id = agents_get_agent_id($agent_name); - if ($agent_id == 0) { - returnError('error_get_module_properties_by_name', __('Does not exist agent with this name.')); - return; - } - if (!util_api_check_agent_and_print_error($agent_id, $returnType)) return; + $returnReplace = ' '; + $fields = false; + } - $tagente_modulo = modules_get_agentmodule_id ($module_name, $agent_id); - if ($tagente_modulo === false) { - returnError('error_get_module_properties_by_name', __('Does not exist module with this name.')); - return; - } - $module_id = $tagente_modulo['id_agente_modulo']; + $agent_id = agents_get_agent_id($agent_name); + if ($agent_id == 0) { + returnError('error_get_module_properties_by_name', __('Does not exist agent with this name.')); + return; + } - get_module_properties($module_id, $fields, $separator, $returnType, $returnReplace); + if (!util_api_check_agent_and_print_error($agent_id, $returnType)) { + return; + } + + $tagente_modulo = modules_get_agentmodule_id($module_name, $agent_id); + if ($tagente_modulo === false) { + returnError('error_get_module_properties_by_name', __('Does not exist module with this name.')); + return; + } + + $module_id = $tagente_modulo['id_agente_modulo']; + + get_module_properties($module_id, $fields, $separator, $returnType, $returnReplace); } + /* * subroutine for api_get_module_properties() and api_get_module_properties_by_name(). */ + /** - * - * @param $alias - * @param $module_name - * @param mixed $other If $other is string is only the separator, - * but if it's array, $other as param is ;;(,...) in this order - * and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " " - * api.php?op=get&op2=module_properties_by_name&id=sample_agent&id2=sample_module&return_type=csv&other=;| |module_id_agent,module_name,module_str_critical,module_str_warning&other_mode=url_encode_separator_| - * - * @param $returnType - * @return unknown_type - */ + * + * @param $alias + * @param $module_name + * @param mixed $other If $other is string is only the separator, + * but if it's array, $other as param is ;;(,...) in this order + * and separator char (after text ; ) must be diferent that separator (and other) url (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * return csv with fields type_row,group_id and agent_name, separate with ";" and the return of the text replace for " " + * api.php?op=get&op2=module_properties_by_name&id=sample_agent&id2=sample_module&return_type=csv&other=;| |module_id_agent,module_name,module_str_critical,module_str_warning&other_mode=url_encode_separator_| + * + * @param $returnType + * @return unknown_type + */ function api_get_module_properties_by_alias($alias, $module_name, $other, $returnType) { - if ($other['type'] == 'array') { - $separator = $other['data'][0]; - $returnReplace = $other['data'][1]; - if (trim($other['data'][2]) == '') - $fields = false; - else { - $fields = explode(',', $other['data'][2]); - foreach($fields as $index => $field) - $fields[$index] = trim($field); - } - - } - else { - if (strlen($other['data']) == 0) - $separator = ';'; //by default - else - $separator = $other['data']; - $returnReplace = ' '; - $fields = false; - } + if ($other['type'] == 'array') { + $separator = $other['data'][0]; + $returnReplace = $other['data'][1]; + if (trim($other['data'][2]) == '') { + $fields = false; + } else { + $fields = explode(',', $other['data'][2]); + foreach ($fields as $index => $field) { + $fields[$index] = trim($field); + } + } + } else { + if (strlen($other['data']) == 0) { + $separator = ';'; + // by default + } else { + $separator = $other['data']; + } - $sql = sprintf('SELECT tagente_modulo.id_agente_modulo, tagente.id_agente FROM tagente_modulo + $returnReplace = ' '; + $fields = false; + } + + $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"', $alias, $module_name); + WHERE tagente.alias LIKE "%s" AND tagente_modulo.nombre LIKE "%s"', + $alias, + $module_name + ); - $data = db_get_row_sql($sql); - if ($data === false) { - returnError('error_get_module_properties_by_name', __('Does not exist the pair alias/module required.')); - } - if (!util_api_check_agent_and_print_error($data['id_agente'], $returnType)) return; + $data = db_get_row_sql($sql); + if ($data === false) { + returnError('error_get_module_properties_by_name', __('Does not exist the pair alias/module required.')); + } - $module_id = $data['id_agente_modulo']; + if (!util_api_check_agent_and_print_error($data['id_agente'], $returnType)) { + return; + } - get_module_properties($module_id, $fields, $separator, $returnType, $returnReplace); + $module_id = $data['id_agente_modulo']; + + get_module_properties($module_id, $fields, $separator, $returnType, $returnReplace); } + /* * subroutine for api_get_module_properties() and api_get_module_properties_by_name(). */ function get_module_properties($id_module, $fields, $separator, $returnType, $returnReplace) { - /** NOTE: if you want to add an output field, you have to add it to; - 1. $module_properties_master_fields (field name in order) - 2. Update field_column_mapping array (arraies are shared with get_tree_agents()). - Each entry is (DB coloum name => query fragment) - **/ - - /* all of output field names */ - $module_properties_master_fields = array( - 'module_id_agent_modulo', - 'module_id_agent', - 'module_id_module_type', - 'module_description', - 'module_name', - 'module_max', - 'module_min', - 'module_interval', - 'module_tcp_port', - 'module_tcp_send', - 'module_tcp_rcv', - 'module_snmp_community', - 'module_snmp_oid', - 'module_ip_target', - 'module_id_module_group', - 'module_flag', - 'module_id_module', - 'module_disabled', - 'module_id_export', - 'module_plugin_user', - 'module_plugin_pass', - 'module_plugin_parameter', - 'module_id_plugin', - 'module_post_process', - 'module_prediction_module', - 'module_max_timeout', - 'module_max_retries', - 'module_custom_id', - 'module_history_data', - 'module_min_warning', - 'module_max_warning', - 'module_str_warning', - 'module_min_critical', - 'module_max_critical', - 'module_str_critical', - 'module_min_ff_event', - 'module_delete_pending', - 'module_id_agent_state', - 'module_data', - 'module_timestamp', - 'module_state', - 'module_last_try', - 'module_utimestamp', - 'module_current_interval', - 'module_running_by', - 'module_last_execution_try', - 'module_status_changes', - 'module_last_status', - 'module_plugin_macros', - 'module_macros', - 'module_critical_inverse', - 'module_warning_inverse'); + /* + NOTE: if you want to add an output field, you have to add it to; + 1. $module_properties_master_fields (field name in order) + 2. Update field_column_mapping array (arraies are shared with get_tree_agents()). + Each entry is (DB coloum name => query fragment) + */ - /* module related field mappings 1/2 (output field => column for 'tagente_modulo') */ + // all of output field names + $module_properties_master_fields = [ + 'module_id_agent_modulo', + 'module_id_agent', + 'module_id_module_type', + 'module_description', + 'module_name', + 'module_max', + 'module_min', + 'module_interval', + 'module_tcp_port', + 'module_tcp_send', + 'module_tcp_rcv', + 'module_snmp_community', + 'module_snmp_oid', + 'module_ip_target', + 'module_id_module_group', + 'module_flag', + 'module_id_module', + 'module_disabled', + 'module_id_export', + 'module_plugin_user', + 'module_plugin_pass', + 'module_plugin_parameter', + 'module_id_plugin', + 'module_post_process', + 'module_prediction_module', + 'module_max_timeout', + 'module_max_retries', + 'module_custom_id', + 'module_history_data', + 'module_min_warning', + 'module_max_warning', + 'module_str_warning', + 'module_min_critical', + 'module_max_critical', + 'module_str_critical', + 'module_min_ff_event', + 'module_delete_pending', + 'module_id_agent_state', + 'module_data', + 'module_timestamp', + 'module_state', + 'module_last_try', + 'module_utimestamp', + 'module_current_interval', + 'module_running_by', + 'module_last_execution_try', + 'module_status_changes', + 'module_last_status', + 'module_plugin_macros', + 'module_macros', + 'module_critical_inverse', + 'module_warning_inverse', + ]; - global $module_field_column_mampping; - - /* module related field mappings 2/2 (output field => column for 'tagente_estado') */ + // module related field mappings 1/2 (output field => column for 'tagente_modulo') + global $module_field_column_mampping; - global $estado_fields_to_columns_mapping; + // module related field mappings 2/2 (output field => column for 'tagente_estado') + global $estado_fields_to_columns_mapping; - if ($fields == false) { - $fields = $module_properties_master_fields; - } - - /* construct column list to query for tagente, tagente_modulo, tagente_estado and alert-related tables */ - $module_additional_columns = ""; - $estado_additional_columns = ""; - foreach ($fields as $fld ) { - if (array_key_exists ($fld, $module_field_column_mampping ) ) { - $module_additional_columns .= (", " . $module_field_column_mampping[$fld]); - } - if (array_key_exists ($fld, $estado_fields_to_columns_mapping ) ) { - $estado_additional_columns .= (", " . $estado_fields_to_columns_mapping[$fld]); - } - } - - /* query to the DB */ - $returnVar = array(); - $modules = db_get_all_rows_sql('SELECT * - FROM (SELECT id_agente_modulo as module_id_agent_modulo ' . $module_additional_columns . ' + if ($fields == false) { + $fields = $module_properties_master_fields; + } + + // construct column list to query for tagente, tagente_modulo, tagente_estado and alert-related tables + $module_additional_columns = ''; + $estado_additional_columns = ''; + foreach ($fields as $fld) { + if (array_key_exists($fld, $module_field_column_mampping)) { + $module_additional_columns .= (', '.$module_field_column_mampping[$fld]); + } + + if (array_key_exists($fld, $estado_fields_to_columns_mapping)) { + $estado_additional_columns .= (', '.$estado_fields_to_columns_mapping[$fld]); + } + } + + // query to the DB + $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 . ' + 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'); + WHERE id_agente_modulo = '.$id_module.') t2 + ON t1.module_id_agent_modulo = t2.module_id_agent_modulo' + ); - if ($modules === false) $modules = array(); - $modules = str_replace('\n', $returnReplace, $modules); + if ($modules === false) { + $modules = []; + } - foreach ($modules as &$module) { - $module['type_row'] = 'module'; + $modules = str_replace('\n', $returnReplace, $modules); - if( $module['module_macros'] ) { - $module['module_macros'] = base64_decode( $module['module_macros']); - } + foreach ($modules as &$module) { + $module['type_row'] = 'module'; - $returnVar[] = $module; - - } + if ($module['module_macros']) { + $module['module_macros'] = base64_decode($module['module_macros']); + } - $data = array('type' => 'array', 'data' => $returnVar); - - $data['list_index'] = $fields; - - returnData($returnType, $data, $separator); + $returnVar[] = $module; + } + + $data = [ + 'type' => 'array', + 'data' => $returnVar, + ]; + + $data['list_index'] = $fields; + + returnData($returnType, $data, $separator); } -function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) { - global $config; - if (defined ('METACONSOLE')) { - return; - } - - if (!check_acl($config['id_user'], 0, "AW")) { - returnError('forbidden', 'string'); - return; - } +function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) +{ + global $config; - if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AW')) { - return; - } + if (defined('METACONSOLE')) { + 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]; - $nameServer = $other['data'][8]; - $customId = $other['data'][9]; - $learningMode = $other['data'][10]; - $disabled = $other['data'][11]; - $description = $other['data'][12]; - - if ($cascadeProtection == 1) { - if (($idParent != 0) && (db_get_value_sql('SELECT id_agente_modulo + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'string'); + return; + } + + if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AW')) { + 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]; + $nameServer = $other['data'][8]; + $customId = $other['data'][9]; + $learningMode = $other['data'][10]; + $disabled = $other['data'][11]; + $description = $other['data'][12]; + + 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) === false)) { - returnError('parent_agent_not_exist', 'Is not a parent module to do cascade protection.'); - } - } - else { - $cascadeProtectionModule = 0; - } - // Check ACL group - if (!check_acl($config['id_user'], $idGroup, "AW")) { - returnError('forbidden', 'string'); - return; - } + WHERE id_agente = '.$idParent.' AND id_agente_modulo = '.$cascadeProtectionModule + ) === false) + ) { + returnError('parent_agent_not_exist', 'Is not a parent module to do cascade protection.'); + } + } else { + $cascadeProtectionModule = 0; + } - // 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; - } - } - $values_old = db_get_row_filter('tagente', - array('id_agente' => $id_agent), - array('id_grupo', 'disabled') - ); - $tpolicy_group_old = db_get_all_rows_sql("SELECT id_policy FROM tpolicy_groups - WHERE id_group = ".$values_old['id_grupo']); - + // Check ACL group + if (!check_acl($config['id_user'], $idGroup, 'AW')) { + returnError('forbidden', 'string'); + return; + } - $return = db_process_sql_update('tagente', - array('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), - array('id_agente' => $id_agent)); + // 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 ( $return && !empty($ip)) { - // register ip for this agent in 'taddress' - agents_add_address ($id_agent, $ip); - } + if ($parentCheck === false) { + returnError('parent_agent_forbidden', __('The user cannot access to parent agent.')); + return; + } + } - if($return){ - // Update config file - if (isset($disabled) && $values_old['disabled'] != $disabled) { - enterprise_hook( - 'config_agents_update_config_token', - array($id_agent, 'standby', $disabled) - ); - } + $values_old = db_get_row_filter( + 'tagente', + ['id_agente' => $id_agent], + [ + 'id_grupo', + 'disabled', + ] + ); + $tpolicy_group_old = db_get_all_rows_sql( + 'SELECT id_policy FROM tpolicy_groups + WHERE id_group = '.$values_old['id_grupo'] + ); - if($tpolicy_group_old){ - 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); - - if($tpolicy_agents_old){ - $result2 = db_process_sql_update ('tpolicy_agents', - array('pending_delete' => 1), - array ('id_agent' => $id_agent, 'id_policy' => $value['id_policy'])); - } - } - } - - $tpolicy_group = db_get_all_rows_sql("SELECT id_policy FROM tpolicy_groups - 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); - - if(!$tpolicy_agents){ - db_process_sql_insert ('tpolicy_agents', - array('id_policy' => $value['id_policy'], 'id_agent' => $id_agent)); - } else { - $result3 = db_process_sql_update ('tpolicy_agents', - array('pending_delete' => 0), - array ('id_agent' => $id_agent, 'id_policy' => $value['id_policy'])); - } - } - } - } + $return = db_process_sql_update( + 'tagente', + [ + '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, + ], + ['id_agente' => $id_agent] + ); - returnData('string', - array('type' => 'string', 'data' => (int)((bool)$return))); + if ($return && !empty($ip)) { + // register ip for this agent in 'taddress' + agents_add_address($id_agent, $ip); + } + + if ($return) { + // Update config file + if (isset($disabled) && $values_old['disabled'] != $disabled) { + enterprise_hook( + 'config_agents_update_config_token', + [ + $id_agent, + 'standby', + $disabled, + ] + ); + } + + if ($tpolicy_group_old) { + 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 + ); + + if ($tpolicy_agents_old) { + $result2 = db_process_sql_update( + 'tpolicy_agents', + ['pending_delete' => 1], + [ + 'id_agent' => $id_agent, + 'id_policy' => $value['id_policy'], + ] + ); + } + } + } + + $tpolicy_group = db_get_all_rows_sql( + 'SELECT id_policy FROM tpolicy_groups + 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 + ); + + if (!$tpolicy_agents) { + db_process_sql_insert( + 'tpolicy_agents', + [ + 'id_policy' => $value['id_policy'], + 'id_agent' => $id_agent, + ] + ); + } else { + $result3 = db_process_sql_update( + 'tpolicy_agents', + ['pending_delete' => 0], + [ + 'id_agent' => $id_agent, + 'id_policy' => $value['id_policy'], + ] + ); + } + } + } + } + + returnData( + 'string', + [ + 'type' => 'string', + 'data' => (int) ((bool) $return), + ] + ); } + /** * Create a new agent, and print the id for new agent. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param is ;;;; - * ;;;;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=new_agent&other=pepito|1.1.1.1|0|4|0|30|8|10||0|0|nose%20nose&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;;; + * ;;;;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=new_agent&other=pepito|1.1.1.1|0|4|0|30|8|10||0|0|nose%20nose&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_set_new_agent($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_set_new_agent($thrash1, $thrash2, $other, $thrash3) +{ + global $config; - if (!check_acl($config['id_user'], 0, "AW")) { - returnError('forbidden', 'string'); - return; - } - - if (defined ('METACONSOLE')) { - 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]; + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'string'); + return; + } - 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 (defined('METACONSOLE')) { + return; + } - if ($cascadeProtection == 1) { - if (($idParent != 0) && (db_get_value_sql('SELECT id_agente_modulo + $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]; + + 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( + 'SELECT id_agente_modulo 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.'); - } - } - else { - $cascadeProtectionModule = 0; - } - - switch ($config["dbtype"]) { - case "mysql": - $sql1 = 'SELECT name - FROM tserver WHERE BINARY name LIKE "' . $nameServer . '"'; - break; - case "postgresql": - case "oracle": - $sql1 = 'SELECT name - FROM tserver WHERE name LIKE \'' . $nameServer . '\''; - break; - } - - $nameServer = db_get_value_sql($sql1); + WHERE id_agente = '.$idParent.' AND id_agente_modulo = '.$cascadeProtectionModule + ) === false) + ) { + returnError('parent_agent_not_exist', 'Is not a parent module to do cascade protection.'); + } + } else { + $cascadeProtectionModule = 0; + } - // Check ACL group - if (!check_acl($config['id_user'], $idGroup, "AW")) { - returnError('forbidden', 'string'); - return; - } + switch ($config['dbtype']) { + case 'mysql': + $sql1 = 'SELECT name + FROM tserver WHERE BINARY name LIKE "'.$nameServer.'"'; + break; - // 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)) { - returnError('agent_name_exist', 'The name of agent yet exist in DB.'); - } - else if (db_get_value_sql('SELECT id_grupo + 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)) { + 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) { - - returnError('id_grupo_not_exist', 'The group don`t exist.'); - } - else if (db_get_value_sql('SELECT id_os + WHERE id_grupo = '.$idGroup + ) === 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) { - - returnError('id_os_not_exist', 'The OS don`t exist.'); - } - else if (db_get_value_sql($sql1) === false) { - returnError('server_not_exist', 'The ' . get_product_name() . ' Server don`t exist.'); - } - else { - $idAgente = db_process_sql_insert ('tagente', - array ('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($idGroup && !empty($idAgente)){ - $tpolicy_group_old = db_get_all_rows_sql("SELECT id_policy FROM tpolicy_groups - WHERE id_group = ".$idGroup); - - if($tpolicy_group_old){ - foreach ($tpolicy_group_old as $key => $old_group) { - db_process_sql_insert ('tpolicy_agents', - array('id_policy' => $old_group['id_policy'], 'id_agent' => $idAgente)); - } - } - } - - returnData('string', - array('type' => 'string', 'data' => $idAgente)); - } + WHERE id_os = '.$idOS + ) === false + ) { + returnError('id_os_not_exist', 'The OS don`t exist.'); + } else if (db_get_value_sql($sql1) === 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 ($idGroup && !empty($idAgente)) { + $tpolicy_group_old = db_get_all_rows_sql( + 'SELECT id_policy FROM tpolicy_groups + WHERE id_group = '.$idGroup + ); + + if ($tpolicy_group_old) { + foreach ($tpolicy_group_old as $key => $old_group) { + db_process_sql_insert( + 'tpolicy_agents', + [ + 'id_policy' => $old_group['id_policy'], + 'id_agent' => $idAgente, + ] + ); + } + } + } + + returnData( + 'string', + [ + 'type' => 'string', + 'data' => $idAgente, + ] + ); + } } -function api_set_create_os($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_set_create_os($thrash1, $thrash2, $other, $thrash3) +{ + global $config; + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'string'); + return; + } - if (!check_acl($config['id_user'], 0, "AW")) { - returnError('forbidden', 'string'); - return; - } + $values = []; - $values = array(); - - $values['name'] = $other['data'][0]; - $values['description'] = $other['data'][1]; + $values['name'] = $other['data'][0]; + $values['description'] = $other['data'][1]; - if (($other['data'][2] !== 0) && ($other['data'][2] != '')) { - $values['icon_name'] = $other['data'][2]; - } + if (($other['data'][2] !== 0) && ($other['data'][2] != '')) { + $values['icon_name'] = $other['data'][2]; + } + $resultOrId = false; + if ($other['data'][0] != '') { + $resultOrId = db_process_sql_insert('tconfig_os', $values); - - $resultOrId = false; - if ($other['data'][0] != '') { - $resultOrId = db_process_sql_insert('tconfig_os', $values); - - if ($resultOrId) - echo __('Success creating OS'); - else - echo __('Error creating OS'); - } + if ($resultOrId) { + echo __('Success creating OS'); + } else { + echo __('Error creating OS'); + } + } } -function api_set_update_os($id_os, $thrash2, $other, $thrash3) { - global $config; - if (!check_acl($config['id_user'], 0, "AW")) { - returnError('forbidden', 'string'); - return; - } - - $values = array(); - $values['name'] = $other['data'][0]; - $values['description'] = $other['data'][1]; - - if (($other['data'][2] !== 0) && ($other['data'][2] != '')) { - $values['icon_name'] = $other['data'][2];; - } - $result = false; +function api_set_update_os($id_os, $thrash2, $other, $thrash3) +{ + global $config; + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'string'); + return; + } - if ($other['data'][0] != '') { + $values = []; + $values['name'] = $other['data'][0]; + $values['description'] = $other['data'][1]; - if (db_process_sql_update('tconfig_os', $values, array('id_os' => $id_os))) - echo __('Success updating OS'); - else - echo __('Error updating OS'); - } + if (($other['data'][2] !== 0) && ($other['data'][2] != '')) { + $values['icon_name'] = $other['data'][2]; + ; + } + + $result = false; + + if ($other['data'][0] != '') { + if (db_process_sql_update('tconfig_os', $values, ['id_os' => $id_os])) { + echo __('Success updating OS'); + } else { + echo __('Error updating OS'); + } + } } /** - * * Creates a custom field * - * @param string $name Custom field name + * @param string $name Custom field name * @param boolean $display_front Flag to display custom field in agent's operation view */ -function api_set_create_custom_field($t1, $t2, $other, $returnType) { - global $config; +function api_set_create_custom_field($t1, $t2, $other, $returnType) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "PM")) { - returnError('forbidden', $returnType); - return; - } + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', $returnType); + return; + } - if ($other['type'] == 'string') { - returnError('error_parameter', 'Error in the parameters.'); - return; - } - else if ($other['type'] == 'array') { - - $name = ""; - - if ($other['data'][0] != '') { - $name = $other['data'][0]; - } - else { - returnError('error_parameter', 'Custom field name required'); - return; - } - - $display_front = 0; - - if ($other['data'][1] != '') { - $display_front = $other['data'][1]; - } - else { - returnError('error_parameter', 'Custom field display flag required'); - return; - } + if ($other['type'] == 'string') { + returnError('error_parameter', 'Error in the parameters.'); + return; + } else if ($other['type'] == 'array') { + $name = ''; - $is_password_type = 0; - - if ($other['data'][2] != '') { - $is_password_type = $other['data'][2]; - } - else { - returnError('error_parameter', 'Custom field is password type required'); - return; - } - - $result = db_process_sql_insert('tagent_custom_fields', - array('name' => $name, 'display_on_front' => $display_front, - 'is_password_type' => $is_password_type)); - - $data['type'] = "string"; - $data["data"] = $result; - - returnData("string", $data); - } + if ($other['data'][0] != '') { + $name = $other['data'][0]; + } else { + returnError('error_parameter', 'Custom field name required'); + return; + } + + $display_front = 0; + + if ($other['data'][1] != '') { + $display_front = $other['data'][1]; + } else { + returnError('error_parameter', 'Custom field display flag required'); + return; + } + + $is_password_type = 0; + + if ($other['data'][2] != '') { + $is_password_type = $other['data'][2]; + } else { + returnError('error_parameter', 'Custom field is password type required'); + return; + } + + $result = db_process_sql_insert( + 'tagent_custom_fields', + [ + 'name' => $name, + 'display_on_front' => $display_front, + 'is_password_type' => $is_password_type, + ] + ); + + $data['type'] = 'string'; + $data['data'] = $result; + + returnData('string', $data); + } } + /** - * * Returns ID of custom field zero if not exists * * @param string $name Custom field name */ -function api_get_custom_field_id($t1, $t2, $other, $returnType) { - if (defined ('METACONSOLE')) { - return; - } +function api_get_custom_field_id($t1, $t2, $other, $returnType) +{ + if (defined('METACONSOLE')) { + return; + } - $name = $other["data"][0]; - $id = db_get_value ('id_field', 'tagent_custom_fields', 'name', $name); + $name = $other['data'][0]; + $id = db_get_value('id_field', 'tagent_custom_fields', 'name', $name); - if ($id === false) { - returnError('id_not_found', $returnType); - return; - } + if ($id === false) { + returnError('id_not_found', $returnType); + return; + } - $data['type'] = "string"; - $data["data"] = $id; - returnData("string", $data); + $data['type'] = 'string'; + $data['data'] = $id; + returnData('string', $data); } + /** * Delete a agent with the name pass as parameter. - * - * @param string $id Name of agent to delete. + * + * @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) { - global $config; +function api_set_delete_agent($id, $thrash1, $thrast2, $thrash3) +{ + global $config; - if (is_metaconsole()) { - if (!check_acl($config['id_user'], 0, "PM")) { - returnError('forbidden', 'string'); - return; - } - $servers = db_get_all_rows_sql ("SELECT * + if (is_metaconsole()) { + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } + + $servers = db_get_all_rows_sql( + 'SELECT * FROM tmetaconsole_setup - WHERE disabled = 0"); - - if ($servers === false) - $servers = array(); - - - foreach($servers as $server) { - if (metaconsole_connect($server) == NOERR) { - $idAgent[0] = agents_get_agent_id($id,true); - if ($idAgent[0]) { - $result = agents_delete_agent ($idAgent, true); - } - } - } - } - else { - $idAgent = agents_get_agent_id($id); - if (!util_api_check_agent_and_print_error($idAgent, 'string', "AD")) { - return; - } - $result = agents_delete_agent ($idAgent, true); - } - if (!$result) - returnError('error_delete', 'Error in delete operation.'); - else - returnData('string', array('type' => 'string', 'data' => __('Correct Delete'))); + WHERE disabled = 0' + ); + + if ($servers === false) { + $servers = []; + } + + foreach ($servers as $server) { + if (metaconsole_connect($server) == NOERR) { + $idAgent[0] = agents_get_agent_id($id, true); + if ($idAgent[0]) { + $result = agents_delete_agent($idAgent, true); + } + } + } + } else { + $idAgent = agents_get_agent_id($id); + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AD')) { + return; + } + + $result = agents_delete_agent($idAgent, true); + } + + if (!$result) { + returnError('error_delete', 'Error in delete operation.'); + } else { + returnData('string', ['type' => 'string', 'data' => __('Correct Delete')]); + } } + /** * Get all agents, and print all the result like a csv or other type for example json. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available ;;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example for CSV: - * - * api.php?op=get&op2=all_agents&return_type=csv&other=1|2|warning|j|2|~&other_mode=url_encode_separator_| - * - * example for JSON: - * - * api.php?op=get&op2=all_agents&return_type=json&other=1|2|warning|j|2|~&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param are the filters available ;;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example for CSV: + * + * api.php?op=get&op2=all_agents&return_type=csv&other=1|2|warning|j|2|~&other_mode=url_encode_separator_| + * + * example for JSON: + * + * api.php?op=get&op2=all_agents&return_type=json&other=1|2|warning|j|2|~&other_mode=url_encode_separator_| + * * @param $returnType. */ -function api_get_all_agents($thrash1, $thrash2, $other, $returnType) { - global $config; +function api_get_all_agents($thrash1, $thrash2, $other, $returnType) +{ + global $config; - // Error if user cannot read agents. - if (!check_acl($config['id_user'], 0, "AR")) { - returnError('forbidden', $returnType); - return; - } + // Error if user cannot read agents. + if (!check_acl($config['id_user'], 0, 'AR')) { + returnError('forbidden', $returnType); + return; + } - $groups = '1 = 1'; - if (!is_user_admin($config['id_user'])) { - $user_groups = implode (',', array_keys(users_get_groups())); - $groups = "(id_grupo IN ($user_groups) OR id_group IN ($user_groups))"; - } + $groups = '1 = 1'; + if (!is_user_admin($config['id_user'])) { + $user_groups = implode(',', array_keys(users_get_groups())); + $groups = "(id_grupo IN ($user_groups) OR id_group IN ($user_groups))"; + } - if (isset($other['data'][0])) { - // Filter by SO - if ($other['data'][0] != "") { - $where .= " AND tconfig_os.id_os = " . $other['data'][0]; - } - } - if (isset($other['data'][1])) { - // Filter by group - if ($other['data'][1] != "") { - $where .= " AND id_grupo = " . $other['data'][1]; - } - } - if (isset($other['data'][3])) { - // Filter by alias - if ($other['data'][3] != "") { - $where .= " AND alias LIKE ('%" . $other['data'][3] . "%')"; - } - } - if (isset($other['data'][4])) { - // Filter by policy - if ($other['data'][4] != "") { - $filter_by_policy = enterprise_hook('policies_get_filter_by_agent', array($other['data'][4])); - if ($filter_by_policy !== ENTERPRISE_NOT_HOOK) { - $where .= $filter_by_policy; - } - } - } - - if (!isset($other['data'][5])) - $separator = ';'; //by default - else - $separator = $other['data'][5]; - - // Initialization of array - $result_agents = array(); - // Filter by state - - if (defined ('METACONSOLE')) { - $sql = "SELECT id_agente, alias, direccion, comentarios, + if (isset($other['data'][0])) { + // Filter by SO + if ($other['data'][0] != '') { + $where .= ' AND tconfig_os.id_os = '.$other['data'][0]; + } + } + + if (isset($other['data'][1])) { + // Filter by group + if ($other['data'][1] != '') { + $where .= ' AND id_grupo = '.$other['data'][1]; + } + } + + if (isset($other['data'][3])) { + // Filter by alias + if ($other['data'][3] != '') { + $where .= " AND alias LIKE ('%".$other['data'][3]."%')"; + } + } + + if (isset($other['data'][4])) { + // Filter by policy + if ($other['data'][4] != '') { + $filter_by_policy = enterprise_hook('policies_get_filter_by_agent', [$other['data'][4]]); + if ($filter_by_policy !== ENTERPRISE_NOT_HOOK) { + $where .= $filter_by_policy; + } + } + } + + if (!isset($other['data'][5])) { + $separator = ';'; + // by default + } else { + $separator = $other['data'][5]; + } + + // Initialization of array + $result_agents = []; + // 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"; - } - else{ - $sql = "SELECT id_agente, alias, direccion, comentarios, + } 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"; - } + } - $all_agents = db_get_all_rows_sql($sql); + $all_agents = db_get_all_rows_sql($sql); - // Filter by status: unknown, warning, critical, without modules - if (isset($other['data'][2])) { - if ($other['data'][2] != "") { - foreach($all_agents as $agent) { - $filter_modules['id_agente'] = $agent['id_agente']; - $filter_modules['disabled'] = 0; - $filter_modules['delete_pending'] = 0; - $modules = db_get_all_rows_filter('tagente_modulo', - $filter_modules, 'id_agente_modulo'); - $result_modules = array(); - // Skip non init modules - foreach ($modules as $module) { - if (modules_get_agentmodule_is_init($module['id_agente_modulo'])) { - $result_modules[] = $module; - } - } - - // Without modules NO_MODULES - if ($other['data'][2] == 'no_modules') { - if (empty($result_modules) and $other['data'][2] == 'no_modules') { - $result_agents[] = $agent; - } - } - // filter by NORMAL, WARNING, CRITICAL, UNKNOWN, ALERT_FIRED - else { - $status = agents_get_status($agent['id_agente'], true); - // Filter by status - switch ($other['data'][2]) { - case 'warning': - if ($status == 2) { - $result_agents[] = $agent; - } - break; - case 'critical': - if ($status == 1) { - $result_agents[] = $agent; - } - break; - case 'unknown': - if ($status == 3) { - $result_agents[] = $agent; - } - break; - case 'normal': - if ($status == 0) { - $result_agents[] = $agent; - } - break; - case 'alert_fired': - if ($status == 4) { - $result_agents[] = $agent; - } - break; - } - } - } - } - else { - $result_agents = $all_agents; - } - } - else { - $result_agents = $all_agents; - } - - if (empty($returnType)) { - $returnType = "string"; - } - - if (empty($separator)) { - $separator = ";"; - } - - foreach ($result_agents as $key => $value) { - $result_agents[$key]['status'] = agents_get_status($result_agents[$key]['id_agente'], true); - } - - if (count($result_agents) > 0 and $result_agents !== false) { - $data = array('type' => 'array', 'data' => $result_agents); - returnData($returnType, $data, $separator); - } - else { - returnError('error_all_agents', 'No agents retrieved.'); - } + // Filter by status: unknown, warning, critical, without modules + if (isset($other['data'][2])) { + if ($other['data'][2] != '') { + foreach ($all_agents as $agent) { + $filter_modules['id_agente'] = $agent['id_agente']; + $filter_modules['disabled'] = 0; + $filter_modules['delete_pending'] = 0; + $modules = db_get_all_rows_filter( + 'tagente_modulo', + $filter_modules, + 'id_agente_modulo' + ); + $result_modules = []; + // Skip non init modules + foreach ($modules as $module) { + if (modules_get_agentmodule_is_init($module['id_agente_modulo'])) { + $result_modules[] = $module; + } + } + + // Without modules NO_MODULES + if ($other['data'][2] == 'no_modules') { + if (empty($result_modules) and $other['data'][2] == 'no_modules') { + $result_agents[] = $agent; + } + } + // filter by NORMAL, WARNING, CRITICAL, UNKNOWN, ALERT_FIRED + else { + $status = agents_get_status($agent['id_agente'], true); + // Filter by status + switch ($other['data'][2]) { + case 'warning': + if ($status == 2) { + $result_agents[] = $agent; + } + break; + + case 'critical': + if ($status == 1) { + $result_agents[] = $agent; + } + break; + + case 'unknown': + if ($status == 3) { + $result_agents[] = $agent; + } + break; + + case 'normal': + if ($status == 0) { + $result_agents[] = $agent; + } + break; + + case 'alert_fired': + if ($status == 4) { + $result_agents[] = $agent; + } + break; + } + } + } + } else { + $result_agents = $all_agents; + } + } else { + $result_agents = $all_agents; + } + + if (empty($returnType)) { + $returnType = 'string'; + } + + if (empty($separator)) { + $separator = ';'; + } + + foreach ($result_agents as $key => $value) { + $result_agents[$key]['status'] = agents_get_status($result_agents[$key]['id_agente'], true); + } + + if (count($result_agents) > 0 and $result_agents !== false) { + $data = [ + 'type' => 'array', + 'data' => $result_agents, + ]; + returnData($returnType, $data, $separator); + } else { + returnError('error_all_agents', 'No agents retrieved.'); + } } + /** * Get modules for an agent, and print all the result like a csv. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=agents_modules&return_type=csv&other=14&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param are the filters available in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=agents_modules&return_type=csv&other=14&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_get_agent_modules($thrash1, $thrash2, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if (!util_api_check_agent_and_print_error($other['data'][0], 'csv')) return; +function api_get_agent_modules($thrash1, $thrash2, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - $sql = sprintf("SELECT id_agente, id_agente_modulo, nombre + if (!util_api_check_agent_and_print_error($other['data'][0], 'csv')) { + return; + } + + $sql = sprintf( + 'SELECT id_agente, id_agente_modulo, nombre FROM tagente_modulo WHERE id_agente = %d AND disabled = 0 - AND delete_pending = 0", $other['data'][0]); - - $all_modules = db_get_all_rows_sql($sql); - - if (count($all_modules) > 0 and $all_modules !== false) { - $data = array('type' => 'array', 'data' => $all_modules); - - returnData('csv', $data, ';'); - } - else { - returnError('error_agent_modules', 'No modules retrieved.'); - } + AND delete_pending = 0', + $other['data'][0] + ); + + $all_modules = db_get_all_rows_sql($sql); + + if (count($all_modules) > 0 and $all_modules !== false) { + $data = [ + 'type' => 'array', + 'data' => $all_modules, + ]; + + returnData('csv', $data, ';'); + } else { + returnError('error_agent_modules', 'No modules retrieved.'); + } } -function api_get_db_uncompress_module_data ($id_agente_modulo,$tstart,$other){ - global $config; - - if (!isset($id_agente_modulo)) { - return false; - } - if ((!isset($tstart)) || ($tstart === false)) { - // Return data from the begining - //$tstart = 0; - $tstart = 0; - } - $tend = $other['data']; - if ((!isset($tend)) || ($tend === false)) { - // Return data until now - $tend = time(); - } +function api_get_db_uncompress_module_data($id_agente_modulo, $tstart, $other) +{ + global $config; - if ($tstart > $tend) { - return false; - } - - $search_historydb = false; - $table = "tagente_datos"; - - $module = modules_get_agentmodule($id_agente_modulo); - - if ($module === false){ - // module not exists - return false; - } - $module_type = $module['id_tipo_modulo']; - $module_type_str = modules_get_type_name ($module_type); - if (strstr ($module_type_str, 'string') !== false) { - $table = "tagente_datos_string"; - } - - // Get first available utimestamp in active DB - $query = " SELECT utimestamp, datos FROM $table "; - $query .= " WHERE id_agente_modulo=$id_agente_modulo AND utimestamp < $tstart"; - $query .= " ORDER BY utimestamp DESC LIMIT 1"; + if (!isset($id_agente_modulo)) { + return false; + } + if ((!isset($tstart)) || ($tstart === false)) { + // Return data from the begining + // $tstart = 0; + $tstart = 0; + } - $ret = db_get_all_rows_sql( $query , $search_historydb); + $tend = $other['data']; + if ((!isset($tend)) || ($tend === false)) { + // Return data until now + $tend = time(); + } - - if ( ( $ret === false ) || (( isset($ret[0]["utimestamp"]) && ($ret[0]["utimestamp"] > $tstart )))) { - // Value older than first retrieved from active DB - $search_historydb = true; + if ($tstart > $tend) { + return false; + } - $ret = db_get_all_rows_sql( $query , $search_historydb); - } - else { - $first_data["utimestamp"] = $ret[0]["utimestamp"]; - $first_data["datos"] = $ret[0]["datos"]; - } + $search_historydb = false; + $table = 'tagente_datos'; - if ( ( $ret === false ) || (( isset($ret[0]["utimestamp"]) && ($ret[0]["utimestamp"] > $tstart )))) { - // No previous data. -> not init - // Avoid false unknown status - $first_data["utimestamp"] = time(); - $first_data["datos"] = false; - } - else { - $first_data["utimestamp"] = $ret[0]["utimestamp"]; - $first_data["datos"] = $ret[0]["datos"]; - } - - $query = " SELECT utimestamp, datos FROM $table "; - $query .= " WHERE id_agente_modulo=$id_agente_modulo AND utimestamp >= $tstart AND utimestamp <= $tend"; - $query .= " ORDER BY utimestamp ASC"; + $module = modules_get_agentmodule($id_agente_modulo); - // Retrieve all data from module in given range - $raw_data = db_get_all_rows_sql($query, $search_historydb); - - if (($raw_data === false) && ($ret === false)) { - // No data - return false; - } + if ($module === false) { + // module not exists + return false; + } - // Retrieve going unknown events in range - $unknown_events = db_get_module_ranges_unknown($id_agente_modulo, $tstart, $tend); - - // Retrieve module_interval to build the template - $module_interval = modules_get_interval ($id_agente_modulo); - $slice_size = $module_interval; - - + $module_type = $module['id_tipo_modulo']; + $module_type_str = modules_get_type_name($module_type); + if (strstr($module_type_str, 'string') !== false) { + $table = 'tagente_datos_string'; + } - // We'll return a bidimensional array - // Structure returned: schema: - // - // uncompressed_data => - // pool_id (int) - // utimestamp (start of current slice) - // data - // array - // utimestamp - // datos + // Get first available utimestamp in active DB + $query = " SELECT utimestamp, datos FROM $table "; + $query .= " WHERE id_agente_modulo=$id_agente_modulo AND utimestamp < $tstart"; + $query .= ' ORDER BY utimestamp DESC LIMIT 1'; - $return = array(); - // Point current_timestamp to begin of the set and initialize flags - $current_timestamp = $tstart; - $last_inserted_value = $first_data["datos"]; - $last_timestamp = $first_data["utimestamp"]; - $data_found = 0; + $ret = db_get_all_rows_sql($query, $search_historydb); - // Build template - $pool_id = 0; - $now = time(); + if (( $ret === false ) || (( isset($ret[0]['utimestamp']) && ($ret[0]['utimestamp'] > $tstart )))) { + // Value older than first retrieved from active DB + $search_historydb = true; - $in_unknown_status = 0; - if (is_array($unknown_events)) { - $current_unknown = array_shift($unknown_events); - } - - while ( $current_timestamp < $tend ) { - $expected_data_generated = 0; + $ret = db_get_all_rows_sql($query, $search_historydb); + } else { + $first_data['utimestamp'] = $ret[0]['utimestamp']; + $first_data['datos'] = $ret[0]['datos']; + } - $return[$pool_id]["data"] = array(); - $tmp_data = array(); - $data_found = 0; - - if (is_array($unknown_events)) { - $i = 0; - while ($current_timestamp >= $unknown_events[$i]["time_to"] ) { - // Skip unknown events in past - array_splice($unknown_events, $i,1); - $i++; - if (!isset($unknown_events[$i])) { - break; - } - } - if (isset($current_unknown)) { + if (( $ret === false ) || (( isset($ret[0]['utimestamp']) && ($ret[0]['utimestamp'] > $tstart )))) { + // No previous data. -> not init + // Avoid false unknown status + $first_data['utimestamp'] = time(); + $first_data['datos'] = false; + } else { + $first_data['utimestamp'] = $ret[0]['utimestamp']; + $first_data['datos'] = $ret[0]['datos']; + } - // check if recovered from unknown status - if(is_array($unknown_events) && isset($current_unknown)) { - if ( (($current_timestamp+$slice_size) > $current_unknown["time_to"]) - && ($current_timestamp < $current_unknown["time_to"]) - && ($in_unknown_status == 1) ) { - // Recovered from unknown + $query = " SELECT utimestamp, datos FROM $table "; + $query .= " WHERE id_agente_modulo=$id_agente_modulo AND utimestamp >= $tstart AND utimestamp <= $tend"; + $query .= ' ORDER BY utimestamp ASC'; - if ( ($current_unknown["time_to"] > $current_timestamp) - && ($expected_data_generated == 0) ) { - // also add the "expected" data - $tmp_data["utimestamp"] = $current_timestamp; - if ($in_unknown_status == 1) { - $tmp_data["datos"] = null; - } - else { - $tmp_data["datos"] = $last_inserted_value; - } - $return[$pool_id]["utimestamp"] = $current_timestamp; - array_push($return[$pool_id]["data"], $tmp_data); - $expected_data_generated = 1; - } + // Retrieve all data from module in given range + $raw_data = db_get_all_rows_sql($query, $search_historydb); + if (($raw_data === false) && ($ret === false)) { + // No data + return false; + } - $tmp_data["utimestamp"] = $current_unknown["time_to"]; - $tmp_data["datos"] = $last_inserted_value; - // debug purpose - $tmp_data["obs"] = "event recovery data"; - - $return[$pool_id]["utimestamp"] = $current_timestamp; - array_push($return[$pool_id]["data"], $tmp_data); - $data_found = 1; - $in_unknown_status = 0; - } + // Retrieve going unknown events in range + $unknown_events = db_get_module_ranges_unknown($id_agente_modulo, $tstart, $tend); - if ( (($current_timestamp+$slice_size) > $current_unknown["time_from"]) - && (($current_timestamp+$slice_size) < $current_unknown["time_to"]) - && ($in_unknown_status == 0) ) { - // Add unknown state detected + // Retrieve module_interval to build the template + $module_interval = modules_get_interval($id_agente_modulo); + $slice_size = $module_interval; - if ( $current_unknown["time_from"] < ($current_timestamp+$slice_size)) { - if ( ($current_unknown["time_from"] > $current_timestamp) - && ($expected_data_generated == 0) ) { - // also add the "expected" data - $tmp_data["utimestamp"] = $current_timestamp; - if ($in_unknown_status == 1) { - $tmp_data["datos"] = null; - } - else { - $tmp_data["datos"] = $last_inserted_value; - } - $return[$pool_id]["utimestamp"] = $current_timestamp; - array_push($return[$pool_id]["data"], $tmp_data); - $expected_data_generated = 1; - } + // We'll return a bidimensional array + // Structure returned: schema: + // + // uncompressed_data => + // pool_id (int) + // utimestamp (start of current slice) + // data + // array + // utimestamp + // datos + $return = []; + // Point current_timestamp to begin of the set and initialize flags + $current_timestamp = $tstart; + $last_inserted_value = $first_data['datos']; + $last_timestamp = $first_data['utimestamp']; + $data_found = 0; - $tmp_data["utimestamp"] = $current_unknown["time_from"]; - $tmp_data["datos"] = null; - // debug purpose - $tmp_data["obs"] = "event data"; - $return[$pool_id]["utimestamp"] = $current_timestamp; - array_push($return[$pool_id]["data"], $tmp_data); - $data_found = 1; - } - $in_unknown_status = 1; - } + // Build template + $pool_id = 0; + $now = time(); - if ( ($in_unknown_status == 0) && ($current_timestamp >= $current_unknown["time_to"]) ) { - $current_unknown = array_shift($unknown_events); - } - } - } // unknown events handle - } + $in_unknown_status = 0; + if (is_array($unknown_events)) { + $current_unknown = array_shift($unknown_events); + } - // Search for data - $i=0; - - if (is_array($raw_data)) { - foreach ($raw_data as $data) { - if ( ($data["utimestamp"] >= $current_timestamp) - && ($data["utimestamp"] < ($current_timestamp+$slice_size)) ) { - // Data in block, push in, and remove from $raw_data (processed) + while ($current_timestamp < $tend) { + $expected_data_generated = 0; - if ( ($data["utimestamp"] > $current_timestamp) - && ($expected_data_generated == 0) ) { - // also add the "expected" data - $tmp_data["utimestamp"] = $current_timestamp; - if ($in_unknown_status == 1) { - $tmp_data["datos"] = null; - } - else { - $tmp_data["datos"] = $last_inserted_value; - } - $tmp_data["obs"] = "expected data"; - $return[$pool_id]["utimestamp"] = $current_timestamp; - array_push($return[$pool_id]["data"], $tmp_data); - $expected_data_generated = 1; - } + $return[$pool_id]['data'] = []; + $tmp_data = []; + $data_found = 0; - $tmp_data["utimestamp"] = intval($data["utimestamp"]); - $tmp_data["datos"] = $data["datos"]; - // debug purpose - $tmp_data["obs"] = "real data"; + if (is_array($unknown_events)) { + $i = 0; + while ($current_timestamp >= $unknown_events[$i]['time_to']) { + // Skip unknown events in past + array_splice($unknown_events, $i, 1); + $i++; + if (!isset($unknown_events[$i])) { + break; + } + } - $return[$pool_id]["utimestamp"] = $current_timestamp; - array_push($return[$pool_id]["data"], $tmp_data); + if (isset($current_unknown)) { + // check if recovered from unknown status + if (is_array($unknown_events) && isset($current_unknown)) { + if ((($current_timestamp + $slice_size) > $current_unknown['time_to']) + && ($current_timestamp < $current_unknown['time_to']) + && ($in_unknown_status == 1) + ) { + // Recovered from unknown + if (($current_unknown['time_to'] > $current_timestamp) + && ($expected_data_generated == 0) + ) { + // also add the "expected" data + $tmp_data['utimestamp'] = $current_timestamp; + if ($in_unknown_status == 1) { + $tmp_data['datos'] = null; + } else { + $tmp_data['datos'] = $last_inserted_value; + } - $last_inserted_value = $data["datos"]; - $last_timestamp = intval($data["utimestamp"]); + $return[$pool_id]['utimestamp'] = $current_timestamp; + array_push($return[$pool_id]['data'], $tmp_data); + $expected_data_generated = 1; + } - unset($raw_data[$i]); - $data_found = 1; - $in_unknown_status = 0; - } - elseif ($data["utimestamp"] > ($current_timestamp+$slice_size)) { - // Data in future, stop searching new ones - break; - } - } - $i++; - } + $tmp_data['utimestamp'] = $current_unknown['time_to']; + $tmp_data['datos'] = $last_inserted_value; + // debug purpose + $tmp_data['obs'] = 'event recovery data'; - if ($data_found == 0) { - // No data found, lug the last_value until SECONDS_1DAY + 2*modules_get_interval - // UNKNOWN! + $return[$pool_id]['utimestamp'] = $current_timestamp; + array_push($return[$pool_id]['data'], $tmp_data); + $data_found = 1; + $in_unknown_status = 0; + } - if (($current_timestamp > $now) || (($current_timestamp - $last_timestamp) > (SECONDS_1DAY + 2*$module_interval))) { - if (isset($last_inserted_value)) { - // unhandled unknown status control - $unhandled_time_unknown = $current_timestamp - (SECONDS_1DAY + 2*$module_interval) - $last_timestamp; - if ($unhandled_time_unknown > 0) { - // unhandled unknown status detected. Add to previous pool - $tmp_data["utimestamp"] = intval($last_timestamp) + (SECONDS_1DAY + 2*$module_interval); - $tmp_data["datos"] = null; - // debug purpose - $tmp_data["obs"] = "unknown extra"; - // add to previous pool if needed - if (isset($return[$pool_id-1])) { - array_push($return[$pool_id-1]["data"], $tmp_data); - } - } - } - $last_inserted_value = null; - } + if ((($current_timestamp + $slice_size) > $current_unknown['time_from']) + && (($current_timestamp + $slice_size) < $current_unknown['time_to']) + && ($in_unknown_status == 0) + ) { + // Add unknown state detected + if ($current_unknown['time_from'] < ($current_timestamp + $slice_size)) { + if (($current_unknown['time_from'] > $current_timestamp) + && ($expected_data_generated == 0) + ) { + // also add the "expected" data + $tmp_data['utimestamp'] = $current_timestamp; + if ($in_unknown_status == 1) { + $tmp_data['datos'] = null; + } else { + $tmp_data['datos'] = $last_inserted_value; + } - $tmp_data["utimestamp"] = $current_timestamp; + $return[$pool_id]['utimestamp'] = $current_timestamp; + array_push($return[$pool_id]['data'], $tmp_data); + $expected_data_generated = 1; + } - if ($in_unknown_status == 1) { - $tmp_data["datos"] = null; - } - else { - $tmp_data["datos"] = $last_inserted_value; - } - // debug purpose - $tmp_data["obs"] = "virtual data"; - - $return[$pool_id]["utimestamp"] = $current_timestamp; - array_push($return[$pool_id]["data"], $tmp_data); - } + $tmp_data['utimestamp'] = $current_unknown['time_from']; + $tmp_data['datos'] = null; + // debug purpose + $tmp_data['obs'] = 'event data'; + $return[$pool_id]['utimestamp'] = $current_timestamp; + array_push($return[$pool_id]['data'], $tmp_data); + $data_found = 1; + } - $pool_id++; - $current_timestamp += $slice_size; - - } - $data = array('type' => 'array', 'data' => $return); - returnData('json', $return, ';'); + $in_unknown_status = 1; + } + + if (($in_unknown_status == 0) && ($current_timestamp >= $current_unknown['time_to'])) { + $current_unknown = array_shift($unknown_events); + } + } + } //end if + } + + // Search for data + $i = 0; + + if (is_array($raw_data)) { + foreach ($raw_data as $data) { + if (($data['utimestamp'] >= $current_timestamp) + && ($data['utimestamp'] < ($current_timestamp + $slice_size)) + ) { + // Data in block, push in, and remove from $raw_data (processed) + if (($data['utimestamp'] > $current_timestamp) + && ($expected_data_generated == 0) + ) { + // also add the "expected" data + $tmp_data['utimestamp'] = $current_timestamp; + if ($in_unknown_status == 1) { + $tmp_data['datos'] = null; + } else { + $tmp_data['datos'] = $last_inserted_value; + } + + $tmp_data['obs'] = 'expected data'; + $return[$pool_id]['utimestamp'] = $current_timestamp; + array_push($return[$pool_id]['data'], $tmp_data); + $expected_data_generated = 1; + } + + $tmp_data['utimestamp'] = intval($data['utimestamp']); + $tmp_data['datos'] = $data['datos']; + // debug purpose + $tmp_data['obs'] = 'real data'; + + $return[$pool_id]['utimestamp'] = $current_timestamp; + array_push($return[$pool_id]['data'], $tmp_data); + + $last_inserted_value = $data['datos']; + $last_timestamp = intval($data['utimestamp']); + + unset($raw_data[$i]); + $data_found = 1; + $in_unknown_status = 0; + } else if ($data['utimestamp'] > ($current_timestamp + $slice_size)) { + // Data in future, stop searching new ones + break; + } + } + + $i++; + } + + if ($data_found == 0) { + // No data found, lug the last_value until SECONDS_1DAY + 2*modules_get_interval + // UNKNOWN! + if (($current_timestamp > $now) || (($current_timestamp - $last_timestamp) > (SECONDS_1DAY + 2 * $module_interval))) { + if (isset($last_inserted_value)) { + // unhandled unknown status control + $unhandled_time_unknown = ($current_timestamp - (SECONDS_1DAY + 2 * $module_interval) - $last_timestamp); + if ($unhandled_time_unknown > 0) { + // unhandled unknown status detected. Add to previous pool + $tmp_data['utimestamp'] = (intval($last_timestamp) + (SECONDS_1DAY + 2 * $module_interval)); + $tmp_data['datos'] = null; + // debug purpose + $tmp_data['obs'] = 'unknown extra'; + // add to previous pool if needed + if (isset($return[($pool_id - 1)])) { + array_push($return[($pool_id - 1)]['data'], $tmp_data); + } + } + } + + $last_inserted_value = null; + } + + $tmp_data['utimestamp'] = $current_timestamp; + + if ($in_unknown_status == 1) { + $tmp_data['datos'] = null; + } else { + $tmp_data['datos'] = $last_inserted_value; + } + + // debug purpose + $tmp_data['obs'] = 'virtual data'; + + $return[$pool_id]['utimestamp'] = $current_timestamp; + array_push($return[$pool_id]['data'], $tmp_data); + } + + $pool_id++; + $current_timestamp += $slice_size; + } + + $data = [ + 'type' => 'array', + 'data' => $return, + ]; + returnData('json', $return, ';'); } @@ -2121,2825 +2396,3270 @@ function api_get_db_uncompress_module_data ($id_agente_modulo,$tstart,$other){ * Get modules id for an agent, and print the result like a csv. * * @param $id Id of agent. - * @param array $name name of module. + * @param array $name name of module. * @param $thrash1 Don't use. * * pi.php?op=get&op2=module_id&id=5&other=Host%20Alive&apipass=1234&user=admin&pass=pandora * * @param $thrash3 Don't use. */ -function api_get_module_id($id , $thrash1 , $name, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } +function api_get_module_id($id, $thrash1, $name, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error($id, 'csv')) return; + if (!util_api_check_agent_and_print_error($id, 'csv')) { + return; + } - $sql = sprintf('SELECT id_agente_modulo + $sql = sprintf( + 'SELECT id_agente_modulo FROM tagente_modulo WHERE id_agente = %d AND nombre = "%s" AND disabled = 0 - AND delete_pending = 0', $id , $name['data']); + AND delete_pending = 0', + $id, + $name['data'] + ); - $module_id = db_get_all_rows_sql($sql); + $module_id = db_get_all_rows_sql($sql); - if (count($module_id) > 0 and $module_id !== false) { - $data = array('type' => 'array', 'data' => $module_id); - returnData('csv', $data, ';'); - } - else { - returnError('error_module_id', 'does not exist module or agent'); - } + if (count($module_id) > 0 and $module_id !== false) { + $data = [ + 'type' => 'array', + 'data' => $module_id, + ]; + returnData('csv', $data, ';'); + } else { + returnError('error_module_id', 'does not exist module or agent'); + } } + /** * Get modules for an agent, and print all the result like a csv. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=group_agent&return_type=csv&other=14&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param are the filters available in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=group_agent&return_type=csv&other=14&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_get_group_agent($thrash1, $thrash2, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - $sql = sprintf("SELECT groups.nombre nombre +function api_get_group_agent($thrash1, $thrash2, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + $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", $other['data'][0]); - - $group_names = db_get_all_rows_sql($sql); - - if (count($group_names) > 0 and $group_names !== false) { - $data = array('type' => 'array', 'data' => $group_names); - - returnData('csv', $data, ';'); - } - else { - returnError('error_group_agent', 'No groups retrieved.'); - } -} + AND agents.id_grupo = groups.id_grupo', + $other['data'][0] + ); -/** - * Get name group for an agent, and print all the result like a csv. - * - * @param $thrash1 Don't use. - * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=group_agent&return_type=csv&other=Pepito&other_mode=url_encode_separator_| - * - * @param $thrash3 Don't use. - */ -function api_get_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) { - - $group_names =array(); - - if (is_metaconsole()) { - $servers = db_get_all_rows_sql ("SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0"); - - if ($servers === false) - $servers = array(); - - - foreach($servers as $server) { - if (metaconsole_connect($server) == NOERR) { - $agent_id = agents_get_agent_id($other['data'][0],true); - - 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",$agent_id); - $group_server_names = db_get_all_rows_sql($sql); - - if ($group_server_names) { - foreach($group_server_names as $group_server_name) { - $group_names[] = $group_server_name; - } - } - } - } - metaconsole_restore_db(); - } - } - else { - $agent_id = agents_get_agent_id($other['data'][0],true); - if (!util_api_check_agent_and_print_error($agent_id, 'csv')) return; - - $sql = sprintf("SELECT groups.nombre nombre - 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); - } - - if (count($group_names) > 0 and $group_names !== false) { - $data = array('type' => 'array', 'data' => $group_names); - - returnData('csv', $data, ';'); - } - else { - returnError('error_group_agent', 'No groups retrieved.'); - } + $group_names = db_get_all_rows_sql($sql); + + if (count($group_names) > 0 and $group_names !== false) { + $data = [ + 'type' => 'array', + 'data' => $group_names, + ]; + + returnData('csv', $data, ';'); + } else { + returnError('error_group_agent', 'No groups retrieved.'); + } } /** * Get name group for an agent, and print all the result like a csv. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=group_agent_by_alias&return_type=csv&other=Pepito&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param are the filters available in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=group_agent&return_type=csv&other=Pepito&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_get_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_get_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) +{ + $group_names = []; - if (is_metaconsole()) { - return; - } - - if (!check_acl($config['id_user'], 0, "AR")) { - returnError('forbidden', 'csv'); - return; - } - $group_names =array(); - - if (is_metaconsole()) { - $servers = db_get_all_rows_sql ("SELECT * + if (is_metaconsole()) { + $servers = db_get_all_rows_sql( + 'SELECT * FROM tmetaconsole_setup - WHERE disabled = 0"); - - if ($servers === false) - $servers = array(); - - - foreach($servers as $server) { - if (metaconsole_connect($server) == NOERR) { - $sql = sprintf("SELECT tagente.id_agente FROM tagente WHERE alias LIKE '%s' ",$other['data'][0]); - $agent_id = db_get_all_rows_sql($sql); - - foreach ($agent_id as &$id) { - $sql = sprintf("SELECT groups.nombre nombre + WHERE disabled = 0' + ); + + if ($servers === false) { + $servers = []; + } + + foreach ($servers as $server) { + if (metaconsole_connect($server) == NOERR) { + $agent_id = agents_get_agent_id($other['data'][0], true); + + 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",$id['id_agente']); - $group_server_names = db_get_all_rows_sql($sql); - - if ($group_server_names) { - foreach($group_server_names as $group_server_name) { - $group_names[] = $group_server_name; - } - } - } - } - metaconsole_restore_db(); - } - } - else { - $sql = sprintf("SELECT tagente.id_agente FROM tagente WHERE alias LIKE '%s' ",$other['data'][0]); - $agent_id = db_get_all_rows_sql($sql); + AND agents.id_grupo = groups.id_grupo', + $agent_id + ); + $group_server_names = db_get_all_rows_sql($sql); - foreach ($agent_id as &$id) { - if(!users_access_to_agent($id['id_agente'])) continue; + if ($group_server_names) { + foreach ($group_server_names as $group_server_name) { + $group_names[] = $group_server_name; + } + } + } + } - $sql = sprintf("SELECT groups.nombre nombre + metaconsole_restore_db(); + } + } else { + $agent_id = agents_get_agent_id($other['data'][0], true); + if (!util_api_check_agent_and_print_error($agent_id, 'csv')) { + return; + } + + $sql = sprintf( + 'SELECT groups.nombre nombre 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); - $group_names[] = $group_name[0]; - } - } - - if (count($group_names) > 0 and $group_names !== false) { - $data = array('type' => 'array', 'data' => $group_names); - - returnData('csv', $data, ';'); - } - else { - returnError('error_group_agent', 'No groups retrieved.'); - } + AND agents.id_grupo = groups.id_grupo', + $agent_id + ); + $group_names = db_get_all_rows_sql($sql); + } + + if (count($group_names) > 0 and $group_names !== false) { + $data = [ + 'type' => 'array', + 'data' => $group_names, + ]; + + returnData('csv', $data, ';'); + } else { + returnError('error_group_agent', 'No groups retrieved.'); + } } + +/** + * Get name group for an agent, and print all the result like a csv. + * + * @param $thrash1 Don't use. + * @param $thrash2 Don't use. + * @param array $other it's array, $other as param are the filters available in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=group_agent_by_alias&return_type=csv&other=Pepito&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use. + */ +function api_get_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) +{ + global $config; + + if (is_metaconsole()) { + return; + } + + if (!check_acl($config['id_user'], 0, 'AR')) { + returnError('forbidden', 'csv'); + return; + } + + $group_names = []; + + if (is_metaconsole()) { + $servers = db_get_all_rows_sql( + 'SELECT * + FROM tmetaconsole_setup + WHERE disabled = 0' + ); + + if ($servers === false) { + $servers = []; + } + + foreach ($servers as $server) { + if (metaconsole_connect($server) == NOERR) { + $sql = sprintf("SELECT tagente.id_agente FROM tagente WHERE alias LIKE '%s' ", $other['data'][0]); + $agent_id = db_get_all_rows_sql($sql); + + 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', + $id['id_agente'] + ); + $group_server_names = db_get_all_rows_sql($sql); + + if ($group_server_names) { + foreach ($group_server_names as $group_server_name) { + $group_names[] = $group_server_name; + } + } + } + } + + metaconsole_restore_db(); + } + } else { + $sql = sprintf("SELECT tagente.id_agente FROM tagente WHERE alias LIKE '%s' ", $other['data'][0]); + $agent_id = db_get_all_rows_sql($sql); + + foreach ($agent_id as &$id) { + if (!users_access_to_agent($id['id_agente'])) { + continue; + } + + $sql = sprintf( + 'SELECT groups.nombre nombre + 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); + $group_names[] = $group_name[0]; + } + } + + if (count($group_names) > 0 and $group_names !== false) { + $data = [ + 'type' => 'array', + 'data' => $group_names, + ]; + + returnData('csv', $data, ';'); + } else { + returnError('error_group_agent', 'No groups retrieved.'); + } +} + + /** * Get id server whare agent is located, and print all the result like a csv. - * + * * @param $id name of agent. * @param $thrash1 Don't use. * @param $thrash2 Don't use. * example: - * + * * api.php?op=get&op2=locate_agent&return_type=csv&id=Pepito&other_mode=url_encode_separator_| - * + * * @param $thrash3 Don't use. */ -function api_get_locate_agent($id, $thrash1, $thrash2, $thrash3) { - if (!is_metaconsole()) - return; - - $servers = db_get_all_rows_sql ("SELECT * + +function api_get_locate_agent($id, $thrash1, $thrash2, $thrash3) +{ + if (!is_metaconsole()) { + return; + } + + $servers = db_get_all_rows_sql( + 'SELECT * FROM tmetaconsole_setup - WHERE disabled = 0"); - - if ($servers === false) - $servers = array(); - - foreach($servers as $server) { - $id_server = $server['id']; - if (metaconsole_connect($server) == NOERR) { - $agent_id = agents_get_agent_id($id,true); - - if ($agent_id && agents_check_access_agent($agent_id)) { - $group_servers[]['server'] = $id_server; - } - } - metaconsole_restore_db(); - } - - if (count($group_servers) > 0 and $group_servers !== false) { - $data = array('type' => 'array', 'data' => $group_servers); - - returnData('csv', $data, ';'); - } - else { - returnError('error_locate_agents', 'No agents located.'); - } + WHERE disabled = 0' + ); + + if ($servers === false) { + $servers = []; + } + + foreach ($servers as $server) { + $id_server = $server['id']; + if (metaconsole_connect($server) == NOERR) { + $agent_id = agents_get_agent_id($id, true); + + if ($agent_id && agents_check_access_agent($agent_id)) { + $group_servers[]['server'] = $id_server; + } + } + + metaconsole_restore_db(); + } + + if (count($group_servers) > 0 and $group_servers !== false) { + $data = [ + 'type' => 'array', + 'data' => $group_servers, + ]; + + returnData('csv', $data, ';'); + } else { + returnError('error_locate_agents', 'No agents located.'); + } } /** * Get id group for an agent, and print all the result like a csv. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=id_group_agent_by_name&return_type=csv&other=Pepito&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param are the filters available in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=id_group_agent_by_name&return_type=csv&other=Pepito&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_get_id_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) { - if (is_metaconsole()) { - return; - } +function api_get_id_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) +{ + if (is_metaconsole()) { + return; + } - $group_names =array(); - - if (is_metaconsole()) { - $servers = db_get_all_rows_sql ("SELECT * + $group_names = []; + + if (is_metaconsole()) { + $servers = db_get_all_rows_sql( + 'SELECT * FROM tmetaconsole_setup - WHERE disabled = 0"); - - if ($servers === false) - $servers = array(); - - - foreach($servers as $server) { - if (metaconsole_connect($server) == NOERR) { - $agent_id = agents_get_agent_id($other['data'][0],true); - - if ($agent_id) { - $sql = sprintf("SELECT groups.id_grupo id_group + WHERE disabled = 0' + ); + + if ($servers === false) { + $servers = []; + } + + foreach ($servers as $server) { + if (metaconsole_connect($server) == NOERR) { + $agent_id = agents_get_agent_id($other['data'][0], true); + + 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",$agent_id); - $group_server_names = db_get_all_rows_sql($sql); - - if ($group_server_names) { - foreach($group_server_names as $group_server_name) { - $group_names[] = $group_server_name; - } - } - } - } - metaconsole_restore_db(); - } - } - else { - $agent_id = agents_get_agent_id($other['data'][0],true); + AND agents.id_grupo = groups.id_grupo', + $agent_id + ); + $group_server_names = db_get_all_rows_sql($sql); - if(!util_api_check_agent_and_print_error($agent_id, 'csv')) return; - - $sql = sprintf("SELECT groups.id_grupo id_group + if ($group_server_names) { + foreach ($group_server_names as $group_server_name) { + $group_names[] = $group_server_name; + } + } + } + } + + metaconsole_restore_db(); + } + } else { + $agent_id = agents_get_agent_id($other['data'][0], true); + + if (!util_api_check_agent_and_print_error($agent_id, 'csv')) { + return; + } + + $sql = sprintf( + 'SELECT groups.id_grupo id_group 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); - } - - if (count($group_names) > 0 and $group_names !== false) { - $data = array('type' => 'array', 'data' => $group_names); - - returnData('csv', $data); - } - else { - returnError('error_group_agent', 'No groups retrieved.'); - } + AND agents.id_grupo = groups.id_grupo', + $agent_id + ); + $group_names = db_get_all_rows_sql($sql); + } + + if (count($group_names) > 0 and $group_names !== false) { + $data = [ + 'type' => 'array', + 'data' => $group_names, + ]; + + returnData('csv', $data); + } else { + returnError('error_group_agent', 'No groups retrieved.'); + } } /** * Get id group for an agent, and print all the result like a csv. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=id_group_agent_by_alias&return_type=csv&other=Nova&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param are the filters available in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=id_group_agent_by_alias&return_type=csv&other=Nova&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_get_id_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_get_id_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) +{ + global $config; - if (is_metaconsole()) { - return; - } + if (is_metaconsole()) { + return; + } - if (!check_acl($config['id_user'], 0, "AR")) { - returnError('forbidden', 'csv'); - return; - } + if (!check_acl($config['id_user'], 0, 'AR')) { + returnError('forbidden', 'csv'); + return; + } - $group_names =array(); + $group_names = []; - if (is_metaconsole()) { - $servers = db_get_all_rows_sql ("SELECT * + if (is_metaconsole()) { + $servers = db_get_all_rows_sql( + 'SELECT * FROM tmetaconsole_setup - WHERE disabled = 0"); - - if ($servers === false) - $servers = array(); - - - foreach($servers as $server) { - if (metaconsole_connect($server) == NOERR) { - $sql = sprintf("SELECT tagente.id_agente FROM tagente WHERE alias LIKE '%s' ",$other['data'][0]); - $agent_id = db_get_all_rows_sql($sql); - - foreach ($agent_id as &$id) { - $sql = sprintf("SELECT groups.id_grupo id_group + WHERE disabled = 0' + ); + + if ($servers === false) { + $servers = []; + } + + foreach ($servers as $server) { + if (metaconsole_connect($server) == NOERR) { + $sql = sprintf("SELECT tagente.id_agente FROM tagente WHERE alias LIKE '%s' ", $other['data'][0]); + $agent_id = db_get_all_rows_sql($sql); + + 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",$id['id_agente']); - $group_server_names = db_get_all_rows_sql($sql); - - if ($group_server_names) { - foreach($group_server_names as $group_server_name) { - $group_names[] = $group_server_name; - } - } - } - } - metaconsole_restore_db(); - } - } - else { - $sql = sprintf("SELECT tagente.id_agente FROM tagente WHERE alias LIKE '%s' ",$other['data'][0]); - $agent_id = db_get_all_rows_sql($sql); + AND agents.id_grupo = groups.id_grupo', + $id['id_agente'] + ); + $group_server_names = db_get_all_rows_sql($sql); - foreach ($agent_id as &$id) { - if(!users_access_to_agent($id['id_agente'])) continue; + if ($group_server_names) { + foreach ($group_server_names as $group_server_name) { + $group_names[] = $group_server_name; + } + } + } + } - $sql = sprintf("SELECT groups.id_grupo id_group + metaconsole_restore_db(); + } + } else { + $sql = sprintf("SELECT tagente.id_agente FROM tagente WHERE alias LIKE '%s' ", $other['data'][0]); + $agent_id = db_get_all_rows_sql($sql); + + foreach ($agent_id as &$id) { + if (!users_access_to_agent($id['id_agente'])) { + continue; + } + + $sql = sprintf( + 'SELECT groups.id_grupo id_group 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); - $group_names[] = $group_name[0]; - } - - } - if (count($group_names) > 0 and $group_names !== false) { - $data = array('type' => 'array', 'data' => $group_names); - returnData('csv', $data); - } - else { - returnError('error_group_agent', 'No groups retrieved.'); - } + AND agents.id_grupo = groups.id_grupo', + $id['id_agente'] + ); + $group_name = db_get_all_rows_sql($sql); + $group_names[] = $group_name[0]; + } + } + + if (count($group_names) > 0 and $group_names !== false) { + $data = [ + 'type' => 'array', + 'data' => $group_names, + ]; + returnData('csv', $data); + } else { + returnError('error_group_agent', 'No groups retrieved.'); + } } + /** * Get all policies, possible filtered by agent, and print all the result like a csv. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=policies&return_type=csv&other=&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param are the filters available in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=policies&return_type=csv&other=&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_get_policies($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_get_policies($thrash1, $thrash2, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "AW")) { - returnError('forbidden', 'csv'); - return; - } + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'csv'); + return; + } - $user_groups = implode (',', array_keys(users_get_groups($config["id_user"], "AW"))); + $user_groups = implode(',', array_keys(users_get_groups($config['id_user'], 'AW'))); - if ($other['data'][0] != "") { - if (!users_access_to_agent($other['data'][0])) { - returnError ('forbidden', 'csv'); - return; - } - $where = ' AND pol_agents.id_agent = ' . $other['data'][0]; + if ($other['data'][0] != '') { + if (!users_access_to_agent($other['data'][0])) { + returnError('forbidden', 'csv'); + return; + } - $sql = sprintf("SELECT policy.id, name, id_agent + $where = ' AND pol_agents.id_agent = '.$other['data'][0]; + + $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)", - $where, $user_groups); - } - else { - $sql = "SELECT id, name FROM tpolicies AS policy WHERE id_group IN ($user_groups)"; - } + WHERE policy.id = pol_agents.id_policy %s AND id_group IN (%s)', + $where, + $user_groups + ); + } else { + $sql = "SELECT id, name FROM tpolicies AS policy WHERE id_group IN ($user_groups)"; + } - $policies = db_get_all_rows_sql($sql); - - if (count($policies) > 0 and $policies !== false) { - $data = array('type' => 'array', 'data' => $policies); - - returnData('csv', $data, ';'); - } - else { - returnError('error_get_policies', 'No policies retrieved.'); - } + $policies = db_get_all_rows_sql($sql); + + if (count($policies) > 0 and $policies !== false) { + $data = [ + 'type' => 'array', + 'data' => $policies, + ]; + + returnData('csv', $data, ';'); + } else { + returnError('error_get_policies', 'No policies retrieved.'); + } } + /** * Get policy modules, possible filtered by agent, and print all the result like a csv. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param are the filters available in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=policy_modules&return_type=csv&other=2&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param are the filters available in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=policy_modules&return_type=csv&other=2&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_get_policy_modules($thrash1, $thrash2, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - $where = ''; - - if ($other['data'][0] == "") { - returnError('error_policy_modules', 'Error retrieving policy modules. Id_policy cannot be left blank.'); - return; - } - - $policies = enterprise_hook('policies_get_modules_api', - array($other['data'][0], $other['data'][1])); - - if ($policies === ENTERPRISE_NOT_HOOK) { - returnError('error_policy_modules', 'Error retrieving policy modules.'); - return; - } - - if (count($policies) > 0 and $policies !== false) { - $data = array('type' => 'array', 'data' => $policies); - - returnData('csv', $data, ';'); - } - else { - returnError('error_policy_modules', 'No policy modules retrieved.'); - } +function api_get_policy_modules($thrash1, $thrash2, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + $where = ''; + + if ($other['data'][0] == '') { + returnError('error_policy_modules', 'Error retrieving policy modules. Id_policy cannot be left blank.'); + return; + } + + $policies = enterprise_hook( + 'policies_get_modules_api', + [ + $other['data'][0], + $other['data'][1], + ] + ); + + if ($policies === ENTERPRISE_NOT_HOOK) { + returnError('error_policy_modules', 'Error retrieving policy modules.'); + return; + } + + if (count($policies) > 0 and $policies !== false) { + $data = [ + 'type' => 'array', + 'data' => $policies, + ]; + + returnData('csv', $data, ';'); + } else { + returnError('error_policy_modules', 'No policy modules retrieved.'); + } } /** * Create a network module in agent. And return the id_agent_module of new module. - * - * @param string $id Name of agent to add the module. + * + * @param string $id Name of agent to add the module. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;; - * ;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=create_network_module&id=pepito&other=prueba|0|7|1|10|15|0|16|18|0|15|0|www.google.es|0||0|180|0|0|0|0|latency%20ping&other_mode=url_encode_separator_| - * - * - * @param $thrash3 Don't use - */ -function api_set_create_network_module($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - $agentName = $id; - - $idAgent = agents_get_agent_id($agentName); - - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; - } - - if ($other['data'][2] < 6 or $other['data'][2] > 18) { - returnError('error_create_network_module', - __('Error in creation network module. Id_module_type is not correct for network modules.')); - return; - } - - $name = $other['data'][0]; - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][22]; - $disabled_types_event = json_encode($disabled_types_event); - - $values = array( - 'id_agente' => $idAgent, - 'disabled' => $other['data'][1], - 'id_tipo_modulo' => $other['data'][2], - 'id_module_group' => $other['data'][3], - 'min_warning' => $other['data'][4], - 'max_warning' => $other['data'][5], - 'str_warning' => $other['data'][6], - 'min_critical' => $other['data'][7], - 'max_critical' => $other['data'][8], - 'str_critical' => $other['data'][9], - 'min_ff_event' => $other['data'][10], - 'history_data' => $other['data'][11], - 'ip_target' => $other['data'][12], - 'tcp_port' => $other['data'][13], - 'snmp_community' => $other['data'][14], - 'snmp_oid' => $other['data'][15], - 'module_interval' => $other['data'][16], - 'post_process' => $other['data'][17], - 'min' => $other['data'][18], - 'max' => $other['data'][19], - 'custom_id' => $other['data'][20], - 'descripcion' => $other['data'][21], - 'id_modulo' => 2, - 'disabled_types_event' => $disabled_types_event, - 'module_macros' => $other['data'][23], - 'each_ff' => $other['data'][24], - 'min_ff_event_normal' => $other['data'][25], - 'min_ff_event_warning' => $other['data'][26], - 'min_ff_event_critical' => $other['data'][27], - 'critical_inverse' => $other['data'][28], - 'warning_inverse' => $other['data'][29] - ); - - if ( ! $values['descripcion'] ) { - $values['descripcion'] = ''; // Column 'descripcion' cannot be null - } - if ( ! $values['module_macros'] ) { - $values['module_macros'] = ''; // Column 'module_macros' cannot be null - } - - $idModule = modules_create_agent_module($idAgent, $name, $values, true); - - if (is_error($idModule)) { - // TODO: Improve the error returning more info - returnError('error_create_network_module', __('Error in creation network module.')); - } - else { - returnData('string', array('type' => 'string', 'data' => $idModule)); - } -} - -/** - * Update a network module in agent. And return a message with the result of the operation. - * - * @param string $id Id of the network module to update. - * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;; - * ;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=update_network_module&id=271&other=156|0|2|10|15||16|18||7|0|127.0.0.1|0||0|300|30.00|0|0|0|latency%20ping%20modified%20by%20the%20Api&other_mode=url_encode_separator_| - * - * - * @param $thrash3 Don't use - */ -function api_set_update_network_module($id_module, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id_module == "") { - returnError('error_update_network_module', - __('Error updating network module. Module name cannot be left blank.')); - return; - } - - if (!util_api_check_agent_and_print_error( - modules_get_agentmodule_agent($id_module), 'string', 'AW') - ) { - return; - } - - $check_id_module = db_get_value ('id_agente_modulo', 'tagente_modulo', 'id_agente_modulo', $id_module); - - if (!$check_id_module) { - returnError('error_update_network_module', - __('Error updating network module. Id_module doesn\'t exist.')); - return; - } - - // If we want to change the module to a new agent - if ($other['data'][0] != "") { - if (!util_api_check_agent_and_print_error($other['data'][0], 'string', 'AW')) { - return; - } - $id_agent_old = db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module); - - if ($id_agent_old != $other['data'][0]) { - $id_module_exists = db_get_value_filter ('id_agente_modulo', - 'tagente_modulo', - array('nombre' => $module_name, 'id_agente' => $other['data'][0])); - - if ($id_module_exists) { - returnError('error_update_network_module', - __('Error updating network module. Id_module exists in the new agent.')); - return; - } - } - } - - $network_module_fields = array('id_agente', - 'disabled', - 'id_module_group', - 'min_warning', - 'max_warning', - 'str_warning', - 'min_critical', - 'max_critical', - 'str_critical', - 'min_ff_event', - 'history_data', - 'ip_target', - 'tcp_port', - 'snmp_community', - 'snmp_oid', - 'module_interval', - 'post_process', - 'min', - 'max', - 'custom_id', - 'descripcion', - 'disabled_types_event', - 'module_macros', - 'each_ff', - 'min_ff_event_normal', - 'min_ff_event_warning', - 'min_ff_event_critical', - 'critical_inverse', - 'warning_inverse', - 'policy_linked'); - - $values = array(); - $cont = 0; - foreach ($network_module_fields as $field) { - if ($other['data'][$cont] != "") { - $values[$field] = $other['data'][$cont]; - } - - $cont++; - } - $values['policy_linked'] = 0; - - - $result_update = modules_update_agent_module($id_module, $values); - - if ($result_update < 0) - returnError('error_update_network_module', 'Error updating network module.'); - else - returnData('string', array('type' => 'string', 'data' => __('Network module updated.'))); -} - -/** - * Create a plugin module in agent. And return the id_agent_module of new module. - * - * @param string $id Name of agent to add the module. - * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;;;; - * ;;;;; - * ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=create_plugin_module&id=pepito&other=prueba|0|1|2|0|0||0|0||0|0|127.0.0.1|0||0|300|0|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_| - * - * @param $thrash3 Don't use - */ -function api_set_create_plugin_module($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - 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); - - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][26]; - $disabled_types_event = json_encode($disabled_types_event); - - $name = $other['data'][0]; - - $values = array( - 'id_agente' => $idAgent, - 'disabled' => $other['data'][1], - 'id_tipo_modulo' => $other['data'][2], - 'id_module_group' => $other['data'][3], - 'min_warning' => $other['data'][4], - 'max_warning' => $other['data'][5], - 'str_warning' => $other['data'][6], - 'min_critical' => $other['data'][7], - 'max_critical' => $other['data'][8], - 'str_critical' => $other['data'][9], - 'min_ff_event' => $other['data'][10], - 'history_data' => $other['data'][11], - 'ip_target' => $other['data'][12], - 'tcp_port' => $other['data'][13], - 'snmp_community' => $other['data'][14], - 'snmp_oid' => $other['data'][15], - 'module_interval' => $other['data'][16], - 'post_process' => $other['data'][17], - 'min' => $other['data'][18], - 'max' => $other['data'][19], - 'custom_id' => $other['data'][20], - 'descripcion' => $other['data'][21], - 'id_modulo' => 4, - 'id_plugin' => $other['data'][22], - 'plugin_user' => $other['data'][23], - 'plugin_pass' => $other['data'][24], - 'plugin_parameter' => $other['data'][25], - 'disabled_types_event' => $disabled_types_event, - 'macros' => base64_decode ($other['data'][27]), - 'module_macros' => $other['data'][28], - 'each_ff' => $other['data'][29], - 'min_ff_event_normal' => $other['data'][30], - 'min_ff_event_warning' => $other['data'][31], - 'min_ff_event_critical' => $other['data'][32], - 'critical_inverse' => $other['data'][33], - 'warning_inverse' => $other['data'][34] - ); - - if ( ! $values['descripcion'] ) { - $values['descripcion'] = ''; // Column 'descripcion' cannot be null - } - if ( ! $values['module_macros'] ) { - $values['module_macros'] = ''; // Column 'module_macros' cannot be null - } - - $idModule = modules_create_agent_module($idAgent, $name, $values, true); - - if (is_error($idModule)) { - // TODO: Improve the error returning more info - returnError('error_create_plugin_module', __('Error in creation plugin module.')); - } - else { - returnData('string', array('type' => 'string', 'data' => $idModule)); - } -} - -/** - * Update a plugin module in agent. And return the id_agent_module of new module. - * @param string $id Id of the plugin module to update. - * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;;;; - * ;;;;; - * ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=update_plugin_module&id=293&other=156|0|2|0|0||0|0||0|0|127.0.0.1|0||0|300|0|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_| - * - * - * @param $thrash3 Don't use - */ -function api_set_update_plugin_module($id_module, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id_module == "") { - returnError('error_update_plugin_module', __('Error updating plugin module. Id_module cannot be left blank.')); - return; - } - - if (!util_api_check_agent_and_print_error( - modules_get_agentmodule_agent($id_module), 'string', 'AW') - ) { - return; - } - - // If we want to change the module to a new agent - if ($other['data'][0] != "") { - if (!util_api_check_agent_and_print_error($other['data'][0], 'string', 'AW')) { - return; - } - $id_agent_old = db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module); - - if ($id_agent_old != $other['data'][0]) { - $id_module_exists = db_get_value_filter ('id_agente_modulo', 'tagente_modulo', array('nombre' => $module_name, 'id_agente' => $other['data'][0])); - - if ($id_module_exists) { - returnError('error_update_plugin_module', __('Error updating plugin module. Id_module exists in the new agent.')); - return; - } - } - // Check if agent exists - $check_id_agent = db_get_value ('id_agente', 'tagente', 'id_agente', $other['data'][0]); - if (!$check_id_agent) { - returnError('error_update_data_module', __('Error updating plugin module. Id_agent doesn\'t exist.')); - return; - } - } - - $plugin_module_fields = array('id_agente', - 'disabled', - 'id_module_group', - 'min_warning', - 'max_warning', - 'str_warning', - 'min_critical', - 'max_critical', - 'str_critical', - 'min_ff_event', - 'history_data', - 'ip_target', - 'tcp_port', - 'snmp_community', - 'snmp_oid', - 'module_interval', - 'post_process', - 'min', - 'max', - 'custom_id', - 'descripcion', - 'id_plugin', - 'plugin_user', - 'plugin_pass', - 'plugin_parameter', - 'disabled_types_event', - 'macros', - 'module_macros', - 'each_ff', - 'min_ff_event_normal', - 'min_ff_event_warning', - 'min_ff_event_critical', - 'critical_inverse', - 'warning_inverse', - 'policy_linked'); - - $values = array(); - $cont = 0; - foreach ($plugin_module_fields as $field) { - if ($other['data'][$cont] != "") { - $values[$field] = $other['data'][$cont]; - - if( $field === 'macros' ) { - $values[$field] = base64_decode($values[$field]); - } - } - - $cont++; - } - - $values['policy_linked']= 0; - $result_update = modules_update_agent_module($id_module, $values); - - if ($result_update < 0) - returnError('error_update_plugin_module', 'Error updating plugin module.'); - else - returnData('string', array('type' => 'string', 'data' => __('Plugin module updated.'))); -} - -/** - * Create a data module in agent. And return the id_agent_module of new module. - * Note: Only adds database information, this function doesn't alter config file information. - * - * @param string $id Name of agent to add the module. - * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;; - * ;;;;;; - * ;;;; - * ;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=create_data_module&id=pepito&other=prueba|0|1|data%20module%20from%20api|1|10|20|10.50|180|10|15||16|20||0&other_mode=url_encode_separator_| - * - * @param $thrash3 Don't use - */ -function api_set_create_data_module($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - 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); - - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; - } - - $name = $other['data'][0]; - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][16]; - $disabled_types_event = json_encode($disabled_types_event); - - $values = array( - 'id_agente' => $idAgent, - 'disabled' => $other['data'][1], - 'id_tipo_modulo' => $other['data'][2], - 'descripcion' => $other['data'][3], - 'id_module_group' => $other['data'][4], - 'min' => $other['data'][5], - 'max' => $other['data'][6], - 'post_process' => $other['data'][7], - 'module_interval' => $other['data'][8], - 'min_warning' => $other['data'][9], - 'max_warning' => $other['data'][10], - 'str_warning' => $other['data'][11], - 'min_critical' => $other['data'][12], - 'max_critical' => $other['data'][13], - 'str_critical' => $other['data'][14], - 'history_data' => $other['data'][15], - 'id_modulo' => 1, - 'disabled_types_event' => $disabled_types_event, - 'module_macros' => $other['data'][17], - 'min_ff_event' => $other['data'][18], - 'each_ff' => $other['data'][19], - 'min_ff_event_normal' => $other['data'][20], - 'min_ff_event_warning' => $other['data'][21], - 'min_ff_event_critical' => $other['data'][22], - 'ff_timeout' => $other['data'][23], - 'critical_inverse' => $other['data'][24], - 'warning_inverse' => $other['data'][25] - ); - - if ( ! $values['descripcion'] ) { - $values['descripcion'] = ''; // Column 'descripcion' cannot be null - } - if ( ! $values['module_macros'] ) { - $values['module_macros'] = ''; // Column 'module_macros' cannot be null - } - - $idModule = modules_create_agent_module($idAgent, $name, $values, true); - - if (is_error($idModule)) { - // TODO: Improve the error returning more info - returnError('error_create_data_module', __('Error in creation data module.')); - } - else { - returnData('string', array('type' => 'string', 'data' => $idModule)); - } -} - - -/** - * Create a synthetic module in agent. And return the id_agent_module of new module. - * Note: Only adds database information, this function doesn't alter config file information. - * - * @param string $id Name of agent to add the module. - * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is OR OR in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=create_synthetic_module&id=pepito&other=prueba|average|Agent%20Name;AVG;Name%20Module|Agent%20Name2;AVG;Name%20Module2&other_mode=url_encode_separator_| - * - * @param $thrash3 Don't use - */ -function api_set_create_synthetic_module($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - global $config; - - $agentName = $id; - - io_safe_input_array($other); - - if ($other['data'][0] == "") { - returnError('error_create_data_module', __('Error in creation synthetic module. Module_name cannot be left blank.')); - return; - } - - $idAgent = agents_get_agent_id(io_safe_output($agentName),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; - } - - $name = io_safe_output($other['data'][0]); - $name = io_safe_input($name); - $id_tipo_modulo = db_get_row_sql ("SELECT id_tipo FROM ttipo_modulo WHERE nombre = 'generic_data'"); - - $values = array( - 'id_agente' => $idAgent, - 'id_modulo' => 5, - 'custom_integer_1' => 0, - 'custom_integer_2' => 0, - 'prediction_module' => 3, - 'id_tipo_modulo' => $id_tipo_modulo['id_tipo'] - ); - - if ( ! $values['descripcion'] ) { - $values['descripcion'] = ''; // Column 'descripcion' cannot be null - } - - $idModule = modules_create_agent_module($idAgent, $name, $values, true); - - 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]); - - - $filterdata = array(); - foreach ($other['data'] as $data) { - $data = str_replace(array('ADD','SUB','MUL','DIV'),array('+','-','*','/'),$data); - $split_data = explode(';',$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 = array("",$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(io_safe_output($split_data[0]),true); - $data_module = array($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 = array($idAgent,$operator,$split_data[2]); - $text_data = implode('_',$data_module); - array_push($filterdata,$text_data); - } - } - } - - $serialize_ops = implode(',',$filterdata); - - //modules_create_synthetic_operations - $synthetic = enterprise_hook('modules_create_synthetic_operations', - array($idModule, $serialize_ops)); - - if ($synthetic === ENTERPRISE_NOT_HOOK) { - returnError('error_synthetic_modules', 'Error Synthetic modules.'); - db_process_sql_delete ('tagente_modulo', - array ('id_agente_modulo' => $idModule)); - return; - } - else { - $status = AGENT_MODULE_STATUS_NO_DATA; - switch ($config["dbtype"]) { - case "mysql": - $result = db_process_sql_insert ('tagente_estado', - array ('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', - array ('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', - array ('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', - array ('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', array('type' => 'string', 'data' => __('Synthetic module created ID: ' . $idModule))); - } - } - } -} - -/** - * Update a data module in agent. And return a message with the result of the operation. - * - * @param string $id Id of the data module to update. - * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;; - * ;;;; - * in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=update_data_module&id=170&other=44|0|data%20module%20modified%20from%20API|6|0|0|50.00|300|10|15||16|18||0&other_mode=url_encode_separator_| - * - * - * @param $thrash3 Don't use - */ -function api_set_update_data_module($id_module, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id_module == "") { - returnError('error_update_data_module', __('Error updating data module. Id_module cannot be left blank.')); - return; - } - - if (!util_api_check_agent_and_print_error( - modules_get_agentmodule_agent($id_module), 'string', 'AW') - ) { - return; - } - - // If we want to change the module to a new agent - if ($other['data'][0] != "") { - if (!util_api_check_agent_and_print_error($other['data'][0], 'string', 'AW')) { - return; - } - $id_agent_old = db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module); - - if ($id_agent_old != $other['data'][0]) { - $id_module_exists = db_get_value_filter ('id_agente_modulo', 'tagente_modulo', array('nombre' => $module_name, 'id_agente' => $other['data'][0])); - - if ($id_module_exists) { - returnError('error_update_data_module', __('Error updating data module. Id_module exists in the new agent.')); - return; - } - } - // Check if agent exists - $check_id_agent = db_get_value ('id_agente', 'tagente', 'id_agente', $other['data'][0]); - if (!$check_id_agent) { - returnError('error_update_data_module', __('Error updating data module. Id_agent doesn\'t exist.')); - return; - } - } - - $data_module_fields = array('id_agente', - 'disabled', - 'descripcion', - 'id_module_group', - 'min', - 'max', - 'post_process', - 'module_interval', - 'min_warning', - 'max_warning', - 'str_warning', - 'min_critical', - 'max_critical', - 'str_critical', - 'history_data', - 'disabled_types_event', - 'module_macros', - 'min_ff_event', - 'each_ff', - 'min_ff_event_normal', - 'min_ff_event_warning', - 'min_ff_event_critical', - 'ff_timeout', - 'critical_inverse', - 'warning_inverse', - 'policy_linked'); - - $values = array(); - $cont = 0; - foreach ($data_module_fields as $field) { - if ($other['data'][$cont] != "") { - $values[$field] = $other['data'][$cont]; - } - - $cont++; - } - - $values['policy_linked'] = 0; - $result_update = modules_update_agent_module($id_module, $values); - - if ($result_update < 0) - returnError('error_update_data_module', 'Error updating data module.'); - else - returnData('string', array('type' => 'string', 'data' => __('Data module updated.'))); -} - - -/** - * Create a SNMP module in agent. And return the id_agent_module of new module. - * - * @param string $id Name of agent to add the module. - * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;;;;; - * ;;;;;;;; - * ;;;;; - * ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example 1 (snmp v: 3, snmp3_priv_method: AES, passw|authNoPriv|MD5|pepito_user|example_priv_passw) - * - * api.php?op=set&op2=create_snmp_module&id=pepito&other=prueba|0|15|1|10|15||16|18||15|0|127.0.0.1|60|3|public|.1.3.6.1.2.1.1.1.0|180|0|0|0|0|SNMP%20module%20from%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_| - * - * example 2 (snmp v: 1) - * - * api.php?op=set&op2=create_snmp_module&id=pepito1&other=prueba2|0|15|1|10|15||16|18||15|0|127.0.0.1|60|1|public|.1.3.6.1.2.1.1.1.0|180|0|0|0|0|SNMP module from API&other_mode=url_encode_separator_| - * - * @param $thrash3 Don't use - */ -function api_set_create_snmp_module($id, $thrash1, $other, $thrash3) { - - if (defined ('METACONSOLE')) { - return; - } - - $agentName = $id; - - if ($other['data'][0] == "") { - returnError('error_create_snmp_module', __('Error in creation SNMP module. Module_name cannot be left blank.')); - return; - } - - if ($other['data'][2] < 15 or $other['data'][2] > 18) { - returnError('error_create_snmp_module', __('Error in creation SNMP module. Invalid id_module_type for a SNMP module.')); - return; - } - - $idAgent = agents_get_agent_id($agentName); - - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; - } - - $name = $other['data'][0]; - - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][27]; - $disabled_types_event = json_encode($disabled_types_event); - - # SNMP version 3 - if ($other['data'][14] == "3") { - - if ($other['data'][23] != "AES" and $other['data'][23] != "DES") { - returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ')); - return; - } - - if ($other['data'][25] != "authNoPriv" and $other['data'][25] != "authPriv" and $other['data'][25] != "noAuthNoPriv") { - returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ')); - return; - } - - if ($other['data'][26] != "MD5" and $other['data'][26] != "SHA") { - returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ')); - return; - } - - $values = array( - 'id_agente' => $idAgent, - 'disabled' => $other['data'][1], - 'id_tipo_modulo' => $other['data'][2], - 'id_module_group' => $other['data'][3], - 'min_warning' => $other['data'][4], - 'max_warning' => $other['data'][5], - 'str_warning' => $other['data'][6], - 'min_critical' => $other['data'][7], - 'max_critical' => $other['data'][8], - 'str_critical' => $other['data'][9], - 'min_ff_event' => $other['data'][10], - 'history_data' => $other['data'][11], - 'ip_target' => $other['data'][12], - 'tcp_port' => $other['data'][13], - 'tcp_send' => $other['data'][14], - 'snmp_community' => $other['data'][15], - 'snmp_oid' => $other['data'][16], - 'module_interval' => $other['data'][17], - 'post_process' => $other['data'][18], - 'min' => $other['data'][19], - 'max' => $other['data'][20], - 'custom_id' => $other['data'][21], - 'descripcion' => $other['data'][22], - 'id_modulo' => 2, - 'custom_string_1' => $other['data'][23], - 'custom_string_2' => $other['data'][24], - 'custom_string_3' => $other['data'][25], - 'plugin_parameter' => $other['data'][26], - 'plugin_user' => $other['data'][27], - 'plugin_pass' => $other['data'][28], - 'disabled_types_event' => $disabled_types_event, - 'each_ff' => $other['data'][30], - 'min_ff_event_normal' => $other['data'][31], - 'min_ff_event_warning' => $other['data'][32], - 'min_ff_event_critical' => $other['data'][33] - ); - } - else { - $values = array( - 'id_agente' => $idAgent, - 'disabled' => $other['data'][1], - 'id_tipo_modulo' => $other['data'][2], - 'id_module_group' => $other['data'][3], - 'min_warning' => $other['data'][4], - 'max_warning' => $other['data'][5], - 'str_warning' => $other['data'][6], - 'min_critical' => $other['data'][7], - 'max_critical' => $other['data'][8], - 'str_critical' => $other['data'][9], - 'min_ff_event' => $other['data'][10], - 'history_data' => $other['data'][11], - 'ip_target' => $other['data'][12], - 'tcp_port' => $other['data'][13], - 'tcp_send' => $other['data'][14], - 'snmp_community' => $other['data'][15], - 'snmp_oid' => $other['data'][16], - 'module_interval' => $other['data'][17], - 'post_process' => $other['data'][18], - 'min' => $other['data'][19], - 'max' => $other['data'][20], - 'custom_id' => $other['data'][21], - 'descripcion' => $other['data'][22], - 'id_modulo' => 2, - 'disabled_types_event' => $disabled_types_event, - 'each_ff' => $other['data'][24], - 'min_ff_event_normal' => $other['data'][25], - 'min_ff_event_warning' => $other['data'][26], - 'min_ff_event_critical' => $other['data'][27] - ); - } - - if ( ! $values['descripcion'] ) { - $values['descripcion'] = ''; // Column 'descripcion' cannot be null - } - - $idModule = modules_create_agent_module($idAgent, $name, $values, true); - - if (is_error($idModule)) { - // TODO: Improve the error returning more info - returnError('error_create_snmp_module', __('Error in creation SNMP module.')); - } - else { - returnData('string', array('type' => 'string', 'data' => $idModule)); - } -} - -/** - * Update a SNMP module in agent. And return a message with the result of the operation. - * - * @param string $id Id of module to update. - * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;;;;; - * ;;;;;;;; - * ;;;;;;;; - * ;;;; - * ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example (update snmp v: 3, snmp3_priv_method: AES, passw|authNoPriv|MD5|pepito_user|example_priv_passw) - * - * api.php?op=set&op2=update_snmp_module&id=example_snmp_module_name&other=44|0|6|20|25||26|30||15|1|127.0.0.1|60|3|public|.1.3.6.1.2.1.1.1.0|180|50.00|10|60|0|SNMP%20module%20modified%20by%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_| + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;; + * ;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=create_network_module&id=pepito&other=prueba|0|7|1|10|15|0|16|18|0|15|0|www.google.es|0||0|180|0|0|0|0|latency%20ping&other_mode=url_encode_separator_| * * @param $thrash3 Don't use */ -function api_set_update_snmp_module($id_module, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id_module == "") { - returnError('error_update_snmp_module', __('Error updating SNMP module. Id_module cannot be left blank.')); - return; - } +function api_set_create_network_module($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error( - modules_get_agentmodule_agent($id_module), 'string', 'AW') - ) { - return; - } - - // If we want to change the module to a new agent - if ($other['data'][0] != "") { - if (!util_api_check_agent_and_print_error($other['data'][0], 'string', 'AW')) { - return; - } - $id_agent_old = db_get_value ('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module); - - if ($id_agent_old != $other['data'][0]) { - $id_module_exists = db_get_value_filter ('id_agente_modulo', 'tagente_modulo', array('nombre' => $module_name, 'id_agente' => $other['data'][0])); - - if ($id_module_exists) { - returnError('error_update_snmp_module', __('Error updating SNMP module. Id_module exists in the new agent.')); - return; - } - } - // Check if agent exists - $check_id_agent = db_get_value ('id_agente', 'tagente', 'id_agente', $other['data'][0]); - if (!$check_id_agent) { - returnError('error_update_data_module', __('Error updating snmp module. Id_agent doesn\'t exist.')); - return; - } - } - - # SNMP version 3 - if ($other['data'][13] == "3") { - - if ($other['data'][22] != "AES" and $other['data'][22] != "DES") { - returnError('error_create_snmp_module', - __('Error in creation SNMP module. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ')); - return; - } - - if ($other['data'][24] != "authNoPriv" - and $other['data'][24] != "authPriv" - and $other['data'][24] != "noAuthNoPriv") { - - returnError('error_create_snmp_module', - __('Error in creation SNMP module. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ')); - return; - } - - if ($other['data'][25] != "MD5" and $other['data'][25] != "SHA") { - returnError('error_create_snmp_module', - __('Error in creation SNMP module. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ')); - return; - } - - $snmp_module_fields = array( - 'id_agente', - 'disabled', - 'id_module_group', - 'min_warning', - 'max_warning', - 'str_warning', - 'min_critical', - 'max_critical', - 'str_critical', - 'min_ff_event', - 'history_data', - 'ip_target', - 'tcp_port', - 'tcp_send', - 'snmp_community', - 'snmp_oid', - 'module_interval', - 'post_process', - 'min', - 'max', - 'custom_id', - 'descripcion', - 'custom_string_1', - 'custom_string_2', - 'custom_string_3', - 'plugin_parameter', - 'plugin_user', - 'plugin_pass', - 'disabled_types_event', - 'each_ff', - 'min_ff_event_normal', - 'min_ff_event_warning', - 'min_ff_event_critical', - 'policy_linked'); - } - else { - $snmp_module_fields = array( - 'id_agente', - 'disabled', - 'id_module_group', - 'min_warning', - 'max_warning', - 'str_warning', - 'min_critical', - 'max_critical', - 'str_critical', - 'min_ff_event', - 'history_data', - 'ip_target', - 'tcp_port', - 'tcp_send', - 'snmp_community', - 'snmp_oid', - 'module_interval', - 'post_process', - 'min', - 'max', - 'custom_id', - 'descripcion', - 'disabled_types_event', - 'each_ff', - 'min_ff_event_normal', - 'min_ff_event_warning', - 'min_ff_event_critical', - 'policy_linked'); - } - - $values = array(); - $cont = 0; - foreach ($snmp_module_fields as $field) { - if ($other['data'][$cont] != "") { - $values[$field] = $other['data'][$cont]; - } - - $cont++; - } + $agentName = $id; - $values['policy_linked'] = 0; - $result_update = modules_update_agent_module($id_module, $values); - - if ($result_update < 0) - returnError('error_update_snmp_module', 'Error updating SNMP module.'); - else - returnData('string', array('type' => 'string', 'data' => __('SNMP module updated.'))); + $idAgent = agents_get_agent_id($agentName); + + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } + + if ($other['data'][2] < 6 or $other['data'][2] > 18) { + returnError( + 'error_create_network_module', + __('Error in creation network module. Id_module_type is not correct for network modules.') + ); + return; + } + + $name = $other['data'][0]; + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][22]; + $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], + 'min_warning' => $other['data'][4], + 'max_warning' => $other['data'][5], + 'str_warning' => $other['data'][6], + 'min_critical' => $other['data'][7], + 'max_critical' => $other['data'][8], + 'str_critical' => $other['data'][9], + 'min_ff_event' => $other['data'][10], + 'history_data' => $other['data'][11], + 'ip_target' => $other['data'][12], + 'tcp_port' => $other['data'][13], + 'snmp_community' => $other['data'][14], + 'snmp_oid' => $other['data'][15], + 'module_interval' => $other['data'][16], + 'post_process' => $other['data'][17], + 'min' => $other['data'][18], + 'max' => $other['data'][19], + 'custom_id' => $other['data'][20], + 'descripcion' => $other['data'][21], + 'id_modulo' => 2, + 'disabled_types_event' => $disabled_types_event, + 'module_macros' => $other['data'][23], + 'each_ff' => $other['data'][24], + 'min_ff_event_normal' => $other['data'][25], + 'min_ff_event_warning' => $other['data'][26], + 'min_ff_event_critical' => $other['data'][27], + 'critical_inverse' => $other['data'][28], + 'warning_inverse' => $other['data'][29], + ]; + + if (! $values['descripcion']) { + $values['descripcion'] = ''; + // Column 'descripcion' cannot be null + } + + if (! $values['module_macros']) { + $values['module_macros'] = ''; + // Column 'module_macros' cannot be null + } + + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + + if (is_error($idModule)) { + // TODO: Improve the error returning more info + returnError('error_create_network_module', __('Error in creation network module.')); + } else { + returnData('string', ['type' => 'string', 'data' => $idModule]); + } } + +/** + * Update a network module in agent. And return a message with the result of the operation. + * + * @param string $id Id of the network module to update. + * @param $thrash1 Don't use. + * @param array $other it's array, $other as param is ; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;; + * ;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=update_network_module&id=271&other=156|0|2|10|15||16|18||7|0|127.0.0.1|0||0|300|30.00|0|0|0|latency%20ping%20modified%20by%20the%20Api&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use + */ +function api_set_update_network_module($id_module, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($id_module == '') { + returnError( + 'error_update_network_module', + __('Error updating network module. Module name cannot be left blank.') + ); + return; + } + + if (!util_api_check_agent_and_print_error( + modules_get_agentmodule_agent($id_module), + 'string', + 'AW' + ) + ) { + return; + } + + $check_id_module = db_get_value('id_agente_modulo', 'tagente_modulo', 'id_agente_modulo', $id_module); + + if (!$check_id_module) { + returnError( + 'error_update_network_module', + __('Error updating network module. Id_module doesn\'t exist.') + ); + return; + } + + // If we want to change the module to a new agent + if ($other['data'][0] != '') { + if (!util_api_check_agent_and_print_error($other['data'][0], 'string', 'AW')) { + return; + } + + $id_agent_old = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module); + + if ($id_agent_old != $other['data'][0]) { + $id_module_exists = db_get_value_filter( + 'id_agente_modulo', + 'tagente_modulo', + [ + 'nombre' => $module_name, + 'id_agente' => $other['data'][0], + ] + ); + + if ($id_module_exists) { + returnError( + 'error_update_network_module', + __('Error updating network module. Id_module exists in the new agent.') + ); + return; + } + } + } + + $network_module_fields = [ + 'id_agente', + 'disabled', + 'id_module_group', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'min_ff_event', + 'history_data', + 'ip_target', + 'tcp_port', + 'snmp_community', + 'snmp_oid', + 'module_interval', + 'post_process', + 'min', + 'max', + 'custom_id', + 'descripcion', + 'disabled_types_event', + 'module_macros', + 'each_ff', + 'min_ff_event_normal', + 'min_ff_event_warning', + 'min_ff_event_critical', + 'critical_inverse', + 'warning_inverse', + 'policy_linked', + ]; + + $values = []; + $cont = 0; + foreach ($network_module_fields as $field) { + if ($other['data'][$cont] != '') { + $values[$field] = $other['data'][$cont]; + } + + $cont++; + } + + $values['policy_linked'] = 0; + + $result_update = modules_update_agent_module($id_module, $values); + + if ($result_update < 0) { + returnError('error_update_network_module', 'Error updating network module.'); + } else { + returnData('string', ['type' => 'string', 'data' => __('Network module updated.')]); + } +} + + +/** + * Create a plugin module in agent. And return the id_agent_module of new module. + * + * @param string $id Name of agent to add the module. + * @param $thrash1 Don't use. + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;;;; + * ;;;;; + * ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=create_plugin_module&id=pepito&other=prueba|0|1|2|0|0||0|0||0|0|127.0.0.1|0||0|300|0|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use + */ +function api_set_create_plugin_module($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + 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); + + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][26]; + $disabled_types_event = json_encode($disabled_types_event); + + $name = $other['data'][0]; + + $values = [ + 'id_agente' => $idAgent, + 'disabled' => $other['data'][1], + 'id_tipo_modulo' => $other['data'][2], + 'id_module_group' => $other['data'][3], + 'min_warning' => $other['data'][4], + 'max_warning' => $other['data'][5], + 'str_warning' => $other['data'][6], + 'min_critical' => $other['data'][7], + 'max_critical' => $other['data'][8], + 'str_critical' => $other['data'][9], + 'min_ff_event' => $other['data'][10], + 'history_data' => $other['data'][11], + 'ip_target' => $other['data'][12], + 'tcp_port' => $other['data'][13], + 'snmp_community' => $other['data'][14], + 'snmp_oid' => $other['data'][15], + 'module_interval' => $other['data'][16], + 'post_process' => $other['data'][17], + 'min' => $other['data'][18], + 'max' => $other['data'][19], + 'custom_id' => $other['data'][20], + 'descripcion' => $other['data'][21], + 'id_modulo' => 4, + 'id_plugin' => $other['data'][22], + 'plugin_user' => $other['data'][23], + 'plugin_pass' => $other['data'][24], + 'plugin_parameter' => $other['data'][25], + 'disabled_types_event' => $disabled_types_event, + 'macros' => base64_decode($other['data'][27]), + 'module_macros' => $other['data'][28], + 'each_ff' => $other['data'][29], + 'min_ff_event_normal' => $other['data'][30], + 'min_ff_event_warning' => $other['data'][31], + 'min_ff_event_critical' => $other['data'][32], + 'critical_inverse' => $other['data'][33], + 'warning_inverse' => $other['data'][34], + ]; + + if (! $values['descripcion']) { + $values['descripcion'] = ''; + // Column 'descripcion' cannot be null + } + + if (! $values['module_macros']) { + $values['module_macros'] = ''; + // Column 'module_macros' cannot be null + } + + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + + if (is_error($idModule)) { + // TODO: Improve the error returning more info + returnError('error_create_plugin_module', __('Error in creation plugin module.')); + } else { + returnData('string', ['type' => 'string', 'data' => $idModule]); + } +} + + +/** + * Update a plugin module in agent. And return the id_agent_module of new module. + * + * @param string $id Id of the plugin module to update. + * @param $thrash1 Don't use. + * @param array $other it's array, $other as param is ;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;;;; + * ;;;;; + * ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=update_plugin_module&id=293&other=156|0|2|0|0||0|0||0|0|127.0.0.1|0||0|300|0|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use + */ +function api_set_update_plugin_module($id_module, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($id_module == '') { + returnError('error_update_plugin_module', __('Error updating plugin module. Id_module cannot be left blank.')); + return; + } + + if (!util_api_check_agent_and_print_error( + modules_get_agentmodule_agent($id_module), + 'string', + 'AW' + ) + ) { + return; + } + + // If we want to change the module to a new agent + if ($other['data'][0] != '') { + if (!util_api_check_agent_and_print_error($other['data'][0], 'string', 'AW')) { + return; + } + + $id_agent_old = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module); + + if ($id_agent_old != $other['data'][0]) { + $id_module_exists = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['nombre' => $module_name, 'id_agente' => $other['data'][0]]); + + if ($id_module_exists) { + returnError('error_update_plugin_module', __('Error updating plugin module. Id_module exists in the new agent.')); + return; + } + } + + // Check if agent exists + $check_id_agent = db_get_value('id_agente', 'tagente', 'id_agente', $other['data'][0]); + if (!$check_id_agent) { + returnError('error_update_data_module', __('Error updating plugin module. Id_agent doesn\'t exist.')); + return; + } + } + + $plugin_module_fields = [ + 'id_agente', + 'disabled', + 'id_module_group', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'min_ff_event', + 'history_data', + 'ip_target', + 'tcp_port', + 'snmp_community', + 'snmp_oid', + 'module_interval', + 'post_process', + 'min', + 'max', + 'custom_id', + 'descripcion', + 'id_plugin', + 'plugin_user', + 'plugin_pass', + 'plugin_parameter', + 'disabled_types_event', + 'macros', + 'module_macros', + 'each_ff', + 'min_ff_event_normal', + 'min_ff_event_warning', + 'min_ff_event_critical', + 'critical_inverse', + 'warning_inverse', + 'policy_linked', + ]; + + $values = []; + $cont = 0; + foreach ($plugin_module_fields as $field) { + if ($other['data'][$cont] != '') { + $values[$field] = $other['data'][$cont]; + + if ($field === 'macros') { + $values[$field] = base64_decode($values[$field]); + } + } + + $cont++; + } + + $values['policy_linked'] = 0; + $result_update = modules_update_agent_module($id_module, $values); + + if ($result_update < 0) { + returnError('error_update_plugin_module', 'Error updating plugin module.'); + } else { + returnData('string', ['type' => 'string', 'data' => __('Plugin module updated.')]); + } +} + + +/** + * Create a data module in agent. And return the id_agent_module of new module. + * Note: Only adds database information, this function doesn't alter config file information. + * + * @param string $id Name of agent to add the module. + * @param $thrash1 Don't use. + * @param array $other it's array, $other as param is ;;; + * ;;;;;;; + * ;;;;;; + * ;;;; + * ;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=create_data_module&id=pepito&other=prueba|0|1|data%20module%20from%20api|1|10|20|10.50|180|10|15||16|20||0&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use + */ +function api_set_create_data_module($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + 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); + + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } + + $name = $other['data'][0]; + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][16]; + $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], + 'id_module_group' => $other['data'][4], + 'min' => $other['data'][5], + 'max' => $other['data'][6], + 'post_process' => $other['data'][7], + 'module_interval' => $other['data'][8], + 'min_warning' => $other['data'][9], + 'max_warning' => $other['data'][10], + 'str_warning' => $other['data'][11], + 'min_critical' => $other['data'][12], + 'max_critical' => $other['data'][13], + 'str_critical' => $other['data'][14], + 'history_data' => $other['data'][15], + 'id_modulo' => 1, + 'disabled_types_event' => $disabled_types_event, + 'module_macros' => $other['data'][17], + 'min_ff_event' => $other['data'][18], + 'each_ff' => $other['data'][19], + 'min_ff_event_normal' => $other['data'][20], + 'min_ff_event_warning' => $other['data'][21], + 'min_ff_event_critical' => $other['data'][22], + 'ff_timeout' => $other['data'][23], + 'critical_inverse' => $other['data'][24], + 'warning_inverse' => $other['data'][25], + ]; + + if (! $values['descripcion']) { + $values['descripcion'] = ''; + // Column 'descripcion' cannot be null + } + + if (! $values['module_macros']) { + $values['module_macros'] = ''; + // Column 'module_macros' cannot be null + } + + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + + if (is_error($idModule)) { + // TODO: Improve the error returning more info + returnError('error_create_data_module', __('Error in creation data module.')); + } else { + returnData('string', ['type' => 'string', 'data' => $idModule]); + } +} + + +/** + * Create a synthetic module in agent. And return the id_agent_module of new module. + * Note: Only adds database information, this function doesn't alter config file information. + * + * @param string $id Name of agent to add the module. + * @param $thrash1 Don't use. + * @param array $other it's array, $other as param is OR OR in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=create_synthetic_module&id=pepito&other=prueba|average|Agent%20Name;AVG;Name%20Module|Agent%20Name2;AVG;Name%20Module2&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use + */ +function api_set_create_synthetic_module($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + global $config; + + $agentName = $id; + + io_safe_input_array($other); + + if ($other['data'][0] == '') { + returnError('error_create_data_module', __('Error in creation synthetic module. Module_name cannot be left blank.')); + return; + } + + $idAgent = agents_get_agent_id(io_safe_output($agentName), 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; + } + + $name = io_safe_output($other['data'][0]); + $name = io_safe_input($name); + $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, + 'prediction_module' => 3, + 'id_tipo_modulo' => $id_tipo_modulo['id_tipo'], + ]; + + if (! $values['descripcion']) { + $values['descripcion'] = ''; + // Column 'descripcion' cannot be null + } + + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + + 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]); + + $filterdata = []; + foreach ($other['data'] as $data) { + $data = str_replace(['ADD', 'SUB', 'MUL', 'DIV'], ['+', '-', '*', '/'], $data); + $split_data = explode(';', $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(io_safe_output($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); + } + } + } + + $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; + } 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; + + 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)]); + } + } + } +} + + +/** + * Update a data module in agent. And return a message with the result of the operation. + * + * @param string $id Id of the data module to update. + * @param $thrash1 Don't use. + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;; + * ;;;; + * in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=update_data_module&id=170&other=44|0|data%20module%20modified%20from%20API|6|0|0|50.00|300|10|15||16|18||0&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use + */ +function api_set_update_data_module($id_module, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($id_module == '') { + returnError('error_update_data_module', __('Error updating data module. Id_module cannot be left blank.')); + return; + } + + if (!util_api_check_agent_and_print_error( + modules_get_agentmodule_agent($id_module), + 'string', + 'AW' + ) + ) { + return; + } + + // If we want to change the module to a new agent + if ($other['data'][0] != '') { + if (!util_api_check_agent_and_print_error($other['data'][0], 'string', 'AW')) { + return; + } + + $id_agent_old = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module); + + if ($id_agent_old != $other['data'][0]) { + $id_module_exists = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['nombre' => $module_name, 'id_agente' => $other['data'][0]]); + + if ($id_module_exists) { + returnError('error_update_data_module', __('Error updating data module. Id_module exists in the new agent.')); + return; + } + } + + // Check if agent exists + $check_id_agent = db_get_value('id_agente', 'tagente', 'id_agente', $other['data'][0]); + if (!$check_id_agent) { + returnError('error_update_data_module', __('Error updating data module. Id_agent doesn\'t exist.')); + return; + } + } + + $data_module_fields = [ + 'id_agente', + 'disabled', + 'descripcion', + 'id_module_group', + 'min', + 'max', + 'post_process', + 'module_interval', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'history_data', + 'disabled_types_event', + 'module_macros', + 'min_ff_event', + 'each_ff', + 'min_ff_event_normal', + 'min_ff_event_warning', + 'min_ff_event_critical', + 'ff_timeout', + 'critical_inverse', + 'warning_inverse', + 'policy_linked', + ]; + + $values = []; + $cont = 0; + foreach ($data_module_fields as $field) { + if ($other['data'][$cont] != '') { + $values[$field] = $other['data'][$cont]; + } + + $cont++; + } + + $values['policy_linked'] = 0; + $result_update = modules_update_agent_module($id_module, $values); + + if ($result_update < 0) { + returnError('error_update_data_module', 'Error updating data module.'); + } else { + returnData('string', ['type' => 'string', 'data' => __('Data module updated.')]); + } +} + + +/** + * Create a SNMP module in agent. And return the id_agent_module of new module. + * + * @param string $id Name of agent to add the module. + * @param $thrash1 Don't use. + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;;;;; + * ;;;;;;;; + * ;;;;; + * ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example 1 (snmp v: 3, snmp3_priv_method: AES, passw|authNoPriv|MD5|pepito_user|example_priv_passw) + * + * api.php?op=set&op2=create_snmp_module&id=pepito&other=prueba|0|15|1|10|15||16|18||15|0|127.0.0.1|60|3|public|.1.3.6.1.2.1.1.1.0|180|0|0|0|0|SNMP%20module%20from%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_| + * + * example 2 (snmp v: 1) + * + * api.php?op=set&op2=create_snmp_module&id=pepito1&other=prueba2|0|15|1|10|15||16|18||15|0|127.0.0.1|60|1|public|.1.3.6.1.2.1.1.1.0|180|0|0|0|0|SNMP module from API&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use + */ +function api_set_create_snmp_module($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + $agentName = $id; + + if ($other['data'][0] == '') { + returnError('error_create_snmp_module', __('Error in creation SNMP module. Module_name cannot be left blank.')); + return; + } + + if ($other['data'][2] < 15 or $other['data'][2] > 18) { + returnError('error_create_snmp_module', __('Error in creation SNMP module. Invalid id_module_type for a SNMP module.')); + return; + } + + $idAgent = agents_get_agent_id($agentName); + + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } + + $name = $other['data'][0]; + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][27]; + $disabled_types_event = json_encode($disabled_types_event); + + // SNMP version 3 + if ($other['data'][14] == '3') { + if ($other['data'][23] != 'AES' and $other['data'][23] != 'DES') { + returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ')); + return; + } + + if ($other['data'][25] != 'authNoPriv' and $other['data'][25] != 'authPriv' and $other['data'][25] != 'noAuthNoPriv') { + returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ')); + return; + } + + if ($other['data'][26] != 'MD5' and $other['data'][26] != 'SHA') { + returnError('error_create_snmp_module', __('Error in creation SNMP module. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ')); + return; + } + + $values = [ + 'id_agente' => $idAgent, + 'disabled' => $other['data'][1], + 'id_tipo_modulo' => $other['data'][2], + 'id_module_group' => $other['data'][3], + 'min_warning' => $other['data'][4], + 'max_warning' => $other['data'][5], + 'str_warning' => $other['data'][6], + 'min_critical' => $other['data'][7], + 'max_critical' => $other['data'][8], + 'str_critical' => $other['data'][9], + 'min_ff_event' => $other['data'][10], + 'history_data' => $other['data'][11], + 'ip_target' => $other['data'][12], + 'tcp_port' => $other['data'][13], + 'tcp_send' => $other['data'][14], + 'snmp_community' => $other['data'][15], + 'snmp_oid' => $other['data'][16], + 'module_interval' => $other['data'][17], + 'post_process' => $other['data'][18], + 'min' => $other['data'][19], + 'max' => $other['data'][20], + 'custom_id' => $other['data'][21], + 'descripcion' => $other['data'][22], + 'id_modulo' => 2, + 'custom_string_1' => $other['data'][23], + 'custom_string_2' => $other['data'][24], + 'custom_string_3' => $other['data'][25], + 'plugin_parameter' => $other['data'][26], + 'plugin_user' => $other['data'][27], + 'plugin_pass' => $other['data'][28], + 'disabled_types_event' => $disabled_types_event, + 'each_ff' => $other['data'][30], + 'min_ff_event_normal' => $other['data'][31], + 'min_ff_event_warning' => $other['data'][32], + 'min_ff_event_critical' => $other['data'][33], + ]; + } else { + $values = [ + 'id_agente' => $idAgent, + 'disabled' => $other['data'][1], + 'id_tipo_modulo' => $other['data'][2], + 'id_module_group' => $other['data'][3], + 'min_warning' => $other['data'][4], + 'max_warning' => $other['data'][5], + 'str_warning' => $other['data'][6], + 'min_critical' => $other['data'][7], + 'max_critical' => $other['data'][8], + 'str_critical' => $other['data'][9], + 'min_ff_event' => $other['data'][10], + 'history_data' => $other['data'][11], + 'ip_target' => $other['data'][12], + 'tcp_port' => $other['data'][13], + 'tcp_send' => $other['data'][14], + 'snmp_community' => $other['data'][15], + 'snmp_oid' => $other['data'][16], + 'module_interval' => $other['data'][17], + 'post_process' => $other['data'][18], + 'min' => $other['data'][19], + 'max' => $other['data'][20], + 'custom_id' => $other['data'][21], + 'descripcion' => $other['data'][22], + 'id_modulo' => 2, + 'disabled_types_event' => $disabled_types_event, + 'each_ff' => $other['data'][24], + 'min_ff_event_normal' => $other['data'][25], + 'min_ff_event_warning' => $other['data'][26], + 'min_ff_event_critical' => $other['data'][27], + ]; + } + + if (! $values['descripcion']) { + $values['descripcion'] = ''; + // Column 'descripcion' cannot be null + } + + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + + if (is_error($idModule)) { + // TODO: Improve the error returning more info + returnError('error_create_snmp_module', __('Error in creation SNMP module.')); + } else { + returnData('string', ['type' => 'string', 'data' => $idModule]); + } +} + + +/** + * Update a SNMP module in agent. And return a message with the result of the operation. + * + * @param string $id Id of module to update. + * @param $thrash1 Don't use. + * @param array $other it's array, $other as param is ;; + * ;;;;;;;; + * ;;;;;;;; + * ;;;;;;;; + * ;;;; + * ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example (update snmp v: 3, snmp3_priv_method: AES, passw|authNoPriv|MD5|pepito_user|example_priv_passw) + * + * api.php?op=set&op2=update_snmp_module&id=example_snmp_module_name&other=44|0|6|20|25||26|30||15|1|127.0.0.1|60|3|public|.1.3.6.1.2.1.1.1.0|180|50.00|10|60|0|SNMP%20module%20modified%20by%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_| + * + * @param $thrash3 Don't use + */ +function api_set_update_snmp_module($id_module, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($id_module == '') { + returnError('error_update_snmp_module', __('Error updating SNMP module. Id_module cannot be left blank.')); + return; + } + + if (!util_api_check_agent_and_print_error( + modules_get_agentmodule_agent($id_module), + 'string', + 'AW' + ) + ) { + return; + } + + // If we want to change the module to a new agent + if ($other['data'][0] != '') { + if (!util_api_check_agent_and_print_error($other['data'][0], 'string', 'AW')) { + return; + } + + $id_agent_old = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $id_module); + + if ($id_agent_old != $other['data'][0]) { + $id_module_exists = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['nombre' => $module_name, 'id_agente' => $other['data'][0]]); + + if ($id_module_exists) { + returnError('error_update_snmp_module', __('Error updating SNMP module. Id_module exists in the new agent.')); + return; + } + } + + // Check if agent exists + $check_id_agent = db_get_value('id_agente', 'tagente', 'id_agente', $other['data'][0]); + if (!$check_id_agent) { + returnError('error_update_data_module', __('Error updating snmp module. Id_agent doesn\'t exist.')); + return; + } + } + + // SNMP version 3 + if ($other['data'][13] == '3') { + if ($other['data'][22] != 'AES' and $other['data'][22] != 'DES') { + returnError( + 'error_create_snmp_module', + __('Error in creation SNMP module. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ') + ); + return; + } + + if ($other['data'][24] != 'authNoPriv' + and $other['data'][24] != 'authPriv' + and $other['data'][24] != 'noAuthNoPriv' + ) { + returnError( + 'error_create_snmp_module', + __('Error in creation SNMP module. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ') + ); + return; + } + + if ($other['data'][25] != 'MD5' and $other['data'][25] != 'SHA') { + returnError( + 'error_create_snmp_module', + __('Error in creation SNMP module. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ') + ); + return; + } + + $snmp_module_fields = [ + 'id_agente', + 'disabled', + 'id_module_group', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'min_ff_event', + 'history_data', + 'ip_target', + 'tcp_port', + 'tcp_send', + 'snmp_community', + 'snmp_oid', + 'module_interval', + 'post_process', + 'min', + 'max', + 'custom_id', + 'descripcion', + 'custom_string_1', + 'custom_string_2', + 'custom_string_3', + 'plugin_parameter', + 'plugin_user', + 'plugin_pass', + 'disabled_types_event', + 'each_ff', + 'min_ff_event_normal', + 'min_ff_event_warning', + 'min_ff_event_critical', + 'policy_linked', + ]; + } else { + $snmp_module_fields = [ + 'id_agente', + 'disabled', + 'id_module_group', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'min_ff_event', + 'history_data', + 'ip_target', + 'tcp_port', + 'tcp_send', + 'snmp_community', + 'snmp_oid', + 'module_interval', + 'post_process', + 'min', + 'max', + 'custom_id', + 'descripcion', + 'disabled_types_event', + 'each_ff', + 'min_ff_event_normal', + 'min_ff_event_warning', + 'min_ff_event_critical', + 'policy_linked', + ]; + } + + $values = []; + $cont = 0; + foreach ($snmp_module_fields as $field) { + if ($other['data'][$cont] != '') { + $values[$field] = $other['data'][$cont]; + } + + $cont++; + } + + $values['policy_linked'] = 0; + $result_update = modules_update_agent_module($id_module, $values); + + if ($result_update < 0) { + returnError('error_update_snmp_module', 'Error updating SNMP module.'); + } else { + returnData('string', ['type' => 'string', 'data' => __('SNMP module updated.')]); + } +} + + /** * Create new network component. - * + * * @param $id string Name of the network component. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;;; - * ;;;;;;; - * ;;;;; - * ;; in this - * order and separator char (after text ; ) and separator (pass in param - * othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=new_network_component&id=example_network_component_name&other=7|network%20component%20created%20by%20Api|300|30|10|public|3||1|10|20|str|21|30|str1|10|50.00|12&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;; + * ;;;;;; + * ;;;;;;; + * ;;;;; + * ;; in this + * order and separator char (after text ; ) and separator (pass in param + * othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=new_network_component&id=example_network_component_name&other=7|network%20component%20created%20by%20Api|300|30|10|public|3||1|10|20|str|21|30|str1|10|50.00|12&other_mode=url_encode_separator_| + * * @param $thrash2 Don't use. - */ -function api_set_new_network_component($id, $thrash1, $other, $thrash2) { - global $config; - if (defined ('METACONSOLE')) { - return; - } +function api_set_new_network_component($id, $thrash1, $other, $thrash2) +{ + global $config; + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "PM")) { - returnError('forbidden', 'string'); - return; - } - - if ($id == "") { - returnError('error_set_new_network_component', __('Error creating network component. Network component name cannot be left blank.')); - return; - } - - if ($other['data'][0] < 6 or $other['data'][0] > 18) { - returnError('error_set_new_network_component', __('Error creating network component. Incorrect value for Network component type field.')); - return; - } - - if ($other['data'][17] == "") { - returnError('error_set_new_network_component', __('Error creating network component. Network component group cannot be left blank.')); - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][18]; - $disabled_types_event = json_encode($disabled_types_event); - - $values = array ( - 'description' => $other['data'][1], - 'module_interval' => $other['data'][2], - 'max' => $other['data'][3], - 'min' => $other['data'][4], - 'snmp_community' => $other['data'][5], - 'id_module_group' => $other['data'][6], - 'id_modulo' => 2, - 'max_timeout' => $other['data'][7], - 'history_data' => $other['data'][8], - 'min_warning' => $other['data'][9], - 'max_warning' => $other['data'][10], - 'str_warning' => $other['data'][11], - 'min_critical' => $other['data'][12], - 'max_critical' => $other['data'][13], - 'str_critical' => $other['data'][14], - 'min_ff_event' => $other['data'][15], - 'post_process' => $other['data'][16], - 'id_group' => $other['data'][17], - 'disabled_types_event' => $disabled_types_event, - 'each_ff' => $other['data'][19], - 'min_ff_event_normal' => $other['data'][20], - 'min_ff_event_warning' => $other['data'][21], - 'min_ff_event_critical' => $other['data'][22]); - - $name_check = db_get_value ('name', 'tnetwork_component', 'name', $id); - - if ($name_check !== false) { - returnError('error_set_new_network_component', __('Error creating network component. This network component already exists.')); - return; - } - - $id = network_components_create_network_component ($id, $other['data'][0], $other['data'][17], $values); - - if (!$id) - returnError('error_set_new_network_component', 'Error creating network component.'); - else - returnData('string', array('type' => 'string', 'data' => $id)); + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } + + if ($id == '') { + returnError('error_set_new_network_component', __('Error creating network component. Network component name cannot be left blank.')); + return; + } + + if ($other['data'][0] < 6 or $other['data'][0] > 18) { + returnError('error_set_new_network_component', __('Error creating network component. Incorrect value for Network component type field.')); + return; + } + + if ($other['data'][17] == '') { + returnError('error_set_new_network_component', __('Error creating network component. Network component group cannot be left blank.')); + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][18]; + $disabled_types_event = json_encode($disabled_types_event); + + $values = [ + 'description' => $other['data'][1], + 'module_interval' => $other['data'][2], + 'max' => $other['data'][3], + 'min' => $other['data'][4], + 'snmp_community' => $other['data'][5], + 'id_module_group' => $other['data'][6], + 'id_modulo' => 2, + 'max_timeout' => $other['data'][7], + 'history_data' => $other['data'][8], + 'min_warning' => $other['data'][9], + 'max_warning' => $other['data'][10], + 'str_warning' => $other['data'][11], + 'min_critical' => $other['data'][12], + 'max_critical' => $other['data'][13], + 'str_critical' => $other['data'][14], + 'min_ff_event' => $other['data'][15], + 'post_process' => $other['data'][16], + 'id_group' => $other['data'][17], + 'disabled_types_event' => $disabled_types_event, + 'each_ff' => $other['data'][19], + 'min_ff_event_normal' => $other['data'][20], + 'min_ff_event_warning' => $other['data'][21], + 'min_ff_event_critical' => $other['data'][22], + ]; + + $name_check = db_get_value('name', 'tnetwork_component', 'name', $id); + + if ($name_check !== false) { + returnError('error_set_new_network_component', __('Error creating network component. This network component already exists.')); + return; + } + + $id = network_components_create_network_component($id, $other['data'][0], $other['data'][17], $values); + + if (!$id) { + returnError('error_set_new_network_component', 'Error creating network component.'); + } else { + returnData('string', ['type' => 'string', 'data' => $id]); + } } + /** * Create new plugin component. - * + * * @param $id string Name of the plugin component. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;;;; - * ;;;;;;; - * ;;;; - * ;;; in this - * order and separator char (after text ; ) and separator (pass in param - * othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=new_plugin_component&id=example_plugin_component_name&other=2|plugin%20component%20created%20by%20Api|300|30|10|66|3|2|example_user|example_pass|-p%20max||1|10|20|str|21|30|str1|10|50.00|12&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;; + * ;;;;;;; + * ;;;;;;; + * ;;;; + * ;;; in this + * order and separator char (after text ; ) and separator (pass in param + * othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=new_plugin_component&id=example_plugin_component_name&other=2|plugin%20component%20created%20by%20Api|300|30|10|66|3|2|example_user|example_pass|-p%20max||1|10|20|str|21|30|str1|10|50.00|12&other_mode=url_encode_separator_| + * * @param $thrash2 Don't use. - */ -function api_set_new_plugin_component($id, $thrash1, $other, $thrash2) { - global $config; +function api_set_new_plugin_component($id, $thrash1, $other, $thrash2) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "PM")) { - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } - if ($id == "") { - returnError('error_set_new_plugin_component', - __('Error creating plugin component. Plugin component name cannot be left blank.')); - return; - } - - if ($other['data'][7] == "") { - returnError('error_set_new_plugin_component', __('Error creating plugin component. Incorrect value for Id plugin.')); - return; - } - - if ($other['data'][21] == "") { - returnError('error_set_new_plugin_component', __('Error creating plugin component. Plugin component group cannot be left blank.')); - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][12]; - $disabled_types_event = json_encode($disabled_types_event); - - $values = array ( - 'description' => $other['data'][1], - 'module_interval' => $other['data'][2], - 'max' => $other['data'][3], - 'min' => $other['data'][4], - 'tcp_port' => $other['data'][5], - 'id_module_group' => $other['data'][6], - 'id_modulo' => 4, - 'id_plugin' => $other['data'][7], - 'plugin_user' => $other['data'][8], - 'plugin_pass' => $other['data'][9], - 'plugin_parameter' => $other['data'][10], - 'max_timeout' => $other['data'][11], - 'history_data' => $other['data'][12], - 'min_warning' => $other['data'][13], - 'max_warning' => $other['data'][14], - 'str_warning' => $other['data'][15], - 'min_critical' => $other['data'][16], - 'max_critical' => $other['data'][17], - 'str_critical' => $other['data'][18], - 'min_ff_event' => $other['data'][19], - 'post_process' => $other['data'][20], - 'id_group' => $other['data'][21], - 'disabled_types_event' => $disabled_types_event, - 'each_ff' => $other['data'][23], - 'min_ff_event_normal' => $other['data'][24], - 'min_ff_event_warning' => $other['data'][25], - 'min_ff_event_critical' => $other['data'][26]); - - $name_check = db_get_value ('name', 'tnetwork_component', 'name', $id); - - if ($name_check !== false) { - returnError('error_set_new_plugin_component', __('Error creating plugin component. This plugin component already exists.')); - return; - } - - $id = network_components_create_network_component ($id, $other['data'][0], $other['data'][21], $values); - - if (!$id) - returnError('error_set_new_plugin_component', 'Error creating plugin component.'); - else - returnData('string', array('type' => 'string', 'data' => $id)); + if ($id == '') { + returnError( + 'error_set_new_plugin_component', + __('Error creating plugin component. Plugin component name cannot be left blank.') + ); + return; + } + + if ($other['data'][7] == '') { + returnError('error_set_new_plugin_component', __('Error creating plugin component. Incorrect value for Id plugin.')); + return; + } + + if ($other['data'][21] == '') { + returnError('error_set_new_plugin_component', __('Error creating plugin component. Plugin component group cannot be left blank.')); + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][12]; + $disabled_types_event = json_encode($disabled_types_event); + + $values = [ + 'description' => $other['data'][1], + 'module_interval' => $other['data'][2], + 'max' => $other['data'][3], + 'min' => $other['data'][4], + 'tcp_port' => $other['data'][5], + 'id_module_group' => $other['data'][6], + 'id_modulo' => 4, + 'id_plugin' => $other['data'][7], + 'plugin_user' => $other['data'][8], + 'plugin_pass' => $other['data'][9], + 'plugin_parameter' => $other['data'][10], + 'max_timeout' => $other['data'][11], + 'history_data' => $other['data'][12], + 'min_warning' => $other['data'][13], + 'max_warning' => $other['data'][14], + 'str_warning' => $other['data'][15], + 'min_critical' => $other['data'][16], + 'max_critical' => $other['data'][17], + 'str_critical' => $other['data'][18], + 'min_ff_event' => $other['data'][19], + 'post_process' => $other['data'][20], + 'id_group' => $other['data'][21], + 'disabled_types_event' => $disabled_types_event, + 'each_ff' => $other['data'][23], + 'min_ff_event_normal' => $other['data'][24], + 'min_ff_event_warning' => $other['data'][25], + 'min_ff_event_critical' => $other['data'][26], + ]; + + $name_check = db_get_value('name', 'tnetwork_component', 'name', $id); + + if ($name_check !== false) { + returnError('error_set_new_plugin_component', __('Error creating plugin component. This plugin component already exists.')); + return; + } + + $id = network_components_create_network_component($id, $other['data'][0], $other['data'][21], $values); + + if (!$id) { + returnError('error_set_new_plugin_component', 'Error creating plugin component.'); + } else { + returnData('string', ['type' => 'string', 'data' => $id]); + } } + /** * Create new SNMP component. - * + * * @param $id string Name of the SNMP component. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;; - * ;;;;;;; - * ;;;;; - * ;;;;;;;;; - * ;;; in this - * order and separator char (after text ; ) and separator (pass in param - * othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=new_snmp_component&id=example_snmp_component_name&other=16|SNMP%20component%20created%20by%20Api|300|30|10|3||1|10|20|str|21|30|str1|15|50.00|3|.1.3.6.1.2.1.2.2.1.8.2|public|example_auth_user|example_auth_pass|66|AES|example_priv_pass|MD5|authNoPriv|12&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;; + * ;;;;; + * ;;;;;;; + * ;;;;; + * ;;;;;;;;; + * ;;; in this + * order and separator char (after text ; ) and separator (pass in param + * othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=new_snmp_component&id=example_snmp_component_name&other=16|SNMP%20component%20created%20by%20Api|300|30|10|3||1|10|20|str|21|30|str1|15|50.00|3|.1.3.6.1.2.1.2.2.1.8.2|public|example_auth_user|example_auth_pass|66|AES|example_priv_pass|MD5|authNoPriv|12&other_mode=url_encode_separator_| + * * @param $thrash2 Don't use. - */ -function api_set_new_snmp_component($id, $thrash1, $other, $thrash2) { - global $config; +function api_set_new_snmp_component($id, $thrash1, $other, $thrash2) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_set_new_snmp_component', __('Error creating SNMP component. SNMP component name cannot be left blank.')); - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "PM")) { - returnError('forbidden', 'string'); - return; - } - - if ($other['data'][0] < 15 or $other['data'][0] > 17) { - returnError('error_set_new_snmp_component', __('Error creating SNMP component. Incorrect value for Snmp component type field.')); - return; - } - - if ($other['data'][25] == "") { - returnError('error_set_new_snmp_component', __('Error creating SNMP component. Snmp component group cannot be left blank.')); - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][27]; - $disabled_types_event = json_encode($disabled_types_event); - - # SNMP version 3 - if ($other['data'][16] == "3") { - - if ($other['data'][22] != "AES" and $other['data'][22] != "DES") { - returnError('error_set_new_snmp_component', __('Error creating SNMP component. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ')); - return; - } - - if ($other['data'][25] != "authNoPriv" - and $other['data'][25] != "authPriv" - and $other['data'][25] != "noAuthNoPriv") { - - returnError('error_set_new_snmp_component', - __('Error creating SNMP component. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ')); - return; - } - - if ($other['data'][24] != "MD5" and $other['data'][24] != "SHA") { - returnError('error_set_new_snmp_component', - __('Error creating SNMP component. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ')); - return; - } - - $values = array ( - 'description' => $other['data'][1], - 'module_interval' => $other['data'][2], - 'max' => $other['data'][3], - 'min' => $other['data'][4], - 'id_module_group' => $other['data'][5], - 'max_timeout' => $other['data'][6], - 'history_data' => $other['data'][7], - 'min_warning' => $other['data'][8], - 'max_warning' => $other['data'][9], - 'str_warning' => $other['data'][10], - 'min_critical' => $other['data'][11], - 'max_critical' => $other['data'][12], - 'str_critical' => $other['data'][13], - 'min_ff_event' => $other['data'][14], - 'post_process' => $other['data'][15], - 'tcp_send' => $other['data'][16], - 'snmp_oid' => $other['data'][17], - 'snmp_community' => $other['data'][18], - 'plugin_user' => $other['data'][19], // snmp3_auth_user - 'plugin_pass' => $other['data'][20], // snmp3_auth_pass - 'tcp_port' => $other['data'][21], - 'id_modulo' => 2, - 'custom_string_1' => $other['data'][22], // snmp3_privacy_method - 'custom_string_2' => $other['data'][23], // snmp3_privacy_pass - 'plugin_parameter' => $other['data'][24], // snmp3_auth_method - 'custom_string_3' => $other['data'][25], // snmp3_security_level - 'id_group' => $other['data'][26], - 'disabled_types_event' => $disabled_types_event, - 'each_ff' => $other['data'][28], - 'min_ff_event_normal' => $other['data'][29], - 'min_ff_event_warning' => $other['data'][30], - 'min_ff_event_critical' => $other['data'][31] - ); - } - else { - $values = array ( - 'description' => $other['data'][1], - 'module_interval' => $other['data'][2], - 'max' => $other['data'][3], - 'min' => $other['data'][4], - 'id_module_group' => $other['data'][5], - 'max_timeout' => $other['data'][6], - 'history_data' => $other['data'][7], - 'min_warning' => $other['data'][8], - 'max_warning' => $other['data'][9], - 'str_warning' => $other['data'][10], - 'min_critical' => $other['data'][11], - 'max_critical' => $other['data'][12], - 'str_critical' => $other['data'][13], - 'min_ff_event' => $other['data'][14], - 'post_process' => $other['data'][15], - 'tcp_send' => $other['data'][16], - 'snmp_oid' => $other['data'][17], - 'snmp_community' => $other['data'][18], - 'plugin_user' => '', - 'plugin_pass' => '', - 'tcp_port' => $other['data'][21], - 'id_modulo' => 2, - 'id_group' => $other['data'][22], - 'disabled_types_event' => $disabled_types_event, - 'each_ff' => $other['data'][24], - 'min_ff_event_normal' => $other['data'][25], - 'min_ff_event_warning' => $other['data'][26], - 'min_ff_event_critical' => $other['data'][27] - ); - } - - $name_check = db_get_value ('name', 'tnetwork_component', 'name', $id); - - if ($name_check !== false) { - returnError('error_set_new_snmp_component', __('Error creating SNMP component. This SNMP component already exists.')); - return; - } - - $id = network_components_create_network_component ($id, $other['data'][0], $other['data'][25], $values); - - if (!$id) - returnError('error_set_new_snmp_component', 'Error creating SNMP component.'); - else - returnData('string', array('type' => 'string', 'data' => $id)); + if ($id == '') { + returnError('error_set_new_snmp_component', __('Error creating SNMP component. SNMP component name cannot be left blank.')); + return; + } + + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } + + if ($other['data'][0] < 15 or $other['data'][0] > 17) { + returnError('error_set_new_snmp_component', __('Error creating SNMP component. Incorrect value for Snmp component type field.')); + return; + } + + if ($other['data'][25] == '') { + returnError('error_set_new_snmp_component', __('Error creating SNMP component. Snmp component group cannot be left blank.')); + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][27]; + $disabled_types_event = json_encode($disabled_types_event); + + // SNMP version 3 + if ($other['data'][16] == '3') { + if ($other['data'][22] != 'AES' and $other['data'][22] != 'DES') { + returnError('error_set_new_snmp_component', __('Error creating SNMP component. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ')); + return; + } + + if ($other['data'][25] != 'authNoPriv' + and $other['data'][25] != 'authPriv' + and $other['data'][25] != 'noAuthNoPriv' + ) { + returnError( + 'error_set_new_snmp_component', + __('Error creating SNMP component. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ') + ); + return; + } + + if ($other['data'][24] != 'MD5' and $other['data'][24] != 'SHA') { + returnError( + 'error_set_new_snmp_component', + __('Error creating SNMP component. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ') + ); + return; + } + + $values = [ + 'description' => $other['data'][1], + 'module_interval' => $other['data'][2], + 'max' => $other['data'][3], + 'min' => $other['data'][4], + 'id_module_group' => $other['data'][5], + 'max_timeout' => $other['data'][6], + 'history_data' => $other['data'][7], + 'min_warning' => $other['data'][8], + 'max_warning' => $other['data'][9], + 'str_warning' => $other['data'][10], + 'min_critical' => $other['data'][11], + 'max_critical' => $other['data'][12], + 'str_critical' => $other['data'][13], + 'min_ff_event' => $other['data'][14], + 'post_process' => $other['data'][15], + 'tcp_send' => $other['data'][16], + 'snmp_oid' => $other['data'][17], + 'snmp_community' => $other['data'][18], + 'plugin_user' => $other['data'][19], + // snmp3_auth_user + 'plugin_pass' => $other['data'][20], + // snmp3_auth_pass + 'tcp_port' => $other['data'][21], + 'id_modulo' => 2, + 'custom_string_1' => $other['data'][22], + // snmp3_privacy_method + 'custom_string_2' => $other['data'][23], + // snmp3_privacy_pass + 'plugin_parameter' => $other['data'][24], + // snmp3_auth_method + 'custom_string_3' => $other['data'][25], + // snmp3_security_level + 'id_group' => $other['data'][26], + 'disabled_types_event' => $disabled_types_event, + 'each_ff' => $other['data'][28], + 'min_ff_event_normal' => $other['data'][29], + 'min_ff_event_warning' => $other['data'][30], + 'min_ff_event_critical' => $other['data'][31], + ]; + } else { + $values = [ + 'description' => $other['data'][1], + 'module_interval' => $other['data'][2], + 'max' => $other['data'][3], + 'min' => $other['data'][4], + 'id_module_group' => $other['data'][5], + 'max_timeout' => $other['data'][6], + 'history_data' => $other['data'][7], + 'min_warning' => $other['data'][8], + 'max_warning' => $other['data'][9], + 'str_warning' => $other['data'][10], + 'min_critical' => $other['data'][11], + 'max_critical' => $other['data'][12], + 'str_critical' => $other['data'][13], + 'min_ff_event' => $other['data'][14], + 'post_process' => $other['data'][15], + 'tcp_send' => $other['data'][16], + 'snmp_oid' => $other['data'][17], + 'snmp_community' => $other['data'][18], + 'plugin_user' => '', + 'plugin_pass' => '', + 'tcp_port' => $other['data'][21], + 'id_modulo' => 2, + 'id_group' => $other['data'][22], + 'disabled_types_event' => $disabled_types_event, + 'each_ff' => $other['data'][24], + 'min_ff_event_normal' => $other['data'][25], + 'min_ff_event_warning' => $other['data'][26], + 'min_ff_event_critical' => $other['data'][27], + ]; + } + + $name_check = db_get_value('name', 'tnetwork_component', 'name', $id); + + if ($name_check !== false) { + returnError('error_set_new_snmp_component', __('Error creating SNMP component. This SNMP component already exists.')); + return; + } + + $id = network_components_create_network_component($id, $other['data'][0], $other['data'][25], $values); + + if (!$id) { + returnError('error_set_new_snmp_component', 'Error creating SNMP component.'); + } else { + returnData('string', ['type' => 'string', 'data' => $id]); + } } + /** * Create new local (data) component. - * + * * @param $id string Name of the local component. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;; - * ;;;; - * ; in this order and separator char - * (after text ; ) and separator (pass in param othermode as - * othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=new_local_component&id=example_local_component_name&other=local%20component%20created%20by%20Api~5~12~module_begin%0dmodule_name%20example_local_component_name%0dmodule_type%20generic_data%0dmodule_exec%20ps%20|%20grep%20pid%20|%20wc%20-l%0dmodule_interval%202%0dmodule_end&other_mode=url_encode_separator_~ - * + * @param array $other it's array, $other as param is ;; + * ;;; + * ;;;; + * ; in this order and separator char + * (after text ; ) and separator (pass in param othermode as + * othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=new_local_component&id=example_local_component_name&other=local%20component%20created%20by%20Api~5~12~module_begin%0dmodule_name%20example_local_component_name%0dmodule_type%20generic_data%0dmodule_exec%20ps%20|%20grep%20pid%20|%20wc%20-l%0dmodule_interval%202%0dmodule_end&other_mode=url_encode_separator_~ + * * @param $thrash2 Don't use. - */ -function api_set_new_local_component($id, $thrash1, $other, $thrash2) { - global $config; +function api_set_new_local_component($id, $thrash1, $other, $thrash2) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_set_new_local_component', - __('Error creating local component. Local component name cannot be left blank.')); - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "PM")) { - returnError('forbidden', 'string'); - return; - } - - if ($other['data'][1] == "") { - returnError('error_set_new_local_component', - __('Error creating local component. Local component group cannot be left blank.')); - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][4]; - $disabled_types_event = json_encode($disabled_types_event); - - $values = array ( - 'description' => $other['data'][0], - 'id_network_component_group' => $other['data'][2], - 'disabled_types_event' => $disabled_types_event, - 'min_ff_event' => $other['data'][5], - 'each_ff' => $other['data'][6], - 'min_ff_event_normal' => $other['data'][7], - 'min_ff_event_warning' => $other['data'][8], - 'min_ff_event_critical' => $other['data'][9], - 'ff_timeout' => $other['data'][10]); - - $name_check = enterprise_hook('local_components_get_local_components', - array(array('name' => $id), 'name')); - - if ($name_check === ENTERPRISE_NOT_HOOK) { - returnError('error_set_new_local_component', - __('Error creating local component.')); - return; - } - - if ($name_check !== false) { - returnError('error_set_new_local_component', - __('Error creating local component. This local component already exists.')); - return; - } - - $id = enterprise_hook('local_components_create_local_component', - array($id, $other['data'][3], $other['data'][1], $values)); - - if (!$id) - returnError('error_set_new_local_component', 'Error creating local component.'); - else - returnData('string', array('type' => 'string', 'data' => $id)); + if ($id == '') { + returnError( + 'error_set_new_local_component', + __('Error creating local component. Local component name cannot be left blank.') + ); + return; + } + + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } + + if ($other['data'][1] == '') { + returnError( + 'error_set_new_local_component', + __('Error creating local component. Local component group cannot be left blank.') + ); + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][4]; + $disabled_types_event = json_encode($disabled_types_event); + + $values = [ + 'description' => $other['data'][0], + 'id_network_component_group' => $other['data'][2], + 'disabled_types_event' => $disabled_types_event, + 'min_ff_event' => $other['data'][5], + 'each_ff' => $other['data'][6], + 'min_ff_event_normal' => $other['data'][7], + 'min_ff_event_warning' => $other['data'][8], + 'min_ff_event_critical' => $other['data'][9], + 'ff_timeout' => $other['data'][10], + ]; + + $name_check = enterprise_hook( + 'local_components_get_local_components', + [ + ['name' => $id], + 'name', + ] + ); + + if ($name_check === ENTERPRISE_NOT_HOOK) { + returnError( + 'error_set_new_local_component', + __('Error creating local component.') + ); + return; + } + + if ($name_check !== false) { + returnError( + 'error_set_new_local_component', + __('Error creating local component. This local component already exists.') + ); + return; + } + + $id = enterprise_hook( + 'local_components_create_local_component', + [ + $id, + $other['data'][3], + $other['data'][1], + $values, + ] + ); + + if (!$id) { + returnError('error_set_new_local_component', 'Error creating local component.'); + } else { + returnData('string', ['type' => 'string', 'data' => $id]); + } } + /** * Get module data value from all agents filter by module name. And return id_agents, agent_name and module value. - * + * * @param $id string Name of the module. * @param $thrash1 Don't use. - * @param array $other Don't use. - * example: - * - * api.php?op=get&op2=module_value_all_agents&id=example_module_name - * + * @param array $other Don't use. + * example: + * + * api.php?op=get&op2=module_value_all_agents&id=example_module_name + * * @param $thrash2 Don't use. - */ -function api_get_module_value_all_agents($id, $thrash1, $other, $thrash2) { - global $config; - if (defined ('METACONSOLE')) { - return; - } +function api_get_module_value_all_agents($id, $thrash1, $other, $thrash2) +{ + global $config; + if (defined('METACONSOLE')) { + return; + } - if ($id == "") { - returnError('error_get_module_value_all_agents', - __('Error getting module value from all agents. Module name cannot be left blank.')); - return; - } + if ($id == '') { + returnError( + 'error_get_module_value_all_agents', + __('Error getting module value from all agents. Module name cannot be left blank.') + ); + return; + } - $id_module = db_get_value ('id_agente_modulo', 'tagente_modulo', 'nombre', $id); + $id_module = db_get_value('id_agente_modulo', 'tagente_modulo', 'nombre', $id); - if ($id_module === false) { - returnError('error_get_module_value_all_agents', - __('Error getting module value from all agents. Module name doesn\'t exist.')); - return; - } + if ($id_module === false) { + returnError( + 'error_get_module_value_all_agents', + __('Error getting module value from all agents. Module name doesn\'t exist.') + ); + return; + } - $groups = '1 = 1'; - if (!is_user_admin($config['id_user'])) { - $user_groups = implode (',', array_keys(users_get_groups())); - $groups = "(id_grupo IN ($user_groups) OR id_group IN ($user_groups))"; - } + $groups = '1 = 1'; + if (!is_user_admin($config['id_user'])) { + $user_groups = implode(',', array_keys(users_get_groups())); + $groups = "(id_grupo IN ($user_groups) OR id_group IN ($user_groups))"; + } - $sql = sprintf( "SELECT agent.id_agente, agent.alias, module_state.datos, agent.nombre + $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", $id, $groups); + AND %s", + $id, + $groups + ); - $module_values = db_get_all_rows_sql($sql); + $module_values = db_get_all_rows_sql($sql); - if (!$module_values) { - returnError('error_get_module_value_all_agents', 'Error getting module values from all agents.'); - } - else { - $data = array('type' => 'array', 'data' => $module_values); - returnData('csv', $data, ';'); - } + if (!$module_values) { + returnError('error_get_module_value_all_agents', 'Error getting module values from all agents.'); + } else { + $data = [ + 'type' => 'array', + 'data' => $module_values, + ]; + returnData('csv', $data, ';'); + } } + /** * Create an alert template. And return the id of new template. - * - * @param string $id Name of alert template to add. + * + * @param string $id Name of alert template to add. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example 1 (condition: regexp =~ /pp/, action: Mail to XXX, max_alert: 10, min_alert: 0, priority: WARNING, group: databases): - * api.php?op=set&op2=create_alert_template&id=pepito&other=regex|template%20based%20in%20regexp|1||||pp|1||||10|0|||||||||||||3&other_mode=url_encode_separator_| - * - * example 2 (condition: value is not between 5 and 10, max_value: 10.00, min_value: 5.00, time_from: 00:00:00, time_to: 15:00:00, priority: CRITICAL, group: Servers): - * api.php?op=set&op2=create_alert_template&id=template_min_max&other=max_min|template%20based%20in%20range|NULL||||||10|5||||00:00:00|15:00:00|||||||||||4|2&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example 1 (condition: regexp =~ /pp/, action: Mail to XXX, max_alert: 10, min_alert: 0, priority: WARNING, group: databases): + * api.php?op=set&op2=create_alert_template&id=pepito&other=regex|template%20based%20in%20regexp|1||||pp|1||||10|0|||||||||||||3&other_mode=url_encode_separator_| + * + * example 2 (condition: value is not between 5 and 10, max_value: 10.00, min_value: 5.00, time_from: 00:00:00, time_to: 15:00:00, priority: CRITICAL, group: Servers): + * api.php?op=set&op2=create_alert_template&id=template_min_max&other=max_min|template%20based%20in%20range|NULL||||||10|5||||00:00:00|15:00:00|||||||||||4|2&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_create_alert_template($name, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($name == "") { - returnError('error_create_alert_template', - __('Error creating alert template. Template name cannot be left blank.')); - return; - } - - $template_name = $name; - - $type = $other['data'][0]; - - if ($other['data'][2] != "") { - $values = array( - 'description' => $other['data'][1], - 'id_alert_action' => $other['data'][2], - 'field1' => $other['data'][3], - 'field2' => $other['data'][4], - 'field3' => $other['data'][5], - 'value' => $other['data'][6], - 'matches_value' => $other['data'][7], - 'max_value' => $other['data'][8], - 'min_value' => $other['data'][9], - 'time_threshold' => $other['data'][10], - 'max_alerts' => $other['data'][11], - 'min_alerts' => $other['data'][12], - 'time_from' => $other['data'][13], - 'time_to' => $other['data'][14], - 'monday' => $other['data'][15], - 'tuesday' => $other['data'][16], - 'wednesday' => $other['data'][17], - 'thursday' => $other['data'][18], - 'friday' => $other['data'][19], - 'saturday' => $other['data'][20], - 'sunday' => $other['data'][21], - 'recovery_notify' => $other['data'][22], - 'field2_recovery' => $other['data'][23], - 'field3_recovery' => $other['data'][24], - 'priority' => $other['data'][25], - 'id_group' => $other['data'][26] - ); - } - else { - $values = array( - 'description' => $other['data'][1], - 'field1' => $other['data'][3], - 'field2' => $other['data'][4], - 'field3' => $other['data'][5], - 'value' => $other['data'][6], - 'matches_value' => $other['data'][7], - 'max_value' => $other['data'][8], - 'min_value' => $other['data'][9], - 'time_threshold' => $other['data'][10], - 'max_alerts' => $other['data'][11], - 'min_alerts' => $other['data'][12], - 'time_from' => $other['data'][13], - 'time_to' => $other['data'][14], - 'monday' => $other['data'][15], - 'tuesday' => $other['data'][16], - 'wednesday' => $other['data'][17], - 'thursday' => $other['data'][18], - 'friday' => $other['data'][19], - 'saturday' => $other['data'][20], - 'sunday' => $other['data'][21], - 'recovery_notify' => $other['data'][22], - 'field2_recovery' => $other['data'][23], - 'field3_recovery' => $other['data'][24], - 'priority' => $other['data'][25], - 'id_group' => $other['data'][26] - ); - } - - $id_template = alerts_create_alert_template($template_name, $type, $values); - - if (is_error($id_template)) { - // TODO: Improve the error returning more info - returnError('error_create_alert_template', __('Error creating alert template.')); - } - else { - returnData('string', array('type' => 'string', 'data' => $id_template)); - } +function api_set_create_alert_template($name, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($name == '') { + returnError( + 'error_create_alert_template', + __('Error creating alert template. Template name cannot be left blank.') + ); + return; + } + + $template_name = $name; + + $type = $other['data'][0]; + + if ($other['data'][2] != '') { + $values = [ + 'description' => $other['data'][1], + 'id_alert_action' => $other['data'][2], + 'field1' => $other['data'][3], + 'field2' => $other['data'][4], + 'field3' => $other['data'][5], + 'value' => $other['data'][6], + 'matches_value' => $other['data'][7], + 'max_value' => $other['data'][8], + 'min_value' => $other['data'][9], + 'time_threshold' => $other['data'][10], + 'max_alerts' => $other['data'][11], + 'min_alerts' => $other['data'][12], + 'time_from' => $other['data'][13], + 'time_to' => $other['data'][14], + 'monday' => $other['data'][15], + 'tuesday' => $other['data'][16], + 'wednesday' => $other['data'][17], + 'thursday' => $other['data'][18], + 'friday' => $other['data'][19], + 'saturday' => $other['data'][20], + 'sunday' => $other['data'][21], + 'recovery_notify' => $other['data'][22], + 'field2_recovery' => $other['data'][23], + 'field3_recovery' => $other['data'][24], + 'priority' => $other['data'][25], + 'id_group' => $other['data'][26], + ]; + } else { + $values = [ + 'description' => $other['data'][1], + 'field1' => $other['data'][3], + 'field2' => $other['data'][4], + 'field3' => $other['data'][5], + 'value' => $other['data'][6], + 'matches_value' => $other['data'][7], + 'max_value' => $other['data'][8], + 'min_value' => $other['data'][9], + 'time_threshold' => $other['data'][10], + 'max_alerts' => $other['data'][11], + 'min_alerts' => $other['data'][12], + 'time_from' => $other['data'][13], + 'time_to' => $other['data'][14], + 'monday' => $other['data'][15], + 'tuesday' => $other['data'][16], + 'wednesday' => $other['data'][17], + 'thursday' => $other['data'][18], + 'friday' => $other['data'][19], + 'saturday' => $other['data'][20], + 'sunday' => $other['data'][21], + 'recovery_notify' => $other['data'][22], + 'field2_recovery' => $other['data'][23], + 'field3_recovery' => $other['data'][24], + 'priority' => $other['data'][25], + 'id_group' => $other['data'][26], + ]; + } + + $id_template = alerts_create_alert_template($template_name, $type, $values); + + if (is_error($id_template)) { + // TODO: Improve the error returning more info + returnError('error_create_alert_template', __('Error creating alert template.')); + } else { + returnData('string', ['type' => 'string', 'data' => $id_template]); + } } + /** * Update an alert template. And return a message with the result of the operation. - * - * @param string $id_template Id of the template to update. + * + * @param string $id_template Id of the template to update. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * - * example: - * - * api.php?op=set&op2=update_alert_template&id=38&other=example_template_with_changed_name|onchange|changing%20from%20min_max%20to%20onchange||||||1||||5|1|||1|1|0|1|1|0|0|1|field%20recovery%20example%201|field%20recovery%20example%202|1|8&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * + * example: + * + * api.php?op=set&op2=update_alert_template&id=38&other=example_template_with_changed_name|onchange|changing%20from%20min_max%20to%20onchange||||||1||||5|1|||1|1|0|1|1|0|0|1|field%20recovery%20example%201|field%20recovery%20example%202|1|8&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_update_alert_template($id_template, $thrash1, $other, $thrash3) { - global $config; +function api_set_update_alert_template($id_template, $thrash1, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "LM")) { - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], 0, 'LM')) { + returnError('forbidden', 'string'); + return; + } - if ($id_template == "") { - returnError('error_update_alert_template', - __('Error updating alert template. Id_template cannot be left blank.')); - return; - } - - $result_template = alerts_get_alert_template_name($id_template); - - if (!$result_template) { - returnError('error_update_alert_template', - __('Error updating alert template. Id_template doesn\'t exist.')); - return; - } - - $fields_template = array('name', 'type', 'description', - 'id_alert_action', 'field1', 'field2', 'field3', 'value', - 'matches_value', 'max_value', 'min_value', 'time_threshold', - 'max_alerts', 'min_alerts', 'time_from', 'time_to', 'monday', - 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', - 'sunday', 'recovery_notify', 'field2_recovery', - 'field3_recovery', 'priority', 'id_group'); - - $cont = 0; - foreach ($fields_template as $field) { - if ($other['data'][$cont] != "") { - $values[$field] = $other['data'][$cont]; - } - - $cont++; - } - - $id_template = alerts_update_alert_template($id_template, $values); - - if (is_error($id_template)) { - // TODO: Improve the error returning more info - returnError('error_create_alert_template', - __('Error updating alert template.')); - } - else { - returnData('string', - array('type' => 'string', - 'data' => __('Correct updating of alert template'))); - } + if ($id_template == '') { + returnError( + 'error_update_alert_template', + __('Error updating alert template. Id_template cannot be left blank.') + ); + return; + } + + $result_template = alerts_get_alert_template_name($id_template); + + if (!$result_template) { + returnError( + 'error_update_alert_template', + __('Error updating alert template. Id_template doesn\'t exist.') + ); + return; + } + + $fields_template = [ + 'name', + 'type', + 'description', + 'id_alert_action', + 'field1', + 'field2', + 'field3', + 'value', + 'matches_value', + 'max_value', + 'min_value', + 'time_threshold', + 'max_alerts', + 'min_alerts', + 'time_from', + 'time_to', + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday', + 'recovery_notify', + 'field2_recovery', + 'field3_recovery', + 'priority', + 'id_group', + ]; + + $cont = 0; + foreach ($fields_template as $field) { + if ($other['data'][$cont] != '') { + $values[$field] = $other['data'][$cont]; + } + + $cont++; + } + + $id_template = alerts_update_alert_template($id_template, $values); + + if (is_error($id_template)) { + // TODO: Improve the error returning more info + returnError( + 'error_create_alert_template', + __('Error updating alert template.') + ); + } else { + returnData( + 'string', + [ + 'type' => 'string', + 'data' => __('Correct updating of alert template'), + ] + ); + } } + /** * Delete an alert template. And return a message with the result of the operation. - * - * @param string $id_template Id of the template to delete. + * + * @param string $id_template Id of the template to delete. * @param $thrash1 Don't use. - * @param array $other Don't use - * - * example: - * - * api.php?op=set&op2=delete_alert_template&id=38 - * + * @param array $other Don't use + * + * example: + * + * api.php?op=set&op2=delete_alert_template&id=38 + * * @param $thrash3 Don't use */ -function api_set_delete_alert_template($id_template, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id_template == "") { - returnError('error_delete_alert_template', - __('Error deleting alert template. Id_template cannot be left blank.')); - return; - } - - $result = alerts_delete_alert_template($id_template); - - if ($result == 0) { - // TODO: Improve the error returning more info - returnError('error_create_alert_template', - __('Error deleting alert template.')); - } - else { - returnData('string', array('type' => 'string', - 'data' => __('Correct deleting of alert template.'))); - } +function api_set_delete_alert_template($id_template, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($id_template == '') { + returnError( + 'error_delete_alert_template', + __('Error deleting alert template. Id_template cannot be left blank.') + ); + return; + } + + $result = alerts_delete_alert_template($id_template); + + if ($result == 0) { + // TODO: Improve the error returning more info + returnError( + 'error_create_alert_template', + __('Error deleting alert template.') + ); + } else { + returnData( + 'string', + [ + 'type' => 'string', + 'data' => __('Correct deleting of alert template.'), + ] + ); + } } + /** * Get all alert tamplates, and print all the result like a csv. - * + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, but only is available. - * example: - * - * api.php?op=get&op2=all_alert_templates&return_type=csv&other=; - * + * @param array $other it's array, but only is available. + * example: + * + * api.php?op=get&op2=all_alert_templates&return_type=csv&other=; + * * @param $thrash3 Don't use. */ -function api_get_all_alert_templates($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_get_all_alert_templates($thrash1, $thrash2, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } - - if (!isset($other['data'][0])) - $separator = ';'; // by default - else - $separator = $other['data'][0]; + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config["id_user"], 0, "LM")) { - returnError("forbidden", "csv"); - return; - } + if (!isset($other['data'][0])) { + $separator = ';'; + // by default + } else { + $separator = $other['data'][0]; + } - $filter_templates = false; - - $template = alerts_get_alert_templates(); - - if ($template !== false) { - $data['type'] = 'array'; - $data['data'] = $template; - } - - if (!$template) { - returnError('error_get_all_alert_templates', - __('Error getting all alert templates.')); - } - else { - returnData('csv', $data, $separator); - } + if (!check_acl($config['id_user'], 0, 'LM')) { + returnError('forbidden', 'csv'); + return; + } + + $filter_templates = false; + + $template = alerts_get_alert_templates(); + + if ($template !== false) { + $data['type'] = 'array'; + $data['data'] = $template; + } + + if (!$template) { + returnError( + 'error_get_all_alert_templates', + __('Error getting all alert templates.') + ); + } else { + returnData('csv', $data, $separator); + } } + +function api_get_all_alert_commands($thrash1, $thrash2, $other, $thrash3) +{ + global $config; + + if (defined('METACONSOLE')) { + return; + } + + if (!isset($other['data'][0])) { + $separator = ';'; + // by default + } else { + $separator = $other['data'][0]; + } + + if (!check_acl($config['id_user'], 0, 'LM')) { + returnError('forbidden', 'csv'); + return; + } + + $commands = db_get_all_rows_filter( + 'talert_commands', + ['id_group' => array_keys(users_get_groups(false, 'LM'))] + ); + + if ($commands === false) { + $commands = []; + } + + if ($commands !== false) { + $data['type'] = 'array'; + $data['data'] = $commands; + } + + if (!$commands) { + returnError( + 'error_get_all_alert_commands', + __('Error getting all alert commands.') + ); + } else { + returnData('csv', $data, $separator); + } +} + + /** * Get an alert tamplate, and print the result like a csv. - * - * @param string $id_template Id of the template to get. + * + * @param string $id_template Id of the template to get. * @param $thrash1 Don't use. - * @param array $other Don't use - * - * example: - * - * api.php?op=get&op2=alert_template&id=25 - * + * @param array $other Don't use + * + * example: + * + * api.php?op=get&op2=alert_template&id=25 + * * @param $thrash3 Don't use */ -function api_get_alert_template($id_template, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - $filter_templates = false; - - if ($id_template != "") { - $result_template = alerts_get_alert_template_name($id_template); - - if (!$result_template) { - returnError('error_get_alert_template', - __('Error getting alert template. Id_template doesn\'t exist.')); - return; - } - - $filter_templates = array('id' => $id_template); - } - - $template = alerts_get_alert_templates($filter_templates, - array('id', 'name', 'description', 'id_alert_action', 'type', 'id_group')); - - if ($template !== false) { - $data['type'] = 'array'; - $data['data'] = $template; - } - - if (!$template) { - returnError('error_get_alert_template', - __('Error getting alert template.')); - } - else { - returnData('csv', $data, ';'); - } +function api_get_alert_template($id_template, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + $filter_templates = false; + + if ($id_template != '') { + $result_template = alerts_get_alert_template_name($id_template); + + if (!$result_template) { + returnError( + 'error_get_alert_template', + __('Error getting alert template. Id_template doesn\'t exist.') + ); + return; + } + + $filter_templates = ['id' => $id_template]; + } + + $template = alerts_get_alert_templates( + $filter_templates, + [ + 'id', + 'name', + 'description', + 'id_alert_action', + 'type', + 'id_group', + ] + ); + + if ($template !== false) { + $data['type'] = 'array'; + $data['data'] = $template; + } + + if (!$template) { + returnError( + 'error_get_alert_template', + __('Error getting alert template.') + ); + } else { + returnData('csv', $data, ';'); + } } + +/** + * List of alert actions. + * + * @param array $other it's array, $other as param is ; and separator (pass in param + * othermode as othermode=url_encode_separator_) + * @param $returnType (csv, string or json). + * + * example: + * + * api.php?op=get&op2=alert_actions&apipass=1234&user=admin&pass=pandora&other=Create|;&other_mode=url_encode_separator_|&return_type=json + */ +function api_get_alert_actions($thrash1, $thrash2, $other, $returnType) +{ + global $config; + if (!check_acl($config['id_user'], 0, 'LM')) { + returnError('forbidden', 'string'); + return; + } + + if (!isset($other['data'][0])) { + $other['data'][1] = ''; + } + + if (!isset($other['data'][1])) { + $separator = ';'; + // by default + } else { + $separator = $other['data'][1]; + } + + $action_name = $other['data'][0]; + + $filter = []; + if (!is_user_admin($config['id_user'])) { + $filter['talert_actions.id_group'] = array_keys(users_get_groups(false, 'LM')); + } + + $filter['talert_actions.name'] = "%$action_name%"; + + $actions = db_get_all_rows_filter( + 'talert_actions INNER JOIN talert_commands ON talert_actions.id_alert_command = talert_commands.id', + $filter, + 'talert_actions.id, talert_actions.name' + ); + if ($actions === false) { + $actions = []; + } + + if ($actions !== false) { + $data['type'] = 'array'; + $data['data'] = $actions; + } + + if (!$actions) { + returnError( + 'error_get_alert_actions', + __('Error getting alert actions.') + ); + } else { + returnData($returnType, $data, $separator); + } +} + + /** * Get module groups, and print all the result like a csv. * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, but only is available. - * example: + * @param array $other it's array, but only is available. + * example: * - * api.php?op=get&op2=module_groups&return_type=csv&other=; + * api.php?op=get&op2=module_groups&return_type=csv&other=; * * @param $thrash3 Don't use. */ -function api_get_module_groups($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_get_module_groups($thrash1, $thrash2, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config["id_user"], 0, "PM")) { - returnError('forbidden', 'csv'); - return; - } + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'csv'); + return; + } - if (!isset($other['data'][0])) - $separator = ';'; // by default - else - $separator = $other['data'][0]; - - $filter = false; - - $module_groups = @db_get_all_rows_filter ('tmodule_group', $filter); - - if ($module_groups !== false) { - $data['type'] = 'array'; - $data['data'] = $module_groups; - } - - if (!$module_groups) { - returnError('error_get_module_groups', __('Error getting module groups.')); - } - else { - returnData('csv', $data, $separator); - } + if (!isset($other['data'][0])) { + $separator = ';'; + // by default + } else { + $separator = $other['data'][0]; + } + + $filter = false; + + $module_groups = @db_get_all_rows_filter('tmodule_group', $filter); + + if ($module_groups !== false) { + $data['type'] = 'array'; + $data['data'] = $module_groups; + } + + if (!$module_groups) { + returnError('error_get_module_groups', __('Error getting module groups.')); + } else { + returnData('csv', $data, $separator); + } } + /** * Get plugins, and print all the result like a csv. * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, but only is available. - * example: + * @param array $other it's array, but only is available. + * example: * - * api.php?op=get&op2=plugins&return_type=csv&other=; + * api.php?op=get&op2=plugins&return_type=csv&other=; * * @param $thrash3 Don't use. */ -function api_get_plugins($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_get_plugins($thrash1, $thrash2, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config["id_user"], 0, "PM")) { - returnError('forbidden', 'csv'); - return; - } + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'csv'); + return; + } - if (!isset($other['data'][0])) - $separator = ';'; // by default - else - $separator = $other['data'][0]; - - $filter = false; - $field_list = array( 'id', 'name', 'description', - 'max_timeout', 'max_retries', - 'execute', 'net_dst_opt', - 'net_port_opt', 'user_opt', - 'pass_opt', 'plugin_type', - 'macros', 'parameters'); - - $plugins = @db_get_all_rows_filter ('tplugin', $filter, $field_list); - - if ($plugins !== false) { - $data['type'] = 'array'; - $data['data'] = $plugins; - } - - if (!$plugins) { - returnError('error_get_plugins', __('Error getting plugins.')); - } - else { - returnData('csv', $data, $separator); - } + if (!isset($other['data'][0])) { + $separator = ';'; + // by default + } else { + $separator = $other['data'][0]; + } + + $filter = false; + $field_list = [ + 'id', + 'name', + 'description', + 'max_timeout', + 'max_retries', + 'execute', + 'net_dst_opt', + 'net_port_opt', + 'user_opt', + 'pass_opt', + 'plugin_type', + 'macros', + 'parameters', + ]; + + $plugins = @db_get_all_rows_filter('tplugin', $filter, $field_list); + + if ($plugins !== false) { + $data['type'] = 'array'; + $data['data'] = $plugins; + } + + if (!$plugins) { + returnError('error_get_plugins', __('Error getting plugins.')); + } else { + returnData('csv', $data, $separator); + } } + /** * Create a network module from a network component. And return the id of new module. - * - * @param string $agent_name The name of the agent where the module will be created - * @param string $component_name The name of the network component + * + * @param string $agent_name The name of the agent where the module will be created + * @param string $component_name The name of the network component * @param $thrash1 Don't use * @param $thrash2 Don't use */ -function api_set_create_network_module_from_component($agent_name, $component_name, $thrash1, $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; - } +function api_set_create_network_module_from_component($agent_name, $component_name, $thrash1, $thrash2) +{ + if (defined('METACONSOLE')) { + return; + } - 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); - - if (!$component) { - returnError('error_network_module_from_component', __('Error creating module from network component. Network component doesn\'t exist.')); - return; - } - - // Adapt fields to module structure - unset($component['id_nc']); - unset($component['id_group']); - $component['id_tipo_modulo'] = $component['type']; - unset($component['type']); - $component['descripcion'] = $component['description']; - unset($component['description']); - unset($component['name']); - $component['ip_target'] = agents_get_address($agent_id); - - // Create module - $module_id = modules_create_agent_module ($agent_id, $component_name, $component, true); - - if (!$module_id) { - returnError('error_network_module_from_component', __('Error creating module from network component. Error creating module.')); - return; - } - - return $module_id; + $agent_id = agents_get_agent_id($agent_name); + if (!util_api_check_agent_and_print_error($agent_id, 'string', 'AW')) { + return; + } + + 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); + + if (!$component) { + returnError('error_network_module_from_component', __('Error creating module from network component. Network component doesn\'t exist.')); + return; + } + + // Adapt fields to module structure + unset($component['id_nc']); + unset($component['id_group']); + $component['id_tipo_modulo'] = $component['type']; + unset($component['type']); + $component['descripcion'] = $component['description']; + unset($component['description']); + unset($component['name']); + $component['ip_target'] = agents_get_address($agent_id); + + // Create module + $module_id = modules_create_agent_module($agent_id, $component_name, $component, true); + + if (!$module_id) { + returnError('error_network_module_from_component', __('Error creating module from network component. Error creating module.')); + return; + } + + return $module_id; } + /** * Assign a module to an alert template. And return the id of new relationship. - * - * @param string $id_template Name of alert template to add. + * + * @param string $id_template Name of alert template to add. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=create_module_template&id=1&other=1|10&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=create_module_template&id=1&other=1|10&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_create_module_template($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_module_to_template', - __('Error assigning module to template. Id_template cannot be left blank.')); - return; - } - - if ($other['data'][0] == "") { - returnError('error_module_to_template', - __('Error assigning module to template. Id_module cannot be left blank.')); - return; - } - - if ($other['data'][1] == "") { - returnError('error_module_to_template', - __('Error assigning module to template. Id_agent cannot be left blank.')); - return; - } - - $id_module = $other['data'][0]; - $id_agent = $other['data'][1]; +function api_set_create_module_template($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error($id_agent, 'string', "AW")) { - return; - } - - $result_template = alerts_get_alert_template($id); - - if (!$result_template) { - returnError('error_module_to_template', - __('Error assigning module to template. Id_template doensn\'t exists.')); - return; - } - - $result_agent = agents_get_name($id_agent); - - if (!$result_agent) { - returnError('error_module_to_template', __('Error assigning module to template. Id_agent doesn\'t exist.')); - return; - } - - $result_module = db_get_value ('nombre', 'tagente_modulo', 'id_agente_modulo', (int) $id_module); - - if (!$result_module) { - returnError('error_module_to_template', __('Error assigning module to template. Id_module doesn\'t exist.')); - return; - } - - $id_template_module = alerts_create_alert_agent_module($id_module, $id); - - if (is_error($id_template_module)) { - // TODO: Improve the error returning more info - returnError('error_module_to_template', __('Error assigning module to template.')); - } - else { - returnData('string', array('type' => 'string', 'data' => $id_template_module)); - } + if ($id == '') { + returnError( + 'error_module_to_template', + __('Error assigning module to template. Id_template cannot be left blank.') + ); + return; + } + + if ($other['data'][0] == '') { + returnError( + 'error_module_to_template', + __('Error assigning module to template. Id_module cannot be left blank.') + ); + return; + } + + if ($other['data'][1] == '') { + returnError( + 'error_module_to_template', + __('Error assigning module to template. Id_agent cannot be left blank.') + ); + return; + } + + $id_module = $other['data'][0]; + $id_agent = $other['data'][1]; + + if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AW')) { + return; + } + + $result_template = alerts_get_alert_template($id); + + if (!$result_template) { + returnError( + 'error_module_to_template', + __('Error assigning module to template. Id_template doensn\'t exists.') + ); + return; + } + + $result_agent = agents_get_name($id_agent); + + if (!$result_agent) { + returnError('error_module_to_template', __('Error assigning module to template. Id_agent doesn\'t exist.')); + return; + } + + $result_module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', (int) $id_module); + + if (!$result_module) { + returnError('error_module_to_template', __('Error assigning module to template. Id_module doesn\'t exist.')); + return; + } + + $id_template_module = alerts_create_alert_agent_module($id_module, $id); + + if (is_error($id_template_module)) { + // TODO: Improve the error returning more info + returnError('error_module_to_template', __('Error assigning module to template.')); + } else { + returnData('string', ['type' => 'string', 'data' => $id_template_module]); + } } -/** - * Delete an module assigned to a template. And return a message with the result of the operation. - * - * @param string $id Id of the relationship between module and template (talert_template_modules) to delete. - * @param $thrash1 Don't use. - * @param array $other Don't use - * - * example: - * - * api.php?op=set&op2=delete_module_template&id=38 - * - * @param $thrash3 Don't use - */ -function api_set_delete_module_template($id, $thrash1, $other, $thrash3) { - global $config; - - if (defined ('METACONSOLE')) { - return; - } - - if (!check_acl($config['id_user'], 0, "AD")) { - returnError('forbidden', 'string'); - return; - } - - if ($id == "") { - returnError('error_delete_module_template', __('Error deleting module template. Id_module_template cannot be left blank.')); - return; - } - - $result_module_template = alerts_get_alert_agent_module($id); - - if (!$result_module_template) { - returnError('error_delete_module_template', __('Error deleting module template. Id_module_template doesn\'t exist.')); - return; - } - - $result = alerts_delete_alert_agent_module($id); - - if ($result == 0) { - // TODO: Improve the error returning more info - returnError('error_delete_module_template', __('Error deleting module template.')); - } - else { - returnData('string', array('type' => 'string', 'data' => __('Correct deleting of module template.'))); - } -} /** * Delete an module assigned to a template. And return a message with the result of the operation. * - * @param $id Agent Name - * @param $id2 Alert Template Name - * @param $other [0] : Module Name - * @param $trash1 Don't use + * @param string $id Id of the relationship between module and template (talert_template_modules) to delete. + * @param $thrash1 Don't use. + * @param array $other Don't use + * + * example: + * + * api.php?op=set&op2=delete_module_template&id=38 + * + * @param $thrash3 Don't use + */ +function api_set_delete_module_template($id, $thrash1, $other, $thrash3) +{ + global $config; + + if (defined('METACONSOLE')) { + return; + } + + if (!check_acl($config['id_user'], 0, 'AD')) { + returnError('forbidden', 'string'); + return; + } + + if ($id == '') { + returnError('error_delete_module_template', __('Error deleting module template. Id_module_template cannot be left blank.')); + return; + } + + $result_module_template = alerts_get_alert_agent_module($id); + + if (!$result_module_template) { + returnError('error_delete_module_template', __('Error deleting module template. Id_module_template doesn\'t exist.')); + return; + } + + $result = alerts_delete_alert_agent_module($id); + + if ($result == 0) { + // TODO: Improve the error returning more info + returnError('error_delete_module_template', __('Error deleting module template.')); + } else { + returnData('string', ['type' => 'string', 'data' => __('Correct deleting of module template.')]); + } +} + + +/** + * Delete an module assigned to a template. And return a message with the result of the operation. + * + * @param $id Agent Name + * @param $id2 Alert Template Name + * @param $other [0] : Module Name + * @param $trash1 Don't use * * example: * * api.php?op=set&op2=delete_module_template_by_names&id=my_latest_agent&id2=test_template&other=memfree - * */ -function api_set_delete_module_template_by_names($id, $id2, $other, $trash1) { - global $config; +function api_set_delete_module_template_by_names($id, $id2, $other, $trash1) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - $result = 0; + $result = 0; - if ($other['type'] != 'string') { - returnError('error_parameter', 'Error in the parameters.'); - return; - } + 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") - ) { - returnError('forbidden', 'string'); - return; - } + if (! check_acl($config['id_user'], 0, 'AD') + && ! check_acl($config['id_user'], 0, 'LM') + ) { + returnError('forbidden', 'string'); + return; + } - $idAgent = agents_get_agent_id($id); + $idAgent = agents_get_agent_id($id); - if (!util_api_check_agent_and_print_error($idAgent, 'string', "AD")) { - return; - } + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AD')) { + return; + } - $row = db_get_row_filter('talert_templates', array('name' => $id2)); - - if ($row === false) { - returnError('error_parameter', 'Error in the parameters.'); - return; - } - - $idTemplate = $row['id']; - $idActionTemplate = $row['id_alert_action']; - - $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', array('id_agente' => $idAgent, 'nombre' => $other['data'])); + $row = db_get_row_filter('talert_templates', ['name' => $id2]); - if ($idAgentModule === false) { - returnError('error_parameter', 'Error in the parameters.'); - return; - } + if ($row === false) { + returnError('error_parameter', 'Error in the parameters.'); + return; + } - $values = array( - 'id_agent_module' => $idAgentModule, - 'id_alert_template' => $idTemplate); + $idTemplate = $row['id']; + $idActionTemplate = $row['id_alert_action']; - $result = db_process_sql_delete ('talert_template_modules', $values); + $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $idAgent, 'nombre' => $other['data']]); - if ($result == 0) { - // TODO: Improve the error returning more info - returnError('error_delete_module_template_by_name', __('Error deleting module template.')); - } - else { - returnData('string', array('type' => 'string', 'data' => __('Correct deleting of module template.'))); - } + if ($idAgentModule === false) { + returnError('error_parameter', 'Error in the parameters.'); + 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.')]); + } } + /** * Validate all alerts. And return a message with the result of the operation. - * + * * @param string Don't use. * @param $thrash1 Don't use. - * @param array $other Don't use - * - * example: - * - * api.php?op=set&op2=validate_all_alerts - * + * @param array $other Don't use + * + * example: + * + * api.php?op=set&op2=validate_all_alerts + * * @param $thrash3 Don't use */ -function api_set_validate_all_alerts($id, $thrash1, $other, $thrash3) { - global $config; +function api_set_validate_all_alerts($id, $thrash1, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "LW")){ - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], 0, 'LW')) { + returnError('forbidden', 'string'); + return; + } - $agents = array(); - $raw_agents = agents_get_agents(false, 'id_agente'); - if ($raw_agents !== false) { - foreach ($raw_agents as $agent) { - $agents[] = $agent['id_agente']; - } - } + $agents = []; + $raw_agents = agents_get_agents(false, 'id_agente'); + if ($raw_agents !== false) { + foreach ($raw_agents as $agent) { + $agents[] = $agent['id_agente']; + } + } - $agents_string = implode(',', $agents); + $agents_string = implode(',', $agents); - $sql = sprintf (" + $sql = sprintf( + ' SELECT talert_template_modules.id FROM talert_template_modules INNER JOIN tagente_modulo t2 @@ -4948,2468 +5668,2912 @@ function api_set_validate_all_alerts($id, $thrash1, $other, $thrash3) { 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); + WHERE t3.id_agente in (%s)', + $agents_string + ); - $alerts = db_get_all_rows_sql($sql); - if ($alerts === false) $alerts = array(); + $alerts = db_get_all_rows_sql($sql); + if ($alerts === false) { + $alerts = []; + } - $total_alerts = count($alerts); - $count_results = 0; - foreach ($alerts as $alert) { - $result = alerts_validate_alert_agent_module($alert['id'], false); - - if ($result) { - $count_results++; - } - } - - if ($total_alerts > $count_results) { - $errors = $total_alerts - $count_results; - returnError('error_validate_all_alerts', __('Error validate all alerts. Failed ' . $errors . '.')); - } - else { - returnData('string', array('type' => 'string', 'data' => __('Correct validating of all alerts (total %d).', $count_results))); - } + $total_alerts = count($alerts); + $count_results = 0; + foreach ($alerts as $alert) { + $result = alerts_validate_alert_agent_module($alert['id'], false); + + if ($result) { + $count_results++; + } + } + + if ($total_alerts > $count_results) { + $errors = ($total_alerts - $count_results); + returnError('error_validate_all_alerts', __('Error validate all alerts. Failed '.$errors.'.')); + } else { + returnData('string', ['type' => 'string', 'data' => __('Correct validating of all alerts (total %d).', $count_results)]); + } } + /** * Validate all policy alerts. And return a message with the result of the operation. - * + * * @param string Don't use. * @param $thrash1 Don't use. - * @param array $other Don't use - * - * example: - * - * api.php?op=set&op2=validate_all_policy_alerts - * + * @param array $other Don't use + * + * example: + * + * api.php?op=set&op2=validate_all_policy_alerts + * * @param $thrash3 Don't use */ -function api_set_validate_all_policy_alerts($id, $thrash1, $other, $thrash3) { - global $config; +function api_set_validate_all_policy_alerts($id, $thrash1, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "AW")) { - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'string'); + return; + } - # Get all policies - $policies = enterprise_hook('policies_get_policies', array(false, false, false)); - - if ($duplicated === ENTERPRISE_NOT_HOOK) { - returnError('error_validate_all_policy_alerts', __('Error validating all alert policies.')); - return; - } - - // Count of valid results - $total_alerts = 0; - $count_results = 0; - // Check all policies - foreach ($policies as $policy) { - $policy_alerts = array(); - $policy_alerts = enterprise_hook('policies_get_alerts', array($policy['id'], false, false)); + // Get all policies + $policies = enterprise_hook('policies_get_policies', [false, false, false]); - // Number of alerts in this policy - if ($policy_alerts != false) { - $partial_alerts = count($policy_alerts); - // Added alerts of this policy to the total - $total_alerts = $total_alerts + $partial_alerts; - } - - $result_pol_alerts = array(); - foreach ($policy_alerts as $policy_alert) { - $result_pol_alerts[] = $policy_alert['id']; - } - - $id_pol_alerts = implode(',', $result_pol_alerts); - - // If the policy has alerts - if (count($result_pol_alerts) != 0) { - $sql = sprintf (" + if ($duplicated === ENTERPRISE_NOT_HOOK) { + returnError('error_validate_all_policy_alerts', __('Error validating all alert policies.')); + return; + } + + // Count of valid results + $total_alerts = 0; + $count_results = 0; + // Check all policies + foreach ($policies as $policy) { + $policy_alerts = []; + $policy_alerts = enterprise_hook('policies_get_alerts', [$policy['id'], false, false]); + + // Number of alerts in this policy + if ($policy_alerts != false) { + $partial_alerts = count($policy_alerts); + // Added alerts of this policy to the total + $total_alerts = ($total_alerts + $partial_alerts); + } + + $result_pol_alerts = []; + foreach ($policy_alerts as $policy_alert) { + $result_pol_alerts[] = $policy_alert['id']; + } + + $id_pol_alerts = implode(',', $result_pol_alerts); + + // If the policy has alerts + if (count($result_pol_alerts) != 0) { + $sql = sprintf( + ' SELECT id FROM talert_template_modules - WHERE id_policy_alerts IN (%s)", - $id_pol_alerts); - - $id_alerts = db_get_all_rows_sql($sql); - - $result_alerts = array(); - foreach ($id_alerts as $id_alert) { - $result_alerts[] = $id_alert['id']; - } - - // Validate alerts of these modules - foreach ($result_alerts as $result_alert) { - $result = alerts_validate_alert_agent_module($result_alert, true); - - if ($result) { - $count_results++; - } - } - } - - } - - // Check results - if ($total_alerts > $count_results) { - $errors = $total_alerts - $count_results; - returnError('error_validate_all_alerts', __('Error validate all policy alerts. Failed ' . $errors . '.')); - } - else { - returnData('string', array('type' => 'string', 'data' => __('Correct validating of all policy alerts.'))); - } + WHERE id_policy_alerts IN (%s)', + $id_pol_alerts + ); + + $id_alerts = db_get_all_rows_sql($sql); + + $result_alerts = []; + foreach ($id_alerts as $id_alert) { + $result_alerts[] = $id_alert['id']; + } + + // Validate alerts of these modules + foreach ($result_alerts as $result_alert) { + $result = alerts_validate_alert_agent_module($result_alert, true); + + if ($result) { + $count_results++; + } + } + } + } + + // Check results + if ($total_alerts > $count_results) { + $errors = ($total_alerts - $count_results); + returnError('error_validate_all_alerts', __('Error validate all policy alerts. Failed '.$errors.'.')); + } else { + returnData('string', ['type' => 'string', 'data' => __('Correct validating of all policy alerts.')]); + } } + /** * Stop a schedule downtime. And return a message with the result of the operation. - * - * @param string $id Id of the downtime to stop. + * + * @param string $id Id of the downtime to stop. * @param $thrash1 Don't use. - * @param array $other Don't use - * - * example: - * - * api.php?op=set&op2=stop_downtime&id=38 - * + * @param array $other Don't use + * + * example: + * + * api.php?op=set&op2=stop_downtime&id=38 + * * @param $thrash3 Don't use */ -function api_set_stop_downtime($id, $thrash1, $other, $thrash3) { - global $config; +function api_set_stop_downtime($id, $thrash1, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if(!check_acl($config['id_user'], 0, "AD")) { - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], 0, 'AD')) { + returnError('forbidden', 'string'); + return; + } - if ($id == "") { - returnError('error_stop_downtime', __('Error stopping downtime. Id_downtime cannot be left blank.')); - return; - } - - $date_time_stop = get_system_time(); - - $values = array(); - $values['date_to'] = $date_time_stop; - - $result_update = db_process_sql_update('tplanned_downtime', $values, array ('id' => $id)); - if ($result_update == 0) { - returnError('error_stop_downtime', __('No action has been taken.')); - } elseif ($result_update < 0) { - returnError('error_stop_downtime', __('Error stopping downtime.')); - } else { - returnData('string', array('type' => 'string', 'data' => __('Downtime stopped.'))); - } + if ($id == '') { + returnError('error_stop_downtime', __('Error stopping downtime. Id_downtime cannot be left blank.')); + return; + } + + $date_time_stop = get_system_time(); + + $values = []; + $values['date_to'] = $date_time_stop; + + $result_update = db_process_sql_update('tplanned_downtime', $values, ['id' => $id]); + if ($result_update == 0) { + returnError('error_stop_downtime', __('No action has been taken.')); + } else if ($result_update < 0) { + returnError('error_stop_downtime', __('Error stopping downtime.')); + } else { + returnData('string', ['type' => 'string', 'data' => __('Downtime stopped.')]); + } } -function api_set_add_tag_module($id, $id2, $thrash1, $thrash2) { - if (defined ('METACONSOLE')) { - return; - } - $id_module = $id; - $id_tag = $id2; +function api_set_add_tag_module($id, $id2, $thrash1, $thrash2) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error(modules_get_agentmodule_agent($id_module), 'string', "AW")) { - return; - } + $id_module = $id; + $id_tag = $id2; - $exists = db_get_row_filter('ttag_module', - array('id_agente_modulo' => $id_module, - 'id_tag' => $id_tag)); + if (!util_api_check_agent_and_print_error(modules_get_agentmodule_agent($id_module), 'string', 'AW')) { + return; + } - if (empty($exists)) { - db_process_sql_insert('ttag_module', - array('id_agente_modulo' => $id_module, - 'id_tag' => $id_tag)); - - $exists = db_get_row_filter('ttag_module', - array('id_agente_modulo' => $id_module, - 'id_tag' => $id_tag)); - } - - if (empty($exists)) - returnError('error_set_tag_module', 'Error set tag module.'); - else - returnData('string', - array('type' => 'string', 'data' => 1)); + $exists = db_get_row_filter( + 'ttag_module', + [ + 'id_agente_modulo' => $id_module, + 'id_tag' => $id_tag, + ] + ); + + if (empty($exists)) { + db_process_sql_insert( + 'ttag_module', + [ + 'id_agente_modulo' => $id_module, + 'id_tag' => $id_tag, + ] + ); + + $exists = db_get_row_filter( + 'ttag_module', + [ + 'id_agente_modulo' => $id_module, + 'id_tag' => $id_tag, + ] + ); + } + + if (empty($exists)) { + returnError('error_set_tag_module', 'Error set tag module.'); + } else { + returnData( + 'string', + [ + 'type' => 'string', + 'data' => 1, + ] + ); + } } -function api_set_remove_tag_module($id, $id2, $thrash1, $thrash2) { - if (defined ('METACONSOLE')) { - return; - } - - $id_module = $id; - $id_tag = $id2; - if (!util_api_check_agent_and_print_error(modules_get_agentmodule_agent($id_module), 'string', "AW")) { - return; - } +function api_set_remove_tag_module($id, $id2, $thrash1, $thrash2) +{ + if (defined('METACONSOLE')) { + return; + } - $row = db_get_row_filter('ttag_module', - array('id_agente_modulo' => $id_module, - 'id_tag' => $id_tag)); - - $correct = 0; - - if (!empty($row)) { - - // Avoid to delete from policies - - if ($row['id_policy_module'] == 0) { - $correct = db_process_sql_delete('ttag_module', - array('id_agente_modulo' => $id_module, - 'id_tag' => $id_tag)); - } - } - - returnData('string', - array('type' => 'string', 'data' => $correct)); + $id_module = $id; + $id_tag = $id2; + + if (!util_api_check_agent_and_print_error(modules_get_agentmodule_agent($id_module), 'string', 'AW')) { + return; + } + + $row = db_get_row_filter( + 'ttag_module', + [ + 'id_agente_modulo' => $id_module, + 'id_tag' => $id_tag, + ] + ); + + $correct = 0; + + if (!empty($row)) { + // Avoid to delete from policies + if ($row['id_policy_module'] == 0) { + $correct = db_process_sql_delete( + 'ttag_module', + [ + 'id_agente_modulo' => $id_module, + 'id_tag' => $id_tag, + ] + ); + } + } + + returnData( + 'string', + [ + 'type' => 'string', + 'data' => $correct, + ] + ); } -function api_set_tag($id, $thrash1, $other, $thrash3) { - global $config; - if (defined ('METACONSOLE')) { - return; - } +function api_set_tag($id, $thrash1, $other, $thrash3) +{ + global $config; - if (!check_acl($config['id_user'], 0, "PM")) { - returnError('forbidden', 'string'); - return; - } + if (defined('METACONSOLE')) { + return; + } - $values = array(); - $values['name'] = $id; - $values['description'] = $other['data'][0]; - $values['url'] = $other['data'][1]; - $values['email'] = $other['data'][2]; - $values['phone'] = $other['data'][3]; - - $id_tag = tags_create_tag($values); - - if (empty($id_tag)) - returnError('error_set_tag', __('Error set tag.')); - else - returnData('string', - array('type' => 'string', 'data' => $id_tag)); + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } + + $values = []; + $values['name'] = $id; + $values['description'] = $other['data'][0]; + $values['url'] = $other['data'][1]; + $values['email'] = $other['data'][2]; + $values['phone'] = $other['data'][3]; + + $id_tag = tags_create_tag($values); + + if (empty($id_tag)) { + returnError('error_set_tag', __('Error set tag.')); + } else { + returnData( + 'string', + [ + 'type' => 'string', + 'data' => $id_tag, + ] + ); + } } + /** * Return all planned downtime. * * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=all_planned_downtimes&other=test|0|quiet|periodically|weekly&other_mode=url_encode_separator_|&return_type=json - * + * @param array $other it's array, $other as param is ;;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=all_planned_downtimes&other=test|0|quiet|periodically|weekly&other_mode=url_encode_separator_|&return_type=json + * * @param type of return json or csv. */ -function api_get_all_planned_downtimes ($thrash1, $thrash2, $other, $returnType = 'json') { - global $config; - if (defined ('METACONSOLE')) { - return; - } +function api_get_all_planned_downtimes($thrash1, $thrash2, $other, $returnType='json') +{ + global $config; - if(!check_acl($config['id_user'], 0, "AR")) { - returnError('forbidden', $returnType); - return; - } + if (defined('METACONSOLE')) { + return; + } - $values = array(); - $values = array( - "name LIKE '%".$other['data'][0]."%'" - ); - - if (isset($other['data'][1]) && ($other['data'][1] != false )) - $values['id_group'] = $other['data'][1]; - if (isset($other['data'][2]) && ($other['data'][2] != false)) - $values['type_downtime'] = $other['data'][2]; - if (isset($other['data'][3]) && ($other['data'][3]!= false) ) - $values['type_execution'] = $other['data'][3]; - if (isset($other['data'][4]) && ($other['data'][4] != false) ) - $values['type_periodicity'] = $other['data'][4]; - - - $returned = all_planned_downtimes($values); + if (!check_acl($config['id_user'], 0, 'AR')) { + returnError('forbidden', $returnType); + return; + } - if ($returned === false) { - returnError("error_get_all_planned_downtimes", __('No planned downtime retrieved')); - return; - } + $values = []; + $values = ["name LIKE '%".$other['data'][0]."%'"]; - returnData($returnType, - array('type' => 'array', 'data' => $returned)); + if (isset($other['data'][1]) && ($other['data'][1] != false )) { + $values['id_group'] = $other['data'][1]; + } + + if (isset($other['data'][2]) && ($other['data'][2] != false)) { + $values['type_downtime'] = $other['data'][2]; + } + + if (isset($other['data'][3]) && ($other['data'][3] != false)) { + $values['type_execution'] = $other['data'][3]; + } + + if (isset($other['data'][4]) && ($other['data'][4] != false)) { + $values['type_periodicity'] = $other['data'][4]; + } + + $returned = all_planned_downtimes($values); + + if ($returned === false) { + returnError('error_get_all_planned_downtimes', __('No planned downtime retrieved')); + return; + } + + returnData( + $returnType, + [ + 'type' => 'array', + 'data' => $returned, + ] + ); } + /** * Return all items of planned downtime. * * @param $id id of planned downtime. - * @param array $other it's array, $other as param is ;;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * - * example: - * - * api.php?op=get&op2=planned_downtimes_items&other=test|0|quiet|periodically|weekly&other_mode=url_encode_separator_|&return_type=json - * + * @param array $other it's array, $other as param is ;;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * + * example: + * + * api.php?op=get&op2=planned_downtimes_items&other=test|0|quiet|periodically|weekly&other_mode=url_encode_separator_|&return_type=json + * * @param type of return json or csv. */ -function api_get_planned_downtimes_items ($thrash1, $thrash2, $other, $returnType = 'json') { - global $config; - if (defined ('METACONSOLE')) { - return; - } - - if(!check_acl($config['id_user'], 0, "AR")) { - returnError('forbidden', $returnType); - return; - } - - $values = array(); - $values = array( - "name LIKE '%".$other['data'][0]."%'" - ); - - if (isset($other['data'][1]) && ($other['data'][1] != false )) - $values['id_group'] = $other['data'][1]; - if (isset($other['data'][2]) && ($other['data'][2] != false)) - $values['type_downtime'] = $other['data'][2]; - if (isset($other['data'][3]) && ($other['data'][3]!= false) ) - $values['type_execution'] = $other['data'][3]; - if (isset($other['data'][4]) && ($other['data'][4] != false) ) - $values['type_periodicity'] = $other['data'][4]; - - - $returned = all_planned_downtimes($values); - - $is_quiet = false; - $return = array('list_index'=>array('id_agents','id_downtime','all_modules')); - - foreach ($returned as $downtime) { - if ($downtime['type_downtime'] === 'quiet') - $is_quiet = true; - - $filter['id_downtime'] = $downtime['id']; - - $items = planned_downtimes_items ($filter); - if ($items !== false) $return[] = $items; - } - - // If the header is the unique element in the array, return an error - if (count($return) == 1) { - returnError('no_data_to_show', $returnType); - return; - } +function api_get_planned_downtimes_items($thrash1, $thrash2, $other, $returnType='json') +{ + global $config; - if ($is_quiet) - $return['list_index'][] = 'modules'; - - if ( $returnType == 'json' ) - unset($return['list_index']); - - returnData($returnType, - array('type' => 'array', 'data' => $return)); + if (defined('METACONSOLE')) { + return; + } + + if (!check_acl($config['id_user'], 0, 'AR')) { + returnError('forbidden', $returnType); + return; + } + + $values = []; + $values = ["name LIKE '%".$other['data'][0]."%'"]; + + if (isset($other['data'][1]) && ($other['data'][1] != false )) { + $values['id_group'] = $other['data'][1]; + } + + if (isset($other['data'][2]) && ($other['data'][2] != false)) { + $values['type_downtime'] = $other['data'][2]; + } + + if (isset($other['data'][3]) && ($other['data'][3] != false)) { + $values['type_execution'] = $other['data'][3]; + } + + if (isset($other['data'][4]) && ($other['data'][4] != false)) { + $values['type_periodicity'] = $other['data'][4]; + } + + $returned = all_planned_downtimes($values); + + $is_quiet = false; + $return = [ + 'list_index' => [ + 'id_agents', + 'id_downtime', + 'all_modules', + ], + ]; + + foreach ($returned as $downtime) { + if ($downtime['type_downtime'] === 'quiet') { + $is_quiet = true; + } + + $filter['id_downtime'] = $downtime['id']; + + $items = planned_downtimes_items($filter); + if ($items !== false) { + $return[] = $items; + } + } + + // If the header is the unique element in the array, return an error + if (count($return) == 1) { + returnError('no_data_to_show', $returnType); + return; + } + + if ($is_quiet) { + $return['list_index'][] = 'modules'; + } + + if ($returnType == 'json') { + unset($return['list_index']); + } + + returnData( + $returnType, + [ + 'type' => 'array', + 'data' => $return, + ] + ); } + /** * Delete planned downtime. * * @param $id id of planned downtime. * @param $thrash1 not use. * @param $thrash2 not use. - * + * * api.php?op=set&op2=planned_downtimes_deleted &id=10 - * + * * @param type of return json or csv. */ -function api_set_planned_downtimes_deleted ($id, $thrash1, $thrash2, $returnType) { - global $config; - if (defined ('METACONSOLE')) { - return; - } +function api_set_planned_downtimes_deleted($id, $thrash1, $thrash2, $returnType) +{ + global $config; - if(!check_acl($config['id_user'], 0, "AD")) { - returnError('forbidden', $returnType); - return; - } - - $values = array(); - $values = array( - 'id_downtime' => $id - ); - - $returned = delete_planned_downtimes($values); - - returnData($returnType, - array('type' => 'string', 'data' => $returned)); + if (defined('METACONSOLE')) { + return; + } + + if (!check_acl($config['id_user'], 0, 'AD')) { + returnError('forbidden', $returnType); + return; + } + + $values = []; + $values = ['id_downtime' => $id]; + + $returned = delete_planned_downtimes($values); + + returnData( + $returnType, + [ + 'type' => 'string', + 'data' => $returned, + ] + ); } + /** * Create a new planned downtime. - * + * * @param $id name of planned downtime. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;;;; - * ;;;;;;;; - * ;;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=planned_downtimes_created&id=pepito&other=testing|08-22-2015|08-31-2015|0|1|1|1|1|1|1|1|17:06:00|19:06:00|1|31|quiet|periodically|weekly&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;;;; + * ;;;;;;;; + * ;;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=planned_downtimes_created&id=pepito&other=testing|08-22-2015|08-31-2015|0|1|1|1|1|1|1|1|17:06:00|19:06:00|1|31|quiet|periodically|weekly&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_set_planned_downtimes_created ($id, $thrash1, $other, $thrash3) { - global $config; - if (defined ('METACONSOLE')) { - return; - } +function api_set_planned_downtimes_created($id, $thrash1, $other, $thrash3) +{ + global $config; - if (!check_acl($config['id_user'], 0, "AD")){ - returnError('forbidden', 'string'); - return; - } + if (defined('METACONSOLE')) { + return; + } - $date_from = strtotime(html_entity_decode($other['data'][1])); - $date_to = strtotime(html_entity_decode($other['data'][2])); + if (!check_acl($config['id_user'], 0, 'AD')) { + returnError('forbidden', 'string'); + return; + } - $values = array(); - $values['name'] = $id; - $values = array( - 'name' => $id, - 'description' => $other['data'][0], - 'date_from' => $date_from, - 'date_to' => $date_to, - 'id_group' => $other['data'][3], - 'monday' => $other['data'][4], - 'tuesday' => $other['data'][5], - 'wednesday' => $other['data'][6], - 'thursday' => $other['data'][7], - 'friday' => $other['data'][8], - 'saturday' => $other['data'][9], - 'sunday' => $other['data'][10], - 'periodically_time_from' => $other['data'][11], - 'periodically_time_to' => $other['data'][12], - 'periodically_day_from' => $other['data'][13], - 'periodically_day_to' => $other['data'][14], - 'type_downtime' => $other['data'][15], - 'type_execution' => $other['data'][16], - 'type_periodicity' => $other['data'][17], - 'id_user' => $other['data'][18] - ); - - $returned = planned_downtimes_created($values); - - if (!$returned['return']) - returnError('error_set_planned_downtime', $returned['message'] ); - else - returnData('string', - array('type' => 'string', 'data' => $returned['return'])); + $date_from = strtotime(html_entity_decode($other['data'][1])); + $date_to = strtotime(html_entity_decode($other['data'][2])); + + $values = []; + $values['name'] = $id; + $values = [ + 'name' => $id, + 'description' => $other['data'][0], + 'date_from' => $date_from, + 'date_to' => $date_to, + 'id_group' => $other['data'][3], + 'monday' => $other['data'][4], + 'tuesday' => $other['data'][5], + 'wednesday' => $other['data'][6], + 'thursday' => $other['data'][7], + 'friday' => $other['data'][8], + 'saturday' => $other['data'][9], + 'sunday' => $other['data'][10], + 'periodically_time_from' => $other['data'][11], + 'periodically_time_to' => $other['data'][12], + 'periodically_day_from' => $other['data'][13], + 'periodically_day_to' => $other['data'][14], + 'type_downtime' => $other['data'][15], + 'type_execution' => $other['data'][16], + 'type_periodicity' => $other['data'][17], + 'id_user' => $other['data'][18], + ]; + + $returned = planned_downtimes_created($values); + + if (!$returned['return']) { + returnError('error_set_planned_downtime', $returned['message']); + } else { + returnData( + 'string', + [ + 'type' => 'string', + 'data' => $returned['return'], + ] + ); + } } + /** * Add new items to planned Downtime. - * + * * @param $id id of planned downtime. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ; - * in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=planned_downtimes_additem&id=123&other=1;2;3;4|Status;Unkown_modules&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ; + * in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=planned_downtimes_additem&id=123&other=1;2;3;4|Status;Unkown_modules&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use. */ -function api_set_planned_downtimes_additem ($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - $total_agents = explode(';',$other['data'][0]); - $agents = $total_agents; - $bad_agents = array(); - $i = 0; - foreach ($total_agents as $agent_id) { - $result_agent = agents_check_access_agent($agent_id, "AD"); - if ( !$result_agent ) { - $bad_agents[] = $agent_id; - unset($agents[$i]); - } - $i++; - } - - if ( isset($other['data'][1]) ) - $name_modules = explode(';',io_safe_output($other['data'][1])); - else - $name_modules = false; - - if ($name_modules) - $all_modules = false; - else - $all_modules = true; - - if ( !empty($agents) ) - $returned = planned_downtimes_add_items($id, $agents, $all_modules, $name_modules); - - if ( empty($agents) ) - returnError('error_set_planned_downtime_additem', "No agents to create planned downtime items"); - else{ - - if ( !empty($returned['bad_modules']) ) - $bad_modules = __("and this modules are doesn't exists or not applicable a this agents: ") . implode(", ",$returned['bad_modules']); - if ( !empty($returned['bad_agents']) ) - $bad_agent = __("and this agents are generate problems: ") . implode(", ", $returned['bad_agents']) ; - if ( !empty($bad_agents) ) - $agents_no_exists = __("and this agents with ids are doesn't exists: ") . implode(", ", $bad_agents) ; - returnData('string', - array('type' => 'string', 'data' => "Successfully created items " . $bad_agent . " " . $bad_modules . " " . $agents_no_exists)); - } + +function api_set_planned_downtimes_additem($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + $total_agents = explode(';', $other['data'][0]); + $agents = $total_agents; + $bad_agents = []; + $i = 0; + foreach ($total_agents as $agent_id) { + $result_agent = agents_check_access_agent($agent_id, 'AD'); + if (!$result_agent) { + $bad_agents[] = $agent_id; + unset($agents[$i]); + } + + $i++; + } + + if (isset($other['data'][1])) { + $name_modules = explode(';', io_safe_output($other['data'][1])); + } else { + $name_modules = false; + } + + if ($name_modules) { + $all_modules = false; + } else { + $all_modules = true; + } + + if (!empty($agents)) { + $returned = planned_downtimes_add_items($id, $agents, $all_modules, $name_modules); + } + + if (empty($agents)) { + returnError('error_set_planned_downtime_additem', 'No agents to create planned downtime items'); + } else { + if (!empty($returned['bad_modules'])) { + $bad_modules = __("and this modules are doesn't exists or not applicable a this agents: ").implode(', ', $returned['bad_modules']); + } + + if (!empty($returned['bad_agents'])) { + $bad_agent = __('and this agents are generate problems: ').implode(', ', $returned['bad_agents']); + } + + if (!empty($bad_agents)) { + $agents_no_exists = __("and this agents with ids are doesn't exists: ").implode(', ', $bad_agents); + } + + returnData( + 'string', + [ + 'type' => 'string', + 'data' => 'Successfully created items '.$bad_agent.' '.$bad_modules.' '.$agents_no_exists, + ] + ); + } } + /** * Add data module to policy. And return id from new module. - * - * @param string $id Id of the target policy. + * + * @param string $id Id of the target policy. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;; - * ;;;;; - * ;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example: - * - * api.php?op=set&op2=add_data_module_policy&id=1&other=data_module_policy_example_name~2~data%20module%20created%20by%20Api~2~0~0~50.00~10~20~180~~21~35~~1~module_begin%0dmodule_name%20pandora_process%0dmodule_type%20generic_data%0dmodule_exec%20ps%20aux%20|%20grep%20pandora%20|%20wc%20-l%0dmodule_end&other_mode=url_encode_separator_~ - * + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;; + * ;;;;; + * ;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example: + * + * api.php?op=set&op2=add_data_module_policy&id=1&other=data_module_policy_example_name~2~data%20module%20created%20by%20Api~2~0~0~50.00~10~20~180~~21~35~~1~module_begin%0dmodule_name%20pandora_process%0dmodule_type%20generic_data%0dmodule_exec%20ps%20aux%20|%20grep%20pandora%20|%20wc%20-l%0dmodule_end&other_mode=url_encode_separator_~ + * * @param $thrash3 Don't use */ -function api_set_add_data_module_policy($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_add_data_module_policy', __('Error adding data module to policy. Id_policy cannot be left blank.')); - return; - } - - if (enterprise_hook('policies_check_user_policy', array($id)) === false) { - returnError('forbidden', 'string'); - return; - } - - if ($other['data'][0] == "") { - returnError('error_add_data_module_policy', __('Error adding data module to policy. Module_name cannot be left blank.')); - return; - } - - // Check if the module is already in the policy - $name_module_policy = enterprise_hook('policies_get_modules', array($id, array('name'=>$other['data'][0]), 'name')); - - if ($name_module_policy === ENTERPRISE_NOT_HOOK) { - returnError('error_add_data_module_policy', __('Error adding data module to policy.')); - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][16]; - $disabled_types_event = json_encode($disabled_types_event); - - $values = array(); - $values['id_tipo_modulo'] = $other['data'][1]; - $values['description'] = $other['data'][2]; - $values['id_module_group'] = $other['data'][3]; - $values['min'] = $other['data'][4]; - $values['max'] = $other['data'][5]; - $values['post_process'] = $other['data'][6]; - $values['module_interval'] = $other['data'][7]; - $values['min_warning'] = $other['data'][8]; - $values['max_warning'] = $other['data'][9]; - $values['str_warning'] = $other['data'][10]; - $values['min_critical'] = $other['data'][11]; - $values['max_critical'] = $other['data'][12]; - $values['str_critical'] = $other['data'][13]; - $values['history_data'] = $other['data'][14]; - $values['configuration_data'] = $other['data'][15]; - $values['disabled_types_event'] = $disabled_types_event; - $values['module_macros'] = $other['data'][17]; - $values['min_ff_event'] = $other['data'][18]; - $values['each_ff'] = $other['data'][19]; - $values['min_ff_event_normal'] = $other['data'][20]; - $values['min_ff_event_warning'] = $other['data'][21]; - $values['min_ff_event_critical'] = $other['data'][22]; - $values['ff_timeout'] = $other['data'][23]; - - if ($name_module_policy !== false) { - if ($name_module_policy[0]['name'] == $other['data'][0]) { - returnError('error_add_data_module_policy', - __('Error adding data module to policy. The module is already in the policy.')); - return; - } - } - - $success = enterprise_hook('policies_create_module', - array($other['data'][0], $id, 1, $values, false)); - - if ($success) - //returnData('string', array('type' => 'string', 'data' => __('Data module added to policy. Is necessary to apply the policy in order to changes take effect.'))); - returnData('string', array('type' => 'string', 'data' => $success)); - else - returnError('error_add_data_module_policy', 'Error adding data module to policy.'); - +function api_set_add_data_module_policy($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($id == '') { + returnError('error_add_data_module_policy', __('Error adding data module to policy. Id_policy cannot be left blank.')); + return; + } + + if (enterprise_hook('policies_check_user_policy', [$id]) === false) { + returnError('forbidden', 'string'); + return; + } + + if ($other['data'][0] == '') { + returnError('error_add_data_module_policy', __('Error adding data module to policy. Module_name cannot be left blank.')); + return; + } + + // Check if the module is already in the policy + $name_module_policy = enterprise_hook('policies_get_modules', [$id, ['name' => $other['data'][0]], 'name']); + + if ($name_module_policy === ENTERPRISE_NOT_HOOK) { + returnError('error_add_data_module_policy', __('Error adding data module to policy.')); + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][16]; + $disabled_types_event = json_encode($disabled_types_event); + + $values = []; + $values['id_tipo_modulo'] = $other['data'][1]; + $values['description'] = $other['data'][2]; + $values['id_module_group'] = $other['data'][3]; + $values['min'] = $other['data'][4]; + $values['max'] = $other['data'][5]; + $values['post_process'] = $other['data'][6]; + $values['module_interval'] = $other['data'][7]; + $values['min_warning'] = $other['data'][8]; + $values['max_warning'] = $other['data'][9]; + $values['str_warning'] = $other['data'][10]; + $values['min_critical'] = $other['data'][11]; + $values['max_critical'] = $other['data'][12]; + $values['str_critical'] = $other['data'][13]; + $values['history_data'] = $other['data'][14]; + $values['configuration_data'] = $other['data'][15]; + $values['disabled_types_event'] = $disabled_types_event; + $values['module_macros'] = $other['data'][17]; + $values['min_ff_event'] = $other['data'][18]; + $values['each_ff'] = $other['data'][19]; + $values['min_ff_event_normal'] = $other['data'][20]; + $values['min_ff_event_warning'] = $other['data'][21]; + $values['min_ff_event_critical'] = $other['data'][22]; + $values['ff_timeout'] = $other['data'][23]; + + if ($name_module_policy !== false) { + if ($name_module_policy[0]['name'] == $other['data'][0]) { + returnError( + 'error_add_data_module_policy', + __('Error adding data module to policy. The module is already in the policy.') + ); + return; + } + } + + $success = enterprise_hook( + 'policies_create_module', + [ + $other['data'][0], + $id, + 1, + $values, + false, + ] + ); + + if ($success) { + // returnData('string', array('type' => 'string', 'data' => __('Data module added to policy. Is necessary to apply the policy in order to changes take effect.'))); + returnData('string', ['type' => 'string', 'data' => $success]); + } else { + returnError('error_add_data_module_policy', 'Error adding data module to policy.'); + } + } + /** * Update data module in policy. And return id from new module. - * - * @param string $id Id of the target policy module. + * + * @param string $id Id of the target policy module. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;;;;; - * ;;;;; - * ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example: - * - * api.php?op=set&op2=update_data_module_policy&id=1&other=10~data%20module%20updated%20by%20Api~2~0~0~50.00~10~20~180~~21~35~~1~module_begin%0dmodule_name%20pandora_process%0dmodule_type%20generic_data%0dmodule_exec%20ps%20aux%20|%20grep%20pandora%20|%20wc%20-l%0dmodule_end&other_mode=url_encode_separator_~ - * + * @param array $other it's array, $other as param is ;; + * ;;;;;;;; + * ;;;;; + * ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example: + * + * api.php?op=set&op2=update_data_module_policy&id=1&other=10~data%20module%20updated%20by%20Api~2~0~0~50.00~10~20~180~~21~35~~1~module_begin%0dmodule_name%20pandora_process%0dmodule_type%20generic_data%0dmodule_exec%20ps%20aux%20|%20grep%20pandora%20|%20wc%20-l%0dmodule_end&other_mode=url_encode_separator_~ + * * @param $thrash3 Don't use */ -function api_set_update_data_module_policy($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_update_data_module_policy', __('Error updating data module in policy. Id_policy cannot be left blank.')); - return; - } +function api_set_update_data_module_policy($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error($id, 'string', "AW")) { - return; - } - - if ($other['data'][0] == "") { - returnError('error_update_data_module_policy', __('Error updating data module in policy. Id_policy_module cannot be left blank.')); - return; - } - - // Check if the module exists - $module_policy = enterprise_hook('policies_get_modules', array($id, array('id' => $other['data'][0]), 'id_module')); - - if ($module_policy === false) { - returnError('error_update_data_module_policy', __('Error updating data module in policy. Module doesn\'t exist.')); - return; - } - - if ($module_policy[0]['id_module'] != 1) { - returnError('error_update_data_module_policy', - __('Error updating data module in policy. Module type is not network type.')); - return; - } - - $fields_data_module = array( - 'id','description', 'id_module_group', 'min', 'max', - 'post_process', 'module_interval', 'min_warning', 'max_warning', - 'str_warning', 'min_critical', 'max_critical', 'str_critical', - 'history_data', 'configuration_data', 'disabled_types_event', - 'module_macros'); - - $cont = 0; - foreach ($fields_data_module as $field) { - if ($other['data'][$cont] != "" and $field != 'id') { - $values[$field] = $other['data'][$cont]; - } - - $cont++; - } - - - $result_update = enterprise_hook('policies_update_module', - array($other['data'][0], $values, false)); - - - if ($result_update < 0) - returnError('error_update_data_module_policy', 'Error updating policy module.'); - else - returnData('string', - array('type' => 'string', 'data' => __('Data policy module updated.'))); + if ($id == '') { + returnError('error_update_data_module_policy', __('Error updating data module in policy. Id_policy cannot be left blank.')); + return; + } + + if (!util_api_check_agent_and_print_error($id, 'string', 'AW')) { + return; + } + + if ($other['data'][0] == '') { + returnError('error_update_data_module_policy', __('Error updating data module in policy. Id_policy_module cannot be left blank.')); + return; + } + + // Check if the module exists + $module_policy = enterprise_hook('policies_get_modules', [$id, ['id' => $other['data'][0]], 'id_module']); + + if ($module_policy === false) { + returnError('error_update_data_module_policy', __('Error updating data module in policy. Module doesn\'t exist.')); + return; + } + + if ($module_policy[0]['id_module'] != 1) { + returnError( + 'error_update_data_module_policy', + __('Error updating data module in policy. Module type is not network type.') + ); + return; + } + + $fields_data_module = [ + 'id', + 'description', + 'id_module_group', + 'min', + 'max', + 'post_process', + 'module_interval', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'history_data', + 'configuration_data', + 'disabled_types_event', + 'module_macros', + ]; + + $cont = 0; + foreach ($fields_data_module as $field) { + if ($other['data'][$cont] != '' and $field != 'id') { + $values[$field] = $other['data'][$cont]; + } + + $cont++; + } + + $result_update = enterprise_hook( + 'policies_update_module', + [ + $other['data'][0], + $values, + false, + ] + ); + + if ($result_update < 0) { + returnError('error_update_data_module_policy', 'Error updating policy module.'); + } else { + returnData( + 'string', + [ + 'type' => 'string', + 'data' => __('Data policy module updated.'), + ] + ); + } } + /** * Add network module to policy. And return a result message. - * - * @param string $id Id of the target policy. + * + * @param string $id Id of the target policy. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;; - * ;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example: - * - * api.php?op=set&op2=add_network_module_policy&id=1&other=network_module_policy_example_name|6|network%20module%20created%20by%20Api|2|0|0|50.00|180|10|20||21|35||1|15|0|66|||0&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;; + * ;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example: + * + * api.php?op=set&op2=add_network_module_policy&id=1&other=network_module_policy_example_name|6|network%20module%20created%20by%20Api|2|0|0|50.00|180|10|20||21|35||1|15|0|66|||0&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_add_network_module_policy($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_network_data_module_policy', - __('Error adding network module to policy. Id_policy cannot be left blank.')); - return; - } - - if (enterprise_hook('policies_check_user_policy', array($id)) === false) { - returnError('forbidden', 'string'); - return; - } +function api_set_add_network_module_policy($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if ($other['data'][0] == "") { - returnError('error_network_data_module_policy', - __('Error adding network module to policy. Module_name cannot be left blank.')); - return; - } - - if ($other['data'][1] < 6 or $other['data'][1] > 18) { - returnError('error_network_data_module_policy', - __('Error adding network module to policy. Id_module_type is not correct for network modules.')); - return; - } - - // Check if the module is already in the policy - $name_module_policy = enterprise_hook('policies_get_modules', - array($id, array('name'=>$other['data'][0]), 'name')); - - if ($name_module_policy === ENTERPRISE_NOT_HOOK) { - returnError('error_network_data_module_policy', - __('Error adding network module to policy.')); - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][21]; - $disabled_types_event = json_encode($disabled_types_event); - - $values = array(); - $values['id_tipo_modulo'] = $other['data'][1]; - $values['description'] = $other['data'][2]; - $values['id_module_group'] = $other['data'][3]; - $values['min'] = $other['data'][4]; - $values['max'] = $other['data'][5]; - $values['post_process'] = $other['data'][6]; - $values['module_interval'] = $other['data'][7]; - $values['min_warning'] = $other['data'][8]; - $values['max_warning'] = $other['data'][9]; - $values['str_warning'] = $other['data'][10]; - $values['min_critical'] = $other['data'][11]; - $values['max_critical'] = $other['data'][12]; - $values['str_critical'] = $other['data'][13]; - $values['history_data'] = $other['data'][14]; - $values['min_ff_event'] = $other['data'][15]; - $values['disabled'] = $other['data'][16]; - $values['tcp_port'] = $other['data'][17]; - $values['snmp_community'] = $other['data'][18]; - $values['snmp_oid'] = $other['data'][19]; - $values['custom_id'] = $other['data'][20]; - $values['disabled_types_event'] = $disabled_types_event; - $values['module_macros'] = $other['data'][22]; - $values['each_ff'] = $other['data'][23]; - $values['min_ff_event_normal'] = $other['data'][24]; - $values['min_ff_event_warning'] = $other['data'][25]; - $values['min_ff_event_critical'] = $other['data'][26]; - - if ($name_module_policy !== false) { - if ($name_module_policy[0]['name'] == $other['data'][0]) { - returnError('error_network_data_module_policy', __('Error adding network module to policy. The module is already in the policy.')); - return; - } - } - - $success = enterprise_hook('policies_create_module', array($other['data'][0], $id, 2, $values, false)); - - if ($success) - returnData('string', array('type' => 'string', 'data' => $success)); - else - returnError('error_add_network_module_policy', 'Error adding network module to policy.'); + if ($id == '') { + returnError( + 'error_network_data_module_policy', + __('Error adding network module to policy. Id_policy cannot be left blank.') + ); + return; + } + + if (enterprise_hook('policies_check_user_policy', [$id]) === false) { + returnError('forbidden', 'string'); + return; + } + + if ($other['data'][0] == '') { + returnError( + 'error_network_data_module_policy', + __('Error adding network module to policy. Module_name cannot be left blank.') + ); + return; + } + + if ($other['data'][1] < 6 or $other['data'][1] > 18) { + returnError( + 'error_network_data_module_policy', + __('Error adding network module to policy. Id_module_type is not correct for network modules.') + ); + return; + } + + // Check if the module is already in the policy + $name_module_policy = enterprise_hook( + 'policies_get_modules', + [ + $id, + ['name' => $other['data'][0]], + 'name', + ] + ); + + if ($name_module_policy === ENTERPRISE_NOT_HOOK) { + returnError( + 'error_network_data_module_policy', + __('Error adding network module to policy.') + ); + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][21]; + $disabled_types_event = json_encode($disabled_types_event); + + $values = []; + $values['id_tipo_modulo'] = $other['data'][1]; + $values['description'] = $other['data'][2]; + $values['id_module_group'] = $other['data'][3]; + $values['min'] = $other['data'][4]; + $values['max'] = $other['data'][5]; + $values['post_process'] = $other['data'][6]; + $values['module_interval'] = $other['data'][7]; + $values['min_warning'] = $other['data'][8]; + $values['max_warning'] = $other['data'][9]; + $values['str_warning'] = $other['data'][10]; + $values['min_critical'] = $other['data'][11]; + $values['max_critical'] = $other['data'][12]; + $values['str_critical'] = $other['data'][13]; + $values['history_data'] = $other['data'][14]; + $values['min_ff_event'] = $other['data'][15]; + $values['disabled'] = $other['data'][16]; + $values['tcp_port'] = $other['data'][17]; + $values['snmp_community'] = $other['data'][18]; + $values['snmp_oid'] = $other['data'][19]; + $values['custom_id'] = $other['data'][20]; + $values['disabled_types_event'] = $disabled_types_event; + $values['module_macros'] = $other['data'][22]; + $values['each_ff'] = $other['data'][23]; + $values['min_ff_event_normal'] = $other['data'][24]; + $values['min_ff_event_warning'] = $other['data'][25]; + $values['min_ff_event_critical'] = $other['data'][26]; + + if ($name_module_policy !== false) { + if ($name_module_policy[0]['name'] == $other['data'][0]) { + returnError('error_network_data_module_policy', __('Error adding network module to policy. The module is already in the policy.')); + return; + } + } + + $success = enterprise_hook('policies_create_module', [$other['data'][0], $id, 2, $values, false]); + + if ($success) { + returnData('string', ['type' => 'string', 'data' => $success]); + } else { + returnError('error_add_network_module_policy', 'Error adding network module to policy.'); + } } + /** * Update network module in policy. And return a result message. - * - * @param string $id Id of the target policy module. + * + * @param string $id Id of the target policy module. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;;;;; - * ;;;;;;; - * ;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example: - * - * api.php?op=set&op2=update_network_module_policy&id=1&other=14|network%20module%20updated%20by%20Api|2|0|0|150.00|300|10|20||21|35||1|15|0|66|||0&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;; + * ;;;;;;;; + * ;;;;;;; + * ;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example: + * + * api.php?op=set&op2=update_network_module_policy&id=1&other=14|network%20module%20updated%20by%20Api|2|0|0|150.00|300|10|20||21|35||1|15|0|66|||0&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_update_network_module_policy($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_update_network_module_policy', - __('Error updating network module in policy. Id_policy cannot be left blank.')); - return; - } - - if ($other['data'][0] == "") { - returnError('error_update_network_module_policy', - __('Error updating network module in policy. Id_policy_module cannot be left blank.')); - return; - } - - // Check if the module exists - $module_policy = enterprise_hook('policies_get_modules', array($id, array('id' => $other['data'][0]), 'id_module')); - - if ($module_policy === false) { - returnError('error_update_network_module_policy', - __('Error updating network module in policy. Module doesn\'t exist.')); - return; - } - - if ($module_policy[0]['id_module'] != 2) { - returnError('error_update_network_module_policy', - __('Error updating network module in policy. Module type is not network type.')); - return; - } - - $fields_network_module = array('id','description', - 'id_module_group', 'min', 'max', 'post_process', - 'module_interval', 'min_warning', 'max_warning', 'str_warning', - 'min_critical', 'max_critical', 'str_critical', 'history_data', - 'min_ff_event', 'disabled', 'tcp_port', 'snmp_community', - 'snmp_oid', 'custom_id', 'disabled_types_event', 'module_macros'); - - $cont = 0; - foreach ($fields_network_module as $field) { - if ($other['data'][$cont] != "" and $field != 'id') { - $values[$field] = $other['data'][$cont]; - } - - $cont++; - } - - $result_update = enterprise_hook('policies_update_module', array($other['data'][0], $values, false)); - - - if ($result_update < 0) - returnError('error_update_network_module_policy', 'Error updating policy module.'); - else - returnData('string', array('type' => 'string', 'data' => __('Network policy module updated.'))); +function api_set_update_network_module_policy($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($id == '') { + returnError( + 'error_update_network_module_policy', + __('Error updating network module in policy. Id_policy cannot be left blank.') + ); + return; + } + + if ($other['data'][0] == '') { + returnError( + 'error_update_network_module_policy', + __('Error updating network module in policy. Id_policy_module cannot be left blank.') + ); + return; + } + + // Check if the module exists + $module_policy = enterprise_hook('policies_get_modules', [$id, ['id' => $other['data'][0]], 'id_module']); + + if ($module_policy === false) { + returnError( + 'error_update_network_module_policy', + __('Error updating network module in policy. Module doesn\'t exist.') + ); + return; + } + + if ($module_policy[0]['id_module'] != 2) { + returnError( + 'error_update_network_module_policy', + __('Error updating network module in policy. Module type is not network type.') + ); + return; + } + + $fields_network_module = [ + 'id', + 'description', + 'id_module_group', + 'min', + 'max', + 'post_process', + 'module_interval', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'history_data', + 'min_ff_event', + 'disabled', + 'tcp_port', + 'snmp_community', + 'snmp_oid', + 'custom_id', + 'disabled_types_event', + 'module_macros', + ]; + + $cont = 0; + foreach ($fields_network_module as $field) { + if ($other['data'][$cont] != '' and $field != 'id') { + $values[$field] = $other['data'][$cont]; + } + + $cont++; + } + + $result_update = enterprise_hook('policies_update_module', [$other['data'][0], $values, false]); + + if ($result_update < 0) { + returnError('error_update_network_module_policy', 'Error updating policy module.'); + } else { + returnData('string', ['type' => 'string', 'data' => __('Network policy module updated.')]); + } } + /** * Add plugin module to policy. And return id from new module. - * - * @param string $id Id of the target policy. + * + * @param string $id Id of the target policy. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;;; - * ;;;;;;;; - * ;;;;; - * ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=add_plugin_module_policy&id=1&other=example%20plugin%20module%20name|0|1|2|0|0||0|0||15|0|66|||300|50.00|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;;; + * ;;;;;;;; + * ;;;;; + * ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=add_plugin_module_policy&id=1&other=example%20plugin%20module%20name|0|1|2|0|0||0|0||15|0|66|||300|50.00|0|0|0|plugin%20module%20from%20api|2|admin|pass|-p%20max&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_add_plugin_module_policy($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Id_policy cannot be left blank.')); - return; - } - - if (enterprise_hook('policies_check_user_policy', array($id)) === false) { - returnError('forbidden', 'string'); - return; - } +function api_set_add_plugin_module_policy($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if ($other['data'][0] == "") { - returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Module_name cannot be left blank.')); - return; - } - - if ($other['data'][22] == "") { - returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Id_plugin cannot be left blank.')); - return; - } - - // Check if the module is already in the policy - $name_module_policy = enterprise_hook('policies_get_modules', array($id, array('name'=>$other['data'][0]), 'name')); - - if ($name_module_policy === ENTERPRISE_NOT_HOOK) { - returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy.')); - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][25]; - $disabled_types_event = json_encode($disabled_types_event); - - $values = array(); - $values['disabled'] = $other['data'][1]; - $values['id_tipo_modulo'] = $other['data'][2]; - $values['id_module_group'] = $other['data'][3]; - $values['min_warning'] = $other['data'][4]; - $values['max_warning'] = $other['data'][5]; - $values['str_warning'] = $other['data'][6]; - $values['min_critical'] = $other['data'][7]; - $values['max_critical'] = $other['data'][8]; - $values['str_critical'] = $other['data'][9]; - $values['min_ff_event'] = $other['data'][10]; - $values['history_data'] = $other['data'][11]; - $values['tcp_port'] = $other['data'][12]; - $values['snmp_community'] = $other['data'][13]; - $values['snmp_oid'] = $other['data'][14]; - $values['module_interval'] = $other['data'][15]; - $values['post_process'] = $other['data'][16]; - $values['min'] = $other['data'][17]; - $values['max'] = $other['data'][18]; - $values['custom_id'] = $other['data'][19]; - $values['description'] = $other['data'][20]; - $values['id_plugin'] = $other['data'][21]; - $values['plugin_user'] = $other['data'][22]; - $values['plugin_pass'] = $other['data'][23]; - $values['plugin_parameter'] = $other['data'][24]; - $values['disabled_types_event'] = $disabled_types_event; - $values['macros'] = base64_decode ($other['data'][26]); - $values['module_macros'] = $other['data'][27]; - $values['each_ff'] = $other['data'][28]; - $values['min_ff_event_normal'] = $other['data'][29]; - $values['min_ff_event_warning'] = $other['data'][30]; - $values['min_ff_event_critical'] = $other['data'][31]; - - if ($name_module_policy !== false) { - if ($name_module_policy[0]['name'] == $other['data'][0]) { - returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. The module is already in the policy.')); - return; - } - } - - $success = enterprise_hook('policies_create_module', array($other['data'][0], $id, 4, $values, false)); - - if ($success) - returnData('string', array('type' => 'string', 'data' => $success)); - else - returnError('error_add_plugin_module_policy', 'Error adding plugin module to policy.'); + if ($id == '') { + returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Id_policy cannot be left blank.')); + return; + } + + if (enterprise_hook('policies_check_user_policy', [$id]) === false) { + returnError('forbidden', 'string'); + return; + } + + if ($other['data'][0] == '') { + returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Module_name cannot be left blank.')); + return; + } + + if ($other['data'][22] == '') { + returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. Id_plugin cannot be left blank.')); + return; + } + + // Check if the module is already in the policy + $name_module_policy = enterprise_hook('policies_get_modules', [$id, ['name' => $other['data'][0]], 'name']); + + if ($name_module_policy === ENTERPRISE_NOT_HOOK) { + returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy.')); + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][25]; + $disabled_types_event = json_encode($disabled_types_event); + + $values = []; + $values['disabled'] = $other['data'][1]; + $values['id_tipo_modulo'] = $other['data'][2]; + $values['id_module_group'] = $other['data'][3]; + $values['min_warning'] = $other['data'][4]; + $values['max_warning'] = $other['data'][5]; + $values['str_warning'] = $other['data'][6]; + $values['min_critical'] = $other['data'][7]; + $values['max_critical'] = $other['data'][8]; + $values['str_critical'] = $other['data'][9]; + $values['min_ff_event'] = $other['data'][10]; + $values['history_data'] = $other['data'][11]; + $values['tcp_port'] = $other['data'][12]; + $values['snmp_community'] = $other['data'][13]; + $values['snmp_oid'] = $other['data'][14]; + $values['module_interval'] = $other['data'][15]; + $values['post_process'] = $other['data'][16]; + $values['min'] = $other['data'][17]; + $values['max'] = $other['data'][18]; + $values['custom_id'] = $other['data'][19]; + $values['description'] = $other['data'][20]; + $values['id_plugin'] = $other['data'][21]; + $values['plugin_user'] = $other['data'][22]; + $values['plugin_pass'] = $other['data'][23]; + $values['plugin_parameter'] = $other['data'][24]; + $values['disabled_types_event'] = $disabled_types_event; + $values['macros'] = base64_decode($other['data'][26]); + $values['module_macros'] = $other['data'][27]; + $values['each_ff'] = $other['data'][28]; + $values['min_ff_event_normal'] = $other['data'][29]; + $values['min_ff_event_warning'] = $other['data'][30]; + $values['min_ff_event_critical'] = $other['data'][31]; + + if ($name_module_policy !== false) { + if ($name_module_policy[0]['name'] == $other['data'][0]) { + returnError('error_add_plugin_module_policy', __('Error adding plugin module to policy. The module is already in the policy.')); + return; + } + } + + $success = enterprise_hook('policies_create_module', [$other['data'][0], $id, 4, $values, false]); + + if ($success) { + returnData('string', ['type' => 'string', 'data' => $success]); + } else { + returnError('error_add_plugin_module_policy', 'Error adding plugin module to policy.'); + } } + /** * Update plugin module in policy. And return a result message. - * - * @param string $id Id of the target policy module. + * + * @param string $id Id of the target policy module. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;;;;; - * ;;;;;; - * ;;;;;;;; - * ;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example: - * - * api.php?op=set&op2=update_plugin_module_policy&id=1&other=23|0|1|0|0||0|0||15|0|166|||180|150.00|0|0|0|plugin%20module%20updated%20from%20api|2|example_user|pass|-p%20min&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;; + * ;;;;;;;; + * ;;;;;; + * ;;;;;;;; + * ;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example: + * + * api.php?op=set&op2=update_plugin_module_policy&id=1&other=23|0|1|0|0||0|0||15|0|166|||180|150.00|0|0|0|plugin%20module%20updated%20from%20api|2|example_user|pass|-p%20min&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_update_plugin_module_policy($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_update_plugin_module_policy', - __('Error updating plugin module in policy. Id_policy cannot be left blank.')); - return; - } - - if ($other['data'][0] == "") { - returnError('error_update_plugin_module_policy', - __('Error updating plugin module in policy. Id_policy_module cannot be left blank.')); - return; - } - - // Check if the module exists - $module_policy = enterprise_hook('policies_get_modules', array($id, array('id' => $other['data'][0]), 'id_module')); - - if ($module_policy === false) { - returnError('error_updating_plugin_module_policy', - __('Error updating plugin module in policy. Module doesn\'t exist.')); - return; - } - - if ($module_policy[0]['id_module'] != 4) { - returnError('error_updating_plugin_module_policy', - __('Error updating plugin module in policy. Module type is not network type.')); - return; - } - - $fields_plugin_module = array('id','disabled', 'id_module_group', - 'min_warning', 'max_warning', 'str_warning', 'min_critical', - 'max_critical', 'str_critical', 'min_ff_event', 'history_data', - 'tcp_port', 'snmp_community', 'snmp_oid', 'module_interval', - 'post_process', 'min', 'max', 'custom_id', 'description', - 'id_plugin', 'plugin_user', 'plugin_pass', 'plugin_parameter', - 'disabled_types_event', 'macros', 'module_macros'); - - $cont = 0; - foreach ($fields_plugin_module as $field) { - if ($other['data'][$cont] != "" and $field != 'id') { - $values[$field] = $other['data'][$cont]; - - if( $field === 'macros' ) { - $values[$field] = base64_decode($values[$field]); - } - } - - $cont++; - } - - $result_update = enterprise_hook('policies_update_module', - array($other['data'][0], $values, false)); - - - if ($result_update < 0) - returnError('error_update_plugin_module_policy', 'Error updating policy module.'); - else - returnData('string', array('type' => 'string', 'data' => __('Plugin policy module updated.'))); +function api_set_update_plugin_module_policy($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } + + if ($id == '') { + returnError( + 'error_update_plugin_module_policy', + __('Error updating plugin module in policy. Id_policy cannot be left blank.') + ); + return; + } + + if ($other['data'][0] == '') { + returnError( + 'error_update_plugin_module_policy', + __('Error updating plugin module in policy. Id_policy_module cannot be left blank.') + ); + return; + } + + // Check if the module exists + $module_policy = enterprise_hook('policies_get_modules', [$id, ['id' => $other['data'][0]], 'id_module']); + + if ($module_policy === false) { + returnError( + 'error_updating_plugin_module_policy', + __('Error updating plugin module in policy. Module doesn\'t exist.') + ); + return; + } + + if ($module_policy[0]['id_module'] != 4) { + returnError( + 'error_updating_plugin_module_policy', + __('Error updating plugin module in policy. Module type is not network type.') + ); + return; + } + + $fields_plugin_module = [ + 'id', + 'disabled', + 'id_module_group', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'min_ff_event', + 'history_data', + 'tcp_port', + 'snmp_community', + 'snmp_oid', + 'module_interval', + 'post_process', + 'min', + 'max', + 'custom_id', + 'description', + 'id_plugin', + 'plugin_user', + 'plugin_pass', + 'plugin_parameter', + 'disabled_types_event', + 'macros', + 'module_macros', + ]; + + $cont = 0; + foreach ($fields_plugin_module as $field) { + if ($other['data'][$cont] != '' and $field != 'id') { + $values[$field] = $other['data'][$cont]; + + if ($field === 'macros') { + $values[$field] = base64_decode($values[$field]); + } + } + + $cont++; + } + + $result_update = enterprise_hook( + 'policies_update_module', + [ + $other['data'][0], + $values, + false, + ] + ); + + if ($result_update < 0) { + returnError('error_update_plugin_module_policy', 'Error updating policy module.'); + } else { + returnData('string', ['type' => 'string', 'data' => __('Plugin policy module updated.')]); + } } + /** * Add module data configuration into agent configuration file - * - * @param string $id_agent Id of the agent - * @param string $module_name - * @param array $configuration_data is an array. The data in it is the new configuration data of the module + * + * @param string $id_agent Id of the agent + * @param string $module_name + * @param array $configuration_data is an array. The data in it is the new configuration data of the module * @param $thrash3 Don't use - * + * * Call example: - * + * * api.php?op=set&op2=add_module_in_conf&user=admin&pass=pandora&id=9043&id2=example_name&other=bW9kdWxlX2JlZ2luCm1vZHVsZV9uYW1lIGV4YW1wbGVfbmFtZQptb2R1bGVfdHlwZSBnZW5lcmljX2RhdGEKbW9kdWxlX2V4ZWMgZWNobyAxOwptb2R1bGVfZW5k - * + * * @return string 0 when success, -1 when error, -2 if already exist */ -function api_set_add_module_in_conf($id_agent, $module_name, $configuration_data, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } +function api_set_add_module_in_conf($id_agent, $module_name, $configuration_data, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error($id_agent, 'string', "AW")) return; + if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AW')) { + return; + } - $new_configuration_data = io_safe_output(urldecode($configuration_data['data'])); - - // Check if exist a current module with the same name in the conf file - $old_configuration_data = config_agents_get_module_from_conf($id_agent, io_safe_output($module_name)); - - // If exists a module with same name, abort - if(!empty($old_configuration_data)) { - returnError('error_adding_module_conf', '-2'); - exit; - } - - $result = enterprise_hook('config_agents_add_module_in_conf', array($id_agent, $new_configuration_data)); - - if($result && $result !== ENTERPRISE_NOT_HOOK) { - returnData('string', array('type' => 'string', 'data' => '0')); - } - else { - returnError('error_adding_module_conf', '-1'); - } + $new_configuration_data = io_safe_output(urldecode($configuration_data['data'])); + + // Check if exist a current module with the same name in the conf file + $old_configuration_data = config_agents_get_module_from_conf($id_agent, io_safe_output($module_name)); + + // If exists a module with same name, abort + if (!empty($old_configuration_data)) { + returnError('error_adding_module_conf', '-2'); + exit; + } + + $result = enterprise_hook('config_agents_add_module_in_conf', [$id_agent, $new_configuration_data]); + + if ($result && $result !== ENTERPRISE_NOT_HOOK) { + returnData('string', ['type' => 'string', 'data' => '0']); + } else { + returnError('error_adding_module_conf', '-1'); + } } /** * Get module data configuration from agent configuration file - * - * @param string $id_agent Id of the agent - * @param string $module_name + * + * @param string $id_agent Id of the agent + * @param string $module_name * @param $thrash2 Don't use * @param $thrash3 Don't use - * + * * Call example: - * + * * api.php?op=get&op2=module_from_conf&user=admin&pass=pandora&id=9043&id2=example_name - * + * * @return string Module data when success, empty when error */ -function api_get_module_from_conf($id_agent, $module_name, $thrash2, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } +function api_get_module_from_conf($id_agent, $module_name, $thrash2, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error($id_agent, 'string')) return; + if (!util_api_check_agent_and_print_error($id_agent, 'string')) { + return; + } - $module_name = io_safe_output($module_name); - $result = enterprise_hook('config_agents_get_module_from_conf', - array($id_agent, $module_name)); + $module_name = io_safe_output($module_name); + $result = enterprise_hook( + 'config_agents_get_module_from_conf', + [ + $id_agent, + $module_name, + ] + ); - if ($result !== ENTERPRISE_NOT_HOOK && !empty($result)) { - returnData('string', array('type' => 'string', 'data' => $result)); - } - else { - returnError('error_adding_module_conf', __('Remote config of module %s not available', $module_name)); - } + if ($result !== ENTERPRISE_NOT_HOOK && !empty($result)) { + returnData('string', ['type' => 'string', 'data' => $result]); + } else { + returnError('error_adding_module_conf', __('Remote config of module %s not available', $module_name)); + } } + /** * Delete module data configuration from agent configuration file - * - * @param string $id_agent Id of the agent - * @param string $module_name + * + * @param string $id_agent Id of the agent + * @param string $module_name * @param $thrash2 Don't use * @param $thrash3 Don't use - * + * * Call example: - * + * * api.php?op=set&op2=delete_module_in_conf&user=admin&pass=pandora&id=9043&id2=example_name - * + * * @return string 0 when success, -1 when error */ -function api_set_delete_module_in_conf($id_agent, $module_name, $thrash2, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } +function api_set_delete_module_in_conf($id_agent, $module_name, $thrash2, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error($id_agent, 'string')) return; - $result = config_agents_delete_module_in_conf($id_agent, $module_name); - - $result = enterprise_hook('config_agents_delete_module_in_conf', array($id_agent, $module_name)); - - if($result && $result !== ENTERPRISE_NOT_HOOK) { - returnData('string', array('type' => 'string', 'data' => '0')); - } - else { - returnError('error_deleting_module_conf', '-1'); - } + if (!util_api_check_agent_and_print_error($id_agent, 'string')) { + return; + } + + $result = config_agents_delete_module_in_conf($id_agent, $module_name); + + $result = enterprise_hook('config_agents_delete_module_in_conf', [$id_agent, $module_name]); + + if ($result && $result !== ENTERPRISE_NOT_HOOK) { + returnData('string', ['type' => 'string', 'data' => '0']); + } else { + returnError('error_deleting_module_conf', '-1'); + } } + /** * Update module data configuration from agent configuration file - * - * @param string $id_agent Id of the agent - * @param string $module_name - * @param array $configuration_data is an array. The data in it is the new configuration data of the module + * + * @param string $id_agent Id of the agent + * @param string $module_name + * @param array $configuration_data is an array. The data in it is the new configuration data of the module * @param $thrash3 Don't use - * + * * Call example: - * + * * api.php?op=set&op2=update_module_in_conf&user=admin&pass=pandora&id=9043&id2=example_name&other=bW9kdWxlX2JlZ2luCm1vZHVsZV9uYW1lIGV4YW1wbGVfbmFtZQptb2R1bGVfdHlwZSBnZW5lcmljX2RhdGEKbW9kdWxlX2V4ZWMgZWNobyAxOwptb2R1bGVfZW5k - * + * * @return string 0 when success, 1 when no changes, -1 when error, -2 if doesnt exist */ -function api_set_update_module_in_conf($id_agent, $module_name, $configuration_data_serialized, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } +function api_set_update_module_in_conf($id_agent, $module_name, $configuration_data_serialized, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error($id_agent, 'string')) return; - $new_configuration_data = io_safe_output(urldecode($configuration_data_serialized['data'])); - - // Get current configuration - $old_configuration_data = config_agents_get_module_from_conf($id_agent, io_safe_output($module_name)); - - // If not exists - if(empty($old_configuration_data)) { - returnError('error_editing_module_conf', '-2'); - exit; - } - - // If current configuration and new configuration are equal, abort - if ($new_configuration_data == $old_configuration_data) { - returnData('string', array('type' => 'string', 'data' => '1')); - exit; - } - - $result = enterprise_hook('config_agents_update_module_in_conf', array($id_agent, $old_configuration_data, $new_configuration_data)); - - if($result && $result !== ENTERPRISE_NOT_HOOK) { - returnData('string', array('type' => 'string', 'data' => '0')); - } - else { - returnError('error_editing_module_conf', '-1'); - } + if (!util_api_check_agent_and_print_error($id_agent, 'string')) { + return; + } + + $new_configuration_data = io_safe_output(urldecode($configuration_data_serialized['data'])); + + // Get current configuration + $old_configuration_data = config_agents_get_module_from_conf($id_agent, io_safe_output($module_name)); + + // If not exists + if (empty($old_configuration_data)) { + returnError('error_editing_module_conf', '-2'); + exit; + } + + // If current configuration and new configuration are equal, abort + if ($new_configuration_data == $old_configuration_data) { + returnData('string', ['type' => 'string', 'data' => '1']); + exit; + } + + $result = enterprise_hook('config_agents_update_module_in_conf', [$id_agent, $old_configuration_data, $new_configuration_data]); + + if ($result && $result !== ENTERPRISE_NOT_HOOK) { + returnData('string', ['type' => 'string', 'data' => '0']); + } else { + returnError('error_editing_module_conf', '-1'); + } } + /** * Add SNMP module to policy. And return id from new module. - * - * @param string $id Id of the target policy. + * + * @param string $id Id of the target policy. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;;;; - * ;;;;;; - * ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=set&op2=add_snmp_module_policy&id=1&other=example%20SNMP%20module%20name|0|15|2|0|0||0|0||15|1|66|3|public|.1.3.6.1.2.1.1.1.0|180|50.00|10|60|0|SNMP%20module%20modified%20by%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;;;; + * ;;;;;; + * ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=set&op2=add_snmp_module_policy&id=1&other=example%20SNMP%20module%20name|0|15|2|0|0||0|0||15|1|66|3|public|.1.3.6.1.2.1.1.1.0|180|50.00|10|60|0|SNMP%20module%20modified%20by%20API|AES|example_priv_passw|authNoPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_add_snmp_module_policy($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Id_policy cannot be left blank.')); - return; - } - - if (enterprise_hook('policies_check_user_policy', array($id)) === false) { - returnError('forbidden', 'string'); - return; - } +function api_set_add_snmp_module_policy($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - if ($other['data'][0] == "") { - returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Module_name cannot be left blank.')); - return; - } - - // Check if the module is already in the policy - $name_module_policy = enterprise_hook('policies_get_modules', array($id, array('name'=>$other['data'][0]), 'name')); - - if ($name_module_policy === ENTERPRISE_NOT_HOOK) { - returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy.')); - return; - } - - if ($other['data'][2] < 15 or $other['data'][2] > 18) { - returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Id_module_type is not correct for SNMP modules.')); - return; - } - - $disabled_types_event = array(); - $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int)!$other['data'][28]; - $disabled_types_event = json_encode($disabled_types_event); - - # SNMP version 3 - if ($other['data'][13] == "3") { - - if ($other['data'][22] != "AES" and $other['data'][22] != "DES") { - returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ')); - return; - } - - if ($other['data'][24] != "authNoPriv" and $other['data'][24] != "authPriv" and $other['data'][24] != "noAuthNoPriv") { - returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ')); - return; - } - - if ($other['data'][25] != "MD5" and $other['data'][25] != "SHA") { - returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ')); - return; - } - - $values = array( - 'disabled' => $other['data'][1], - 'id_tipo_modulo' => $other['data'][2], - 'id_module_group' => $other['data'][3], - 'min_warning' => $other['data'][4], - 'max_warning' => $other['data'][5], - 'str_warning' => $other['data'][6], - 'min_critical' => $other['data'][7], - 'max_critical' => $other['data'][8], - 'str_critical' => $other['data'][9], - 'min_ff_event' => $other['data'][10], - 'history_data' => $other['data'][11], - 'tcp_port' => $other['data'][12], - 'tcp_send' => $other['data'][13], - 'snmp_community' => $other['data'][14], - 'snmp_oid' => $other['data'][15], - 'module_interval' => $other['data'][16], - 'post_process' => $other['data'][17], - 'min' => $other['data'][18], - 'max' => $other['data'][19], - 'custom_id' => $other['data'][20], - 'description' => $other['data'][21], - 'custom_string_1' => $other['data'][22], - 'custom_string_2' => $other['data'][23], - 'custom_string_3' => $other['data'][24], - 'plugin_parameter' => $other['data'][25], - 'plugin_user' => $other['data'][26], - 'plugin_pass' => $other['data'][27], - 'disabled_types_event' => $disabled_types_event, - 'each_ff' => $other['data'][29], - 'min_ff_event_normal' => $other['data'][30], - 'min_ff_event_warning' => $other['data'][31], - 'min_ff_event_critical' => $other['data'][32] - ); - } - else { - $values = array( - 'disabled' => $other['data'][1], - 'id_tipo_modulo' => $other['data'][2], - 'id_module_group' => $other['data'][3], - 'min_warning' => $other['data'][4], - 'max_warning' => $other['data'][5], - 'str_warning' => $other['data'][6], - 'min_critical' => $other['data'][7], - 'max_critical' => $other['data'][8], - 'str_critical' => $other['data'][9], - 'min_ff_event' => $other['data'][10], - 'history_data' => $other['data'][11], - 'tcp_port' => $other['data'][12], - 'tcp_send' => $other['data'][13], - 'snmp_community' => $other['data'][14], - 'snmp_oid' => $other['data'][15], - 'module_interval' => $other['data'][16], - 'post_process' => $other['data'][17], - 'min' => $other['data'][18], - 'max' => $other['data'][19], - 'custom_id' => $other['data'][20], - 'description' => $other['data'][21], - 'disabled_types_event' => $disabled_types_event, - 'each_ff' => $other['data'][23], - 'min_ff_event_normal' => $other['data'][24], - 'min_ff_event_warning' => $other['data'][25], - 'min_ff_event_critical' => $other['data'][26] - ); - } - - if ($name_module_policy !== false) { - if ($name_module_policy[0]['name'] == $other['data'][0]) { - returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. The module is already in the policy.')); - return; - } - } - - $success = enterprise_hook('policies_create_module', array($other['data'][0], $id, 2, $values, false)); - - if ($success) - returnData('string', array('type' => 'string', 'data' => $success)); - else - returnError('error_add_snmp_module_policy', 'Error adding SNMP module to policy.'); + if ($id == '') { + returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Id_policy cannot be left blank.')); + return; + } + + if (enterprise_hook('policies_check_user_policy', [$id]) === false) { + returnError('forbidden', 'string'); + return; + } + + if ($other['data'][0] == '') { + returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Module_name cannot be left blank.')); + return; + } + + // Check if the module is already in the policy + $name_module_policy = enterprise_hook('policies_get_modules', [$id, ['name' => $other['data'][0]], 'name']); + + if ($name_module_policy === ENTERPRISE_NOT_HOOK) { + returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy.')); + return; + } + + if ($other['data'][2] < 15 or $other['data'][2] > 18) { + returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. Id_module_type is not correct for SNMP modules.')); + return; + } + + $disabled_types_event = []; + $disabled_types_event[EVENTS_GOING_UNKNOWN] = (int) !$other['data'][28]; + $disabled_types_event = json_encode($disabled_types_event); + + // SNMP version 3 + if ($other['data'][13] == '3') { + if ($other['data'][22] != 'AES' and $other['data'][22] != 'DES') { + returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ')); + return; + } + + if ($other['data'][24] != 'authNoPriv' and $other['data'][24] != 'authPriv' and $other['data'][24] != 'noAuthNoPriv') { + returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ')); + return; + } + + if ($other['data'][25] != 'MD5' and $other['data'][25] != 'SHA') { + returnError('error_add_snmp_module_policy', __('Error in creation SNMP module. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ')); + return; + } + + $values = [ + 'disabled' => $other['data'][1], + 'id_tipo_modulo' => $other['data'][2], + 'id_module_group' => $other['data'][3], + 'min_warning' => $other['data'][4], + 'max_warning' => $other['data'][5], + 'str_warning' => $other['data'][6], + 'min_critical' => $other['data'][7], + 'max_critical' => $other['data'][8], + 'str_critical' => $other['data'][9], + 'min_ff_event' => $other['data'][10], + 'history_data' => $other['data'][11], + 'tcp_port' => $other['data'][12], + 'tcp_send' => $other['data'][13], + 'snmp_community' => $other['data'][14], + 'snmp_oid' => $other['data'][15], + 'module_interval' => $other['data'][16], + 'post_process' => $other['data'][17], + 'min' => $other['data'][18], + 'max' => $other['data'][19], + 'custom_id' => $other['data'][20], + 'description' => $other['data'][21], + 'custom_string_1' => $other['data'][22], + 'custom_string_2' => $other['data'][23], + 'custom_string_3' => $other['data'][24], + 'plugin_parameter' => $other['data'][25], + 'plugin_user' => $other['data'][26], + 'plugin_pass' => $other['data'][27], + 'disabled_types_event' => $disabled_types_event, + 'each_ff' => $other['data'][29], + 'min_ff_event_normal' => $other['data'][30], + 'min_ff_event_warning' => $other['data'][31], + 'min_ff_event_critical' => $other['data'][32], + ]; + } else { + $values = [ + 'disabled' => $other['data'][1], + 'id_tipo_modulo' => $other['data'][2], + 'id_module_group' => $other['data'][3], + 'min_warning' => $other['data'][4], + 'max_warning' => $other['data'][5], + 'str_warning' => $other['data'][6], + 'min_critical' => $other['data'][7], + 'max_critical' => $other['data'][8], + 'str_critical' => $other['data'][9], + 'min_ff_event' => $other['data'][10], + 'history_data' => $other['data'][11], + 'tcp_port' => $other['data'][12], + 'tcp_send' => $other['data'][13], + 'snmp_community' => $other['data'][14], + 'snmp_oid' => $other['data'][15], + 'module_interval' => $other['data'][16], + 'post_process' => $other['data'][17], + 'min' => $other['data'][18], + 'max' => $other['data'][19], + 'custom_id' => $other['data'][20], + 'description' => $other['data'][21], + 'disabled_types_event' => $disabled_types_event, + 'each_ff' => $other['data'][23], + 'min_ff_event_normal' => $other['data'][24], + 'min_ff_event_warning' => $other['data'][25], + 'min_ff_event_critical' => $other['data'][26], + ]; + } + + if ($name_module_policy !== false) { + if ($name_module_policy[0]['name'] == $other['data'][0]) { + returnError('error_add_snmp_module_policy', __('Error adding SNMP module to policy. The module is already in the policy.')); + return; + } + } + + $success = enterprise_hook('policies_create_module', [$other['data'][0], $id, 2, $values, false]); + + if ($success) { + returnData('string', ['type' => 'string', 'data' => $success]); + } else { + returnError('error_add_snmp_module_policy', 'Error adding SNMP module to policy.'); + } } + /** * Update SNMP module in policy. And return a result message. - * - * @param string $id Id of the target policy module. + * + * @param string $id Id of the target policy module. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; - * ;;;;;;;; - * ;;;;;;; - * ;;;;;;;; - * ; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example: - * - * api.php?op=set&op2=update_snmp_module_policy&id=1&other=14|0|2|0|0||0|0||30|1|66|3|nonpublic|.1.3.6.1.2.1.1.1.0|300|150.00|10|60|0|SNMP%20module%20updated%20by%20API|DES|example_priv_passw|authPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;; + * ;;;;;;;; + * ;;;;;;; + * ;;;;;;;; + * ; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example: + * + * api.php?op=set&op2=update_snmp_module_policy&id=1&other=14|0|2|0|0||0|0||30|1|66|3|nonpublic|.1.3.6.1.2.1.1.1.0|300|150.00|10|60|0|SNMP%20module%20updated%20by%20API|DES|example_priv_passw|authPriv|MD5|pepito_user|example_auth_passw&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_update_snmp_module_policy($id, $thrash1, $other, $thrash3) { - if (defined ('METACONSOLE')) { - return; - } - - if ($id == "") { - returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Id_policy cannot be left blank.')); - return; - } - - if ($other['data'][0] == "") { - returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Id_policy_module cannot be left blank.')); - return; - } - - // Check if the module exists - $module_policy = enterprise_hook('policies_get_modules', array($id, array('id' => $other['data'][0]), 'id_module')); - - if ($module_policy === false) { - returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Module doesn\'t exist.')); - return; - } - - if ($module_policy[0]['id_module'] != 2) { - returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Module type is not SNMP type.')); - return; - } - - - # SNMP version 3 - if ($other['data'][12] == "3") { - - if ($other['data'][21] != "AES" and $other['data'][21] != "DES") { - returnError('error_update_snmp_module_policy', - __('Error updating SNMP module. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ')); +function api_set_update_snmp_module_policy($id, $thrash1, $other, $thrash3) +{ + if (defined('METACONSOLE')) { + return; + } - return; - } - - if ($other['data'][23] != "authNoPriv" - and $other['data'][23] != "authPriv" - and $other['data'][23] != "noAuthNoPriv") { - - returnError('error_update_snmp_module_policy', - __('Error updating SNMP module. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ')); + if ($id == '') { + returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Id_policy cannot be left blank.')); + return; + } - return; - } - - if ($other['data'][24] != "MD5" and $other['data'][24] != "SHA") { - returnError('error_update_snmp_module_policy', - __('Error updating SNMP module. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ')); + if ($other['data'][0] == '') { + returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Id_policy_module cannot be left blank.')); + return; + } - return; - } - - $fields_snmp_module = array('id','disabled', 'id_module_group', - 'min_warning', 'max_warning', 'str_warning', 'min_critical', - 'max_critical', 'str_critical', 'min_ff_event', - 'history_data', 'tcp_port', 'tcp_send', 'snmp_community', - 'snmp_oid', 'module_interval', 'post_process', 'min', 'max', - 'custom_id', 'description', 'custom_string_1', - 'custom_string_2', 'custom_string_3', 'plugin_parameter', - 'plugin_user', 'plugin_pass'); - } - else { - $fields_snmp_module = array('id','disabled', 'id_module_group', - 'min_warning', 'max_warning', 'str_warning', 'min_critical', - 'max_critical', 'str_critical', 'min_ff_event', - 'history_data', 'tcp_port', 'tcp_send', 'snmp_community', - 'snmp_oid', 'module_interval', 'post_process', 'min', 'max', - 'custom_id', 'description'); - } - - $cont = 0; - foreach ($fields_snmp_module as $field) { - if ($other['data'][$cont] != "" and $field != 'id') { - $values[$field] = $other['data'][$cont]; - } - - $cont++; - } - - $result_update = enterprise_hook('policies_update_module', - array($other['data'][0], $values, false)); - - - if ($result_update < 0) - returnError('error_update_snmp_module_policy', 'Error updating policy module.'); - else - returnData('string', - array('type' => 'string', 'data' => __('SNMP policy module updated.'))); + // Check if the module exists + $module_policy = enterprise_hook('policies_get_modules', [$id, ['id' => $other['data'][0]], 'id_module']); + + if ($module_policy === false) { + returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Module doesn\'t exist.')); + return; + } + + if ($module_policy[0]['id_module'] != 2) { + returnError('error_update_snmp_module_policy', __('Error updating SNMP module in policy. Module type is not SNMP type.')); + return; + } + + // SNMP version 3 + if ($other['data'][12] == '3') { + if ($other['data'][21] != 'AES' and $other['data'][21] != 'DES') { + returnError( + 'error_update_snmp_module_policy', + __('Error updating SNMP module. snmp3_priv_method doesn\'t exist. Set it to \'AES\' or \'DES\'. ') + ); + + return; + } + + if ($other['data'][23] != 'authNoPriv' + and $other['data'][23] != 'authPriv' + and $other['data'][23] != 'noAuthNoPriv' + ) { + returnError( + 'error_update_snmp_module_policy', + __('Error updating SNMP module. snmp3_sec_level doesn\'t exist. Set it to \'authNoPriv\' or \'authPriv\' or \'noAuthNoPriv\'. ') + ); + + return; + } + + if ($other['data'][24] != 'MD5' and $other['data'][24] != 'SHA') { + returnError( + 'error_update_snmp_module_policy', + __('Error updating SNMP module. snmp3_auth_method doesn\'t exist. Set it to \'MD5\' or \'SHA\'. ') + ); + + return; + } + + $fields_snmp_module = [ + 'id', + 'disabled', + 'id_module_group', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'min_ff_event', + 'history_data', + 'tcp_port', + 'tcp_send', + 'snmp_community', + 'snmp_oid', + 'module_interval', + 'post_process', + 'min', + 'max', + 'custom_id', + 'description', + 'custom_string_1', + 'custom_string_2', + 'custom_string_3', + 'plugin_parameter', + 'plugin_user', + 'plugin_pass', + ]; + } else { + $fields_snmp_module = [ + 'id', + 'disabled', + 'id_module_group', + 'min_warning', + 'max_warning', + 'str_warning', + 'min_critical', + 'max_critical', + 'str_critical', + 'min_ff_event', + 'history_data', + 'tcp_port', + 'tcp_send', + 'snmp_community', + 'snmp_oid', + 'module_interval', + 'post_process', + 'min', + 'max', + 'custom_id', + 'description', + ]; + } + + $cont = 0; + foreach ($fields_snmp_module as $field) { + if ($other['data'][$cont] != '' and $field != 'id') { + $values[$field] = $other['data'][$cont]; + } + + $cont++; + } + + $result_update = enterprise_hook( + 'policies_update_module', + [ + $other['data'][0], + $values, + false, + ] + ); + + if ($result_update < 0) { + returnError('error_update_snmp_module_policy', 'Error updating policy module.'); + } else { + returnData( + 'string', + [ + 'type' => 'string', + 'data' => __('SNMP policy module updated.'), + ] + ); + } } + /** - * Create a new group. And return the id_group of the new group. - * - * @param string $id Name of the new group. + * Remove an agent from a policy. + * + * @param $id Id of the policy + * @param $id2 Id of the agent policy + * @param $trash1 + * @param $trash2 + * + * Example: + * api.php?op=set&op2=remove_agent_from_policy&apipass=1234&user=admin&pass=pandora&id=11&id2=2 + */ +function api_set_remove_agent_from_policy($id, $id2, $thrash2, $thrash3) +{ + global $config; + + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'string'); + return; + } + + if ($id == '' || !$id) { + returnError('error_parameter', __('Error deleting agent from policy. Policy cannot be left blank.')); + return; + } + + if ($id2 == '' || !$id2) { + returnError('error_parameter', __('Error deleting agent from policy. Agent cannot be left blank.')); + return; + } + + $policy = policies_get_policy($id, false, false); + $agent = db_get_row_filter('tagente', ['id_agente' => $id2]); + $policy_agent = db_get_row_filter('tpolicy_agents', ['id_policy' => $id, 'id_agent' => $id2]); + + if (empty($policy)) { + returnError('error_policy', __('This policy does not exist.')); + return; + } + + if (empty($agent)) { + returnError('error_agent', __('This agent does not exist.')); + return; + } + + if (empty($policy_agent)) { + returnError('error_policy_agent', __('This agent does not exist in this policy.')); + return; + } + + $return = policies_change_delete_pending_agent($policy_agent['id']); + $data = __('Successfully added to delete pending id agent %d to id policy %d.', $id2, $id); + + if ($return === false) { + returnError('error_delete_policy_agent', 'Could not be deleted id agent %d from id policy %d', $id2, $id); + } else { + returnData('string', ['type' => 'string', 'data' => $data]); + } + +} + + +/** + * Create a new group. And return the id_group of the new group. + * + * @param string $id Name of the new group. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * example 1 (with parent group: Servers) - * - * api.php?op=set&op2=create_group&id=example_group_name&other=applications|1&other_mode=url_encode_separator_| - * - * example 2 (without parent group) - * - * api.php?op=set&op2=create_group&id=example_group_name2&other=computer|&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * example 1 (with parent group: Servers) + * + * api.php?op=set&op2=create_group&id=example_group_name&other=applications|1&other_mode=url_encode_separator_| + * + * example 2 (without parent group) + * + * api.php?op=set&op2=create_group&id=example_group_name2&other=computer|&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_create_group($id, $thrash1, $other, $thrash3) { - global $config; +function api_set_create_group($id, $thrash1, $other, $thrash3) +{ + global $config; - if (is_metaconsole()) return; + if (is_metaconsole()) { + return; + } - $group_name = $id; + $group_name = $id; - if (!check_acl($config['id_user'], 0, "PM")){ - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } - if ($id == "") { - returnError('error_create_group', - __('Error in group creation. Group_name cannot be left blank.')); - return; - } - - if ($other['data'][0] == "") { - returnError('error_create_group', - __('Error in group creation. Icon_name cannot be left blank.')); - return; - } - - - - $safe_other_data = io_safe_input($other['data']); - - if ($safe_other_data[1] != "") { - $group = groups_get_group_by_id($safe_other_data[1]); - - if ($group == false) { - returnError('error_create_group', - __('Error in group creation. Id_parent_group doesn\'t exist.')); - return; - } - } - - if ($safe_other_data[1] != "") { - $values = array( - 'icon' => $safe_other_data[0], - 'parent' => $safe_other_data[1], - 'description' => $safe_other_data[2] - ); - } - else { - $values = array( - 'icon' => $safe_other_data[0], - 'description' => $safe_other_data[2] - ); - } - $values['propagate'] = $safe_other_data[3]; - $values['disabled'] = $safe_other_data[4]; - $values['custom_id'] =$safe_other_data[5]; - $values['contact'] = $safe_other_data[6]; - $values['other'] = $safe_other_data[7]; - - $id_group = groups_create_group($group_name, $values); - - if (is_error($id_group)) { - // TODO: Improve the error returning more info - returnError('error_create_group', __('Error in group creation.')); - } - else { - - if (defined("METACONSOLE")) { - $servers = db_get_all_rows_sql ("SELECT * + if ($id == '') { + returnError( + 'error_create_group', + __('Error in group creation. Group_name cannot be left blank.') + ); + return; + } + + if ($other['data'][0] == '') { + returnError( + 'error_create_group', + __('Error in group creation. Icon_name cannot be left blank.') + ); + return; + } + + $safe_other_data = io_safe_input($other['data']); + + if ($safe_other_data[1] != '') { + $group = groups_get_group_by_id($safe_other_data[1]); + + if ($group == false) { + returnError( + 'error_create_group', + __('Error in group creation. Id_parent_group doesn\'t exist.') + ); + return; + } + } + + if ($safe_other_data[1] != '') { + $values = [ + 'icon' => $safe_other_data[0], + 'parent' => $safe_other_data[1], + 'description' => $safe_other_data[2], + ]; + } else { + $values = [ + 'icon' => $safe_other_data[0], + 'description' => $safe_other_data[2], + ]; + } + + $values['propagate'] = $safe_other_data[3]; + $values['disabled'] = $safe_other_data[4]; + $values['custom_id'] = $safe_other_data[5]; + $values['contact'] = $safe_other_data[6]; + $values['other'] = $safe_other_data[7]; + + $id_group = groups_create_group($group_name, $values); + + if (is_error($id_group)) { + // TODO: Improve the error returning more info + returnError('error_create_group', __('Error in group creation.')); + } else { + if (defined('METACONSOLE')) { + $servers = db_get_all_rows_sql( + 'SELECT * FROM tmetaconsole_setup - WHERE disabled = 0"); - - if ($servers === false) - $servers = array(); - - $result = array(); - foreach($servers as $server) { - // If connection was good then retrieve all data server - if (metaconsole_connect($server) == NOERR) { - $values['id_grupo'] = $id_group; - $id_group_node = groups_create_group($group_name, $values); - } - metaconsole_restore_db(); - } - } - - returnData('string', array('type' => 'string', 'data' => $id_group)); - } + WHERE disabled = 0' + ); + + if ($servers === false) { + $servers = []; + } + + $result = []; + foreach ($servers as $server) { + // If connection was good then retrieve all data server + if (metaconsole_connect($server) == NOERR) { + $values['id_grupo'] = $id_group; + $id_group_node = groups_create_group($group_name, $values); + } + + metaconsole_restore_db(); + } + } + + returnData('string', ['type' => 'string', 'data' => $id_group]); + } } + /** * Update a group. * - * @param integer $id Group ID + * @param integer $id Group ID * @param $thrash2 Don't use. - * @param array $other it's array, $other as param is ;;;;;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: + * @param array $other it's array, $other as param is ;;;;;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: * - * api.php?op=set&op2=update_group&id=example_group_id&other=New%20Name|application|2|new%20description|1|0|custom%20id||&other_mode=url_encode_separator_| + * api.php?op=set&op2=update_group&id=example_group_id&other=New%20Name|application|2|new%20description|1|0|custom%20id||&other_mode=url_encode_separator_| * * @param $thrash3 Don't use */ -function api_set_update_group($id_group, $thrash2, $other, $thrash3) { - global $config; - - if (defined ('METACONSOLE')) { - return; - } +function api_set_update_group($id_group, $thrash2, $other, $thrash3) +{ + global $config; - if (!check_acl($config['id_user'], 0, "PM")){ - returnError('forbidden', 'string'); - return; - } + if (defined('METACONSOLE')) { + return; + } - if (db_get_value('id_grupo', 'tgrupo', 'id_grupo', $id_group) === false) { - returnError('error_set_update_group', __('There is not any group with the id provided')); - return; - } + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } - if (!check_acl($config['id_user'], $id_group, "PM")){ - returnError('forbidden', 'string'); - return; - } + if (db_get_value('id_grupo', 'tgrupo', 'id_grupo', $id_group) === false) { + returnError('error_set_update_group', __('There is not any group with the id provided')); + return; + } - $name = $other['data'][0]; - $icon = $other['data'][1]; - $parent = $other['data'][2]; - $description = $other['data'][3]; - $propagate = $other['data'][4]; - $disabled = $other['data'][5]; - $custom_id = $other['data'][6]; - $contact = $other['data'][7]; - $other = $other['data'][8]; + if (!check_acl($config['id_user'], $id_group, 'PM')) { + returnError('forbidden', 'string'); + return; + } - $return = db_process_sql_update('tgrupo', - array('nombre' => $name, - 'icon' => $icon, - 'parent' => $parent, - 'description' => $description, - 'propagate' => $propagate, - 'disabled' => $disabled, - 'custom_id' => $custom_id, - 'contact' => $contact, - 'other' => $other), - array('id_grupo' => $id_group)); + $name = $other['data'][0]; + $icon = $other['data'][1]; + $parent = $other['data'][2]; + $description = $other['data'][3]; + $propagate = $other['data'][4]; + $disabled = $other['data'][5]; + $custom_id = $other['data'][6]; + $contact = $other['data'][7]; + $other = $other['data'][8]; - returnData('string', - array('type' => 'string', 'data' => (int)((bool)$return))); + $return = db_process_sql_update( + 'tgrupo', + [ + 'nombre' => $name, + 'icon' => $icon, + 'parent' => $parent, + 'description' => $description, + 'propagate' => $propagate, + 'disabled' => $disabled, + 'custom_id' => $custom_id, + 'contact' => $contact, + 'other' => $other, + ], + ['id_grupo' => $id_group] + ); + + returnData( + 'string', + [ + 'type' => 'string', + 'data' => (int) ((bool) $return), + ] + ); } + /** - * Delete a group - * - * @param integer $id Group ID + * Delete a group + * + * @param integer $id Group ID * @param $thrash1 Don't use. * @param $thrast2 Don't use. * @param $thrash3 Don't use. */ -function api_set_delete_group($id_group, $thrash2, $other, $thrash3) { - global $config; +function api_set_delete_group($id_group, $thrash2, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "PM")){ - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], 0, 'PM')) { + returnError('forbidden', 'string'); + return; + } - $group = db_get_row_filter('tgrupo', array('id_grupo' => $id_group)); - if (!$group) { - returnError('error_delete', 'Error in delete operation. Id does not exist.'); - return; - } + $group = db_get_row_filter('tgrupo', ['id_grupo' => $id_group]); + if (!$group) { + returnError('error_delete', 'Error in delete operation. Id does not exist.'); + return; + } - if (!check_acl($config['id_user'], $id_group, "PM")){ - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], $id_group, 'PM')) { + returnError('forbidden', 'string'); + return; + } - $usedGroup = groups_check_used($id_group); - if ($usedGroup['return']) { - returnError('error_delete', - 'Error in delete operation. The group is not empty (used in ' . - implode(', ', $usedGroup['tables']) . ').' ); - return; - } + $usedGroup = groups_check_used($id_group); + if ($usedGroup['return']) { + returnError( + 'error_delete', + 'Error in delete operation. The group is not empty (used in '.implode(', ', $usedGroup['tables']).').' + ); + return; + } - db_process_sql_update('tgrupo', array('parent' => $group['parent']), array('parent' => $id_group)); - db_process_sql_delete('tgroup_stat', array('id_group' => $id_group)); + db_process_sql_update('tgrupo', ['parent' => $group['parent']], ['parent' => $id_group]); + db_process_sql_delete('tgroup_stat', ['id_group' => $id_group]); - $result = db_process_sql_delete('tgrupo', array('id_grupo' => $id_group)); + $result = db_process_sql_delete('tgrupo', ['id_grupo' => $id_group]); - if (!$result) - returnError('error_delete', 'Error in delete operation.'); - else - returnData('string', array('type' => 'string', 'data' => __('Correct Delete'))); + if (!$result) { + returnError('error_delete', 'Error in delete operation.'); + } else { + returnData('string', ['type' => 'string', 'data' => __('Correct Delete')]); + } } + /** - * Create a new netflow filter. And return the id_group of the new group. - * + * Create a new netflow filter. And return the id_group of the new group. + * * @param $thrash1 Don't use. * @param $thrash2 Don't use. - * @param array $other it's array, $other as param is ;;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * - * Possible values of 'aggregate_by' field: dstip,dstport,none,proto,srcip,srcport - * Possible values of 'output_format' field: kilobytes,kilobytespersecond,megabytes,megabytespersecond - * - * example: - * - * api.php?op=set&op2=create_netflow_filter&id=Filter name&other=9|host 192.168.50.3 OR host 192.168.50.4 or HOST 192.168.50.6|dstport|kilobytes&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * + * Possible values of 'aggregate_by' field: dstip,dstport,none,proto,srcip,srcport + * Possible values of 'output_format' field: kilobytes,kilobytespersecond,megabytes,megabytespersecond + * + * example: + * + * api.php?op=set&op2=create_netflow_filter&id=Filter name&other=9|host 192.168.50.3 OR host 192.168.50.4 or HOST 192.168.50.6|dstport|kilobytes&other_mode=url_encode_separator_| + * * @param $thrash3 Don't use */ -function api_set_create_netflow_filter($thrash1, $thrash2, $other, $thrash3) { - global $config; +function api_set_create_netflow_filter($thrash1, $thrash2, $other, $thrash3) +{ + global $config; - if (defined ('METACONSOLE')) { - return; - } + if (defined('METACONSOLE')) { + return; + } - if (!check_acl($config['id_user'], 0, "AW")) { - returnError('forbidden', 'string'); - return; - } + if (!check_acl($config['id_user'], 0, 'AW')) { + returnError('forbidden', 'string'); + return; + } - if ($other['data'][0] == "") { - returnError('error_create_netflow_filter', __('Error in netflow filter creation. Filter name cannot be left blank.')); - return; - } - - if ($other['data'][1] == "") { - returnError('error_create_netflow_filter', __('Error in netflow filter creation. Group id cannot be left blank.')); - return; - } - else { - $group = groups_get_group_by_id($other['data'][1]); - - if ($group == false) { - returnError('error_create_group', __('Error in netflow filter creation. Id_group doesn\'t exist.')); - return; - } + if ($other['data'][0] == '') { + returnError('error_create_netflow_filter', __('Error in netflow filter creation. Filter name cannot be left blank.')); + return; + } - if (!check_acl($config['id_user'], $other['data'][1], "AW")) { - returnError('forbidden', 'string'); - return; - } - } - - if ($other['data'][2] == "") { - returnError('error_create_netflow_filter', __('Error in netflow filter creation. Filter cannot be left blank.')); - return; - } - - if ($other['data'][3] == "") { - returnError('error_create_netflow_filter', __('Error in netflow filter creation. Aggregate_by cannot be left blank.')); - return; - } - - if ($other['data'][4] == "") { - returnError('error_create_netflow_filter', __('Error in netflow filter creation. Output_format cannot be left blank.')); - return; - } - - $values = array ( - 'id_name'=> $other['data'][0], - 'id_group' => $other['data'][1], - 'advanced_filter'=> $other['data'][2], - 'aggregate'=> $other['data'][3], - 'output'=> $other['data'][4] - ); - - // Save filter args - $values['filter_args'] = netflow_get_filter_arguments ($values); - - $id = db_process_sql_insert('tnetflow_filter', $values); - - if ($id === false) { - returnError('error_create_netflow_filter', __('Error in netflow filter creation.')); - } - else { - returnData('string', array('type' => 'string', 'data' => $id)); - } + if ($other['data'][1] == '') { + returnError('error_create_netflow_filter', __('Error in netflow filter creation. Group id cannot be left blank.')); + return; + } else { + $group = groups_get_group_by_id($other['data'][1]); + + if ($group == false) { + returnError('error_create_group', __('Error in netflow filter creation. Id_group doesn\'t exist.')); + return; + } + + if (!check_acl($config['id_user'], $other['data'][1], 'AW')) { + returnError('forbidden', 'string'); + return; + } + } + + if ($other['data'][2] == '') { + returnError('error_create_netflow_filter', __('Error in netflow filter creation. Filter cannot be left blank.')); + return; + } + + if ($other['data'][3] == '') { + returnError('error_create_netflow_filter', __('Error in netflow filter creation. Aggregate_by cannot be left blank.')); + return; + } + + if ($other['data'][4] == '') { + returnError('error_create_netflow_filter', __('Error in netflow filter creation. Output_format cannot be left blank.')); + return; + } + + $values = [ + 'id_name' => $other['data'][0], + 'id_group' => $other['data'][1], + 'advanced_filter' => $other['data'][2], + 'aggregate' => $other['data'][3], + 'output' => $other['data'][4], + ]; + + // Save filter args + $values['filter_args'] = netflow_get_filter_arguments($values); + + $id = db_process_sql_insert('tnetflow_filter', $values); + + if ($id === false) { + returnError('error_create_netflow_filter', __('Error in netflow filter creation.')); + } else { + returnData('string', ['type' => 'string', 'data' => $id]); + } } + /** * Get module data in CSV format. - * - * @param integer $id The ID of module in DB. + * + * @param integer $id The ID of module in DB. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;; in this order - * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) - * example: - * - * api.php?op=get&op2=module_data&id=17&other=;|604800|20161201T13:40|20161215T13:40&other_mode=url_encode_separator_| - * + * @param array $other it's array, $other as param is ;;; in this order + * and separator char (after text ; ) and separator (pass in param othermode as othermode=url_encode_separator_) + * example: + * + * api.php?op=get&op2=module_data&id=17&other=;|604800|20161201T13:40|20161215T13:40&other_mode=url_encode_separator_| + * * @param $returnType Don't use. */ -function api_get_module_data($id, $thrash1, $other, $returnType) { - if (defined ('METACONSOLE')) { - return; - } +function api_get_module_data($id, $thrash1, $other, $returnType) +{ + if (defined('METACONSOLE')) { + return; + } - if (!util_api_check_agent_and_print_error(modules_get_agentmodule_agent($id), $returnType)) return; + if (!util_api_check_agent_and_print_error(modules_get_agentmodule_agent($id), $returnType)) { + return; + } - $separator = $other['data'][0]; - $periodSeconds = $other['data'][1]; - $tstart = $other['data'][2]; - $tend = $other['data'][3]; + $separator = $other['data'][0]; + $periodSeconds = $other['data'][1]; + $tstart = $other['data'][2]; + $tend = $other['data'][3]; - if (($tstart != "") && ($tend != "")) { - try { - $dateStart = explode("T", $tstart); - $dateYearStart = substr($dateStart[0], 0, 4); - $dateMonthStart = substr($dateStart[0], 4, 2); - $dateDayStart = substr($dateStart[0], 6, 2); - $date_start = $dateYearStart . "-" . $dateMonthStart . "-" . $dateDayStart . " " . $dateStart[1]; - $date_start = new DateTime($date_start); - $date_start = $date_start->format('U'); + if (($tstart != '') && ($tend != '')) { + try { + $dateStart = explode('T', $tstart); + $dateYearStart = substr($dateStart[0], 0, 4); + $dateMonthStart = substr($dateStart[0], 4, 2); + $dateDayStart = substr($dateStart[0], 6, 2); + $date_start = $dateYearStart.'-'.$dateMonthStart.'-'.$dateDayStart.' '.$dateStart[1]; + $date_start = new DateTime($date_start); + $date_start = $date_start->format('U'); - $dateEnd = explode("T", $tend); - $dateYearEnd = substr($dateEnd[0], 0, 4); - $dateMonthEnd = substr($dateEnd[0], 4, 2); - $dateDayEnd = substr($dateEnd[0], 6, 2); - $date_end = $dateYearEnd . "-" . $dateMonthEnd . "-" . $dateDayEnd . " " . $dateEnd[1]; - $date_end = new DateTime($date_end); - $date_end = $date_end->format('U'); - } - catch (Exception $e) { - returnError('error_query_module_data', 'Error in date format. '); - } + $dateEnd = explode('T', $tend); + $dateYearEnd = substr($dateEnd[0], 0, 4); + $dateMonthEnd = substr($dateEnd[0], 4, 2); + $dateDayEnd = substr($dateEnd[0], 6, 2); + $date_end = $dateYearEnd.'-'.$dateMonthEnd.'-'.$dateDayEnd.' '.$dateEnd[1]; + $date_end = new DateTime($date_end); + $date_end = $date_end->format('U'); + } catch (Exception $e) { + returnError('error_query_module_data', 'Error in date format. '); + } - $sql = sprintf ("SELECT utimestamp, datos + $sql = sprintf( + 'SELECT utimestamp, datos FROM tagente_datos WHERE id_agente_modulo = %d AND utimestamp > %d AND utimestamp < %d - ORDER BY utimestamp DESC", $id, $date_start, $date_end); - } - else { - if ($periodSeconds == null) { - $sql = sprintf ("SELECT utimestamp, datos + ORDER BY utimestamp DESC', + $id, + $date_start, + $date_end + ); + } else { + if ($periodSeconds == null) { + $sql = sprintf( + 'SELECT utimestamp, datos FROM tagente_datos WHERE id_agente_modulo = %d - ORDER BY utimestamp DESC", $id); - } - else { - $sql = sprintf ("SELECT utimestamp, datos + 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", $id, get_system_time () - $periodSeconds); - } - } + ORDER BY utimestamp DESC', + $id, + (get_system_time() - $periodSeconds) + ); + } + } - $data['type'] = 'array'; - $data['list_index'] = array('utimestamp', 'datos'); - $data['data'] = db_get_all_rows_sql($sql); - - if ($data === false) { - returnError('error_query_module_data', 'Error in the query of module data.'); - } - else if ($data['data'] == "") { - returnError('error_query_module_data', 'No data to show.'); - } - else { - returnData('csv', $data, $separator); - } + $data['type'] = 'array'; + $data['list_index'] = [ + 'utimestamp', + 'datos', + ]; + $data['data'] = db_get_all_rows_sql($sql); + + if ($data === false) { + returnError('error_query_module_data', 'Error in the query of module data.'); + } else if ($data['data'] == '') { + returnError('error_query_module_data', 'No data to show.'); + } else { + returnData('csv', $data, $separator); + } } + /** * Return a image file of sparse graph of module data in a period time. - * - * @param integer $id id of a module data. + * + * @param integer $id id of a module data. * @param $thrash1 Don't use. - * @param array $other it's array, $other as param is ;;;
        ' . $label .'
        '; - } - elseif ($label_position == 'right') { - $text = '
        ' . $label .'
        '; - } - else { - $text = '
        ' . $label .'
        '; - } - - - - if (!isset($layoutData['status_calculated'])) { - $layoutData['status_calculated'] = visual_map_get_status_element($layoutData); - } - $status = $layoutData['status_calculated']; - - - switch ($status) { - case VISUAL_MAP_STATUS_CRITICAL_BAD: - //Critical (BAD) - $colorStatus = COL_CRITICAL; - break; - case VISUAL_MAP_STATUS_CRITICAL_ALERT: - //Critical (ALERT) - $colorStatus = COL_ALERTFIRED; - break; - case VISUAL_MAP_STATUS_NORMAL: - //Normal (OK) - $colorStatus = COL_NORMAL; - break; - case VISUAL_MAP_STATUS_WARNING: - //Warning - $colorStatus = COL_WARNING; - break; - case VISUAL_MAP_STATUS_UNKNOWN: - default: - //Unknown - // Default is Blue (Other) - $colorStatus = COL_UNKNOWN; - break; - } - - $element_enterprise = array(); - if (enterprise_installed()) { - $element_enterprise = enterprise_visual_map_print_item( - $mode, $layoutData, $proportion, $show_links, $isExternalLink); - } - - - $link = false; - $url = "#"; - - if ($show_links && ($mode == 'read')) { - switch ($type) { - case STATIC_GRAPH: - case GROUP_ITEM: - if ($layoutData['enable_link'] - && can_user_access_node()) { - $link = true; - } - break; - case LABEL: - if ($layoutData['id_layout_linked'] != 0) { - $link = true; - } - break; - case ICON: - if ($layoutData['id_layout_linked'] > 0) { - $link = true; - } - elseif (preg_match('//', $layoutData['label'], $matches)) { - // Link to an URL - if ($layoutData['enable_link']) { - $link = true; - } - } - elseif (preg_match('/^.*(http:\/\/)((.)+).*$/i', $layoutData['label'])) { - // Link to an URL - if ($layoutData['enable_link']) { - $link = true; - } - } - break; - case SIMPLE_VALUE: - case SIMPLE_VALUE_MAX: - case SIMPLE_VALUE_MIN: - case SIMPLE_VALUE_AVG: - //Extract id service if it is a prediction module. - $id_service = db_get_value_filter('custom_integer_1', - 'tagente_modulo', - array('id_agente_modulo' => $layoutData['id_agente_modulo'], - 'prediction_module' => 1)); - - if (!empty($id_service) && can_user_access_node()) { - if ($layoutData['enable_link']) { - $link = true; - } - - } - elseif ($layoutData['id_layout_linked'] > 0) { - $link = true; - } - elseif ($layoutData['enable_link'] && can_user_access_node()) { - $link = true; - } - break; - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - if (!empty($layoutData['id_agent']) - && empty($layoutData['id_layout_linked'])) { - - - if ($layoutData['enable_link'] - && can_user_access_node()) { - - //Extract id service if it is a prediction module. - $id_service = db_get_value_filter('custom_integer_1', - 'tagente_modulo', - array( - 'id_agente_modulo' => $layoutData['id_agente_modulo'], - 'prediction_module' => 1)); - - if (!empty($id_service)) { - //Link to an service page - - $link = true; - } - else if ($layoutData['id_agente_modulo'] != 0) { - // Link to an module - $link = true; - } - else { - // Link to an agent - $link = true; - } - } - } - elseif ($layoutData['id_layout_linked'] > 0) { - // Link to a map - $link = true; - - } - break; - case MODULE_GRAPH: - if (( - ($layoutData['id_layout_linked'] == "") - || ($layoutData['id_layout_linked'] == 0)) - && can_user_access_node()) { - - if ($layoutData['enable_link']) { - - //Extract id service if it is a prediction module. - $id_service = db_get_value_filter('custom_integer_1', - 'tagente_modulo', - array('id_agente_modulo' => $layoutData['id_agente_modulo'], - 'prediction_module' => 1)); - - if ($id_service === false) { - $id_service = 0; - } - - if ($id_service != 0) { - //Link to an service page - if (!empty($layoutData['id_metaconsole'])) { - $link = true; - } - else { - $link = true; - } - } - else { - $link = true; - } - } - } - else { - // Link to a map - $link = true; - } - - break; - case BARS_GRAPH: - $link = true; - break; - case AUTO_SLA_GRAPH: - $link = true; - break; - case DONUT_GRAPH: - $link = true; - break; - default: - if (!empty($element_enterprise)) { - $link = $element_enterprise['link']; - } - break; - } - } - - if ($link) { - switch ($type) { - case STATIC_GRAPH: - $is_a_service = false; - $is_a_link_to_other_visualconsole = false; - - if (enterprise_installed()) { - $id_service = services_service_from_module - ($layoutData['id_agente_modulo']); - - if (!empty($id_service)) - $is_a_service = true; - } - - if ($layoutData['id_layout_linked'] != 0) { - $is_a_link_to_other_visualconsole = true; - } - - if ($is_a_service) { - if (empty($layoutData['id_metaconsole'])) { - $url = $config['homeurl'] . - 'index.php?sec=services&sec2=enterprise/operation/services/services&id_service=' . - $id_service . '&offset=0'; - } - else { - $server = db_get_row('tmetaconsole_setup', - 'id', $layoutData['id_metaconsole']); - - $url = $server["server_url"] . "/" . - 'index.php?sec=services&sec2=enterprise/operation/services/services&id_service=' . - $id_service . '&offset=0'; - } - } - else if ($is_a_link_to_other_visualconsole) { - if (!is_metaconsole()) { - $url = $config['homeurl'] . "index.php?sec=reporting&sec2=operation/visual_console/render_view&pure=" . $config["pure"] . "&id=" . $layoutData["id_layout_linked"]; - } - else { - $url = "index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=0&id_visualmap=" . $layoutData["id_layout_linked"] . "&refr=0"; - } - } - else { - if ($layoutData['id_agente_modulo'] != 0) { - // Link to an module - if (empty($layoutData['id_metaconsole'])) { - $url = $config['homeurl'] . - 'index.php?sec=view&sec2=operation/agentes/status_monitor&id_module=' . $layoutData['id_agente_modulo']; - } - else { - $url = ui_meta_get_url_console_child( - $layoutData['id_metaconsole'], - "estado", "operation/agentes/ver_agente&id_agente=" . $layoutData['id_agent'], null, null, null, $isExternalLink); - } - } - else { - // Link to an agent - if (empty($layoutData['id_metaconsole'])) { - $url = $config['homeurl'] . - 'index.php?sec=estado&sec2=operation/agentes/ver_agente&id_agente=' . $layoutData['id_agent']; - } - else { - $url = ui_meta_get_url_console_child( - $layoutData['id_metaconsole'], - "estado", "operation/agentes/ver_agente&id_agente=" . $layoutData['id_agent'], null, null, null, $isExternalLink); - } - } - } - - - break; - case AUTO_SLA_GRAPH: - $e_period = $layoutData['period']; - $date = get_system_time (); - $datelimit = $date - $e_period; - - $time_format = "Y/m/d H:i:s"; - - $timestamp_init = date($time_format, $datelimit); - $timestamp_end = date($time_format, $date); - - $timestamp_init_aux = explode(" ", $timestamp_init); - $timestamp_end_aux = explode(" ", $timestamp_end); - - $date_from = $timestamp_init_aux[0]; - $time_from = $timestamp_init_aux[1]; - - $date_to = $timestamp_end_aux[0]; - $time_to = $timestamp_end_aux[1]; - - if (empty($layout_data['id_metaconsole'])) { - $url = $config['homeurl'] . "index.php?sec=eventos&sec2=operation/events/events&id_agent=" . $layoutData['id_agent'] . - "&module_search_hidden=" . $layoutData['id_agente_modulo'] . "&date_from=" . $date_from . "&time_from=" . $time_from . - "&date_to=" . $date_to . "&time_to=" . $time_to . "&status=-1"; - } - else { - $url = "index.php?sec=eventos&sec2=operation/events/events&id_agent=" . $layoutData['id_agent'] . - "&module_search_hidden=" . $layoutData['id_agente_modulo'] . "&date_from=" . $date_from . "&time_from=" . $time_from . - "&date_to=" . $date_to . "&time_to=" . $time_to . "&status=-1"; - } - break; - - case DONUT_GRAPH: - if (empty($layout_data['id_metaconsole'])) { - $url = $config['homeurl'] . "index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&id_agente=" . $layoutData['id_agent'] . - "&tab=module&edit_module=1&id_agent_module=" . $layoutData['id_agente_modulo']; - } - else { - $url = "index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&id_agente=" . $layoutData['id_agent'] . - "&tab=module&edit_module=1&id_agent_module=" . $layoutData['id_agente_modulo']; - } - break; - - case BARS_GRAPH: - if (empty($layout_data['id_metaconsole'])) { - $url = $config['homeurl'] . "index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&id_agente=" . $layoutData['id_agent'] . - "&tab=module&edit_module=1&id_agent_module=" . $layoutData['id_agente_modulo']; - } - else { - $url = "index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&id_agente=" . $layoutData['id_agent'] . - "&tab=module&edit_module=1&id_agent_module=" . $layoutData['id_agente_modulo']; - } - break; - - case GROUP_ITEM: - $is_a_link_to_other_visualconsole = false; - if ($layoutData['id_layout_linked'] != 0) { - $is_a_link_to_other_visualconsole = true; - } - if ($is_a_link_to_other_visualconsole) { - if (METACONSOLE == 1) { - $url = $config['homeurl'] . "index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=0&id_visualmap=".$layoutData["id_layout_linked"]."&refr=300"; - } - else { - $url = $config['homeurl'] . "index.php?sec=reporting&sec2=operation/visual_console/render_view&pure=" . $config["pure"] . "&id=" . $layoutData["id_layout_linked"]; - } - } - else { - if (METACONSOLE == 1) { - $url = $config['homeurl'] . - 'index.php?sec=estado&sec2=operation/agentes/status_monitor&refr=0&ag_group='.$layoutData['id_group'].'&ag_freestring=&module_option=1&ag_modulename=&moduletype=&datatype=&status=-1&sort_field=&sort=none&pure='; - } - else { - $url = $config['homeurl'] . - 'index.php?sec=estado&sec2=operation/agentes/estado_agente&group_id='.$layoutData['id_group']; - } - } - break; - case LABEL: - if ($layoutData['id_layout_linked'] != 0) { - // Link to a map - $url = $config['homeurl'] . - 'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config["pure"].'&id='.$layoutData["id_layout_linked"]; - } - break; - case ICON: - $url_icon = ""; - if ($layoutData['id_layout_linked'] != 0) { - // Link to a map - if (empty($layoutData['id_metaconsole'])) { - $url = 'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config["pure"].'&id='.$layoutData["id_layout_linked"]; - } - else { - $pure = get_parameter('pure', 0); - $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=' . $pure . '&id_visualmap=' . $layoutData["id_layout_linked"] . '&refr=0'; - } - } - elseif (preg_match('//', $layoutData['label'], $matches)) { - // Link to an URL - if ($layoutData['enable_link']) { - $url = strip_tags($matches[1]); - } - } - elseif (preg_match('/^.*(http:\/\/)((.)+).*$/i', $layoutData['label'])) { - // Link to an URL - if ($layoutData['enable_link']) { - $url = strip_tags($layoutData['label']); - } - } - break; - case SIMPLE_VALUE: - case SIMPLE_VALUE_MAX: - case SIMPLE_VALUE_MIN: - case SIMPLE_VALUE_AVG: - //Extract id service if it is a prediction module. - $id_service = db_get_value_filter('custom_integer_1', - 'tagente_modulo', - array('id_agente_modulo' => $layoutData['id_agente_modulo'], - 'prediction_module' => 1)); - - if (!empty($id_service) && can_user_access_node()) { - - //Link to an service page - if (!empty($layoutData['id_metaconsole'])) { - $server = db_get_row('tmetaconsole_setup', - 'id', $layoutData['id_metaconsole']); - - $url = $server["server_url"] . "/" . - 'index.php?sec=services&sec2=enterprise/operation/services/services&id_service=' . - $id_service . '&offset=0'; - } - else { - $url = 'index.php?sec=services&sec2=enterprise/operation/services/services&id_service=' . - $id_service . '&offset=0'; - } - - } - elseif ($layoutData['id_layout_linked'] > 0) { - - // Link to a map - if (empty($layoutData['id_metaconsole'])) { - $url = 'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config["pure"].'&id='.$layoutData["id_layout_linked"]; - } - else { - $pure = get_parameter('pure', 0); - $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=' . $pure . '&id_visualmap=' . $layoutData["id_layout_linked"] . '&refr=0'; - } - } - elseif ($layoutData['id_agente_modulo'] != 0) { - // Link to an module - if (empty($layoutData['id_metaconsole'])) { - $url = $config['homeurl'] . - 'index.php?sec=view&sec2=operation/agentes/status_monitor&id_module=' . $layoutData['id_agente_modulo']; - } - else { - $url = ui_meta_get_url_console_child( - $layoutData['id_metaconsole'], - "estado", "operation/agentes/ver_agente&id_agente=" . $layoutData['id_agent'], null, null, null, $isExternalLink); - } - } - break; - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - if (!empty($layoutData['id_agent'])) { - - //Extract id service if it is a prediction module. - $id_service = db_get_value_filter('custom_integer_1', - 'tagente_modulo', - array( - 'id_agente_modulo' => $layoutData['id_agente_modulo'], - 'prediction_module' => 1)); - - - - if (!empty($id_service)) { - //Link to an service page - - if (!empty($layoutData['id_metaconsole'])) { - $server = db_get_row('tmetaconsole_setup', - 'id', $layoutData['id_metaconsole']); - - $url = - $server["server_url"] . "/" . - 'index.php?sec=services&sec2=enterprise/operation/services/services&id_service=' . - $id_service . '&offset=0'; - } - else { - $url = 'index.php?sec=services&sec2=enterprise/operation/services/services&id_service=' . - $id_service . '&offset=0'; - } - } - else if ($layoutData['id_agente_modulo'] != 0) { - // Link to an module - if (!empty($layoutData['id_metaconsole'])) { - $server = db_get_row('tmetaconsole_setup', - 'id', $layoutData['id_metaconsole']); - - $url = - $server["server_url"] . - '/index.php?sec=view&sec2=operation/agentes/status_monitor&id_module=' . $layoutData['id_agente_modulo']; - } - else { - $url = - $config['homeurl'].'/index.php?sec=view&sec2=operation/agentes/status_monitor&id_module=' . $layoutData['id_agente_modulo']; - } - } - else { - // Link to an agent - if (empty($layoutData['id_metaconsole'])) { - $url = $config['homeurl'] . - 'index.php?' . - 'sec=estado&' . - 'sec2=operation/agentes/ver_agente&id_agente='.$layoutData['id_agent']; - } - else { - $url = ui_meta_get_url_console_child( - $layoutData['id_metaconsole'], - "estado", 'operation/agentes/ver_agente&id_agente='.$layoutData['id_agent'], null, null, null, $isExternalLink); - } - } - } - elseif ($layoutData['id_layout_linked'] > 0) { - - // Link to a map - if (empty($layoutData['id_metaconsole'])) { - $url = 'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config["pure"].'&id='.$layoutData["id_layout_linked"]; - } - else { - $pure = get_parameter('pure', 0); - $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=' . $pure . '&id_visualmap=' . $layoutData["id_layout_linked"] . '&refr=0'; - } - } - break; - case MODULE_GRAPH: - if (( - ($layoutData['id_layout_linked'] == "") - || ($layoutData['id_layout_linked'] == 0)) - && can_user_access_node()) { - - if ($layoutData['enable_link']) { - - //Extract id service if it is a prediction module. - $id_service = db_get_value_filter('custom_integer_1', - 'tagente_modulo', - array('id_agente_modulo' => $layoutData['id_agente_modulo'], - 'prediction_module' => 1)); - - if (!empty($id_service)) { - //Link to an service page - if (!empty($layoutData['id_metaconsole'])) { - $server = db_get_row('tmetaconsole_setup', - 'id', $layoutData['id_metaconsole']); - - $url = - $server["server_url"] . - '/index.php?sec=services&sec2=enterprise/operation/services/services&id_service=' . - $id_service . '&offset=0'; - } - else { - $url = $config['homeurl'] . - '/index.php?sec=services&sec2=enterprise/operation/services/services&id_service=' . - $id_service . '&offset=0'; - } - } - else { - if (empty($layoutData['id_metaconsole'])) { - $url = $config['homeurl'] . - '/index.php?sec=view&sec2=operation/agentes/status_monitor&id_module=' . $layoutData['id_agente_modulo']; - } - else { - $url = ui_meta_get_url_console_child( - $layoutData['id_metaconsole'], - "estado", 'operation/agentes/ver_agente&id_agente='.$layoutData["id_agent"].'&tab=data', null, null, null, $isExternalLink); - } - } - } - } - else { - // Link to a map - if (empty($layoutData['id_metaconsole'])) { - $url = $config['homeurl'] . - '/index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config["pure"].'&id='.$layoutData["id_layout_linked"]; - } - else { - $pure = get_parameter('pure', 0); - $url = $config['homeurl'] . - '/index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=' . $pure . '&id_visualmap=' . $layoutData["id_layout_linked"] . '&refr=0'; - } - } - break; - default: - if (!empty($element_enterprise)) { - $url = $element_enterprise['url']; - } - break; - } - - // Override url - if ( - is_metaconsole() && - !empty($layoutData["id_layout_linked"]) && - !empty($layoutData["linked_layout_node_id"]) - ) { - $url = ui_meta_get_url_console_child( - $layoutData['linked_layout_node_id'], - "network", "operation/visual_console/render_view&id=" . (int) $layoutData["id_layout_linked"] - ); - } - } - - // + 1 for to avoid the box and lines items are on the top of - // others - $z_index = 1 + 1; - - switch ($type) { - case STATIC_GRAPH: - case GROUP_ITEM: - if ($layoutData['image'] != null) { - $img = visual_map_get_image_status_element($layoutData, - $layoutData['status_calculated']); - if (substr($img,0,1) == '4') { - $borderStyle ='border: 2px solid ' . COL_ALERTFIRED . ';'; - $img = substr_replace($img, '', 0,1); - } - } - - if ($status == VISUAL_MAP_STATUS_CRITICAL_BAD) - $z_index = 3 + 1; - elseif ($status == VISUAL_MAP_STATUS_WARNING) - $z_index = 2 + 1; - elseif ($status == VISUAL_MAP_STATUS_CRITICAL_ALERT) - $z_index = 4 + 1; - else - $z_index = 1 + 1; - break; - case ICON: - if ($layoutData['image'] != null) { - $img = visual_map_get_image_status_element($layoutData, - $layoutData['status_calculated']); - } - - if (($width != 0) && ($height != 0)) { - $sizeStyle = 'width: ' . $width . 'px; height: ' . $height . 'px;'; - $imageSize = 'width="' . $width . '" height="' . $height . '"'; - } - - $z_index = 4 + 1; - break; - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - //Metaconsole db connection - if ($layoutData['id_metaconsole'] != 0) { - $connection = db_get_row_filter ('tmetaconsole_setup', - array('id' => $layoutData['id_metaconsole'])); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_name); - continue; - } - } - - //data - $module_value = db_get_sql ('SELECT datos - FROM tagente_estado - WHERE id_agente_modulo = ' . $id_module); - //state - $module_status = db_get_sql ('SELECT estado - FROM tagente_estado - WHERE id_agente_modulo = ' . $id_module); - - if (empty($module_value) || $module_value == 0) { - $colorStatus = COL_UNKNOWN; - } - else{ - switch ($module_status) { - case 0: //Normal - $colorStatus = COL_NORMAL; - break; - case 1: //Critical - $colorStatus = COL_CRITICAL; - break; - case 2: //Warning - $colorStatus = COL_WARNING; - break; - case 4: //Not_INIT - $colorStatus = COL_NOTINIT; - break; - case 3: //Unknown - default: - $colorStatus = COL_UNKNOWN; - break; - } - } - - $value_text = false; - if ($layoutData['image'] == 'percent') { - $value_text = false; - } - elseif ($layoutData['image'] == 'value') { - $unit_text = db_get_sql ('SELECT unit - FROM tagente_modulo - WHERE id_agente_modulo = ' . $id_module); - $unit_text = trim(io_safe_output($unit_text)); - - $value_text = format_for_graph($module_value, 2); - if($value_text<=0){ - $value_text = remove_right_zeros(number_format($module_value, $config['graph_precision'])); - - } - if (!empty($unit_text)) - $value_text .= " " . $unit_text; - } - - //Restore db connection - if ($layoutData['id_metaconsole'] != 0) { - metaconsole_restore_db(); - } - - if ( $max_percentile > 0) - $percentile = format_numeric($module_value / $max_percentile * 100, 0); - else - $percentile = 100; - break; - case MODULE_GRAPH: - - $imgpos = ''; - - if($layoutData['label_position']=='left'){ - $imgpos = 'float:right'; - } - else if($layoutData['label_position']=='right'){ - $imgpos = 'float:left'; - } - - if (!empty($proportion)) { - $width = - ((integer)($proportion['proportion_width'] * $width)); - $height = - ((integer)($proportion['proportion_height'] * $height)); - } - //Metaconsole db connection - if ($layoutData['id_metaconsole'] != 0) { - $connection = db_get_row_filter ('tmetaconsole_setup', - array('id' => $layoutData['id_metaconsole'])); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_name); - continue; - } - } - - $only_image = !$graph_javascript && $isExternalLink; - - if ($layoutData['id_custom_graph'] != 0) { - // Show only avg on the visual console - if (get_parameter('action') == 'edit') { - if($width == 0 || $height == 0) { - $img = ''; - } - else { - $img = ''; - } - } - else { - if ($width == 0 ) { - $width = 180; - } - if($height == 0) { - $height = 480; - } - - $graphs = db_get_all_rows_field_filter ("tgraph", "id_graph", $layoutData['id_custom_graph']); - - $params =array( - 'period' => $period, - 'width' => $width, - 'height' => $height, - 'title' => '', - 'unit_name' => null, - 'show_alerts' => false, - 'only_image' => $only_image, - 'vconsole' => true, - 'backgroundColor' => $layoutData['image'] - ); - - $params_combined = array( - 'id_graph' => $layoutData['id_custom_graph'], - 'stacked' => $graphs[0]["stacked"], - 'summatory' => $graphs[0]["summatory_series"], - 'average' => $graphs[0]["average_series"], - 'modules_series' => $graphs[0]["modules_series"] - ); - - if ($layoutData['label_position']=='left') { - $img = '
        '. - graphic_combined_module( - false, - $params, - $params_combined - ).'
        '; - } - elseif ($layoutData['label_position']=='right') { - $img = '
        '. - graphic_combined_module( - false, - $params, - $params_combined - ).'
        '; - } - else { - $img = graphic_combined_module( - false, - $params, - $params_combined - ); - } - } - } - else { - if ($isExternalLink) - $homeurl = $config['homeurl']; - else - $homeurl = ''; - - if ( (get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap') ) { - if($width == 0 || $height == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else { - - if ($width == 0 || $height == 0) { - $width = 300; - $height = 180; - } - - $params =array( - 'agent_module_id' => $id_module, - 'period' => $period, - 'show_events' => false, - 'width' => $width, - 'height' => $height, - 'title' => modules_get_agentmodule_name($id_module), - 'unit' => modules_get_unit($id_module), - 'only_image' => $only_image, - 'menu' => false, - 'backgroundColor' => $layoutData['image'], - 'type_graph' => $type_graph, - 'vconsole' => true - ); - - if ($layoutData['label_position']=='left') { - $img = '
        '. - grafico_modulo_sparse($params) . '
        '; - } - elseif($layoutData['label_position']=='right') { - - $img = '
        ' . - grafico_modulo_sparse($params) . '
        '; - } - else { - $img = grafico_modulo_sparse($params); - } - - } - } - - //Restore db connection - if ($layoutData['id_metaconsole'] != 0) { - metaconsole_restore_db(); - } - break; - - case BARS_GRAPH: - $imgpos = ''; - - if($layoutData['label_position']=='left'){ - $imgpos = 'float:right'; - } - else if($layoutData['label_position']=='right'){ - $imgpos = 'float:left'; - } - - if (!empty($proportion)) { - $width = - ((integer)($proportion['proportion_width'] * $width)); - $height = - ((integer)($proportion['proportion_height'] * $height)); - } - //Metaconsole db connection - if ($layoutData['id_metaconsole'] != 0) { - $connection = db_get_row_filter ('tmetaconsole_setup', - array('id' => $layoutData['id_metaconsole'])); - if (metaconsole_load_external_db($connection) != NOERR) { - continue; - } - } - - if ($isExternalLink) - $homeurl = $config['homeurl']; - else - $homeurl = ''; - - $is_string = db_get_value_filter ('id_tipo_modulo', 'tagente_modulo', - array ('id_agente' => $layoutData['id_agent'], - 'id_agente_modulo' => $id_module)); - - if ( (get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap') ) { - if($width == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else { - $color = array(); - - $color[0] = array('border' => '#000000', - 'color' => $config['graph_color1'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[1] = array('border' => '#000000', - 'color' => $config['graph_color2'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[2] = array('border' => '#000000', - 'color' => $config['graph_color3'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[3] = array('border' => '#000000', - 'color' => $config['graph_color4'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[4] = array('border' => '#000000', - 'color' => $config['graph_color5'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[5] = array('border' => '#000000', - 'color' => $config['graph_color6'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[6] = array('border' => '#000000', - 'color' => $config['graph_color7'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[7] = array('border' => '#000000', - 'color' => $config['graph_color8'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[8] = array('border' => '#000000', - 'color' => $config['graph_color9'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[9] = array('border' => '#000000', - 'color' => $config['graph_color10'], - 'alpha' => CHART_DEFAULT_ALPHA); - $color[11] = array('border' => '#000000', - 'color' => COL_GRAPH9, - 'alpha' => CHART_DEFAULT_ALPHA); - $color[12] = array('border' => '#000000', - 'color' => COL_GRAPH10, - 'alpha' => CHART_DEFAULT_ALPHA); - $color[13] = array('border' => '#000000', - 'color' => COL_GRAPH11, - 'alpha' => CHART_DEFAULT_ALPHA); - $color[14] = array('border' => '#000000', - 'color' => COL_GRAPH12, - 'alpha' => CHART_DEFAULT_ALPHA); - $color[15] = array('border' => '#000000', - 'color' => COL_GRAPH13, - 'alpha' => CHART_DEFAULT_ALPHA); - - $module_data = get_bars_module_data($id_module); - $water_mark = array('file' => '/var/www/html/pandora_console/images/logo_vertical_water.png', - 'url' => 'http://localhost/pandora_console/images/logo_vertical_water.png'); - - if ($width == 0 && $height == 0) { - if ($layoutData['label_position']=='left') { - if ($layoutData['type_graph'] == 'horizontal') { - $img = '
        '. - hbar_graph($module_data, - 400, 400, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], $layoutData['border_color']) . '
        '; - } - else { - $img = '
        '. - vbar_graph($module_data, - 400, 400, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], true, false, $layoutData['border_color']) . '
        '; - } - } - elseif($layoutData['label_position']=='right') { - if ($layoutData['type_graph'] == 'horizontal') { - $img = '
        '. - hbar_graph($module_data, - 400, 400, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], $layoutData['border_color']) . '
        '; - } - else { - $img = '
        '. - vbar_graph($module_data, - 400, 400, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], true, false, $layoutData['border_color']) . '
        '; - } - } - else { - if ($layoutData['type_graph'] == 'horizontal') { - $img = hbar_graph($module_data, - 400, 400, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], $layoutData['border_color']); - } - else { - $img = vbar_graph($module_data, - 400, 400, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], true, false, $layoutData['border_color']); - } - } - } - else{ - if ($layoutData['label_position']=='left') { - if ($layoutData['type_graph'] == 'horizontal') { - $img = '
        '. - hbar_graph($module_data, - $width, $height, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], $layoutData['border_color']) . '
        '; - } - else { - $img = '
        '. - vbar_graph($module_data, - $width, $height, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], true, false, $layoutData['border_color']) . '
        '; - } - } - elseif($layoutData['label_position']=='right') { - if ($layoutData['type_graph'] == 'horizontal') { - $img = '
        '. - hbar_graph($module_data, - $width, $height, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], $layoutData['border_color']) . '
        '; - } - else { - $img = '
        '. - vbar_graph($module_data, - $width, $height, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], true, false, $layoutData['border_color']) . '
        '; - } - } - else { - if ($layoutData['type_graph'] == 'horizontal') { - $img = hbar_graph($module_data, - $width, $height, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], $layoutData['border_color']); - } - else { - $img = vbar_graph($module_data, - $width, $height, $color, array(), array(), - ui_get_full_url("images/image_problem_area.png", false, false, false), - "", "", $water_mark, $config['fontpath'], 6, - "", 0, $config['homeurl'], $layoutData['image'], true, false, $layoutData['border_color']); - } - } - } - } - - //Restore db connection - if ($layoutData['id_metaconsole'] != 0) { - metaconsole_restore_db(); - } - - break; - - case DONUT_GRAPH: - if (!empty($id_metaconsole)) { - $connection = db_get_row_filter ('tmetaconsole_setup', $id_metaconsole); - if (metaconsole_load_external_db($connection) != NOERR) { - continue; - } - } - - - $is_string = db_get_value_filter ('id_tipo_modulo', 'tagente_modulo', - array ('id_agente' => $layoutData['id_agent'], - 'id_agente_modulo' => $id_module)); - - if (!empty($id_metaconsole)) { - metaconsole_restore_db(); - } - - if (($is_string == 17) || ($is_string == 23) || ($is_string == 3) || - ($is_string == 10) || ($is_string == 33)) { - $no_data = false; - } - else { - $no_data = true; - } - - if ($no_data) { - if($width == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else { - $donut_data = get_donut_module_data($layoutData['id_agente_modulo']); - - if ((get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap')) { - if($width == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else { - if ($width == 0) { - $img = d3_donut_graph ($layoutData['id'], 300, 300, $donut_data, $layoutData['border_color']); - } - else{ - $img = d3_donut_graph ($layoutData['id'], $width, $width, $donut_data, $layoutData['border_color']); - } - } - } - - //Restore db connection - if ($layoutData['id_metaconsole'] != 0) { - metaconsole_restore_db(); - } - - $z_index = 2 + 1; - break; - - case LABEL: - $z_index = 4 + 1; - break; - case BOX_ITEM: - $z_index = 1; - break; - case CLOCK: - if ((get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap')) { - if($width == 0){ - if ($layoutData['id_metaconsole'] != 0) { - if($layoutData['clock_animation'] == 'analogic_1'){ - $img = ''; - } - else{ - - if($layoutData['time_format'] = 'time'){ - $img = ''; - } - else{ - $img = ''; - } - } - } - else{ - if($layoutData['clock_animation'] == 'analogic_1'){ - $img = ''; - } - else{ - - if($layoutData['time_format'] == 'time'){ - $img = ''; - } - else{ - $img = ''; - } - } - } - } - else{ - $image_prefix = ($layoutData['id_metaconsole'] != 0) ? "../../" : ""; - if($layoutData['clock_animation'] == 'analogic_1'){ - $img = ''; - } - else{ - $height_offset = ($layoutData['time_format'] == 'time') ? 20 : 40; - $img = ''; - } - } - } - else{ - if($layoutData['clock_animation'] == 'analogic_1'){ - if ($layoutData['label_position']=='left') { - $img = '
        ' . print_clock_analogic_1 ($layoutData['time_format'], $layoutData['timezone'],$layoutData['clock_animation'],$layoutData['width'],$layoutData['height'],$layoutData['id'],$layoutData['fill_color']).'
        '; - } - elseif ($layoutData['label_position']=='right') { - $img = '
        ' . print_clock_analogic_1 ($layoutData['time_format'], $layoutData['timezone'],$layoutData['clock_animation'],$layoutData['width'],$layoutData['height'],$layoutData['id'],$layoutData['fill_color']).'
        '; - } - else { - $img = '
        ' . print_clock_analogic_1 ($layoutData['time_format'], $layoutData['timezone'],$layoutData['clock_animation'],$layoutData['width'],$layoutData['height'],$layoutData['id'],$layoutData['fill_color']).'
        '; - } - } - elseif($layoutData['clock_animation'] == 'digital_1'){ - if ($layoutData['label_position']=='left') { - $img = '
        ' . print_clock_digital_1 ($layoutData['time_format'], $layoutData['timezone'],$layoutData['clock_animation'],$layoutData['width'],$layoutData['height'],$layoutData['id'],$layoutData['fill_color']).'
        '; - } - elseif ($layoutData['label_position']=='right') { - $img = '
        ' .print_clock_digital_1 ($layoutData['time_format'], $layoutData['timezone'],$layoutData['clock_animation'],$layoutData['width'],$layoutData['height'],$layoutData['id'],$layoutData['fill_color']).'
        '; - } - else { - $img ='
        ' . print_clock_digital_1 ($layoutData['time_format'], $layoutData['timezone'],$layoutData['clock_animation'],$layoutData['width'],$layoutData['height'],$layoutData['id'],$layoutData['fill_color']).'
        '; - } - } - } - break; - case AUTO_SLA_GRAPH: - if ((get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap')) { - if($width == 0 || $height == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else { - if ($width == 0 || $height == 0) { - if ($layoutData['label_position']=='left') { - $img = '
        ' .graph_graphic_moduleevents ($layoutData['id_agent'], $layoutData['id_agente_modulo'], 500, 50, $layoutData['period'], '', true).'
        '; - } - elseif ($layoutData['label_position']=='right') { - $img = '
        ' . graph_graphic_moduleevents ($layoutData['id_agent'], $layoutData['id_agente_modulo'], 500, 50, $layoutData['period'], '', true).'
        '; - } - else { - $img = '
        ' . graph_graphic_moduleevents ($layoutData['id_agent'], $layoutData['id_agente_modulo'], 500, 50, $layoutData['period'], '', true).'
        '; - } - } - else{ - if ($layoutData['label_position']=='left') { - $img = '
        ' . graph_graphic_moduleevents ($layoutData['id_agent'], $layoutData['id_agente_modulo'], $width, $height, $layoutData['period'], '', true).'
        '; - } - elseif ($layoutData['label_position']=='right') { - $img = '
        ' .graph_graphic_moduleevents ($layoutData['id_agent'], $layoutData['id_agente_modulo'], $width, $height, $layoutData['period'], '', true).'
        '; - } - else { - $img = '
        ' . graph_graphic_moduleevents ($layoutData['id_agent'], $layoutData['id_agente_modulo'], $width, $height, $layoutData['period'], '', true).'
        '; - } - } - } - - //Restore db connection - if ($layoutData['id_metaconsole'] != 0) { - metaconsole_restore_db(); - } - - $z_index = 2 + 1; - break; - } - - $class = "item "; - switch ($type) { - case STATIC_GRAPH: - $class .= "static_graph"; - break; - case AUTO_SLA_GRAPH: - $class .= "auto_sla_graph"; - break; - case GROUP_ITEM: - $class .= "group_item"; - break; - case DONUT_GRAPH: - $class .= "donut_graph"; - break; - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - $class .= "percentile_item"; - break; - case MODULE_GRAPH: - $class .= "module_graph"; - break; - case BARS_GRAPH: - $class .= "bars_graph"; - break; - case SIMPLE_VALUE: - case SIMPLE_VALUE_MAX: - case SIMPLE_VALUE_MIN: - case SIMPLE_VALUE_AVG: - $class .= "simple_value"; - break; - case LABEL: - $class .= "label"; - break; - case ICON: - $class .= "icon"; - break; - case CLOCK: - $class .= "clock"; - break; - case BOX_ITEM: - $class .= "box_item"; - break; - default: - if (!empty($element_enterprise)) { - $class .= $element_enterprise['class']; - } - break; - } - - if($show_on_top){ - $z_index = 10; - } - - echo '
        '; - - if ($link) { - echo ""; - } - - //for clean link text from bbdd only edit_visualmap - if (get_parameter('action') == 'edit' || get_parameter('operation') == 'edit_visualmap') { - $text = preg_replace("/<\/*a.*?>/", '', $text); +function visual_map_print_item_toolbox($idDiv, $text, $float) +{ + if ($float == 'left') { + $margin = 'margin-right'; + } else { + $margin = 'margin-left'; } - switch ($type) { - case BOX_ITEM: - if ($width == 0 || $width == 0) { - $style = ""; - $style .= "width: 300px; "; - $style .= "height: 180px; "; - $style .= "border-style: solid; "; - $style .= "border-width: " . $border_width . "px; "; - $style .= "border-color: " . $border_color . "; "; - $style .= "background-color: " . $fill_color . "; "; - echo "
        "; - } - else { - if (!empty($proportion)) { - $style = ""; - $style .= "width: " . ($width * $proportion['proportion_width']) . "px; "; - $style .= "height: " . ($height * $proportion['proportion_height']) . "px; "; - $style .= "border-style: solid; "; - $style .= "border-width: " . $border_width . "px; "; - $style .= "border-color: " . $border_color . "; "; - $style .= "background-color: " . $fill_color . "; "; - echo "
        "; - } - else { - $style = ""; - $style .= "width: " . $width . "px; "; - $style .= "height: " . $height . "px; "; - $style .= "border-style: solid; "; - $style .= "border-width: " . $border_width . "px; "; - $style .= "border-color: " . $border_color . "; "; - $style .= "background-color: " . $fill_color . "; "; - echo "
        "; - } - } - break; - case STATIC_GRAPH: - case GROUP_ITEM: - if (($layoutData['image'] != null && $layoutData['image'] != 'none') || $layoutData['show_statistics'] == 1) { - - $img_style_title = strip_tags($label); - if ($layoutData['type'] == STATIC_GRAPH) { - if ($layoutData['id_agente_modulo'] != 0) { - if ($layoutData['id_metaconsole'] != 0) { - //Metaconsole db connection - $connection = db_get_row_filter ('tmetaconsole_setup', - array('id' => $layoutData['id_metaconsole'])); - if (metaconsole_load_external_db($connection) != NOERR) { - continue; - } - } - - $unit_text = trim(io_safe_output( - modules_get_unit($layoutData['id_agente_modulo']))); - - $value = modules_get_last_value( - $layoutData['id_agente_modulo']); - - if (!is_string($value)) { - $value = format_for_graph($value, 2); - } - - // Hide value on boolean modules - if ($layoutData['show_last_value'] != 2) { - if ((!modules_is_boolean($layoutData['id_agente_modulo'])) || - (modules_is_boolean($layoutData['id_agente_modulo']) && $layoutData['show_last_value'] != 0)){ - if (is_numeric($value)) { - $img_style_title .= - "
        " . __("Last value: ") - . remove_right_zeros(number_format($value, $config['graph_precision'])); - } else { - $img_style_title .= - "
        " . __("Last value: ") - . $value; - } - } - } - - if (!empty($unit_text)) - $img_style_title .= " " . $unit_text; - - if ($layoutData['id_metaconsole'] != 0) { - //Restore db connection - metaconsole_restore_db(); - } - } - - if(get_parameter('action') == 'edit'){ - $img_style_title = ''; - } - } - - if (!empty($proportion)) { - if (is_file($config['homedir'] . '/' . $img)) - $infoImage = getimagesize($config['homedir'] . '/' . $img); - - if ($height == 0 || $height == 0) { - $height = '70px'; - $width = '70px'; - } - else { - $height = (integer)($proportion['proportion_height'] * $height); - $width = (integer)($proportion['proportion_width'] * $width); - } - } - - $imgpos = ''; - - if($layoutData['label_position']=='up'){ - echo io_safe_output($text); - } - - if($layoutData['label_position']=='left'){ - $imgpos = 'float:right'; - } - else if($layoutData['label_position']=='right'){ - $imgpos = 'float:left'; - } - $varsize = getimagesize($config['homedir'] . '/' . $img); - - if($layoutData['show_statistics'] == 1) { - if (get_parameter('action') == 'edit') { - if ($width == 0 || $height == 0) { - echo ''; - } - else{ - echo ''; - } - } - else{ - $agents_critical = agents_get_agents( - array ( - 'disabled' => 0, - 'id_grupo' => $layoutData['id_group'], - 'status' => AGENT_STATUS_CRITICAL - ), - array ('COUNT(*) as total'), - 'AR', - false - ); - $agents_warning = agents_get_agents( - array ( - 'disabled' => 0, - 'id_grupo' => $layoutData['id_group'], - 'status' => AGENT_STATUS_WARNING - ), - array ('COUNT(*) as total'), - 'AR', - false - ); - $agents_unknown = agents_get_agents( - array ( - 'disabled' => 0, - 'id_grupo' => $layoutData['id_group'], - 'status' => AGENT_STATUS_UNKNOWN - ), - array ('COUNT(*) as total'), - 'AR', - false - ); - $agents_ok = agents_get_agents( - array ( - 'disabled' => 0, - 'id_grupo' => $layoutData['id_group'], - 'status' => AGENT_STATUS_OK - ), - array ('COUNT(*) as total'), - 'AR', - false - ); - $total_agents = $agents_critical[0]['total'] + $agents_warning[0]['total'] + $agents_unknown[0]['total'] + $agents_ok[0]['total']; - $stat_agent_ok = $agents_ok[0]['total']/$total_agents*100; - $stat_agent_wa = $agents_warning[0]['total']/$total_agents*100; - $stat_agent_cr = $agents_critical[0]['total']/$total_agents*100; - $stat_agent_un = $agents_unknown[0]['total']/$total_agents*100; - if($width == 0 || $height == 0){ - $dyn_width = 520; - $dyn_height = 80; - } else { - $dyn_width = $width; - $dyn_height = $height; - } - echo ''; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo "
        " .groups_get_name($layoutData['id_group'],true) . "
        "; - echo "
        ". remove_right_zeros(number_format($stat_agent_cr, 2)) ."%
        "; - echo "
        Critical
        "; - echo "
        ". remove_right_zeros(number_format($stat_agent_wa, 2)) ."%
        "; - echo "
        Warning
        "; - echo "
        ". remove_right_zeros(number_format($stat_agent_ok, 2)) ."%
        "; - echo "
        Normal
        "; - echo "
        ". remove_right_zeros(number_format($stat_agent_un, 2)) ."%
        "; - echo "
        Unknown
        "; - echo "
        "; - } - } else { - $options = array( - "class" => "image", - "id" => "image_" . $id, - "title" => $img_style_title, - "style" => $borderStyle.$imgpos - ); - if ($width == 0 || $height == 0) { - if($varsize[0] > 150 || $varsize[1] > 150){ - $options['width'] = "70px"; - $options['height'] = "70px"; - } - } - else{ - $options['width'] = $width; - $options['height'] = $height; - } - echo html_print_image($img, true, $options, - false, false, false, $isExternalLink); - } - } - - if ($layoutData['label_position'] != 'up') { - echo io_safe_output($text); - } - - if (is_metaconsole()) metaconsole_restore_db(); - break; - case PERCENTILE_BAR: - if (($layoutData['image'] == 'value') && ($value_text !== false)) { - $unit_text = db_get_sql ('SELECT unit - FROM tagente_modulo - WHERE id_agente_modulo = ' . $id_module); - $unit_text = trim(io_safe_output($unit_text)); - - $percentile = $value_text; - } - else { - $unit_text = "%"; - } - - if (get_parameter('action') == 'edit' || (get_parameter('operation') == 'edit_visualmap')) { - if($width == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else{ - $img = d3_progress_bar($id, $percentile, $width, 50, $border_color, $unit_text, io_safe_output($label), $fill_color); - } - - echo $img; - - if (get_parameter('tab')=='editor') - echo "".io_safe_output($text).""; - - break; - case PERCENTILE_BUBBLE: - if (($layoutData['image'] == 'value') && ($value_text !== false)) { - $unit_text = db_get_sql ('SELECT unit - FROM tagente_modulo - WHERE id_agente_modulo = ' . $id_module); - $unit_text = trim(io_safe_output($unit_text)); - - $percentile = $value_text; - } - else { - $unit_text = "%"; - } - - if(get_parameter('action') == 'edit' || (get_parameter('operation') == 'edit_visualmap')){ - if($width == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else{ - if($width == 0){ - $img = d3_progress_bubble($id, $percentile, 200,200, $border_color, $unit_text, io_safe_output($label), $fill_color); - } - else{ - $img = d3_progress_bubble($id, $percentile, $width, $width, $border_color, $unit_text, io_safe_output($label), $fill_color); - } - } - - echo $img; - - if (get_parameter('tab')=='editor') - echo "".io_safe_output($text).""; - - break; - case CIRCULAR_PROGRESS_BAR: - if(get_parameter('action') == 'edit' || (get_parameter('operation') == 'edit_visualmap')){ - if($width == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else { - if (($layoutData['image'] == 'value') && ($value_text !== false)) { - $unit_text = db_get_sql ('SELECT unit - FROM tagente_modulo - WHERE id_agente_modulo = ' . $id_module); - $unit_text = trim(io_safe_output($unit_text)); - - $percentile = $value_text; - } - else { - $unit_text = "%"; - } - - if($width == 0){ - $img = progress_circular_bar($id, $percentile, 200,200, $border_color, $unit_text, io_safe_output($label), $fill_color); - } - else{ - $img = progress_circular_bar($id, $percentile, $width, $width, $border_color, $unit_text, io_safe_output($label), $fill_color); - } - } - - echo $img; - - if (get_parameter('tab')=='editor') - echo "".io_safe_output($text).""; - - break; - case CIRCULAR_INTERIOR_PROGRESS_BAR: - if(get_parameter('action') == 'edit' || (get_parameter('operation') == 'edit_visualmap')){ - if($width == 0){ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - else{ - if ($layoutData['id_metaconsole'] != 0) { - $img = ''; - } - else{ - $img = ''; - } - } - } - else { - if (($layoutData['image'] == 'value') && ($value_text !== false)) { - $unit_text = db_get_sql ('SELECT unit - FROM tagente_modulo - WHERE id_agente_modulo = ' . $id_module); - $unit_text = trim(io_safe_output($unit_text)); - - $percentile = $value_text; - } - else { - $unit_text = "%"; - } - - if($width == 0){ - $img = progress_circular_bar_interior($id, $percentile, 200,200, $border_color, $unit_text, io_safe_output($label), $fill_color); - - } - else{ - $img = progress_circular_bar_interior($id, $percentile, $width, $width, $border_color, $unit_text, io_safe_output($label), $fill_color); - } - } - - echo $img; - - if (get_parameter('tab')=='editor') - echo "".io_safe_output($text).""; - - break; - case MODULE_GRAPH: - if ($layoutData['label_position']=='up') { - echo io_safe_output($text); - } - - echo $img; - - if ($layoutData['label_position']=='down') { - echo io_safe_output($text); - } - elseif($layoutData['label_position']=='left' || $layoutData['label_position']=='right') { - echo io_safe_output($text); - } - break; - case CLOCK: - if ($layoutData['label_position']=='up') { - echo io_safe_output($text); - } - echo $img; - - if ($layoutData['label_position']=='down') { - echo io_safe_output($text); - } - elseif($layoutData['label_position']=='left' || $layoutData['label_position']=='right') { - echo io_safe_output($text); - } - break; - case BARS_GRAPH: - if ($layoutData['label_position']=='up') { - echo io_safe_output($text); - } - - echo $img; - - if ($layoutData['label_position']=='down') { - echo io_safe_output($text); - } - elseif($layoutData['label_position']=='left' || $layoutData['label_position']=='right') { - echo io_safe_output($text); - } - break; - case AUTO_SLA_GRAPH: - if ($layoutData['label_position']=='up') { - echo io_safe_output($text); - } - - echo $img; - - if ($layoutData['label_position']=='down') { - echo io_safe_output($text); - } - elseif($layoutData['label_position']=='left' || $layoutData['label_position']=='right') { - echo io_safe_output($text); - } - break; - case DONUT_GRAPH: - echo $img; - break; - - case SIMPLE_VALUE: - case SIMPLE_VALUE_MAX: - case SIMPLE_VALUE_MIN: - case SIMPLE_VALUE_AVG: - $io_safe_output_text = io_safe_output($text); - - //Metaconsole db connection - if ($layoutData['id_metaconsole'] != 0) { - $connection = db_get_row_filter ('tmetaconsole_setup', - array('id' => $layoutData['id_metaconsole'])); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_name); - continue; - } - } - - $unit_text = db_get_sql ('SELECT unit - FROM tagente_modulo - WHERE id_agente_modulo = ' . $layoutData['id_agente_modulo']); - $unit_text = trim(io_safe_output($unit_text)); - - - //$value = db_get_value ('datos', - //'tagente_estado', 'id_agente_modulo', $layoutData['id_agente_modulo']); - $value = visual_map_get_simple_value($type, - $layoutData['id_agente_modulo'], $period); - - global $config; - - $is_image = get_if_module_is_image($layoutData['id_agente_modulo']); - if(get_parameter('action') == 'edit') { - if(!$is_image) { - echo $io_safe_output_text; - } - else { - echo ""; - } - } - else { - if(!$is_image) { - $new_text = str_replace(array("(_VALUE_)","(_value_)"), $value, $io_safe_output_text); - $new_text = str_replace(array('_VALUE_','_value_'), $value, $new_text); - - echo $new_text; - } - else { - $simple_value_img = str_replace('>', ' style="width:'.$layoutData['width'].'px">', $value); - echo $simple_value_img; - } - } - - //Restore db connection - if ($layoutData['id_metaconsole'] != 0) { - metaconsole_restore_db(); - } - break; - case LABEL: - echo io_safe_output($text); - break; - case ICON: - if ($layoutData['image'] != null) { - // If match with protocol://direction - if (preg_match('/^(http:\/\/)((.)+)$/i', $text)) { - echo '
        ' . '' . '
        '; - } - - if (!empty($proportion)) { - if (is_file($config['homedir'] . '/' . $img)) - $infoImage = getimagesize($config['homedir'] . '/' . $img); - - if ($width != 0) { - $width = (integer)($proportion['proportion_width'] * $width); - } - else { - $width = (integer)($proportion['proportion_width'] * $infoImage[0]); - } - - if ($height != 0) { - $height = (integer)($proportion['proportion_height'] * $height); - } - else { - $height = (integer)($proportion['proportion_height'] * $infoImage[1]); - } - } - - $varsize = getimagesize($img); - if (($width != 0) && ($height != 0)){ - echo html_print_image($img, true, - array("class" => "image", - "id" => "image_" . $id, - "width" => "$width", - "height" => "$height"), false, - false, false, $isExternalLink); - } - else{ - if($varsize[0] > 150 || $varsize[0] > 150){ - echo html_print_image($img, true, - array("class" => "image", "id" => "image_" . $id,"width" => "70px", - "70px" => "$height"), - false, false, false, $isExternalLink); - } - else{ - echo html_print_image($img, true, - array("class" => "image", - "id" => "image_" . $id), false, - false, false, $isExternalLink); - } - } - - } - break; - default: - if (!empty($element_enterprise)) { - echo $element_enterprise['item']; - } - break; - } - - if ($link) { - echo ""; - } - - echo "
        "; - - //Add the line between elements. - if ($layoutData['parent_item'] != 0) { - $parent = db_get_row_filter('tlayout_data', - array('id' => $layoutData['parent_item'])); - - echo ''; - } + echo '
        '; + echo $text; + echo ''; + echo '
        '; } -function get_if_module_is_image ($id_module) { - $sql = 'SELECT datos FROM tagente_estado WHERE id_agente_modulo = ' . $id_module; - - $result = db_get_sql($sql); - $image = strpos($result, 'data:image'); - if($image === false){ - return false; - } - else{ - return true; - } +function visual_map_print_user_line_handles($layoutData) +{ + $id = $layoutData['id']; + + $start_x = $layoutData['pos_x']; + $start_y = $layoutData['pos_y']; + $end_x = $layoutData['width']; + $end_y = $layoutData['height']; + $z_index = 2; + + $sizeStyle = ''; + + $radious_handle = (12 / 2); + + // Handle of start + echo '
        '; + + html_print_image('images/dot_red.png'); + + echo '
        '; + + // Handle of end + echo '
        '; + + html_print_image('images/dot_green.png'); + + echo '
        '; } -function get_bars_module_data ($id_module) { - //This charts is only serialize graphs. - //In other string show image no data to show. - $mod_values = db_get_value_filter( - 'datos', - 'tagente_estado', - array( - 'id_agente_modulo' => $id_module - ) - ); +function visual_map_print_item( + $mode='read', + $layoutData, + $proportion=null, + $show_links=true, + $isExternalLink=false, + $graph_javascript=true +) { + global $config; - $values = false; - //avoid showing the image type modules. WUX - if(strpos($mod_values, 'data:image/png;base64') !== 0){ - if (preg_match("/\r\n/", $mod_values)) { - $values = explode("\r\n", $mod_values); - } - elseif (preg_match("/\n/", $mod_values)) { - $values = explode("\n", $mod_values); - } - } + include_once $config['homedir'].'/include/functions_graph.php'; + include_once $config['homedir'].'/include/functions_custom_graphs.php'; - $values_to_return = array(); - $index = 0; - $color_index = 0; - $total = 0; + // add 60 px for visual console map + $width = $layoutData['width']; + $height = $layoutData['height']; + $max_percentile = $layoutData['height']; + $top = $layoutData['pos_y']; + $left = $layoutData['pos_x']; + $id = $layoutData['id']; + $label = io_safe_output($layoutData['label']); + $id_module = $layoutData['id_agente_modulo']; + $type = $layoutData['type']; + $period = $layoutData['period']; + $type_graph = $layoutData['type_graph']; + $border_width = $layoutData['border_width']; + $border_color = $layoutData['border_color']; + $fill_color = $layoutData['fill_color']; + $label_position = $layoutData['label_position']; + $show_on_top = $layoutData['show_on_top']; + $clock_animation = $layoutData['clock_animation']; + $time_format = $layoutData['time_format']; + $timezone = $layoutData['timezone']; - if(!$values) return false; + if ($show_on_top) { + $show_on_top_index = 10; + } else { + $show_on_top_index = ''; + } - foreach ($values as $val) { - $data = explode(",", $val); - $values_to_return[$data[0]] = array('g' =>$data[1]); - } + $sizeStyle = ''; + $borderStyle = ''; + $imageSize = ''; - return $values_to_return; + if (!empty($proportion)) { + $top = ($top * $proportion['proportion_height']); + $left = ($left * $proportion['proportion_width']); + } + + $text = ''.$label.''; + + if ($height == 0) { + switch ($type) { + case 0: + case 11: + $tableheight0 = '70'; + break; + + case 3: + $tableheight0 = '30'; + break; + + case 9: + $tableheight0 = '130'; + break; + + case 1: + $tableheight0 = '180'; + break; + + case SERVICE: + $tableheight0 = '50'; + break; + } + } else { + $tableheight0 = $height; + } + + if ($layoutData['width'] == 0) { + switch ($type) { + case 19: + if ($layoutData['clock_animation'] == 'analogic_1') { + $himg = '200'; + $wimg = '200'; + } else { + $himg = '60'; + $wimg = '200'; + } + break; + } + } else { + switch ($type) { + case 19: + if ($layoutData['clock_animation'] == 'analogic_1') { + $himg = $width; + $wimg = $width; + } else { + $himg = ($width / 3.9); + $wimg = $width; + } + break; + } + } + + if ($layoutData['width'] == 0 || $layoutData['height'] == 0) { + switch ($type) { + case 0: + case 11: + $himg = '70'; + $wimg = '70'; + break; + + case 3: + case 14: + if (get_parameter('action') == 'edit') { + $himg = '30'; + $wimg = '150'; + } else { + $himg = '15'; + $wimg = '150'; + } + break; + + case 9: + $himg = '130'; + $wimg = '130'; + break; + + case 1: + $himg = '180'; + $wimg = '300'; + break; + + case SERVICE: + $himg = '50'; + $wimg = '150'; + break; + } + } else { + $wimg = $layoutData['width']; + $himg = $layoutData['height']; + + if ($type == 3) { + if (get_parameter('action') == 'edit') { + $himg = '30'; + } else { + $himg = '15'; + } + } + + if ($type == 9) { + $himg = $wimg; + } + } + + if ($label_position == 'left') { + $text = '
        '.$label.'
        '; + } else if ($label_position == 'right') { + $text = '
        '.$label.'
        '; + } else { + $text = '
        '.$label.'
        '; + } + + if (!isset($layoutData['status_calculated'])) { + $layoutData['status_calculated'] = visual_map_get_status_element($layoutData); + } + + $status = $layoutData['status_calculated']; + + switch ($status) { + case VISUAL_MAP_STATUS_CRITICAL_BAD: + // Critical (BAD) + $colorStatus = COL_CRITICAL; + break; + + case VISUAL_MAP_STATUS_CRITICAL_ALERT: + // Critical (ALERT) + $colorStatus = COL_ALERTFIRED; + break; + + case VISUAL_MAP_STATUS_NORMAL: + // Normal (OK) + $colorStatus = COL_NORMAL; + break; + + case VISUAL_MAP_STATUS_WARNING: + // Warning + $colorStatus = COL_WARNING; + break; + + case VISUAL_MAP_STATUS_UNKNOWN: + default: + // Unknown + // Default is Blue (Other) + $colorStatus = COL_UNKNOWN; + break; + } + + $element_enterprise = []; + if (enterprise_installed()) { + $element_enterprise = enterprise_visual_map_print_item( + $mode, + $layoutData, + $proportion, + $show_links, + $isExternalLink + ); + } + + $link = false; + $url = '#'; + + if ($show_links && ($mode == 'read')) { + switch ($type) { + case STATIC_GRAPH: + case GROUP_ITEM: + if ($layoutData['enable_link'] + && can_user_access_node() + ) { + $link = true; + } + break; + + case LABEL: + if ($layoutData['id_layout_linked'] != 0) { + $link = true; + } + break; + + case ICON: + if ($layoutData['id_layout_linked'] > 0) { + $link = true; + } else if (preg_match('//', $layoutData['label'], $matches)) { + // Link to an URL + if ($layoutData['enable_link']) { + $link = true; + } + } else if (preg_match('/^.*(http:\/\/)((.)+).*$/i', $layoutData['label'])) { + // Link to an URL + if ($layoutData['enable_link']) { + $link = true; + } + } + break; + + case SIMPLE_VALUE: + case SIMPLE_VALUE_MAX: + case SIMPLE_VALUE_MIN: + case SIMPLE_VALUE_AVG: + // Extract id service if it is a prediction module. + $id_service = db_get_value_filter( + 'custom_integer_1', + 'tagente_modulo', + [ + 'id_agente_modulo' => $layoutData['id_agente_modulo'], + 'prediction_module' => 1, + ] + ); + + if (!empty($id_service) && can_user_access_node()) { + if ($layoutData['enable_link']) { + $link = true; + } + } else if ($layoutData['id_layout_linked'] > 0) { + $link = true; + } else if ($layoutData['enable_link'] && can_user_access_node()) { + $link = true; + } + break; + + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + if (!empty($layoutData['id_agent']) + && empty($layoutData['id_layout_linked']) + ) { + if ($layoutData['enable_link'] + && can_user_access_node() + ) { + // Extract id service if it is a prediction module. + $id_service = db_get_value_filter( + 'custom_integer_1', + 'tagente_modulo', + [ + 'id_agente_modulo' => $layoutData['id_agente_modulo'], + 'prediction_module' => 1, + ] + ); + + if (!empty($id_service)) { + // Link to an service page + $link = true; + } else if ($layoutData['id_agente_modulo'] != 0) { + // Link to an module + $link = true; + } else { + // Link to an agent + $link = true; + } + } + } else if ($layoutData['id_layout_linked'] > 0) { + // Link to a map + $link = true; + } + break; + + case MODULE_GRAPH: + if ((($layoutData['id_layout_linked'] == '') + || ($layoutData['id_layout_linked'] == 0)) + && can_user_access_node() + ) { + if ($layoutData['enable_link']) { + // Extract id service if it is a prediction module. + $id_service = db_get_value_filter( + 'custom_integer_1', + 'tagente_modulo', + [ + 'id_agente_modulo' => $layoutData['id_agente_modulo'], + 'prediction_module' => 1, + ] + ); + + if ($id_service === false) { + $id_service = 0; + } + + if ($id_service != 0) { + // Link to an service page + if (!empty($layoutData['id_metaconsole'])) { + $link = true; + } else { + $link = true; + } + } else { + $link = true; + } + } + } else { + // Link to a map + $link = true; + } + break; + + case BARS_GRAPH: + $link = true; + break; + + case AUTO_SLA_GRAPH: + $link = true; + break; + + case DONUT_GRAPH: + $link = true; + break; + + default: + if (!empty($element_enterprise)) { + $link = $element_enterprise['link']; + } + break; + } + } + + if ($link) { + switch ($type) { + case STATIC_GRAPH: + $is_a_service = false; + $is_a_link_to_other_visualconsole = false; + + if (enterprise_installed()) { + $id_service = services_service_from_module($layoutData['id_agente_modulo']); + + if (!empty($id_service)) { + $is_a_service = true; + } + } + + if ($layoutData['id_layout_linked'] != 0) { + $is_a_link_to_other_visualconsole = true; + } + + if ($is_a_service) { + if (empty($layoutData['id_metaconsole'])) { + $url = $config['homeurl'].'index.php?sec=services&sec2=enterprise/operation/services/services&id_service='.$id_service.'&offset=0'; + } else { + $server = db_get_row( + 'tmetaconsole_setup', + 'id', + $layoutData['id_metaconsole'] + ); + + $url = $server['server_url'].'/'.'index.php?sec=services&sec2=enterprise/operation/services/services&id_service='.$id_service.'&offset=0'; + } + } else if ($is_a_link_to_other_visualconsole) { + if (!is_metaconsole()) { + $url = $config['homeurl'].'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config['pure'].'&id='.$layoutData['id_layout_linked']; + } else { + $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=0&id_visualmap='.$layoutData['id_layout_linked'].'&refr=0'; + } + } else { + if ($layoutData['id_agente_modulo'] != 0) { + // Link to an module + if (empty($layoutData['id_metaconsole'])) { + $url = $config['homeurl'].'index.php?sec=view&sec2=operation/agentes/status_monitor&id_module='.$layoutData['id_agente_modulo']; + } else { + $url = ui_meta_get_url_console_child( + $layoutData['id_metaconsole'], + 'view', + 'operation/agentes/status_monitor&id_module='.$layoutData['id_agente_modulo'], + null, + null, + null, + $isExternalLink + ); + } + } else { + // Link to an agent + if (empty($layoutData['id_metaconsole'])) { + $url = $config['homeurl'].'index.php?sec=estado&sec2=operation/agentes/ver_agente&id_agente='.$layoutData['id_agent']; + } else { + $url = ui_meta_get_url_console_child( + $layoutData['id_metaconsole'], + 'estado', + 'operation/agentes/ver_agente&id_agente='.$layoutData['id_agent'], + null, + null, + null, + $isExternalLink + ); + } + } + } + break; + + case AUTO_SLA_GRAPH: + $e_period = $layoutData['period']; + $date = get_system_time(); + $datelimit = ($date - $e_period); + + $time_format = 'Y/m/d H:i:s'; + + $timestamp_init = date($time_format, $datelimit); + $timestamp_end = date($time_format, $date); + + $timestamp_init_aux = explode(' ', $timestamp_init); + $timestamp_end_aux = explode(' ', $timestamp_end); + + $date_from = $timestamp_init_aux[0]; + $time_from = $timestamp_init_aux[1]; + + $date_to = $timestamp_end_aux[0]; + $time_to = $timestamp_end_aux[1]; + + if (empty($layout_data['id_metaconsole'])) { + $url = $config['homeurl'].'index.php?sec=eventos&sec2=operation/events/events&id_agent='.$layoutData['id_agent'].'&module_search_hidden='.$layoutData['id_agente_modulo'].'&date_from='.$date_from.'&time_from='.$time_from.'&date_to='.$date_to.'&time_to='.$time_to.'&status=-1'; + } else { + $url = 'index.php?sec=eventos&sec2=operation/events/events&id_agent='.$layoutData['id_agent'].'&module_search_hidden='.$layoutData['id_agente_modulo'].'&date_from='.$date_from.'&time_from='.$time_from.'&date_to='.$date_to.'&time_to='.$time_to.'&status=-1'; + } + break; + + case DONUT_GRAPH: + if (empty($layout_data['id_metaconsole'])) { + $url = $config['homeurl'].'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&id_agente='.$layoutData['id_agent'].'&tab=module&edit_module=1&id_agent_module='.$layoutData['id_agente_modulo']; + } else { + $url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&id_agente='.$layoutData['id_agent'].'&tab=module&edit_module=1&id_agent_module='.$layoutData['id_agente_modulo']; + } + break; + + case BARS_GRAPH: + if (empty($layout_data['id_metaconsole'])) { + $url = $config['homeurl'].'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&id_agente='.$layoutData['id_agent'].'&tab=module&edit_module=1&id_agent_module='.$layoutData['id_agente_modulo']; + } else { + $url = 'index.php?sec=gagente&sec2=godmode/agentes/configurar_agente&id_agente='.$layoutData['id_agent'].'&tab=module&edit_module=1&id_agent_module='.$layoutData['id_agente_modulo']; + } + break; + + case GROUP_ITEM: + $is_a_link_to_other_visualconsole = false; + if ($layoutData['id_layout_linked'] != 0) { + $is_a_link_to_other_visualconsole = true; + } + + if ($is_a_link_to_other_visualconsole) { + if (METACONSOLE == 1) { + $url = $config['homeurl'].'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure=0&id_visualmap='.$layoutData['id_layout_linked'].'&refr=300'; + } else { + $url = $config['homeurl'].'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config['pure'].'&id='.$layoutData['id_layout_linked']; + } + } else { + if (METACONSOLE == 1) { + $url = $config['homeurl'].'index.php?sec=estado&sec2=operation/agentes/status_monitor&refr=0&ag_group='.$layoutData['id_group'].'&ag_freestring=&module_option=1&ag_modulename=&moduletype=&datatype=&status=-1&sort_field=&sort=none&pure='; + } else { + $url = $config['homeurl'].'index.php?sec=estado&sec2=operation/agentes/estado_agente&group_id='.$layoutData['id_group']; + } + } + break; + + case LABEL: + if ($layoutData['id_layout_linked'] != 0) { + // Link to a map + $url = $config['homeurl'].'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config['pure'].'&id='.$layoutData['id_layout_linked']; + } + break; + + case ICON: + $url_icon = ''; + if ($layoutData['id_layout_linked'] != 0) { + // Link to a map + if (empty($layoutData['id_metaconsole'])) { + $url = 'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config['pure'].'&id='.$layoutData['id_layout_linked']; + } else { + $pure = get_parameter('pure', 0); + $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure='.$pure.'&id_visualmap='.$layoutData['id_layout_linked'].'&refr=0'; + } + } else if (preg_match('//', $layoutData['label'], $matches)) { + // Link to an URL + if ($layoutData['enable_link']) { + $url = strip_tags($matches[1]); + } + } else if (preg_match('/^.*(http:\/\/)((.)+).*$/i', $layoutData['label'])) { + // Link to an URL + if ($layoutData['enable_link']) { + $url = strip_tags($layoutData['label']); + } + } + break; + + case SIMPLE_VALUE: + case SIMPLE_VALUE_MAX: + case SIMPLE_VALUE_MIN: + case SIMPLE_VALUE_AVG: + // Extract id service if it is a prediction module. + $id_service = db_get_value_filter( + 'custom_integer_1', + 'tagente_modulo', + [ + 'id_agente_modulo' => $layoutData['id_agente_modulo'], + 'prediction_module' => 1, + ] + ); + + if (!empty($id_service) && can_user_access_node()) { + // Link to an service page + if (!empty($layoutData['id_metaconsole'])) { + $server = db_get_row( + 'tmetaconsole_setup', + 'id', + $layoutData['id_metaconsole'] + ); + + $url = $server['server_url'].'/'.'index.php?sec=services&sec2=enterprise/operation/services/services&id_service='.$id_service.'&offset=0'; + } else { + $url = 'index.php?sec=services&sec2=enterprise/operation/services/services&id_service='.$id_service.'&offset=0'; + } + } else if ($layoutData['id_layout_linked'] > 0) { + // Link to a map + if (empty($layoutData['id_metaconsole'])) { + $url = 'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config['pure'].'&id='.$layoutData['id_layout_linked']; + } else { + $pure = get_parameter('pure', 0); + $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure='.$pure.'&id_visualmap='.$layoutData['id_layout_linked'].'&refr=0'; + } + } else if ($layoutData['id_agente_modulo'] != 0) { + // Link to an module + if (empty($layoutData['id_metaconsole'])) { + $url = $config['homeurl'].'index.php?sec=view&sec2=operation/agentes/status_monitor&id_module='.$layoutData['id_agente_modulo']; + } else { + $url = ui_meta_get_url_console_child( + $layoutData['id_metaconsole'], + 'estado', + 'operation/agentes/ver_agente&id_agente='.$layoutData['id_agent'], + null, + null, + null, + $isExternalLink + ); + } + } + break; + + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + if (!empty($layoutData['id_agent'])) { + // Extract id service if it is a prediction module. + $id_service = db_get_value_filter( + 'custom_integer_1', + 'tagente_modulo', + [ + 'id_agente_modulo' => $layoutData['id_agente_modulo'], + 'prediction_module' => 1, + ] + ); + + if (!empty($id_service)) { + // Link to an service page + if (!empty($layoutData['id_metaconsole'])) { + $server = db_get_row( + 'tmetaconsole_setup', + 'id', + $layoutData['id_metaconsole'] + ); + + $url = $server['server_url'].'/'.'index.php?sec=services&sec2=enterprise/operation/services/services&id_service='.$id_service.'&offset=0'; + } else { + $url = 'index.php?sec=services&sec2=enterprise/operation/services/services&id_service='.$id_service.'&offset=0'; + } + } else if ($layoutData['id_agente_modulo'] != 0) { + // Link to an module + if (!empty($layoutData['id_metaconsole'])) { + $server = db_get_row( + 'tmetaconsole_setup', + 'id', + $layoutData['id_metaconsole'] + ); + + $url = $server['server_url'].'/index.php?sec=view&sec2=operation/agentes/status_monitor&id_module='.$layoutData['id_agente_modulo']; + } else { + $url = $config['homeurl'].'/index.php?sec=view&sec2=operation/agentes/status_monitor&id_module='.$layoutData['id_agente_modulo']; + } + } else { + // Link to an agent + if (empty($layoutData['id_metaconsole'])) { + $url = $config['homeurl'].'index.php?'.'sec=estado&'.'sec2=operation/agentes/ver_agente&id_agente='.$layoutData['id_agent']; + } else { + $url = ui_meta_get_url_console_child( + $layoutData['id_metaconsole'], + 'estado', + 'operation/agentes/ver_agente&id_agente='.$layoutData['id_agent'], + null, + null, + null, + $isExternalLink + ); + } + } + } else if ($layoutData['id_layout_linked'] > 0) { + // Link to a map + if (empty($layoutData['id_metaconsole'])) { + $url = 'index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config['pure'].'&id='.$layoutData['id_layout_linked']; + } else { + $pure = get_parameter('pure', 0); + $url = 'index.php?sec=screen&sec2=screens/screens&action=visualmap&pure='.$pure.'&id_visualmap='.$layoutData['id_layout_linked'].'&refr=0'; + } + } + break; + + case MODULE_GRAPH: + if ((($layoutData['id_layout_linked'] == '') + || ($layoutData['id_layout_linked'] == 0)) + && can_user_access_node() + ) { + if ($layoutData['enable_link']) { + // Extract id service if it is a prediction module. + $id_service = db_get_value_filter( + 'custom_integer_1', + 'tagente_modulo', + [ + 'id_agente_modulo' => $layoutData['id_agente_modulo'], + 'prediction_module' => 1, + ] + ); + + if (!empty($id_service)) { + // Link to an service page + if (!empty($layoutData['id_metaconsole'])) { + $server = db_get_row( + 'tmetaconsole_setup', + 'id', + $layoutData['id_metaconsole'] + ); + + $url = $server['server_url'].'/index.php?sec=services&sec2=enterprise/operation/services/services&id_service='.$id_service.'&offset=0'; + } else { + $url = $config['homeurl'].'/index.php?sec=services&sec2=enterprise/operation/services/services&id_service='.$id_service.'&offset=0'; + } + } else { + if (empty($layoutData['id_metaconsole'])) { + $url = $config['homeurl'].'/index.php?sec=view&sec2=operation/agentes/status_monitor&id_module='.$layoutData['id_agente_modulo']; + } else { + $url = ui_meta_get_url_console_child( + $layoutData['id_metaconsole'], + 'estado', + 'operation/agentes/ver_agente&id_agente='.$layoutData['id_agent'].'&tab=data', + null, + null, + null, + $isExternalLink + ); + } + } + } + } else { + // Link to a map + if (empty($layoutData['id_metaconsole'])) { + $url = $config['homeurl'].'/index.php?sec=reporting&sec2=operation/visual_console/render_view&pure='.$config['pure'].'&id='.$layoutData['id_layout_linked']; + } else { + $pure = get_parameter('pure', 0); + $url = $config['homeurl'].'/index.php?sec=screen&sec2=screens/screens&action=visualmap&pure='.$pure.'&id_visualmap='.$layoutData['id_layout_linked'].'&refr=0'; + } + } + break; + + default: + if (!empty($element_enterprise)) { + $url = $element_enterprise['url']; + } + break; + } + + // Override url + if (is_metaconsole() + && !empty($layoutData['id_layout_linked']) + && !empty($layoutData['linked_layout_node_id']) + ) { + $url = ui_meta_get_url_console_child( + $layoutData['linked_layout_node_id'], + 'network', + 'operation/visual_console/render_view&id='.(int) $layoutData['id_layout_linked'] + ); + } + } + + // + 1 for to avoid the box and lines items are on the top of + // others + $z_index = (1 + 1); + + switch ($type) { + case STATIC_GRAPH: + case GROUP_ITEM: + if ($layoutData['image'] != null) { + $img = visual_map_get_image_status_element( + $layoutData, + $layoutData['status_calculated'] + ); + if (substr($img, 0, 1) == '4') { + $borderStyle = 'border: 2px solid '.COL_ALERTFIRED.';'; + $img = substr_replace($img, '', 0, 1); + } + } + + if ($status == VISUAL_MAP_STATUS_CRITICAL_BAD) { + $z_index = (3 + 1); + } else if ($status == VISUAL_MAP_STATUS_WARNING) { + $z_index = (2 + 1); + } else if ($status == VISUAL_MAP_STATUS_CRITICAL_ALERT) { + $z_index = (4 + 1); + } else { + $z_index = (1 + 1); + } + break; + + case ICON: + if ($layoutData['image'] != null) { + $img = visual_map_get_image_status_element( + $layoutData, + $layoutData['status_calculated'] + ); + } + + if (($width != 0) && ($height != 0)) { + $sizeStyle = 'width: '.$width.'px; height: '.$height.'px;'; + $imageSize = 'width="'.$width.'" height="'.$height.'"'; + } + + $z_index = (4 + 1); + break; + + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + // Metaconsole db connection + if ($layoutData['id_metaconsole'] != 0) { + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $layoutData['id_metaconsole']] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + continue; + } + } + + // data + $module_value = db_get_sql( + 'SELECT datos + FROM tagente_estado + WHERE id_agente_modulo = '.$id_module + ); + // state + $module_status = db_get_sql( + 'SELECT estado + FROM tagente_estado + WHERE id_agente_modulo = '.$id_module + ); + + if (empty($module_value) || $module_value == 0) { + $colorStatus = COL_UNKNOWN; + } else { + switch ($module_status) { + case 0: + // Normal + $colorStatus = COL_NORMAL; + break; + + case 1: + // Critical + $colorStatus = COL_CRITICAL; + break; + + case 2: + // Warning + $colorStatus = COL_WARNING; + break; + + case 4: + // Not_INIT + $colorStatus = COL_NOTINIT; + break; + + case 3: + // Unknown + default: + $colorStatus = COL_UNKNOWN; + break; + } + } + + $value_text = false; + if ($layoutData['image'] == 'percent') { + $value_text = false; + } else if ($layoutData['image'] == 'value') { + $unit_text = db_get_sql( + 'SELECT unit + FROM tagente_modulo + WHERE id_agente_modulo = '.$id_module + ); + $unit_text = trim(io_safe_output($unit_text)); + + $value_text = format_for_graph($module_value, 2); + if ($value_text <= 0) { + $value_text = remove_right_zeros(number_format($module_value, $config['graph_precision'])); + } + + if (!empty($unit_text)) { + $value_text .= ' '.$unit_text; + } + } + + // Restore db connection + if ($layoutData['id_metaconsole'] != 0) { + metaconsole_restore_db(); + } + + if ($max_percentile > 0) { + $percentile = format_numeric(($module_value / $max_percentile * 100), 0); + } else { + $percentile = 100; + } + break; + + case MODULE_GRAPH: + + $imgpos = ''; + + if ($layoutData['label_position'] == 'left') { + $imgpos = 'float:right'; + } else if ($layoutData['label_position'] == 'right') { + $imgpos = 'float:left'; + } + + if (!empty($proportion)) { + $width = ((integer) ($proportion['proportion_width'] * $width)); + $height = ((integer) ($proportion['proportion_height'] * $height)); + } + + // Metaconsole db connection + if ($layoutData['id_metaconsole'] != 0) { + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $layoutData['id_metaconsole']] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + continue; + } + } + + $only_image = !$graph_javascript && $isExternalLink; + + if ($layoutData['id_custom_graph'] != 0) { + // Show only avg on the visual console + if (get_parameter('action') == 'edit') { + if ($width == 0 || $height == 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($width == 0) { + $width = 180; + } + + if ($height == 0) { + $height = 480; + } + + $graphs = db_get_all_rows_field_filter('tgraph', 'id_graph', $layoutData['id_custom_graph']); + + $params = [ + 'period' => $period, + 'width' => $width, + 'height' => $height, + 'title' => '', + 'unit_name' => null, + 'show_alerts' => false, + 'only_image' => $only_image, + 'vconsole' => true, + 'backgroundColor' => $layoutData['image'], + ]; + + $params_combined = [ + 'id_graph' => $layoutData['id_custom_graph'], + 'stacked' => $graphs[0]['stacked'], + 'summatory' => $graphs[0]['summatory_series'], + 'average' => $graphs[0]['average_series'], + 'modules_series' => $graphs[0]['modules_series'], + ]; + + if ($layoutData['label_position'] == 'left') { + $img = '
        '.graphic_combined_module( + false, + $params, + $params_combined + ).'
        '; + } else if ($layoutData['label_position'] == 'right') { + $img = '
        '.graphic_combined_module( + false, + $params, + $params_combined + ).'
        '; + } else { + $img = graphic_combined_module( + false, + $params, + $params_combined + ); + } + } + } else { + if ($isExternalLink) { + $homeurl = $config['homeurl']; + } else { + $homeurl = ''; + } + + if ((get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0 || $height == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + if ($width == 0 || $height == 0) { + $width = 300; + $height = 180; + } + + $params = [ + 'agent_module_id' => $id_module, + 'period' => $period, + 'show_events' => false, + 'width' => $width, + 'height' => $height, + 'title' => modules_get_agentmodule_name($id_module), + 'unit' => modules_get_unit($id_module), + 'only_image' => $only_image, + 'menu' => false, + 'backgroundColor' => $layoutData['image'], + 'type_graph' => $type_graph, + 'vconsole' => true, + ]; + + if ($layoutData['label_position'] == 'left') { + $img = '
        '.grafico_modulo_sparse($params).'
        '; + } else if ($layoutData['label_position'] == 'right') { + $img = '
        '.grafico_modulo_sparse($params).'
        '; + } else { + $img = grafico_modulo_sparse($params); + } + } + } + + // Restore db connection + if ($layoutData['id_metaconsole'] != 0) { + metaconsole_restore_db(); + } + break; + + case BARS_GRAPH: + $imgpos = ''; + + if ($layoutData['label_position'] == 'left') { + $imgpos = 'float:right'; + } else if ($layoutData['label_position'] == 'right') { + $imgpos = 'float:left'; + } + + if (!empty($proportion)) { + $width = ((integer) ($proportion['proportion_width'] * $width)); + $height = ((integer) ($proportion['proportion_height'] * $height)); + } + + // Metaconsole db connection + if ($layoutData['id_metaconsole'] != 0) { + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $layoutData['id_metaconsole']] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + continue; + } + } + + if ($isExternalLink) { + $homeurl = $config['homeurl']; + } else { + $homeurl = ''; + } + + $is_string = db_get_value_filter( + 'id_tipo_modulo', + 'tagente_modulo', + [ + 'id_agente' => $layoutData['id_agent'], + 'id_agente_modulo' => $id_module, + ] + ); + + if ((get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + $color = []; + + $color[0] = [ + 'border' => '#000000', + 'color' => $config['graph_color1'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[1] = [ + 'border' => '#000000', + 'color' => $config['graph_color2'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[2] = [ + 'border' => '#000000', + 'color' => $config['graph_color3'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[3] = [ + 'border' => '#000000', + 'color' => $config['graph_color4'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[4] = [ + 'border' => '#000000', + 'color' => $config['graph_color5'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[5] = [ + 'border' => '#000000', + 'color' => $config['graph_color6'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[6] = [ + 'border' => '#000000', + 'color' => $config['graph_color7'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[7] = [ + 'border' => '#000000', + 'color' => $config['graph_color8'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[8] = [ + 'border' => '#000000', + 'color' => $config['graph_color9'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[9] = [ + 'border' => '#000000', + 'color' => $config['graph_color10'], + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[11] = [ + 'border' => '#000000', + 'color' => COL_GRAPH9, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[12] = [ + 'border' => '#000000', + 'color' => COL_GRAPH10, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[13] = [ + 'border' => '#000000', + 'color' => COL_GRAPH11, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[14] = [ + 'border' => '#000000', + 'color' => COL_GRAPH12, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + $color[15] = [ + 'border' => '#000000', + 'color' => COL_GRAPH13, + 'alpha' => CHART_DEFAULT_ALPHA, + ]; + + $module_data = get_bars_module_data($id_module); + $water_mark = [ + 'file' => '/var/www/html/pandora_console/images/logo_vertical_water.png', + 'url' => 'http://localhost/pandora_console/images/logo_vertical_water.png', + ]; + + if ($width == 0 && $height == 0) { + if ($layoutData['label_position'] == 'left') { + if ($layoutData['type_graph'] == 'horizontal') { + $img = '
        '.hbar_graph( + $module_data, + 400, + 400, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + $layoutData['border_color'] + ).'
        '; + } else { + $img = '
        '.vbar_graph( + $module_data, + 400, + 400, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + true, + false, + $layoutData['border_color'] + ).'
        '; + } + } else if ($layoutData['label_position'] == 'right') { + if ($layoutData['type_graph'] == 'horizontal') { + $img = '
        '.hbar_graph( + $module_data, + 400, + 400, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + $layoutData['border_color'] + ).'
        '; + } else { + $img = '
        '.vbar_graph( + $module_data, + 400, + 400, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + true, + false, + $layoutData['border_color'] + ).'
        '; + } + } else { + if ($layoutData['type_graph'] == 'horizontal') { + $img = hbar_graph( + $module_data, + 400, + 400, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + $layoutData['border_color'] + ); + } else { + $img = vbar_graph( + $module_data, + 400, + 400, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + true, + false, + $layoutData['border_color'] + ); + } + } + } else { + if ($layoutData['label_position'] == 'left') { + if ($layoutData['type_graph'] == 'horizontal') { + $img = '
        '.hbar_graph( + $module_data, + $width, + $height, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + $layoutData['border_color'] + ).'
        '; + } else { + $img = '
        '.vbar_graph( + $module_data, + $width, + $height, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + true, + false, + $layoutData['border_color'] + ).'
        '; + } + } else if ($layoutData['label_position'] == 'right') { + if ($layoutData['type_graph'] == 'horizontal') { + $img = '
        '.hbar_graph( + $module_data, + $width, + $height, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + $layoutData['border_color'] + ).'
        '; + } else { + $img = '
        '.vbar_graph( + $module_data, + $width, + $height, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + true, + false, + $layoutData['border_color'] + ).'
        '; + } + } else { + if ($layoutData['type_graph'] == 'horizontal') { + $img = hbar_graph( + $module_data, + $width, + $height, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + $layoutData['border_color'] + ); + } else { + $img = vbar_graph( + $module_data, + $width, + $height, + $color, + [], + [], + ui_get_full_url('images/image_problem_area.png', false, false, false), + '', + '', + $water_mark, + $config['fontpath'], + 6, + '', + 0, + $config['homeurl'], + $layoutData['image'], + true, + false, + $layoutData['border_color'] + ); + } + } + } + } + + // Restore db connection + if ($layoutData['id_metaconsole'] != 0) { + metaconsole_restore_db(); + } + break; + + case DONUT_GRAPH: + if (!empty($id_metaconsole)) { + $connection = db_get_row_filter('tmetaconsole_setup', $id_metaconsole); + if (metaconsole_load_external_db($connection) != NOERR) { + continue; + } + } + + $is_string = db_get_value_filter( + 'id_tipo_modulo', + 'tagente_modulo', + [ + 'id_agente' => $layoutData['id_agent'], + 'id_agente_modulo' => $id_module, + ] + ); + + if (!empty($id_metaconsole)) { + metaconsole_restore_db(); + } + + if (($is_string == 17) || ($is_string == 23) || ($is_string == 3) + || ($is_string == 10) || ($is_string == 33) + ) { + $no_data = false; + } else { + $no_data = true; + } + + if ($no_data) { + if ($width == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + $donut_data = get_donut_module_data($layoutData['id_agente_modulo']); + + if ((get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + if ($width == 0) { + $img = d3_donut_graph($layoutData['id'], 300, 300, $donut_data, $layoutData['border_color']); + } else { + $img = d3_donut_graph($layoutData['id'], $width, $width, $donut_data, $layoutData['border_color']); + } + } + } + + // Restore db connection + if ($layoutData['id_metaconsole'] != 0) { + metaconsole_restore_db(); + } + + $z_index = (2 + 1); + break; + + case LABEL: + $z_index = (4 + 1); + break; + + case BOX_ITEM: + $z_index = 1; + break; + + case CLOCK: + if ((get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0) { + if ($layoutData['id_metaconsole'] != 0) { + if ($layoutData['clock_animation'] == 'analogic_1') { + $img = ''; + } else { + if ($layoutData['time_format'] = 'time') { + $img = ''; + } else { + $img = ''; + } + } + } else { + if ($layoutData['clock_animation'] == 'analogic_1') { + $img = ''; + } else { + if ($layoutData['time_format'] == 'time') { + $img = ''; + } else { + $img = ''; + } + } + } + } else { + $image_prefix = ($layoutData['id_metaconsole'] != 0) ? '../../' : ''; + if ($layoutData['clock_animation'] == 'analogic_1') { + $img = ''; + } else { + $height_offset = ($layoutData['time_format'] == 'time') ? 20 : 40; + $img = ''; + } + } + } else { + if ($layoutData['clock_animation'] == 'analogic_1') { + if ($layoutData['label_position'] == 'left') { + $img = '
        '.print_clock_analogic_1($layoutData['time_format'], $layoutData['timezone'], $layoutData['clock_animation'], $layoutData['width'], $layoutData['height'], $layoutData['id'], $layoutData['fill_color']).'
        '; + } else if ($layoutData['label_position'] == 'right') { + $img = '
        '.print_clock_analogic_1($layoutData['time_format'], $layoutData['timezone'], $layoutData['clock_animation'], $layoutData['width'], $layoutData['height'], $layoutData['id'], $layoutData['fill_color']).'
        '; + } else { + $img = '
        '.print_clock_analogic_1($layoutData['time_format'], $layoutData['timezone'], $layoutData['clock_animation'], $layoutData['width'], $layoutData['height'], $layoutData['id'], $layoutData['fill_color']).'
        '; + } + } else if ($layoutData['clock_animation'] == 'digital_1') { + if ($layoutData['label_position'] == 'left') { + $img = '
        '.print_clock_digital_1($layoutData['time_format'], $layoutData['timezone'], $layoutData['clock_animation'], $layoutData['width'], $layoutData['height'], $layoutData['id'], $layoutData['fill_color']).'
        '; + } else if ($layoutData['label_position'] == 'right') { + $img = '
        '.print_clock_digital_1($layoutData['time_format'], $layoutData['timezone'], $layoutData['clock_animation'], $layoutData['width'], $layoutData['height'], $layoutData['id'], $layoutData['fill_color']).'
        '; + } else { + $img = '
        '.print_clock_digital_1($layoutData['time_format'], $layoutData['timezone'], $layoutData['clock_animation'], $layoutData['width'], $layoutData['height'], $layoutData['id'], $layoutData['fill_color']).'
        '; + } + } + } + break; + + case AUTO_SLA_GRAPH: + if ((get_parameter('action') == 'edit') || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0 || $height == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + if ($width == 0 || $height == 0) { + if ($layoutData['label_position'] == 'left') { + $img = '
        '.graph_graphic_moduleevents($layoutData['id_agent'], $layoutData['id_agente_modulo'], 500, 50, $layoutData['period'], '', true).'
        '; + } else if ($layoutData['label_position'] == 'right') { + $img = '
        '.graph_graphic_moduleevents($layoutData['id_agent'], $layoutData['id_agente_modulo'], 500, 50, $layoutData['period'], '', true).'
        '; + } else { + $img = '
        '.graph_graphic_moduleevents($layoutData['id_agent'], $layoutData['id_agente_modulo'], 500, 50, $layoutData['period'], '', true).'
        '; + } + } else { + if ($layoutData['label_position'] == 'left') { + $img = '
        '.graph_graphic_moduleevents($layoutData['id_agent'], $layoutData['id_agente_modulo'], $width, $height, $layoutData['period'], '', true).'
        '; + } else if ($layoutData['label_position'] == 'right') { + $img = '
        '.graph_graphic_moduleevents($layoutData['id_agent'], $layoutData['id_agente_modulo'], $width, $height, $layoutData['period'], '', true).'
        '; + } else { + $img = '
        '.graph_graphic_moduleevents($layoutData['id_agent'], $layoutData['id_agente_modulo'], $width, $height, $layoutData['period'], '', true).'
        '; + } + } + } + + // Restore db connection + if ($layoutData['id_metaconsole'] != 0) { + metaconsole_restore_db(); + } + + $z_index = (2 + 1); + break; + } + + $class = 'item '; + switch ($type) { + case STATIC_GRAPH: + $class .= 'static_graph'; + break; + + case AUTO_SLA_GRAPH: + $class .= 'auto_sla_graph'; + break; + + case GROUP_ITEM: + $class .= 'group_item'; + break; + + case DONUT_GRAPH: + $class .= 'donut_graph'; + break; + + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + $class .= 'percentile_item'; + break; + + case MODULE_GRAPH: + $class .= 'module_graph'; + break; + + case BARS_GRAPH: + $class .= 'bars_graph'; + break; + + case SIMPLE_VALUE: + case SIMPLE_VALUE_MAX: + case SIMPLE_VALUE_MIN: + case SIMPLE_VALUE_AVG: + $class .= 'simple_value'; + break; + + case LABEL: + $class .= 'label'; + break; + + case ICON: + $class .= 'icon'; + break; + + case CLOCK: + $class .= 'clock'; + break; + + case BOX_ITEM: + $class .= 'box_item'; + break; + + case COLOR_CLOUD: + $class .= 'color_cloud'; + break; + + default: + if (!empty($element_enterprise)) { + $class .= $element_enterprise['class']; + } + break; + } + + if ($show_on_top) { + $z_index = 10; + } + + echo '
        '; + + if ($link) { + echo ""; + } + + // for clean link text from bbdd only edit_visualmap + if (get_parameter('action') == 'edit' || get_parameter('operation') == 'edit_visualmap') { + $text = preg_replace('/<\/*a.*?>/', '', $text); + } + + switch ($type) { + case BOX_ITEM: + if ($width == 0 || $width == 0) { + $style = ''; + $style .= 'width: 300px; '; + $style .= 'height: 180px; '; + $style .= 'border-style: solid; '; + $style .= 'border-width: '.$border_width.'px; '; + $style .= 'border-color: '.$border_color.'; '; + $style .= 'background-color: '.$fill_color.'; '; + echo "
        "; + } else { + if (!empty($proportion)) { + $style = ''; + $style .= 'width: '.($width * $proportion['proportion_width']).'px; '; + $style .= 'height: '.($height * $proportion['proportion_height']).'px; '; + $style .= 'border-style: solid; '; + $style .= 'border-width: '.$border_width.'px; '; + $style .= 'border-color: '.$border_color.'; '; + $style .= 'background-color: '.$fill_color.'; '; + echo "
        "; + } else { + $style = ''; + $style .= 'width: '.$width.'px; '; + $style .= 'height: '.$height.'px; '; + $style .= 'border-style: solid; '; + $style .= 'border-width: '.$border_width.'px; '; + $style .= 'border-color: '.$border_color.'; '; + $style .= 'background-color: '.$fill_color.'; '; + echo "
        "; + } + } + break; + + case STATIC_GRAPH: + case GROUP_ITEM: + if (($layoutData['image'] != null && $layoutData['image'] != 'none') || $layoutData['show_statistics'] == 1) { + $img_style_title = strip_tags($label); + if ($layoutData['type'] == STATIC_GRAPH) { + if ($layoutData['id_agente_modulo'] != 0) { + if ($layoutData['id_metaconsole'] != 0) { + // Metaconsole db connection + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $layoutData['id_metaconsole']] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + continue; + } + } + + $unit_text = trim( + io_safe_output( + modules_get_unit($layoutData['id_agente_modulo']) + ) + ); + + $value = modules_get_last_value( + $layoutData['id_agente_modulo'] + ); + + if (!is_string($value)) { + $value = format_for_graph($value, 2); + } + + // Hide value on boolean modules + if ($layoutData['show_last_value'] != 2) { + if ((!modules_is_boolean($layoutData['id_agente_modulo'])) + || (modules_is_boolean($layoutData['id_agente_modulo']) && $layoutData['show_last_value'] != 0) + ) { + if (is_numeric($value)) { + $img_style_title .= '
        '.__('Last value: ').remove_right_zeros(number_format($value, $config['graph_precision'])); + } else { + $img_style_title .= '
        '.__('Last value: ').$value; + } + } + } + + if (!empty($unit_text)) { + $img_style_title .= ' '.$unit_text; + } + + if ($layoutData['id_metaconsole'] != 0) { + // Restore db connection + metaconsole_restore_db(); + } + } + + if (get_parameter('action') == 'edit') { + $img_style_title = ''; + } + } + + if (!empty($proportion)) { + if (is_file($config['homedir'].'/'.$img)) { + $infoImage = getimagesize($config['homedir'].'/'.$img); + } + + if ($height == 0 || $height == 0) { + $height = '70px'; + $width = '70px'; + } else { + $height = (integer) ($proportion['proportion_height'] * $height); + $width = (integer) ($proportion['proportion_width'] * $width); + } + } + + $imgpos = ''; + + if ($layoutData['label_position'] == 'up') { + echo io_safe_output($text); + } + + if ($layoutData['label_position'] == 'left') { + $imgpos = 'float:right'; + } else if ($layoutData['label_position'] == 'right') { + $imgpos = 'float:left'; + } + + $varsize = getimagesize($config['homedir'].'/'.$img); + + if ($layoutData['show_statistics'] == 1) { + if (get_parameter('action') == 'edit') { + if ($width == 0 || $height == 0) { + echo ''; + } else { + echo ''; + } + } else { + $agents_critical = agents_get_agents( + [ + 'disabled' => 0, + 'id_grupo' => $layoutData['id_group'], + 'status' => AGENT_STATUS_CRITICAL, + ], + ['COUNT(*) as total'], + 'AR', + false + ); + $agents_warning = agents_get_agents( + [ + 'disabled' => 0, + 'id_grupo' => $layoutData['id_group'], + 'status' => AGENT_STATUS_WARNING, + ], + ['COUNT(*) as total'], + 'AR', + false + ); + $agents_unknown = agents_get_agents( + [ + 'disabled' => 0, + 'id_grupo' => $layoutData['id_group'], + 'status' => AGENT_STATUS_UNKNOWN, + ], + ['COUNT(*) as total'], + 'AR', + false + ); + $agents_ok = agents_get_agents( + [ + 'disabled' => 0, + 'id_grupo' => $layoutData['id_group'], + 'status' => AGENT_STATUS_OK, + ], + ['COUNT(*) as total'], + 'AR', + false + ); + $total_agents = ($agents_critical[0]['total'] + $agents_warning[0]['total'] + $agents_unknown[0]['total'] + $agents_ok[0]['total']); + $stat_agent_ok = ($agents_ok[0]['total'] / $total_agents * 100); + $stat_agent_wa = ($agents_warning[0]['total'] / $total_agents * 100); + $stat_agent_cr = ($agents_critical[0]['total'] / $total_agents * 100); + $stat_agent_un = ($agents_unknown[0]['total'] / $total_agents * 100); + if ($width == 0 || $height == 0) { + $dyn_width = 520; + $dyn_height = 80; + } else { + $dyn_width = $width; + $dyn_height = $height; + } + + echo ''; + echo ""; + echo "'; + echo ''; + echo ""; + echo ''; + echo ''; + echo '
        ".groups_get_name($layoutData['id_group'], true).'
        '; + echo "
        ".remove_right_zeros(number_format($stat_agent_cr, 2)).'%
        '; + echo "
        Critical
        "; + echo "
        ".remove_right_zeros(number_format($stat_agent_wa, 2)).'%
        '; + echo "
        Warning
        "; + echo "
        ".remove_right_zeros(number_format($stat_agent_ok, 2)).'%
        '; + echo "
        Normal
        "; + echo "
        ".remove_right_zeros(number_format($stat_agent_un, 2)).'%
        '; + echo "
        Unknown
        "; + echo '
        '; + } + } else { + $options = [ + 'class' => 'image', + 'id' => 'image_'.$id, + 'title' => $img_style_title, + 'style' => $borderStyle.$imgpos, + ]; + if ($width == 0 || $height == 0) { + if ($varsize[0] > 150 || $varsize[1] > 150) { + $options['width'] = '70px'; + $options['height'] = '70px'; + } + } else { + $options['width'] = $width; + $options['height'] = $height; + } + + echo html_print_image( + $img, + true, + $options, + false, + false, + false, + $isExternalLink + ); + } + } + + if ($layoutData['label_position'] != 'up') { + echo io_safe_output($text); + } + + if (is_metaconsole()) { + metaconsole_restore_db(); + } + break; + + case PERCENTILE_BAR: + if (($layoutData['image'] == 'value') && ($value_text !== false)) { + $unit_text = db_get_sql( + 'SELECT unit + FROM tagente_modulo + WHERE id_agente_modulo = '.$id_module + ); + $unit_text = trim(io_safe_output($unit_text)); + + $percentile = $value_text; + } else { + $unit_text = '%'; + } + + if (get_parameter('action') == 'edit' || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + $img = d3_progress_bar($id, $percentile, $width, 50, $border_color, $unit_text, io_safe_output($label), $fill_color); + } + + echo $img; + + if (get_parameter('tab') == 'editor') { + echo "".io_safe_output($text).''; + } + break; + + case PERCENTILE_BUBBLE: + if (($layoutData['image'] == 'value') && ($value_text !== false)) { + $unit_text = db_get_sql( + 'SELECT unit + FROM tagente_modulo + WHERE id_agente_modulo = '.$id_module + ); + $unit_text = trim(io_safe_output($unit_text)); + + $percentile = $value_text; + } else { + $unit_text = '%'; + } + + if (get_parameter('action') == 'edit' || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + if ($width == 0) { + $img = d3_progress_bubble($id, $percentile, 200, 200, $border_color, $unit_text, io_safe_output($label), $fill_color); + } else { + $img = d3_progress_bubble($id, $percentile, $width, $width, $border_color, $unit_text, io_safe_output($label), $fill_color); + } + } + + echo $img; + + if (get_parameter('tab') == 'editor') { + echo "".io_safe_output($text).''; + } + break; + + case CIRCULAR_PROGRESS_BAR: + if (get_parameter('action') == 'edit' || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + if (($layoutData['image'] == 'value') && ($value_text !== false)) { + $unit_text = db_get_sql( + 'SELECT unit + FROM tagente_modulo + WHERE id_agente_modulo = '.$id_module + ); + $unit_text = trim(io_safe_output($unit_text)); + + $percentile = $value_text; + } else { + $unit_text = '%'; + } + + if ($width == 0) { + $img = progress_circular_bar($id, $percentile, 200, 200, $border_color, $unit_text, io_safe_output($label), $fill_color); + } else { + $img = progress_circular_bar($id, $percentile, $width, $width, $border_color, $unit_text, io_safe_output($label), $fill_color); + } + } + + echo $img; + + if (get_parameter('tab') == 'editor') { + echo "".io_safe_output($text).''; + } + break; + + case CIRCULAR_INTERIOR_PROGRESS_BAR: + if (get_parameter('action') == 'edit' || (get_parameter('operation') == 'edit_visualmap')) { + if ($width == 0) { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } else { + if ($layoutData['id_metaconsole'] != 0) { + $img = ''; + } else { + $img = ''; + } + } + } else { + if (($layoutData['image'] == 'value') && ($value_text !== false)) { + $unit_text = db_get_sql( + 'SELECT unit + FROM tagente_modulo + WHERE id_agente_modulo = '.$id_module + ); + $unit_text = trim(io_safe_output($unit_text)); + + $percentile = $value_text; + } else { + $unit_text = '%'; + } + + if ($width == 0) { + $img = progress_circular_bar_interior($id, $percentile, 200, 200, $border_color, $unit_text, io_safe_output($label), $fill_color); + } else { + $img = progress_circular_bar_interior($id, $percentile, $width, $width, $border_color, $unit_text, io_safe_output($label), $fill_color); + } + } + + echo $img; + + if (get_parameter('tab') == 'editor') { + echo "".io_safe_output($text).''; + } + break; + + case MODULE_GRAPH: + if ($layoutData['label_position'] == 'up') { + echo io_safe_output($text); + } + + echo $img; + + if ($layoutData['label_position'] == 'down') { + echo io_safe_output($text); + } else if ($layoutData['label_position'] == 'left' || $layoutData['label_position'] == 'right') { + echo io_safe_output($text); + } + break; + + case CLOCK: + if ($layoutData['label_position'] == 'up') { + echo io_safe_output($text); + } + + echo $img; + + if ($layoutData['label_position'] == 'down') { + echo io_safe_output($text); + } else if ($layoutData['label_position'] == 'left' || $layoutData['label_position'] == 'right') { + echo io_safe_output($text); + } + break; + + case BARS_GRAPH: + if ($layoutData['label_position'] == 'up') { + echo io_safe_output($text); + } + + echo $img; + + if ($layoutData['label_position'] == 'down') { + echo io_safe_output($text); + } else if ($layoutData['label_position'] == 'left' || $layoutData['label_position'] == 'right') { + echo io_safe_output($text); + } + break; + + case AUTO_SLA_GRAPH: + if ($layoutData['label_position'] == 'up') { + echo io_safe_output($text); + } + + echo $img; + + if ($layoutData['label_position'] == 'down') { + echo io_safe_output($text); + } else if ($layoutData['label_position'] == 'left' || $layoutData['label_position'] == 'right') { + echo io_safe_output($text); + } + break; + + case DONUT_GRAPH: + echo $img; + break; + + case SIMPLE_VALUE: + case SIMPLE_VALUE_MAX: + case SIMPLE_VALUE_MIN: + case SIMPLE_VALUE_AVG: + $io_safe_output_text = io_safe_output($text); + + // Metaconsole db connection + if ($layoutData['id_metaconsole'] != 0) { + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $layoutData['id_metaconsole']] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + continue; + } + } + + $unit_text = db_get_sql( + 'SELECT unit + FROM tagente_modulo + WHERE id_agente_modulo = '.$layoutData['id_agente_modulo'] + ); + $unit_text = trim(io_safe_output($unit_text)); + + // $value = db_get_value ('datos', + // 'tagente_estado', 'id_agente_modulo', $layoutData['id_agente_modulo']); + $value = visual_map_get_simple_value( + $type, + $layoutData['id_agente_modulo'], + $period + ); + + global $config; + + $is_image = get_if_module_is_image($layoutData['id_agente_modulo']); + if (get_parameter('action') == 'edit') { + if (!$is_image) { + echo $io_safe_output_text; + } else { + echo ""; + } + } else { + if (!$is_image) { + $new_text = str_replace(['(_VALUE_)', '(_value_)'], $value, $io_safe_output_text); + $new_text = str_replace(['_VALUE_', '_value_'], $value, $new_text); + + echo $new_text; + } else { + $simple_value_img = str_replace('>', ' style="width:'.$layoutData['width'].'px">', $value); + echo $simple_value_img; + } + } + + // Restore db connection + if ($layoutData['id_metaconsole'] != 0) { + metaconsole_restore_db(); + } + break; + + case LABEL: + echo io_safe_output($text); + break; + + case ICON: + if ($layoutData['image'] != null) { + // If match with protocol://direction + if (preg_match('/^(http:\/\/)((.)+)$/i', $text)) { + echo '
        '.''.'
        '; + } + + if (!empty($proportion)) { + if (is_file($config['homedir'].'/'.$img)) { + $infoImage = getimagesize($config['homedir'].'/'.$img); + } + + if ($width != 0) { + $width = (integer) ($proportion['proportion_width'] * $width); + } else { + $width = (integer) ($proportion['proportion_width'] * $infoImage[0]); + } + + if ($height != 0) { + $height = (integer) ($proportion['proportion_height'] * $height); + } else { + $height = (integer) ($proportion['proportion_height'] * $infoImage[1]); + } + } + + $varsize = getimagesize($img); + if (($width != 0) && ($height != 0)) { + echo html_print_image( + $img, + true, + [ + 'class' => 'image', + 'id' => 'image_'.$id, + 'width' => "$width", + 'height' => "$height", + ], + false, + false, + false, + $isExternalLink + ); + } else { + if ($varsize[0] > 150 || $varsize[0] > 150) { + echo html_print_image( + $img, + true, + [ + 'class' => 'image', + 'id' => 'image_'.$id, + 'width' => '70px', + '70px' => "$height", + ], + false, + false, + false, + $isExternalLink + ); + } else { + echo html_print_image( + $img, + true, + [ + 'class' => 'image', + 'id' => 'image_'.$id, + ], + false, + false, + false, + $isExternalLink + ); + } + } + } + break; + + case COLOR_CLOUD: + echo visual_map_get_color_cloud_element($layoutData); + break; + + default: + if (!empty($element_enterprise)) { + echo $element_enterprise['item']; + } + break; + } + + if ($link) { + echo ''; + } + + echo '
        '; + + // Add the line between elements. + if ($layoutData['parent_item'] != 0) { + $parent = db_get_row_filter( + 'tlayout_data', + ['id' => $layoutData['parent_item']] + ); + + echo ''; + } +} + + +function get_if_module_is_image($id_module) +{ + $sql = 'SELECT datos FROM tagente_estado WHERE id_agente_modulo = '.$id_module; + + $result = db_get_sql($sql); + $image = strpos($result, 'data:image'); + + if ($image === false) { + return false; + } else { + return true; + } +} + + +function get_bars_module_data($id_module) +{ + // This charts is only serialize graphs. + // In other string show image no data to show. + $mod_values = db_get_value_filter( + 'datos', + 'tagente_estado', + ['id_agente_modulo' => $id_module] + ); + + $values = false; + // avoid showing the image type modules. WUX + if (strpos($mod_values, 'data:image/png;base64') !== 0) { + if (preg_match("/\r\n/", $mod_values)) { + $values = explode("\r\n", $mod_values); + } else if (preg_match("/\n/", $mod_values)) { + $values = explode("\n", $mod_values); + } + } + + $values_to_return = []; + $index = 0; + $color_index = 0; + $total = 0; + + if (!$values) { + return false; + } + + foreach ($values as $val) { + $data = explode(',', $val); + $values_to_return[$data[0]] = ['g' => $data[1]]; + } + + return $values_to_return; } /** * The function to get simple value type from the value of process type in the form - * + * * @param int process simple value from form - * - * @return int type among the constants: + * + * @return integer type among the constants: * SIMPLE_VALUE, SIMPLE_VALUE_MAX, SIMPLE_VALUE_MIN, SIMPLE_VALUE_AVG */ -function visual_map_get_simple_value_type($process_simple_value) { - switch ($process_simple_value) { - case PROCESS_VALUE_NONE: - return SIMPLE_VALUE; - break; - case PROCESS_VALUE_MIN: - return SIMPLE_VALUE_MIN; - break; - case PROCESS_VALUE_MAX: - return SIMPLE_VALUE_MAX; - break; - case PROCESS_VALUE_AVG: - return SIMPLE_VALUE_AVG; - break; - } +function visual_map_get_simple_value_type($process_simple_value) +{ + switch ($process_simple_value) { + case PROCESS_VALUE_NONE: + return SIMPLE_VALUE; + + break; + case PROCESS_VALUE_MIN: + return SIMPLE_VALUE_MIN; + + break; + case PROCESS_VALUE_MAX: + return SIMPLE_VALUE_MAX; + + break; + case PROCESS_VALUE_AVG: + return SIMPLE_VALUE_AVG; + + break; + } } + /** - * The function to get the simple value of a module - * + * The function to get the simple value of a module + * * @param int type of the retrieving choosed among the constants: * SIMPLE_VALUE, SIMPLE_VALUE_MAX, SIMPLE_VALUE_MIN, SIMPLE_VALUE_AVG * @param int id agent module * @param int period The period in seconds for calculate the avg or min or max value. - * + * * @return string value retrieved with units */ -function visual_map_get_simple_value($type, $id_module, $period = SECONDS_1DAY) { - global $config; - - $unit_text = db_get_sql ('SELECT unit - FROM tagente_modulo WHERE id_agente_modulo = ' . $id_module); - $unit_text = trim(io_safe_output($unit_text)); - - switch ($type) { - case SIMPLE_VALUE: - $value = db_get_value ('datos', 'tagente_estado', - 'id_agente_modulo', $id_module); - if ($value === false) { - $value = __('Unknown'); - - $value = preg_replace ('/\n/i','
        ',$value); - $value = preg_replace ('/\s/i',' ',$value); - } - else { - if(strpos($value, 'data:image') !== false){ - $value = ''; - } - else{ - - if ( is_numeric($value) ) { - if ($config['simple_module_value']) { - $value = remove_right_zeros(number_format($value, $config['graph_precision'])); - } - } - if (!empty($unit_text)) { - $value .= " " . $unit_text; - } - - $value = preg_replace ('/\n/i','
        ',$value); - $value = preg_replace ('/\s/i',' ',$value); - - } - - } - return $value; - break; - case SIMPLE_VALUE_MAX: - $value = reporting_get_agentmodule_data_max ($id_module, $period, 0); - if ($value === false) { - $value = __('Unknown'); - } - else { - if ( is_numeric($value) ) { - if ($config['simple_module_value']) { - $value = format_for_graph($value, $config['graph_precision']); - } - } - if (!empty($unit_text)) - $value .= " " . $unit_text; - } - return $value; - break; - case SIMPLE_VALUE_MIN: - $value = reporting_get_agentmodule_data_min ($id_module, $period, 0); - if ($value === false) { - $value = __('Unknown'); - } - else { - if ( is_numeric($value) ) { - if ($config['simple_module_value']) { - $value = format_for_graph($value, $config['graph_precision']); - } - } - if (!empty($unit_text)) - $value .= " " . $unit_text; - } - return $value; - break; - case SIMPLE_VALUE_AVG: - $value = reporting_get_agentmodule_data_average ($id_module, $period, 0); - if ($value === false) { - $value = __('Unknown'); - } - else { - if ( is_numeric($value) ) { - if ($config['simple_module_value']) { - $value = format_for_graph($value, $config['graph_precision']); - } - } - if (!empty($unit_text)) - $value .= " " . $unit_text; - } - return $value; - break; - } +function visual_map_get_simple_value($type, $id_module, $period=SECONDS_1DAY) +{ + global $config; + + $unit_text = db_get_sql( + 'SELECT unit + FROM tagente_modulo WHERE id_agente_modulo = '.$id_module + ); + $unit_text = trim(io_safe_output($unit_text)); + + switch ($type) { + case SIMPLE_VALUE: + $value = db_get_value( + 'datos', + 'tagente_estado', + 'id_agente_modulo', + $id_module + ); + if ($value === false) { + $value = __('Unknown'); + + $value = preg_replace('/\n/i', '
        ', $value); + $value = preg_replace('/\s/i', ' ', $value); + } else { + if (strpos($value, 'data:image') !== false) { + $value = ''; + } else { + if (is_numeric($value)) { + if ($config['simple_module_value']) { + $value = remove_right_zeros(number_format($value, $config['graph_precision'])); + } + } + + if (!empty($unit_text)) { + $value .= ' '.$unit_text; + } + + $value = preg_replace('/\n/i', '
        ', $value); + $value = preg_replace('/\s/i', ' ', $value); + } + } + return $value; + + break; + case SIMPLE_VALUE_MAX: + $value = reporting_get_agentmodule_data_max($id_module, $period, 0); + if ($value === false) { + $value = __('Unknown'); + } else { + if (is_numeric($value)) { + if ($config['simple_module_value']) { + $value = format_for_graph($value, $config['graph_precision']); + } + } + + if (!empty($unit_text)) { + $value .= ' '.$unit_text; + } + } + return $value; + + break; + case SIMPLE_VALUE_MIN: + $value = reporting_get_agentmodule_data_min($id_module, $period, 0); + if ($value === false) { + $value = __('Unknown'); + } else { + if (is_numeric($value)) { + if ($config['simple_module_value']) { + $value = format_for_graph($value, $config['graph_precision']); + } + } + + if (!empty($unit_text)) { + $value .= ' '.$unit_text; + } + } + return $value; + + break; + case SIMPLE_VALUE_AVG: + $value = reporting_get_agentmodule_data_average($id_module, $period, 0); + if ($value === false) { + $value = __('Unknown'); + } else { + if (is_numeric($value)) { + if ($config['simple_module_value']) { + $value = format_for_graph($value, $config['graph_precision']); + } + } + + if (!empty($unit_text)) { + $value .= ' '.$unit_text; + } + } + return $value; + + break; + } } + /** * The function to save the new elements of agents make as wizard. - * - * @param array $id_agents The list of id of agents. - * @param string $image The image to set the elements. + * + * @param array $id_agents The list of id of agents. + * @param string $image The image to set the elements. * @param integer $id_layout The id of visual console to insert the elements. - * @param integer $range The distance between elements. - * @param integer $width Width of image. - * @param integer $height Height of image. - * + * @param integer $range The distance between elements. + * @param integer $width Width of image. + * @param integer $height Height of image. + * * @return string Return the message status to insert DB. */ -function visual_map_process_wizard_add ($id_agents, $image, $id_layout, $range, - $width = 0, $height = 0, $period, $process_value, $percentileitem_width, - $max_value, $type_percentile, $value_show, $type) { - if (empty ($id_agents)) { - print_error_message (__('No agents selected')); - return false; - } - - $id_agents = (array) $id_agents; - - $error = false; - $pos_y = 10; - $pos_x = 10; - foreach ($id_agents as $id_agent) { - if ($pos_x > 600) { - $pos_x = 10; - $pos_y = $pos_y + $range; - } - - $value_height = $height; - $value_image = $image; - $value_type = $type; - switch ($type) { - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - $value_height = $max_value; - $value_image = $value_show; - if ($type_percentile == 'percentile') { - $value_type = PERCENTILE_BAR; - } - elseif ($type_percentile == 'interior_circular_progress_bar') { - $value_type = CIRCULAR_INTERIOR_PROGRESS_BAR; - } - elseif ($type_percentile == 'circular_progress_bar') { - $value_type = CIRCULAR_PROGRESS_BAR; - } - else { - $value_type = PERCENTILE_BUBBLE; - } - break; - case SIMPLE_VALUE: - $value_type = $process_value; - break; - } - - $label = agents_get_alias($id_agent); - - $value_label = '(_VALUE_)'; - if ($type === SIMPLE_VALUE) { - $label .= ' ' . $value_label; - } - - $values = array ('type' => $value_type, - 'id_layout' => $id_layout, - 'pos_x' => $pos_x, - 'pos_y' => $pos_y, - 'label' => $label, - 'image' => $value_image, - 'id_agent' => $id_agent, - 'width' => $width, - 'period' => $period, - 'height' => $value_height); - - db_process_sql_insert ('tlayout_data', $values); - - $pos_x = $pos_x + $range; - } - - $return = ui_print_success_message (__('Agent successfully added to layout'), '', true); - - return $return; +function visual_map_process_wizard_add( + $id_agents, + $image, + $id_layout, + $range, + $width=0, + $height=0, + $period, + $process_value, + $percentileitem_width, + $max_value, + $type_percentile, + $value_show, + $type +) { + if (empty($id_agents)) { + print_error_message(__('No agents selected')); + return false; + } + + $id_agents = (array) $id_agents; + + $error = false; + $pos_y = 10; + $pos_x = 10; + foreach ($id_agents as $id_agent) { + if ($pos_x > 600) { + $pos_x = 10; + $pos_y = ($pos_y + $range); + } + + $value_height = $height; + $value_image = $image; + $value_type = $type; + switch ($type) { + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + $value_height = $max_value; + $value_image = $value_show; + if ($type_percentile == 'percentile') { + $value_type = PERCENTILE_BAR; + } else if ($type_percentile == 'interior_circular_progress_bar') { + $value_type = CIRCULAR_INTERIOR_PROGRESS_BAR; + } else if ($type_percentile == 'circular_progress_bar') { + $value_type = CIRCULAR_PROGRESS_BAR; + } else { + $value_type = PERCENTILE_BUBBLE; + } + break; + + case SIMPLE_VALUE: + $value_type = $process_value; + break; + } + + $label = agents_get_alias($id_agent); + + $value_label = '(_VALUE_)'; + if ($type === SIMPLE_VALUE) { + $label .= ' '.$value_label; + } + + $values = [ + 'type' => $value_type, + 'id_layout' => $id_layout, + 'pos_x' => $pos_x, + 'pos_y' => $pos_y, + 'label' => $label, + 'image' => $value_image, + 'id_agent' => $id_agent, + 'width' => $width, + 'period' => $period, + 'height' => $value_height, + ]; + + db_process_sql_insert('tlayout_data', $values); + + $pos_x = ($pos_x + $range); + } + + $return = ui_print_success_message(__('Agent successfully added to layout'), '', true); + + return $return; } + /** * The function to save the new elements of modules make as wizard. - * - * @param array $id_modules The list of id of modules. - * @param string $image The image to set the elements. - * @param integer $id_layout The id of visual console to insert the elements. - * @param integer $range The distance between elements. - * @param integer $width Width of image. - * @param integer $height Height of image. - * + * + * @param array $id_modules The list of id of modules. + * @param string $image The image to set the elements. + * @param integer $id_layout The id of visual console to insert the elements. + * @param integer $range The distance between elements. + * @param integer $width Width of image. + * @param integer $height Height of image. + * * @return string Return the message status to insert DB. */ -function visual_map_process_wizard_add_modules ($id_modules, $image, - $id_layout, $range, $width = 0, $height = 0, $period, - $process_value, $percentileitem_width, $max_value, $type_percentile, - $value_show, $label_type, $type, $enable_link = true, - $id_server = 0, $kind_relationship = VISUAL_MAP_WIZARD_PARENTS_NONE, - $item_in_the_map = 0,$fontf = 'arial',$fonts = '12pt') { - - if (empty ($id_modules)) { - $return = ui_print_error_message( - __('No modules selected'), '', true); - return $return; - } - - $id_modules = (array) $id_modules; - - $error = false; - $pos_y = 10; - $pos_x = 10; - - foreach ($id_modules as $id_module) { - if ($pos_x > 600) { - $pos_x = 10; - $pos_y = $pos_y + $range; - } - - - if ($id_server != 0) { - $connection = db_get_row_filter('tmetaconsole_setup', - array('id' => $id_server)); - if (metaconsole_load_external_db($connection) != NOERR) { - $return = ui_print_error_message( - "Error connecting to " . $server_name, '', true); - - return $return; - } - } - - $id_agent = modules_get_agentmodule_agent($id_module); - - switch ($label_type) { - case 'agent_module': - default: - $agent_label = agents_get_alias($id_agent); - $module_label = modules_get_agentmodule_name($id_module); - $label = '

        '.$agent_label . " - " . $module_label.'

        '; - break; - case 'module': - $module_label = modules_get_agentmodule_name($id_module); - $label = '

        '.$module_label.'

        '; - break; - case 'agent': - $agent_label = agents_get_alias($id_agent); - $label = '

        '.$agent_label.'

        '; - break; - case 'none': - $label = ''; - break; - } - $label = io_safe_input($label); - - //Restore db connection - if ($id_server != 0) { - metaconsole_restore_db(); - } - - $value_height = $height; - $value_image = $image; - $value_type = $type; - $value_width = $width; - switch ($type) { - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - $value_height = $max_value; - $value_width = $percentileitem_width; - $value_image = $value_show; - if ($type_percentile == 'percentile') { - $value_type = PERCENTILE_BAR; - } - elseif ($type_percentile == 'interior_circular_progress_bar') { - $value_type = CIRCULAR_INTERIOR_PROGRESS_BAR; - } - elseif ($type_percentile == 'circular_progress_bar') { - $value_type = CIRCULAR_PROGRESS_BAR; - } - else { - $value_type = PERCENTILE_BUBBLE; - } - break; - case SIMPLE_VALUE: - $label = !empty($label) ? $label . ' (_VALUE_)' : '(_VALUE_)'; - $value_image = ''; - switch ($process_value) { - case PROCESS_VALUE_NONE: - $value_type = SIMPLE_VALUE; - break; - case PROCESS_VALUE_MIN: - $value_type = SIMPLE_VALUE_MIN; - break; - case PROCESS_VALUE_MAX: - $value_type = SIMPLE_VALUE_MAX; - break; - case PROCESS_VALUE_AVG: - $value_type = SIMPLE_VALUE_AVG; - break; - } - break; - } - - $parent_item = 0; - switch ($kind_relationship) { - case VISUAL_MAP_WIZARD_PARENTS_ITEM_MAP: - $parent_item = $item_in_the_map; - break; - } - - - $values = array ('type' => $value_type, - 'id_layout' => $id_layout, - 'pos_x' => $pos_x, - 'pos_y' => $pos_y, - 'label' => $label, - 'image' => $value_image, - 'id_agent' => $id_agent, - 'id_agente_modulo' => $id_module, - 'width' => $value_width, - 'period' => $period, - 'height' => $value_height, - 'enable_link' => $enable_link, - 'id_metaconsole' => $id_server, - 'parent_item' => $parent_item); - - db_process_sql_insert ('tlayout_data', $values); - - $pos_x = $pos_x + $range; - } - - $return = ui_print_success_message (__('Modules successfully added to layout'), '', true); - - return $return; +function visual_map_process_wizard_add_modules( + $id_modules, + $image, + $id_layout, + $range, + $width=0, + $height=0, + $period, + $process_value, + $percentileitem_width, + $max_value, + $type_percentile, + $value_show, + $label_type, + $type, + $enable_link=true, + $id_server=0, + $kind_relationship=VISUAL_MAP_WIZARD_PARENTS_NONE, + $item_in_the_map=0, + $fontf='arial', + $fonts='12pt' +) { + if (empty($id_modules)) { + $return = ui_print_error_message( + __('No modules selected'), + '', + true + ); + return $return; + } + + $id_modules = (array) $id_modules; + + $error = false; + $pos_y = 10; + $pos_x = 10; + + foreach ($id_modules as $id_module) { + if ($pos_x > 600) { + $pos_x = 10; + $pos_y = ($pos_y + $range); + } + + if ($id_server != 0) { + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $id_server] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + $return = ui_print_error_message( + 'Error connecting to '.$server_name, + '', + true + ); + + return $return; + } + } + + $id_agent = modules_get_agentmodule_agent($id_module); + + switch ($label_type) { + case 'agent_module': + default: + $agent_label = agents_get_alias($id_agent); + $module_label = modules_get_agentmodule_name($id_module); + $label = '

        '.$agent_label.' - '.$module_label.'

        '; + break; + + case 'module': + $module_label = modules_get_agentmodule_name($id_module); + $label = '

        '.$module_label.'

        '; + break; + + case 'agent': + $agent_label = agents_get_alias($id_agent); + $label = '

        '.$agent_label.'

        '; + break; + + case 'none': + $label = ''; + break; + } + + $label = io_safe_input($label); + + // Restore db connection + if ($id_server != 0) { + metaconsole_restore_db(); + } + + $value_height = $height; + $value_image = $image; + $value_type = $type; + $value_width = $width; + switch ($type) { + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + $value_height = $max_value; + $value_width = $percentileitem_width; + $value_image = $value_show; + if ($type_percentile == 'percentile') { + $value_type = PERCENTILE_BAR; + } else if ($type_percentile == 'interior_circular_progress_bar') { + $value_type = CIRCULAR_INTERIOR_PROGRESS_BAR; + } else if ($type_percentile == 'circular_progress_bar') { + $value_type = CIRCULAR_PROGRESS_BAR; + } else { + $value_type = PERCENTILE_BUBBLE; + } + break; + + case SIMPLE_VALUE: + $label = !empty($label) ? $label.' (_VALUE_)' : '(_VALUE_)'; + $value_image = ''; + switch ($process_value) { + case PROCESS_VALUE_NONE: + $value_type = SIMPLE_VALUE; + break; + + case PROCESS_VALUE_MIN: + $value_type = SIMPLE_VALUE_MIN; + break; + + case PROCESS_VALUE_MAX: + $value_type = SIMPLE_VALUE_MAX; + break; + + case PROCESS_VALUE_AVG: + $value_type = SIMPLE_VALUE_AVG; + break; + } + break; + } + + $parent_item = 0; + switch ($kind_relationship) { + case VISUAL_MAP_WIZARD_PARENTS_ITEM_MAP: + $parent_item = $item_in_the_map; + break; + } + + $values = [ + 'type' => $value_type, + 'id_layout' => $id_layout, + 'pos_x' => $pos_x, + 'pos_y' => $pos_y, + 'label' => $label, + 'image' => $value_image, + 'id_agent' => $id_agent, + 'id_agente_modulo' => $id_module, + 'width' => $value_width, + 'period' => $period, + 'height' => $value_height, + 'enable_link' => $enable_link, + 'id_metaconsole' => $id_server, + 'parent_item' => $parent_item, + ]; + + db_process_sql_insert('tlayout_data', $values); + + $pos_x = ($pos_x + $range); + } + + $return = ui_print_success_message(__('Modules successfully added to layout'), '', true); + + return $return; } -function get_donut_module_data ($id_module) { - $mod_values = db_get_value_filter('datos', 'tagente_estado', array('id_agente_modulo' => $id_module)); - $no_data_to_show = false; +function get_donut_module_data($id_module) +{ + $mod_values = db_get_value_filter('datos', 'tagente_estado', ['id_agente_modulo' => $id_module]); - if (preg_match("/\r\n/", $mod_values)) { - $values = explode("\r\n", $mod_values); - } - elseif (preg_match("/\n/", $mod_values)) { - $values = explode("\n", $mod_values); - } - else { - $values=array(__('No data to show').",1"); - $no_data_to_show=true; - } - + $no_data_to_show = false; - $colors = array(); - $colors[] = "#aa3333"; - $colors[] = "#045FB4"; - $colors[] = "#8181F7"; - $colors[] = "#F78181"; - $colors[] = "#D0A9F5"; - $colors[] = "#BDBDBD"; - $colors[] = "#6AB277"; + if (preg_match("/\r\n/", $mod_values)) { + $values = explode("\r\n", $mod_values); + } else if (preg_match("/\n/", $mod_values)) { + $values = explode("\n", $mod_values); + } else { + $values = [__('No data to show').',1']; + $no_data_to_show = true; + } - $max_elements = 6; - $values_to_return = array(); - $index = 0; - $total = 0; - foreach ($values as $val) { - if ($index < $max_elements) { - $data = explode(",", $val); - if ($data[1] == 0) { - $data[1] = __('No data'); - } + $colors = []; + $colors[] = '#aa3333'; + $colors[] = '#045FB4'; + $colors[] = '#8181F7'; + $colors[] = '#F78181'; + $colors[] = '#D0A9F5'; + $colors[] = '#BDBDBD'; + $colors[] = '#6AB277'; - if ($no_data_to_show) - $values_to_return[$index]['tag_name'] = $data[0]; - else - $values_to_return[$index]['tag_name'] = $data[0] . ": " . $data[1]; + $max_elements = 6; + $values_to_return = []; + $index = 0; + $total = 0; + foreach ($values as $val) { + if ($index < $max_elements) { + $data = explode(',', $val); + if ($data[1] == 0) { + $data[1] = __('No data'); + } - $values_to_return[$index]['color'] = $colors[$index]; - $values_to_return[$index]['value'] = (int)$data[1]; - $total += (int)$data[1]; - $index++; - } - else { - if ($data[1] == 0) { - $data[1] = __('No data'); - } - $data = explode(",", $val); - $values_to_return[$index]['tag_name'] = __('Others') . ": " . $data[1]; - $values_to_return[$index]['color'] = $colors[$index]; - $values_to_return[$index]['value'] += (int)$data[1]; - $total += (int)$data[1]; - } - } + if ($no_data_to_show) { + $values_to_return[$index]['tag_name'] = $data[0]; + } else { + $values_to_return[$index]['tag_name'] = $data[0].': '.$data[1]; + } - foreach ($values_to_return as $ind => $donut_data) { - $values_to_return[$ind]['percent'] = ($donut_data['value'] * 100) / $total; - } + $values_to_return[$index]['color'] = $colors[$index]; + $values_to_return[$index]['value'] = (int) $data[1]; + $total += (int) $data[1]; + $index++; + } else { + if ($data[1] == 0) { + $data[1] = __('No data'); + } - $new_values_to_return = array(); - while (!empty($values_to_return)) { - $first = true; - $max_elem = 0; - $max_elem_array = array(); - $index_to_del = 0; - foreach ($values_to_return as $i => $val) { - if ($first) { - $max_elem = $val['value']; - $max_elem_array = $val; - $index_to_del = $i; - $first = false; - } - else { - if ($val['value'] > $max_elem) { - $max_elem = $val['value']; - $max_elem_array = $val; - $index_to_del = $i; - } - } - } + $data = explode(',', $val); + $values_to_return[$index]['tag_name'] = __('Others').': '.$data[1]; + $values_to_return[$index]['color'] = $colors[$index]; + $values_to_return[$index]['value'] += (int) $data[1]; + $total += (int) $data[1]; + } + } - $new_values_to_return[] = $max_elem_array; - unset($values_to_return[$index_to_del]); - } - $values_to_return = $new_values_to_return; + foreach ($values_to_return as $ind => $donut_data) { + $values_to_return[$ind]['percent'] = (($donut_data['value'] * 100) / $total); + } - return $values_to_return; + $new_values_to_return = []; + while (!empty($values_to_return)) { + $first = true; + $max_elem = 0; + $max_elem_array = []; + $index_to_del = 0; + foreach ($values_to_return as $i => $val) { + if ($first) { + $max_elem = $val['value']; + $max_elem_array = $val; + $index_to_del = $i; + $first = false; + } else { + if ($val['value'] > $max_elem) { + $max_elem = $val['value']; + $max_elem_array = $val; + $index_to_del = $i; + } + } + } + + $new_values_to_return[] = $max_elem_array; + unset($values_to_return[$index_to_del]); + } + + $values_to_return = $new_values_to_return; + + return $values_to_return; } /** * The function to save the new elements of agents make as wizard. - * - * @param array $id_agents The list of id of agents. - * @param string $image The image to set the elements. + * + * @param array $id_agents The list of id of agents. + * @param string $image The image to set the elements. * @param integer $id_layout The id of visual console to insert the elements. - * @param integer $range The distance between elements. - * @param integer $width Width of image. - * @param integer $height Height of image. - * + * @param integer $range The distance between elements. + * @param integer $width Width of image. + * @param integer $height Height of image. + * * @return string Return the message status to insert DB. */ -function visual_map_process_wizard_add_agents ($id_agents, $image, - $id_layout, $range, $width = 0, $height = 0, $period, - $process_value, $percentileitem_width, $max_value, $type_percentile, - $value_show, $label_type, $type, $enable_link = 1, $id_server = 0, - $kind_relationship = VISUAL_MAP_WIZARD_PARENTS_NONE, - $item_in_the_map = 0,$fontf = 'arial',$fonts = '12pt') { - - global $config; - - if (empty ($id_agents)) { - $return = ui_print_error_message( - __('No agents selected'), '', true); - - return $return; - } - - $id_agents = (array)$id_agents; - - $error = false; - $pos_y = 10; - $pos_x = 10; - - $relationship = true; - $relationships_agents = array(); - //Check if the set a none relationship - if (($kind_relationship == VISUAL_MAP_WIZARD_PARENTS_NONE) || - ($kind_relationship == VISUAL_MAP_WIZARD_PARENTS_AGENT_RELANTIONSHIP && - $item_in_the_map = 0)) { - - $relationship = false; - } - - - foreach ($id_agents as $id_agent) { - if (is_array($id_agent)) { - $id_a = $id_agent['id_agent']; - $id_server = $id_agent['id_server']; - $id_agent = $id_a; - } - - if ($pos_x > 600) { - $pos_x = 10; - $pos_y = $pos_y + $range; - } - - $value_height = $height; - $value_image = $image; - $value_type = $type; - $value_width = $width; - - switch ($type) { - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - $value_height = $max_value; - $value_width = $percentileitem_width; - $value_image = $value_show; - if ($type_percentile == 'percentile') { - $value_type = PERCENTILE_BAR; - } - elseif ($type_percentile == 'interior_circular_progress_bar') { - $value_type = CIRCULAR_INTERIOR_PROGRESS_BAR; - } - elseif ($type_percentile == 'circular_progress_bar') { - $value_type = CIRCULAR_PROGRESS_BAR; - } - else { - $value_type = PERCENTILE_BUBBLE; - } - break; - case SIMPLE_VALUE: - $value_image = ''; - switch ($process_value) { - case PROCESS_VALUE_NONE: - $value_type = SIMPLE_VALUE; - break; - case PROCESS_VALUE_MIN: - $value_type = SIMPLE_VALUE_MIN; - break; - case PROCESS_VALUE_MAX: - $value_type = SIMPLE_VALUE_MAX; - break; - case PROCESS_VALUE_AVG: - $value_type = SIMPLE_VALUE_AVG; - break; - } - break; - } - - if ($id_server != 0) { - - $connection = db_get_row_filter('tmetaconsole_setup', - array('id' => $id_server)); - if (metaconsole_load_external_db($connection) != NOERR) { - $return = ui_print_error_message( - "Error connecting to " . $server_name, '', true); - - return $return; - } - } - - switch ($label_type) { - case 'agent': - $label = agents_get_alias($id_agent); - break; - case 'none': - $label = ''; - break; - } - $label = io_safe_input($label); - - if ($type === SIMPLE_VALUE) $label = !empty($label) ? $label . ' (_VALUE_)' : '(_VALUE_)'; - - //Restore db connection - if ($id_server != 0) { - metaconsole_restore_db(); - } - - $parent_item = 0; - if ($relationship) { - switch ($kind_relationship) { - case VISUAL_MAP_WIZARD_PARENTS_ITEM_MAP: - $parent_item = $item_in_the_map; - break; - } - } - - $values = array ('type' => $value_type, - 'id_layout' => $id_layout, - 'pos_x' => $pos_x, - 'pos_y' => $pos_y, - 'label' => $label, - 'image' => $value_image, - 'id_agent' => $id_agent, - 'id_agente_modulo' => 0, - 'width' => $value_width, - 'period' => $period, - 'height' => $value_height, - 'enable_link' => $enable_link, - 'id_metaconsole' => $id_server, - 'parent_item' => $parent_item); - - $id_item = db_process_sql_insert ('tlayout_data', $values); - - if ($relationship) { - switch ($kind_relationship) { - case VISUAL_MAP_WIZARD_PARENTS_AGENT_RELANTIONSHIP: - - if (!isset($relationships_agents[$id_agent])) { - $relationships_agents[$id_agent]['id_layout_data_parent'] = $id_item; - $relationships_agents[$id_agent]['id_layout_data_children'] = array(); - } - else { - $relationships_agents[$id_agent]['id_layout_data_parent'] = $id_item; - } - - $agent_id_parent = db_get_value('id_parent', 'tagente', - 'id_agente', $id_agent); - - //Check in the group of new items is the father - if (array_search($agent_id_parent, $id_agents) !== false) { - if (isset($relationships_agents[$agent_id_parent])) { - $relationships_agents[$agent_id_parent]['id_layout_data_children'][] = $id_item; - } - else { - $relationships_agents[$agent_id_parent] = array(); - $relationships_agents[$agent_id_parent]['id_layout_data_parent'] = null; - $relationships_agents[$agent_id_parent]['id_layout_data_children'] = array(); - $relationships_agents[$agent_id_parent]['id_layout_data_children'][] = $id_item; - } - } - break; - } - } - - $pos_x = $pos_x + $range; - } - - foreach ($relationships_agents as $relationship_item) { - foreach ($relationship_item['id_layout_data_children'] as $children) { - db_process_sql_update('tlayout_data', - array('parent_item' => $relationship_item['id_layout_data_parent']), - array('id' => $children)); - } - } - - $return = ui_print_success_message( - __('Agents successfully added to layout'), '', true); - - return $return; +function visual_map_process_wizard_add_agents( + $id_agents, + $image, + $id_layout, + $range, + $width=0, + $height=0, + $period, + $process_value, + $percentileitem_width, + $max_value, + $type_percentile, + $value_show, + $label_type, + $type, + $enable_link=1, + $id_server=0, + $kind_relationship=VISUAL_MAP_WIZARD_PARENTS_NONE, + $item_in_the_map=0, + $fontf='arial', + $fonts='12pt' +) { + global $config; + + if (empty($id_agents)) { + $return = ui_print_error_message( + __('No agents selected'), + '', + true + ); + + return $return; + } + + $id_agents = (array) $id_agents; + + $error = false; + $pos_y = 10; + $pos_x = 10; + + $relationship = true; + $relationships_agents = []; + // Check if the set a none relationship + if (($kind_relationship == VISUAL_MAP_WIZARD_PARENTS_NONE) + || ($kind_relationship == VISUAL_MAP_WIZARD_PARENTS_AGENT_RELANTIONSHIP + && $item_in_the_map = 0) + ) { + $relationship = false; + } + + foreach ($id_agents as $id_agent) { + if (is_array($id_agent)) { + $id_a = $id_agent['id_agent']; + $id_server = $id_agent['id_server']; + $id_agent = $id_a; + } + + if ($pos_x > 600) { + $pos_x = 10; + $pos_y = ($pos_y + $range); + } + + $value_height = $height; + $value_image = $image; + $value_type = $type; + $value_width = $width; + + switch ($type) { + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + $value_height = $max_value; + $value_width = $percentileitem_width; + $value_image = $value_show; + if ($type_percentile == 'percentile') { + $value_type = PERCENTILE_BAR; + } else if ($type_percentile == 'interior_circular_progress_bar') { + $value_type = CIRCULAR_INTERIOR_PROGRESS_BAR; + } else if ($type_percentile == 'circular_progress_bar') { + $value_type = CIRCULAR_PROGRESS_BAR; + } else { + $value_type = PERCENTILE_BUBBLE; + } + break; + + case SIMPLE_VALUE: + $value_image = ''; + switch ($process_value) { + case PROCESS_VALUE_NONE: + $value_type = SIMPLE_VALUE; + break; + + case PROCESS_VALUE_MIN: + $value_type = SIMPLE_VALUE_MIN; + break; + + case PROCESS_VALUE_MAX: + $value_type = SIMPLE_VALUE_MAX; + break; + + case PROCESS_VALUE_AVG: + $value_type = SIMPLE_VALUE_AVG; + break; + } + break; + } + + if ($id_server != 0) { + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $id_server] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + $return = ui_print_error_message( + 'Error connecting to '.$server_name, + '', + true + ); + + return $return; + } + } + + switch ($label_type) { + case 'agent': + $label = agents_get_alias($id_agent); + break; + + case 'none': + $label = ''; + break; + } + + $label = io_safe_input($label); + + if ($type === SIMPLE_VALUE) { + $label = !empty($label) ? $label.' (_VALUE_)' : '(_VALUE_)'; + } + + // Restore db connection + if ($id_server != 0) { + metaconsole_restore_db(); + } + + $parent_item = 0; + if ($relationship) { + switch ($kind_relationship) { + case VISUAL_MAP_WIZARD_PARENTS_ITEM_MAP: + $parent_item = $item_in_the_map; + break; + } + } + + $values = [ + 'type' => $value_type, + 'id_layout' => $id_layout, + 'pos_x' => $pos_x, + 'pos_y' => $pos_y, + 'label' => $label, + 'image' => $value_image, + 'id_agent' => $id_agent, + 'id_agente_modulo' => 0, + 'width' => $value_width, + 'period' => $period, + 'height' => $value_height, + 'enable_link' => $enable_link, + 'id_metaconsole' => $id_server, + 'parent_item' => $parent_item, + ]; + + $id_item = db_process_sql_insert('tlayout_data', $values); + + if ($relationship) { + switch ($kind_relationship) { + case VISUAL_MAP_WIZARD_PARENTS_AGENT_RELANTIONSHIP: + + if (!isset($relationships_agents[$id_agent])) { + $relationships_agents[$id_agent]['id_layout_data_parent'] = $id_item; + $relationships_agents[$id_agent]['id_layout_data_children'] = []; + } else { + $relationships_agents[$id_agent]['id_layout_data_parent'] = $id_item; + } + + $agent_id_parent = db_get_value( + 'id_parent', + 'tagente', + 'id_agente', + $id_agent + ); + + // Check in the group of new items is the father + if (array_search($agent_id_parent, $id_agents) !== false) { + if (isset($relationships_agents[$agent_id_parent])) { + $relationships_agents[$agent_id_parent]['id_layout_data_children'][] = $id_item; + } else { + $relationships_agents[$agent_id_parent] = []; + $relationships_agents[$agent_id_parent]['id_layout_data_parent'] = null; + $relationships_agents[$agent_id_parent]['id_layout_data_children'] = []; + $relationships_agents[$agent_id_parent]['id_layout_data_children'][] = $id_item; + } + } + break; + } + } + + $pos_x = ($pos_x + $range); + } + + foreach ($relationships_agents as $relationship_item) { + foreach ($relationship_item['id_layout_data_children'] as $children) { + db_process_sql_update( + 'tlayout_data', + ['parent_item' => $relationship_item['id_layout_data_parent']], + ['id' => $children] + ); + } + } + + $return = ui_print_success_message( + __('Agents successfully added to layout'), + '', + true + ); + + return $return; } /** * Get the color of line between elements in the visual map. - * + * * @param array $layoutData The row of element in DB. - * + * * @return string The color as hexadecimal color in html. */ -function visual_map_get_color_line_status($layoutData) { - if (($layoutData['type'] == 5) || ($layoutData['type'] == 4)) { - //ICON ELEMENT OR LABEL ELEMENT - $color = "#cccccc"; - } - else { - switch (visual_map_get_status_element($layoutData)) { - case 3: - $color = "#cccccc"; // Gray - break; - case 2: - $color = "#20f6f6"; // Yellow - break; - case 0: - $color = "#00ff00"; // Green - break; - case 4: - case 1: - $color = "#ff0000"; // Red - break; - } - } - - return $color; +function visual_map_get_color_line_status($layoutData) +{ + if (($layoutData['type'] == 5) || ($layoutData['type'] == 4)) { + // ICON ELEMENT OR LABEL ELEMENT + $color = '#cccccc'; + } else { + switch (visual_map_get_status_element($layoutData)) { + case 3: + $color = '#cccccc'; + // Gray + break; + + case 2: + $color = '#20f6f6'; + // Yellow + break; + + case 0: + $color = '#00ff00'; + // Green + break; + + case 4: + case 1: + $color = '#ff0000'; + // Red + break; + } + } + + return $color; } + /** * Get image of element in the visual console with status. - * + * * @param array $layoutData The row of element in DB. - * + * * @return string The image with the relative path to pandora console directory. */ -function visual_map_get_image_status_element($layoutData, $status = false) { - $img = "images/console/icons/" . $layoutData["image"]; - - if ($layoutData['type'] == 5) { - //ICON ELEMENT - $img .= ".png"; - } - else { - if ($status === false) { - $status = visual_map_get_status_element($layoutData); - } - - switch ($status) { - case 1: - //Critical (BAD) - $img .= "_bad.png"; - break; - case 4: - //Critical (ALERT) - $img = "4" . $img . "_bad.png"; - break; - case 0: - //Normal (OK) - $img .= "_ok.png"; - break; - case 2: - //Warning - $img .= "_warning.png"; - break; - case 10: - //Warning (ALERT) - $img = "4" . $img . "_warning.png"; - break; - case 3: - //Unknown - default: - $img .= ".png"; - // Default is Grey (Other) - } - } - - return $img; +function visual_map_get_image_status_element($layoutData, $status=false) +{ + $img = 'images/console/icons/'.$layoutData['image']; + + if ($layoutData['type'] == 5) { + // ICON ELEMENT + $img .= '.png'; + } else { + if ($status === false) { + $status = visual_map_get_status_element($layoutData); + } + + switch ($status) { + case 1: + // Critical (BAD) + $img .= '_bad.png'; + break; + + case 4: + // Critical (ALERT) + $img = '4'.$img.'_bad.png'; + break; + + case 0: + // Normal (OK) + $img .= '_ok.png'; + break; + + case 2: + // Warning + $img .= '_warning.png'; + break; + + case 10: + // Warning (ALERT) + $img = '4'.$img.'_warning.png'; + break; + + case 3: + // Unknown + default: + $img .= '.png'; + // Default is Grey (Other) + } + } + + return $img; } + /** * Get the status of element in visual console. Check the agent state or * module or layout linked. - * + * * @param array $layoutData The row of element in DB. - * - * @return integer + * + * @return integer */ -function visual_map_get_status_element($layoutData) { - global $config; +function visual_map_get_status_element($layoutData) +{ + global $config; - enterprise_include_once('include/functions_visual_map.php'); - if (enterprise_installed()) { - $status = enterprise_visual_map_get_status_element($layoutData); - - //The function return value. - if ($status !== false) { - //Return this value as call of open function. - return $status; - } - } + enterprise_include_once('include/functions_visual_map.php'); + if (enterprise_installed()) { + $status = enterprise_visual_map_get_status_element($layoutData); - $module_value = db_get_sql ('SELECT datos - FROM tagente_estado - WHERE id_agente_modulo = ' . $layoutData['id_agente_modulo']); + // The function return value. + if ($status !== false) { + // Return this value as call of open function. + return $status; + } + } - //Linked to other layout ?? - Only if not module defined - if (!empty($layoutData['id_layout_linked'])) { - if (!empty($layoutData['linked_layout_node_id'])) { - //Metaconsole db connection - $connection = db_get_row_filter ('tmetaconsole_setup', - array('id' => $layoutData['linked_layout_node_id'])); - if (metaconsole_load_external_db($connection) != NOERR) return VISUAL_MAP_STATUS_UNKNOWN; - } + $module_value = db_get_sql( + 'SELECT datos + FROM tagente_estado + WHERE id_agente_modulo = '.$layoutData['id_agente_modulo'] + ); - $status = visual_map_get_layout_status($layoutData['id_layout_linked'], $layoutData); + // Linked to other layout ?? - Only if not module defined + if (!empty($layoutData['id_layout_linked'])) { + if (!empty($layoutData['linked_layout_node_id'])) { + // Metaconsole db connection + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $layoutData['linked_layout_node_id']] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + return VISUAL_MAP_STATUS_UNKNOWN; + } + } - if (!empty($layoutData['linked_layout_node_id'])) { - //Restore db connection - metaconsole_restore_db(); - } + $status = visual_map_get_layout_status($layoutData['id_layout_linked'], $layoutData); - return $status; - } - else { - switch ($layoutData["type"]) { - case STATIC_GRAPH: - // Open metaconsole connection - if ($layoutData['id_metaconsole'] != 0) { - //Metaconsole db connection - $connection = db_get_row_filter ('tmetaconsole_setup', - array('id' => $layoutData['id_metaconsole'])); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_name); - continue; - } - } + if (!empty($layoutData['linked_layout_node_id'])) { + // Restore db connection + metaconsole_restore_db(); + } - //Enter the correct img if the graph has a module selected or not - //Module - if ($layoutData['id_agente_modulo'] != 0) { - $module_status = db_get_sql ('SELECT estado - FROM tagente_estado - WHERE id_agente_modulo = ' . $layoutData['id_agente_modulo']); - - switch($module_status) { - case AGENT_STATUS_NORMAL: - case AGENT_MODULE_STATUS_NORMAL_ALERT: - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_NORMAL; - break; - case AGENT_MODULE_STATUS_WARNING: - case AGENT_MODULE_STATUS_WARNING_ALERT: - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_WARNING; - break; - case AGENT_STATUS_CRITICAL: - case AGENT_MODULE_STATUS_CRITICAL_ALERT: - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_CRITICAL_BAD; - break; - case AGENT_MODULE_STATUS_NO_DATA: - default: - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_UNKNOWN; - break; - } - } - //No module - else if ($layoutData['id_agent'] != 0) { - $agent = db_get_row ("tagente", "id_agente", $layoutData['id_agent']); - if ($agent['total_count'] == 0 || $agent['total_count'] == $agent['notinit_count']) { - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_UNKNOWN; - } - else if ($agent['critical_count'] > 0) { - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_CRITICAL_BAD; - } - else if ($agent['warning_count'] > 0) { - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_WARNING; - } - else if ($agent['unknown_count'] > 0) { - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_UNKNOWN; - } - else { - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_NORMAL; - } - } - //In other case - else { - $layoutData['status_calculated'] = VISUAL_MAP_STATUS_UNKNOWN; - } - $status = $layoutData['status_calculated']; + return $status; + } else { + switch ($layoutData['type']) { + case STATIC_GRAPH: + // Open metaconsole connection + if ($layoutData['id_metaconsole'] != 0) { + // Metaconsole db connection + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $layoutData['id_metaconsole']] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + continue; + } + } - // Close metaconsole connection - if ($layoutData['id_metaconsole'] != 0) { - //Restore db connection - metaconsole_restore_db(); - } - break; + // Enter the correct img if the graph has a module selected or not + // Module + if ($layoutData['id_agente_modulo'] != 0) { + $module_status = db_get_sql( + 'SELECT estado + FROM tagente_estado + WHERE id_agente_modulo = '.$layoutData['id_agente_modulo'] + ); - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - - if (empty($module_value) || $module_value == '') { - return VISUAL_MAP_STATUS_UNKNOWN; - } + switch ($module_status) { + case AGENT_STATUS_NORMAL: + case AGENT_MODULE_STATUS_NORMAL_ALERT: + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_NORMAL; + break; - if ($layoutData['id_metaconsole'] != 0) { - //Metaconsole db connection - $connection = db_get_row_filter ('tmetaconsole_setup', - array('id' => $layoutData['id_metaconsole'])); - if (metaconsole_load_external_db($connection) != NOERR) { - //ui_print_error_message ("Error connecting to ".$server_name); - continue; - } - } - - - - //Status for a simple module - if ($layoutData['id_agente_modulo'] != 0) { - $status = modules_get_agentmodule_status ($layoutData['id_agente_modulo']); - - //We need to get the diference between warning and critical alerts!!! - $real_status = db_get_row ("tagente_estado", "id_agente_modulo", $layoutData["id_agente_modulo"]); - - //Status for a whole agent, if agente_modulo was == 0 - } - else if ($layoutData['id_agent'] != 0) { - - //-------------------------------------------------- - // ADDED NO CHECK ACL FOR AVOID CHECK TAGS THAT - // MAKE VERY SLOW THE VISUALMAPS WITH ACL TAGS - //-------------------------------------------------- - $status = agents_get_status ($layoutData["id_agent"], true); - - if ($status == -1) // agents_get_status return -1 for unknown! - $status = VISUAL_MAP_STATUS_UNKNOWN; - } - else { - $status = VISUAL_MAP_STATUS_UNKNOWN; - $id_agent = 0; - } - - if ($layoutData['id_metaconsole'] != 0) { - //Restore db connection - metaconsole_restore_db(); - } - break; - - case GROUP_ITEM: - $group_status = groups_get_status($layoutData['id_group']); - - switch ($group_status) { - case AGENT_STATUS_ALERT_FIRED: - return VISUAL_MAP_STATUS_CRITICAL_ALERT; - break; - case AGENT_STATUS_CRITICAL: - return VISUAL_MAP_STATUS_CRITICAL_BAD; - break; - case AGENT_STATUS_WARNING: - return VISUAL_MAP_STATUS_WARNING; - break; - case AGENT_STATUS_UNKNOWN: - return VISUAL_MAP_STATUS_UNKNOWN; - break; - case AGENT_STATUS_NORMAL: - default: - return VISUAL_MAP_STATUS_NORMAL; - break; - } - break; - - default: - //If it's a graph, a progress bar or a data tag, ALWAYS report status OK - //(=0) to avoid confussions here. - $status = VISUAL_MAP_STATUS_NORMAL; - break; - - } - } - - switch ($status) { - case AGENT_MODULE_STATUS_CRITICAL_ALERT: - $status = VISUAL_MAP_STATUS_CRITICAL_ALERT; - break; - case AGENT_MODULE_STATUS_WARNING_ALERT: - $status = VISUAL_MAP_STATUS_WARNING_ALERT; - break; - } - - return $status; + case AGENT_MODULE_STATUS_WARNING: + case AGENT_MODULE_STATUS_WARNING_ALERT: + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_WARNING; + break; + + case AGENT_STATUS_CRITICAL: + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_CRITICAL_BAD; + break; + + case AGENT_MODULE_STATUS_NO_DATA: + default: + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_UNKNOWN; + break; + } + } + // No module + else if ($layoutData['id_agent'] != 0) { + $agent = db_get_row('tagente', 'id_agente', $layoutData['id_agent']); + if ($agent['total_count'] == 0 || $agent['total_count'] == $agent['notinit_count']) { + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_UNKNOWN; + } else if ($agent['critical_count'] > 0) { + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_CRITICAL_BAD; + } else if ($agent['warning_count'] > 0) { + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_WARNING; + } else if ($agent['unknown_count'] > 0) { + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_UNKNOWN; + } else { + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_NORMAL; + } + } + // In other case + else { + $layoutData['status_calculated'] = VISUAL_MAP_STATUS_UNKNOWN; + } + + $status = $layoutData['status_calculated']; + + // Close metaconsole connection + if ($layoutData['id_metaconsole'] != 0) { + // Restore db connection + metaconsole_restore_db(); + } + break; + + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + + if (empty($module_value) || $module_value == '') { + return VISUAL_MAP_STATUS_UNKNOWN; + } + + if ($layoutData['id_metaconsole'] != 0) { + // Metaconsole db connection + $connection = db_get_row_filter( + 'tmetaconsole_setup', + ['id' => $layoutData['id_metaconsole']] + ); + if (metaconsole_load_external_db($connection) != NOERR) { + // ui_print_error_message ("Error connecting to ".$server_name); + continue; + } + } + + // Status for a simple module + if ($layoutData['id_agente_modulo'] != 0) { + $status = modules_get_agentmodule_status($layoutData['id_agente_modulo']); + + // We need to get the diference between warning and critical alerts!!! + $real_status = db_get_row('tagente_estado', 'id_agente_modulo', $layoutData['id_agente_modulo']); + + // Status for a whole agent, if agente_modulo was == 0 + } else if ($layoutData['id_agent'] != 0) { + // -------------------------------------------------- + // ADDED NO CHECK ACL FOR AVOID CHECK TAGS THAT + // MAKE VERY SLOW THE VISUALMAPS WITH ACL TAGS + // -------------------------------------------------- + $status = agents_get_status($layoutData['id_agent'], true); + + if ($status == -1) { + // agents_get_status return -1 for unknown! + $status = VISUAL_MAP_STATUS_UNKNOWN; + } + } else { + $status = VISUAL_MAP_STATUS_UNKNOWN; + $id_agent = 0; + } + + if ($layoutData['id_metaconsole'] != 0) { + // Restore db connection + metaconsole_restore_db(); + } + break; + + case GROUP_ITEM: + $group_status = groups_get_status($layoutData['id_group']); + + switch ($group_status) { + case AGENT_STATUS_ALERT_FIRED: + return VISUAL_MAP_STATUS_CRITICAL_ALERT; + + break; + case AGENT_STATUS_CRITICAL: + return VISUAL_MAP_STATUS_CRITICAL_BAD; + + break; + case AGENT_STATUS_WARNING: + return VISUAL_MAP_STATUS_WARNING; + + break; + case AGENT_STATUS_UNKNOWN: + return VISUAL_MAP_STATUS_UNKNOWN; + + break; + case AGENT_STATUS_NORMAL: + default: + return VISUAL_MAP_STATUS_NORMAL; + + break; + } + break; + + default: + // If it's a graph, a progress bar or a data tag, ALWAYS report status OK + // (=0) to avoid confussions here. + $status = VISUAL_MAP_STATUS_NORMAL; + break; + } + } + + switch ($status) { + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + $status = VISUAL_MAP_STATUS_CRITICAL_ALERT; + break; + + case AGENT_MODULE_STATUS_WARNING_ALERT: + $status = VISUAL_MAP_STATUS_WARNING_ALERT; + break; + } + + return $status; } -function visual_map_print_user_lines($layout_data, $proportion = null) { - if (empty($proportion)) { - $line = array(); - $line["id"] = $layout_data['id']; - $line["start_x"] = $layout_data['pos_x']; - $line["start_y"] = $layout_data['pos_y']; - $line["end_x"] = $layout_data['width']; - $line["end_y"] = $layout_data['height']; - $line["line_width"] = $layout_data['border_width']; - $line["line_color"] = $layout_data['border_color']; - } - else { - $proportion_width = $proportion['proportion_width']; - $proportion_height = $proportion['proportion_height']; - - $proportion_line = $proportion_height; - if ($proportion_width > $proportion_height) { - $proportion_line = $proportion_width; - } - $line = array(); - $line["id"] = $layout_data['id']; - $line["start_x"] = $layout_data['pos_x'] * $proportion_width; - $line["start_y"] = $layout_data['pos_y'] * $proportion_height; - $line["end_x"] = $layout_data['width'] * $proportion_width; - $line["end_y"] = $layout_data['height'] * $proportion_height; - $line["line_width"] = $layout_data['border_width'] * $proportion_line; - $line["line_color"] = $layout_data['border_color']; - } +function visual_map_print_user_lines($layout_data, $proportion=null) +{ + if (empty($proportion)) { + $line = []; + $line['id'] = $layout_data['id']; + $line['start_x'] = $layout_data['pos_x']; + $line['start_y'] = $layout_data['pos_y']; + $line['end_x'] = $layout_data['width']; + $line['end_y'] = $layout_data['height']; + $line['line_width'] = $layout_data['border_width']; + $line['line_color'] = $layout_data['border_color']; + } else { + $proportion_width = $proportion['proportion_width']; + $proportion_height = $proportion['proportion_height']; - echo ''; + $proportion_line = $proportion_height; + if ($proportion_width > $proportion_height) { + $proportion_line = $proportion_width; + } + + $line = []; + $line['id'] = $layout_data['id']; + $line['start_x'] = ($layout_data['pos_x'] * $proportion_width); + $line['start_y'] = ($layout_data['pos_y'] * $proportion_height); + $line['end_x'] = ($layout_data['width'] * $proportion_width); + $line['end_y'] = ($layout_data['height'] * $proportion_height); + $line['line_width'] = ($layout_data['border_width'] * $proportion_line); + $line['line_color'] = $layout_data['border_color']; + } + + echo ''; } + /** * Prints visual map * - * @param int $id_layout Layout id - * @param bool $show_links - * @param bool $draw_lines + * @param integer $id_layout Layout id + * @param boolean $show_links + * @param boolean $draw_lines */ -function visual_map_print_visual_map ($id_layout, $show_links = true, - $draw_lines = true, $width = null, $height = null, $home_url = '', - $isExternalLink = false, $graph_javascript = true, $keep_aspect_ratio = false) { +function visual_map_print_visual_map( + $id_layout, + $show_links=true, + $draw_lines=true, + $width=null, + $height=null, + $home_url='', + $isExternalLink=false, + $graph_javascript=true, + $keep_aspect_ratio=false +) { + enterprise_include_once('include/functions_visual_map.php'); - enterprise_include_once('include/functions_visual_map.php'); - - global $config; - - $metaconsole_hack = '/'; - if (defined('METACONSOLE')) { - $metaconsole_hack = '../../'; - } - - enterprise_include_once("meta/include/functions_ui_meta.php"); - - require_once ($config["homedir"] . '/include/functions_custom_graphs.php'); - - $layout = db_get_row ('tlayout', 'id', $id_layout); - - if (empty($layout)) { - ui_print_error_message(__('Cannot load the visualmap')); - return; - } - - ?> - - "; - } - - echo '
        '; - - if ($layout["background"] != 'None.png' ) - echo ""; - - - $layout_datas = db_get_all_rows_field_filter('tlayout_data', - 'id_layout', $id_layout); - if (empty($layout_datas)) - $layout_datas = array(); - - $lines = array (); - - - foreach ($layout_datas as $layout_data) { - $layout_group = $layout_data['element_group']; - if (!check_acl ($config['id_user'], $layout_group, "VR")) { - continue; - } + global $config; - //Check the items are from disabled or pending delete modules - if ($layout_data['id_agente_modulo'] != 0 && - (($layout_data['type'] != LABEL) - || ($layout_data['type'] != ICON) - || ($layout_data['type'] != SERVICE))) { - - $delete_pending_module = db_get_value ("delete_pending", - "tagente_modulo", "id_agente_modulo", - $layout_data["id_agente_modulo"]); - $disabled_module = db_get_value ("disabled", "tagente_modulo", - "id_agente_modulo", $layout_data["id_agente_modulo"]); - - if ($delete_pending_module == 1 || $disabled_module == 1) - continue; - } - - if (($dif_height === 0) && ($dif_width === 0)) { - $proportion = null; - } - else { - $proportion = array( - 'dif_height' => $dif_height, - 'dif_width' => $dif_width, - 'proportion_height' => $proportion_height, - 'proportion_width' => $proportion_width); - } - - $layout_data['label'] = visual_map_macro($layout_data['label'],$layout_data["id_agente_modulo"]); - - switch ($layout_data['type']) { - case LINE_ITEM: - visual_map_print_user_lines($layout_data, $proportion); - break; - default: - visual_map_print_item("read", $layout_data, - $proportion, $show_links, $isExternalLink, $graph_javascript); - break; - } - } - - // End main div - echo "
        "; - - - - if (defined('METACONSOLE')) { - echo "
        "; - } + $metaconsole_hack = '/'; + if (defined('METACONSOLE')) { + $metaconsole_hack = '../../'; + } + + enterprise_include_once('meta/include/functions_ui_meta.php'); + + include_once $config['homedir'].'/include/functions_custom_graphs.php'; + + $layout = db_get_row('tlayout', 'id', $id_layout); + + if (empty($layout)) { + ui_print_error_message(__('Cannot load the visualmap')); + return; + } + + ?> + + "; + } + + echo '
        '; + + if ($layout['background'] != 'None.png') { + echo ""; + } + + $layout_datas = db_get_all_rows_field_filter( + 'tlayout_data', + 'id_layout', + $id_layout + ); + if (empty($layout_datas)) { + $layout_datas = []; + } + + $lines = []; + + foreach ($layout_datas as $layout_data) { + $layout_group = $layout_data['element_group']; + if (!check_acl($config['id_user'], $layout_group, 'VR')) { + continue; + } + + // Check the items are from disabled or pending delete modules + if ($layout_data['id_agente_modulo'] != 0 + && (($layout_data['type'] != LABEL) + || ($layout_data['type'] != ICON) + || ($layout_data['type'] != SERVICE)) + ) { + $delete_pending_module = db_get_value( + 'delete_pending', + 'tagente_modulo', + 'id_agente_modulo', + $layout_data['id_agente_modulo'] + ); + $disabled_module = db_get_value( + 'disabled', + 'tagente_modulo', + 'id_agente_modulo', + $layout_data['id_agente_modulo'] + ); + + if ($delete_pending_module == 1 || $disabled_module == 1) { + continue; + } + } + + if (($dif_height === 0) && ($dif_width === 0)) { + $proportion = null; + } else { + $proportion = [ + 'dif_height' => $dif_height, + 'dif_width' => $dif_width, + 'proportion_height' => $proportion_height, + 'proportion_width' => $proportion_width, + ]; + } + + $layout_data['label'] = visual_map_macro($layout_data['label'], $layout_data['id_agente_modulo']); + + switch ($layout_data['type']) { + case LINE_ITEM: + visual_map_print_user_lines($layout_data, $proportion); + break; + + default: + visual_map_print_item( + 'read', + $layout_data, + $proportion, + $show_links, + $isExternalLink, + $graph_javascript + ); + break; + } + } + + // End main div + echo '
        '; + + if (defined('METACONSOLE')) { + echo '
        '; + } } -//End function - -//Start function +// End function +// Start function /** * Get a list with the layouts for a user. * @@ -3452,588 +3795,733 @@ function visual_map_print_visual_map ($id_layout, $show_links = true, * * @return array A list of layouts the user can see. */ -function visual_map_get_user_layouts ($id_user = 0, $only_names = false, $filter = false, - $returnAllGroup = true, $favourite = false) { - - if (! is_array ($filter)){ - $filter = array (); - } else { - if(!empty($filter['name'])){ - $where .= "name LIKE '%".io_safe_output($filter['name'])."%'"; - unset($filter['name']); - } - } - if($favourite){ - if (empty($where)){ - $where = ""; - } - - if ($where != '') { - $where .= ' AND '; - } - $where .= "is_favourite = 1"; - } +function visual_map_get_user_layouts( + $id_user=0, + $only_names=false, + $filter=false, + $returnAllGroup=true, + $favourite=false +) { + if (! is_array($filter)) { + $filter = []; + } else { + if (!empty($filter['name'])) { + $where .= sprintf( + "name LIKE '%%%s%%'", + db_escape_string_sql(io_safe_output($filter['name'])) + ); - if ($returnAllGroup) { - $groups = users_get_groups ($id_user, 'VR', true, true); - } else { - - if(!empty($filter['group'])) { - $permissions_group = users_get_groups ($id_user, 'VR', false, true); - if(empty($permissions_group)){ - $permissions_group = users_get_groups ($id_user, 'VM', false, true); - } - $groups = array_intersect_key($filter['group'], $permissions_group); - } else { - $groups = users_get_groups ($id_user, 'VR', true, true); - if(empty($groups)) { - $groups = users_get_groups ($id_user, 'VM', true, true); - } - } - - - unset($filter['group']); - } - - if (!empty($groups)) { - if (empty($where)) - $where = ""; - - if ($where != '') { - $where .= ' AND '; - } - $where .= sprintf ('id_group IN (%s)', implode (",", array_keys ($groups))); - } - - $where .= db_format_array_where_clause_sql ($filter); - - if ($where == '') { - $where = array(); - } + unset($filter['name']); + } + } - $layouts = db_get_all_rows_filter ('tlayout', $where); - if ($layouts == false) - return array (); - - $retval = array (); - foreach ($layouts as $layout) { - if ($only_names) - $retval[$layout['id']] = $layout['name']; - else - $retval[$layout['id']] = $layout; + if ($favourite) { + if (empty($where)) { + $where = ''; + } - //add_perms - if (isset($groups[$layout['id_group']]['vconsole_view'])){ - $retval[$layout['id']]['vr'] = $groups[$layout['id_group']]['vconsole_view']; - } - if (isset($groups[$layout['id_group']]['vconsole_edit'])){ - $retval[$layout['id']]['vw'] = $groups[$layout['id_group']]['vconsole_edit']; - } - if (isset($groups[$layout['id_group']]['vconsole_management'])){ - $retval[$layout['id']]['vm'] = $groups[$layout['id_group']]['vconsole_management']; - } - } + if ($where != '') { + $where .= ' AND '; + } - return $retval; + $where .= 'is_favourite = 1'; + } + + if ($returnAllGroup) { + $groups = users_get_groups($id_user, 'VR', true, true); + } else { + if (!empty($filter['group'])) { + $permissions_group = users_get_groups($id_user, 'VR', false, true); + if (empty($permissions_group)) { + $permissions_group = users_get_groups($id_user, 'VM', false, true); + } + + $groups = array_intersect_key($filter['group'], $permissions_group); + } else { + $groups = users_get_groups($id_user, 'VR', true, true); + if (empty($groups)) { + $groups = users_get_groups($id_user, 'VM', true, true); + } + } + + unset($filter['group']); + } + + if (!empty($groups)) { + if (empty($where)) { + $where = ''; + } + + if ($where != '') { + $where .= ' AND '; + } + + $where .= sprintf('id_group IN (%s)', implode(',', array_keys($groups))); + } + + $where .= db_format_array_where_clause_sql($filter); + + if ($where == '') { + $where = []; + } + + $layouts = db_get_all_rows_filter('tlayout', $where); + if ($layouts == false) { + return []; + } + + $retval = []; + foreach ($layouts as $layout) { + if ($only_names) { + $retval[$layout['id']] = $layout['name']; + } else { + $retval[$layout['id']] = $layout; + } + + // add_perms + if (isset($groups[$layout['id_group']]['vconsole_view'])) { + $retval[$layout['id']]['vr'] = $groups[$layout['id_group']]['vconsole_view']; + } + + if (isset($groups[$layout['id_group']]['vconsole_edit'])) { + $retval[$layout['id']]['vw'] = $groups[$layout['id_group']]['vconsole_edit']; + } + + if (isset($groups[$layout['id_group']]['vconsole_management'])) { + $retval[$layout['id']]['vm'] = $groups[$layout['id_group']]['vconsole_management']; + } + } + + return $retval; } -function visual_map_translate_agent_status ($agent_status) { - switch ($agent_status) { - case AGENT_STATUS_NORMAL: - default: - return VISUAL_MAP_STATUS_NORMAL; - case AGENT_STATUS_CRITICAL: - return VISUAL_MAP_STATUS_CRITICAL_BAD; - case AGENT_STATUS_WARNING: - return VISUAL_MAP_STATUS_WARNING; - case AGENT_STATUS_NOT_INIT: - case AGENT_STATUS_UNKNOWN: - case -1: - return VISUAL_MAP_STATUS_UNKNOWN; - case AGENT_STATUS_ALERT_FIRED: - return VISUAL_MAP_STATUS_CRITICAL_ALERT; - } + +function visual_map_translate_agent_status($agent_status) +{ + switch ($agent_status) { + case AGENT_STATUS_NORMAL: + case AGENT_MODULE_STATUS_NORMAL_ALERT: + default: + return VISUAL_MAP_STATUS_NORMAL; + + case AGENT_STATUS_CRITICAL: + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + return VISUAL_MAP_STATUS_CRITICAL_BAD; + + case AGENT_STATUS_WARNING: + case AGENT_MODULE_STATUS_WARNING_ALERT: + return VISUAL_MAP_STATUS_WARNING; + + case AGENT_STATUS_NOT_INIT: + case AGENT_STATUS_UNKNOWN: + case -1: + return VISUAL_MAP_STATUS_UNKNOWN; + + case AGENT_STATUS_ALERT_FIRED: + return VISUAL_MAP_STATUS_CRITICAL_ALERT; + } } -function visual_map_translate_module_status ($module_status) { - switch ($module_status) { - case AGENT_MODULE_STATUS_NORMAL: - case AGENT_MODULE_STATUS_NORMAL_ALERT: - default: - return VISUAL_MAP_STATUS_NORMAL; - case AGENT_MODULE_STATUS_CRITICAL_BAD: - return VISUAL_MAP_STATUS_CRITICAL_BAD; - case AGENT_MODULE_STATUS_WARNING: - return VISUAL_MAP_STATUS_WARNING; - case AGENT_MODULE_STATUS_UNKNOWN: - case AGENT_MODULE_STATUS_NOT_INIT: - case AGENT_MODULE_STATUS_NO_DATA: - case -1: - return VISUAL_MAP_STATUS_UNKNOWN; - case AGENT_MODULE_STATUS_CRITICAL_ALERT: - return VISUAL_MAP_STATUS_CRITICAL_ALERT; - case AGENT_MODULE_STATUS_WARNING_ALERT: - return VISUAL_MAP_STATUS_WARNING_ALERT; - } + +function visual_map_translate_module_status($module_status) +{ + switch ($module_status) { + case AGENT_MODULE_STATUS_NORMAL: + case AGENT_MODULE_STATUS_NORMAL_ALERT: + default: + return VISUAL_MAP_STATUS_NORMAL; + + case AGENT_MODULE_STATUS_CRITICAL_BAD: + return VISUAL_MAP_STATUS_CRITICAL_BAD; + + case AGENT_MODULE_STATUS_WARNING: + return VISUAL_MAP_STATUS_WARNING; + + case AGENT_MODULE_STATUS_UNKNOWN: + case AGENT_MODULE_STATUS_NOT_INIT: + case AGENT_MODULE_STATUS_NO_DATA: + case -1: + return VISUAL_MAP_STATUS_UNKNOWN; + + case AGENT_MODULE_STATUS_CRITICAL_ALERT: + return VISUAL_MAP_STATUS_CRITICAL_ALERT; + + case AGENT_MODULE_STATUS_WARNING_ALERT: + return VISUAL_MAP_STATUS_WARNING_ALERT; + } } -/** + +/** * Get the status of a layout. * * It gets all the data of the contained elements (including nested * layouts), and makes an AND operation to be sure that all the items * are OK. If any of them is down, then result is down (0) - * + * * @param int Id of the layout * @param array Information about the status calculation of the item * @param int Depth (for recursion control) - * - * @return bool The status of the given layout. True if it's OK, false if not. + * + * @return boolean The status of the given layout. True if it's OK, false if not. */ -function visual_map_get_layout_status ($layout_id, $status_data = array(), $depth = 0) { - global $config; +function visual_map_get_layout_status($layout_id, $status_data=[], $depth=0) +{ + global $config; - // TODO: Implement this limit into the setup - if ($depth > 10) return VISUAL_MAP_STATUS_UNKNOWN; - - $layout_items = db_get_all_rows_filter("tlayout_data", array("id_layout" => $layout_id)); + // TODO: Implement this limit into the setup + if ($depth > 10) { + return VISUAL_MAP_STATUS_UNKNOWN; + } - if ($layout_items === false) return VISUAL_MAP_STATUS_UNKNOWN; - - // Check for valid items to retrieve the status for - $valid_layout_items = array(); - foreach ($layout_items as $layout_item_data) { - if ( - // Group items - ( - $layout_item_data['type'] == GROUP_ITEM && - !empty($layout_item_data["id_group"]) && - // ACL check - check_acl($config["id_user"], $layout_item_data["id_group"], "VR") && - check_acl($config["id_user"], $layout_item_data["element_group"], "VR") - ) || - // Rest of items - ( - ( - // At least one of this ids is required - !empty($layout_item_data["id_layout_linked"]) || - !empty($layout_item_data["id_agente_modulo"]) || - !empty($layout_item_data["id_agent"]) - ) && - // ACL check - check_acl($config["id_user"], $layout_item_data["element_group"], "VR") - ) - ) { - $valid_layout_items[] = $layout_item_data; - } - } - - if (empty($valid_layout_items)) return VISUAL_MAP_STATUS_UNKNOWN; + $layout_items = db_get_all_rows_filter('tlayout_data', ['id_layout' => $layout_id]); - // Sort by node id to reduce the number of connections - if (is_metaconsole()) { - sort_by_column($valid_layout_items, "id_metaconsole"); - } + if ($layout_items === false) { + return VISUAL_MAP_STATUS_UNKNOWN; + } - $num_elements_by_status = array(); - $meta_connected_to = null; + // Check for valid items to retrieve the status for + $valid_layout_items = []; + foreach ($layout_items as $layout_item_data) { + if (($layout_item_data['type'] == GROUP_ITEM + && !empty($layout_item_data['id_group']) + && check_acl($config['id_user'], $layout_item_data['id_group'], 'VR') + && check_acl($config['id_user'], $layout_item_data['element_group'], 'VR')) + || ((!empty($layout_item_data['id_layout_linked']) + || !empty($layout_item_data['id_agente_modulo']) + || !empty($layout_item_data['id_agent'])) + && check_acl($config['id_user'], $layout_item_data['element_group'], 'VR')) + ) { + $valid_layout_items[] = $layout_item_data; + } + } - foreach ($valid_layout_items as $layout_item_data) { - $node_id = null; - - if (is_metaconsole()) { - $node_id = ( - !empty($layout_item_data["id_layout_linked"]) && - !empty($layout_item_data["linked_layout_node_id"]) - ) - ? $layout_item_data["linked_layout_node_id"] - : $layout_item_data["id_metaconsole"]; - - if (empty($node_id) && $meta_connected_to) { - metaconsole_restore_db(); // Restore db connection - $meta_connected_to = null; - } - else if ( - !empty($node_id) && ( - empty($meta_connected_to) || - $meta_connected_to != $node_id - ) - ) { - if (!empty($meta_connected_to)) metaconsole_restore_db(); // Restore db connection - $connection = metaconsole_get_connection_by_id($node_id); - if (metaconsole_load_external_db($connection) != NOERR) continue; - $meta_connected_to = $node_id; - } - } + if (empty($valid_layout_items)) { + return VISUAL_MAP_STATUS_UNKNOWN; + } - $status = VISUAL_MAP_STATUS_NORMAL; + // Sort by node id to reduce the number of connections + if (is_metaconsole()) { + sort_by_column($valid_layout_items, 'id_metaconsole'); + } - $ent_element_status = enterprise_hook("enterprise_visual_map_get_status_element", array($layoutData)); - if ($ent_element_status === ENTERPRISE_NOT_HOOK) { - $ent_element_status = false; - } + $num_elements_by_status = []; + $meta_connected_to = null; - // Enterprise element - if ($ent_element_status !== false) { - $status = $ent_element_status; - } - // Other - else { - switch ($layout_item_data["type"]) { - case STATIC_GRAPH: - case PERCENTILE_BAR: - case PERCENTILE_BUBBLE: - case CIRCULAR_PROGRESS_BAR: - case CIRCULAR_INTERIOR_PROGRESS_BAR: - // Linked layout - if (!empty($layout_item_data["id_layout_linked"])) { - $status = visual_map_get_layout_status($layout_item_data["id_layout_linked"], $layout_item_data, $depth + 1); - } - // Module - else if (!empty($layout_item_data["id_agente_modulo"])) { - $module_status = modules_get_agentmodule_status($layout_item_data["id_agente_modulo"]); - $status = visual_map_translate_module_status($module_status); - } - // Agent - else if (!empty($layout_item_data["id_agent"])) { - $agent_status = agents_get_status($layout_item_data["id_agent"], true); - $status = visual_map_translate_agent_status($agent_status); - } - // Unknown - else { - $status = VISUAL_MAP_STATUS_UNKNOWN; - } - break; - case GROUP_ITEM: - $group_status = groups_get_status($layout_item_data['id_group']); - $status = visual_map_translate_agent_status($group_status); - break; - default: - // If it's a graph, a progress bar or a data tag, ALWAYS report status OK - // (=0) to avoid confussions here. - $status = VISUAL_MAP_STATUS_NORMAL; - break; - } - } + foreach ($valid_layout_items as $layout_item_data) { + $node_id = null; - // When the status calculation type is 'default', only one critical element is required to - // set the layout status as critical, so we can return the critical status right now. - if ( - $status_data["linked_layout_status_type"] === "default" && ( - $status == VISUAL_MAP_STATUS_CRITICAL_BAD || - $status == VISUAL_MAP_STATUS_CRITICAL_ALERT - ) - ) { - if (is_metaconsole() && $meta_connected_to) { - metaconsole_restore_db(); // Restore db connection - } - return $status; - } - else { - if (!isset($num_elements_by_status[$status])) $num_elements_by_status[$status] = 0; - $num_elements_by_status[$status]++; - } - } + if (is_metaconsole()) { + $node_id = ( + !empty($layout_item_data['id_layout_linked']) && + !empty($layout_item_data['linked_layout_node_id']) + ) ? $layout_item_data['linked_layout_node_id'] : $layout_item_data['id_metaconsole']; - if (is_metaconsole() && $meta_connected_to) { - metaconsole_restore_db(); // Restore db connection - } + if (empty($node_id) && $meta_connected_to) { + metaconsole_restore_db(); + // Restore db connection + $meta_connected_to = null; + } else if (!empty($node_id) && ( empty($meta_connected_to) + || $meta_connected_to != $node_id) + ) { + if (!empty($meta_connected_to)) { + metaconsole_restore_db(); + // Restore db connection + } - // Status calculation - switch ($status_data["linked_layout_status_type"]) { - default: - case "default": - $num_items_critical_alert = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_ALERT]; - $num_items_critical = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_BAD]; - $num_items_warning = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING]; - $num_items_unknown = $num_elements_by_status[VISUAL_MAP_STATUS_UNKNOWN]; - - if ($num_items_critical_alert > 0) { - return VISUAL_MAP_STATUS_CRITICAL_ALERT; - } - else if ($num_items_critical > 0) { - return VISUAL_MAP_STATUS_CRITICAL_BAD; - } - else if ($num_items_warning > 0) { - return VISUAL_MAP_STATUS_WARNING; - } - else if ($num_items_unknown > 0) { - return VISUAL_MAP_STATUS_UNKNOWN; - } - else { - return VISUAL_MAP_STATUS_NORMAL; - } - break; - case "weight": - $weight = $status_data["id_layout_linked_weight"]; - $num_items = count($valid_layout_items); - $num_items_critical_alert = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_ALERT]; - $num_items_critical = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_BAD]; - $num_items_warning = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING]; - $num_items_unknown = $num_elements_by_status[VISUAL_MAP_STATUS_UNKNOWN]; - - if ( - $num_items_critical > 0 && - ((($num_items_critical_alert + $num_items_critical) * 100) / $num_items) >= $weight - ) { - return $num_items_critical_alert > 0 ? VISUAL_MAP_STATUS_CRITICAL_ALERT : VISUAL_MAP_STATUS_CRITICAL_BAD; - } - else if ( - $num_items_warning > 0 && - (($num_items_warning * 100) / $num_items) >= $weight - ) { - return VISUAL_MAP_STATUS_WARNING; - } - else if ( - $num_items_unknown > 0 && - (($num_items_unknown * 100) / $num_items) >= $weight - ) { - return VISUAL_MAP_STATUS_UNKNOWN; - } - else { - return VISUAL_MAP_STATUS_NORMAL; - } - break; - case "service": - $num_items_critical = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_BAD] - + $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_ALERT]; - $critical_percentage = ($num_items_critical * 100) / count($valid_layout_items); + $connection = metaconsole_get_connection_by_id($node_id); + if (metaconsole_load_external_db($connection) != NOERR) { + continue; + } - if ($critical_percentage >= $status_data["linked_layout_status_as_service_critical"]) { - return VISUAL_MAP_STATUS_CRITICAL_BAD; - } - else if ($critical_percentage >= $status_data["linked_layout_status_as_service_warning"]) { - return VISUAL_MAP_STATUS_WARNING; - } - else { - return VISUAL_MAP_STATUS_NORMAL; - } - break; - } + $meta_connected_to = $node_id; + } + } + + $status = VISUAL_MAP_STATUS_NORMAL; + + $ent_element_status = enterprise_hook('enterprise_visual_map_get_status_element', [$layoutData]); + if ($ent_element_status === ENTERPRISE_NOT_HOOK) { + $ent_element_status = false; + } + + // Enterprise element + if ($ent_element_status !== false) { + $status = $ent_element_status; + } + // Other + else { + switch ($layout_item_data['type']) { + case STATIC_GRAPH: + case PERCENTILE_BAR: + case PERCENTILE_BUBBLE: + case CIRCULAR_PROGRESS_BAR: + case CIRCULAR_INTERIOR_PROGRESS_BAR: + // Linked layout + if (!empty($layout_item_data['id_layout_linked'])) { + $status = visual_map_get_layout_status($layout_item_data['id_layout_linked'], $layout_item_data, ($depth + 1)); + } + // Module + else if (!empty($layout_item_data['id_agente_modulo'])) { + $module_status = modules_get_agentmodule_status($layout_item_data['id_agente_modulo']); + $status = visual_map_translate_module_status($module_status); + } + // Agent + else if (!empty($layout_item_data['id_agent'])) { + $agent_status = agents_get_status($layout_item_data['id_agent'], true); + $status = visual_map_translate_agent_status($agent_status); + } + // Unknown + else { + $status = VISUAL_MAP_STATUS_UNKNOWN; + } + break; + + case GROUP_ITEM: + $group_status = groups_get_status($layout_item_data['id_group']); + $status = visual_map_translate_agent_status($group_status); + break; + + default: + // If it's a graph, a progress bar or a data tag, ALWAYS report status OK + // (=0) to avoid confussions here. + $status = VISUAL_MAP_STATUS_NORMAL; + break; + } + } + + // When the status calculation type is 'default', only one critical element is required to + // set the layout status as critical, so we can return the critical status right now. + if ($status_data['linked_layout_status_type'] === 'default' && ( $status == VISUAL_MAP_STATUS_CRITICAL_BAD + || $status == VISUAL_MAP_STATUS_CRITICAL_ALERT) + ) { + if (is_metaconsole() && $meta_connected_to) { + metaconsole_restore_db(); + // Restore db connection + } + + return $status; + } else { + if (!isset($num_elements_by_status[$status])) { + $num_elements_by_status[$status] = 0; + } + + $num_elements_by_status[$status]++; + } + } + + if (is_metaconsole() && $meta_connected_to) { + metaconsole_restore_db(); + // Restore db connection + } + + // Status calculation + switch ($status_data['linked_layout_status_type']) { + default: + case 'default': + $num_items_critical_alert = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_ALERT]; + $num_items_critical = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_BAD]; + $num_items_warning = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING]; + $num_items_unknown = $num_elements_by_status[VISUAL_MAP_STATUS_UNKNOWN]; + + if ($num_items_critical_alert > 0) { + return VISUAL_MAP_STATUS_CRITICAL_ALERT; + } else if ($num_items_critical > 0) { + return VISUAL_MAP_STATUS_CRITICAL_BAD; + } else if ($num_items_warning > 0) { + return VISUAL_MAP_STATUS_WARNING; + } else if ($num_items_unknown > 0) { + return VISUAL_MAP_STATUS_UNKNOWN; + } else { + return VISUAL_MAP_STATUS_NORMAL; + } + break; + case 'weight': + $weight = $status_data['id_layout_linked_weight']; + $num_items = count($valid_layout_items); + $num_items_critical_alert = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_ALERT]; + $num_items_critical = $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_BAD]; + $num_items_warning = $num_elements_by_status[VISUAL_MAP_STATUS_WARNING]; + $num_items_unknown = $num_elements_by_status[VISUAL_MAP_STATUS_UNKNOWN]; + + if ($num_items_critical > 0 + && ((($num_items_critical_alert + $num_items_critical) * 100) / $num_items) >= $weight + ) { + return $num_items_critical_alert > 0 ? VISUAL_MAP_STATUS_CRITICAL_ALERT : VISUAL_MAP_STATUS_CRITICAL_BAD; + } else if ($num_items_warning > 0 + && (($num_items_warning * 100) / $num_items) >= $weight + ) { + return VISUAL_MAP_STATUS_WARNING; + } else if ($num_items_unknown > 0 + && (($num_items_unknown * 100) / $num_items) >= $weight + ) { + return VISUAL_MAP_STATUS_UNKNOWN; + } else { + return VISUAL_MAP_STATUS_NORMAL; + } + break; + + case 'service': + $num_items_critical = ($num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_BAD] + $num_elements_by_status[VISUAL_MAP_STATUS_CRITICAL_ALERT]); + $critical_percentage = (($num_items_critical * 100) / count($valid_layout_items)); + + if ($critical_percentage >= $status_data['linked_layout_status_as_service_critical']) { + return VISUAL_MAP_STATUS_CRITICAL_BAD; + } else if ($critical_percentage >= $status_data['linked_layout_status_as_service_warning']) { + return VISUAL_MAP_STATUS_WARNING; + } else { + return VISUAL_MAP_STATUS_NORMAL; + } + break; + } } + /** * Make a text for the parent select, when the label is not empty put this for * the return text. Instead for the empty labels make the text with next form - * () - ( - ) () - * - * @param string $label The label of item in visual map. - * @param string $type The label of type in visual map. - * @param string $image The image of item in visual map. - * @param string $agent The agent name of item in visual map. - * @param string $id_module The module name of item in visual map. - * @param int $idData The id of item in visual map. - * + * () - ( - ) () + * + * @param string $label The label of item in visual map. + * @param string $type The label of type in visual map. + * @param string $image The image of item in visual map. + * @param string $agent The agent name of item in visual map. + * @param string $id_module The module name of item in visual map. + * @param integer $idData The id of item in visual map. + * * @return string The text for the parent. */ -function visual_map_create_internal_name_item($label = null, $type, $image, $agent = null, $id_module, $idData) { - $text = ''; - - if (empty($label)) - { - switch ($type) { - case 'box_item': - case BOX_ITEM: - $text = __('Box'); - break; - case 'module_graph': - case MODULE_GRAPH: - $text = __('Module graph'); - break; - case 'clock': - case CLOCK: - $text = __('Clock'); - break; - case 'bars_graph': - case BARS_GRAPH: - $text = __('Bars graph'); - break; - case 'auto_sla_graph': - case AUTO_SLA_GRAPH: - $text = __('Auto SLA Graph'); - break; - case 'percentile_bar': - case PERCENTILE_BAR: - $text = __('Percentile bar'); - break; - case 'circular_progress_bar': - case CIRCULAR_PROGRESS_BAR: - $text = __('Circular progress bar'); - break; - case 'interior_circular_progress_bar': - case CIRCULAR_INTERIOR_PROGRESS_BAR: - $text = __('Circular progress bar (interior)'); - break; - case 'static_graph': - case STATIC_GRAPH: - $text = __('Static graph') . " - " . - $image; - break; - case 'simple_value': - case SIMPLE_VALUE: - $text = __('Simple Value'); - break; - case 'label': - case LABEL: - $text = __('Label'); - break; - case GROUP_ITEM: - case 'group_item': - $text = __('Group') . " - "; - break; - case 'icon': - case ICON: - $text = __('Icon') . " - " . - $image; - break; - } - - if (!empty($agent)) { - $text .= " (" . ui_print_truncate_text($agent, 'agent_small', false); - - $moduleName = io_safe_output(db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $id_module)); - if (!empty($moduleName)) { - $text .= " - " . ui_print_truncate_text($moduleName, 'module_small', false); - } - - $text .= ")"; - } - $text .= ' (' . $idData . ')'; - } - else { - $text = $label; - } - - return io_safe_output($text); +function visual_map_create_internal_name_item($label=null, $type, $image, $agent=null, $id_module, $idData) +{ + $text = ''; + + if (empty($label)) { + switch ($type) { + case 'box_item': + case BOX_ITEM: + $text = __('Box'); + break; + + case 'module_graph': + case MODULE_GRAPH: + $text = __('Module graph'); + break; + + case 'clock': + case CLOCK: + $text = __('Clock'); + break; + + case 'bars_graph': + case BARS_GRAPH: + $text = __('Bars graph'); + break; + + case 'auto_sla_graph': + case AUTO_SLA_GRAPH: + $text = __('Auto SLA Graph'); + break; + + case 'percentile_bar': + case PERCENTILE_BAR: + $text = __('Percentile bar'); + break; + + case 'circular_progress_bar': + case CIRCULAR_PROGRESS_BAR: + $text = __('Circular progress bar'); + break; + + case 'interior_circular_progress_bar': + case CIRCULAR_INTERIOR_PROGRESS_BAR: + $text = __('Circular progress bar (interior)'); + break; + + case 'static_graph': + case STATIC_GRAPH: + $text = __('Static graph').' - '.$image; + break; + + case 'simple_value': + case SIMPLE_VALUE: + $text = __('Simple Value'); + break; + + case 'label': + case LABEL: + $text = __('Label'); + break; + + case GROUP_ITEM: + case 'group_item': + $text = __('Group').' - '; + break; + + case COLOR_CLOUD: + case 'color_cloud': + $text = __('Color cloud').' - '; + break; + + case 'icon': + case ICON: + $text = __('Icon').' - '.$image; + break; + } + + if (!empty($agent)) { + $text .= ' ('.ui_print_truncate_text($agent, 'agent_small', false); + + $moduleName = io_safe_output(db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $id_module)); + if (!empty($moduleName)) { + $text .= ' - '.ui_print_truncate_text($moduleName, 'module_small', false); + } + + $text .= ')'; + } + + $text .= ' ('.$idData.')'; + } else { + $text = $label; + } + + return io_safe_output($text); } -function visual_map_get_items_parents($idVisual) { - // Avoid the sort by 'label' in the query cause oracle cannot sort by columns with CLOB type - $items = db_get_all_rows_filter('tlayout_data', array('id_layout' => $idVisual)); - if ($items == false) { - $items = array(); - } - else { - // Sort by label - sort_by_column($items, 'label'); - } - - $return = array(); - foreach ($items as $item) { - $agent = null; - if ($item['id_agent'] != 0) { - $agent = io_safe_output(agents_get_alias($item['id_agent'])); - } - - $return[$item['id']] = visual_map_create_internal_name_item( - $item['label'], - $item['type'], - $item['image'], - $agent, - $item['id_agente_modulo'], - $item['id']); - } - - return $return; + +function visual_map_get_items_parents($idVisual) +{ + // Avoid the sort by 'label' in the query cause oracle cannot sort by columns with CLOB type + $items = db_get_all_rows_filter('tlayout_data', ['id_layout' => $idVisual]); + if ($items == false) { + $items = []; + } else { + // Sort by label + sort_by_column($items, 'label'); + } + + $return = []; + foreach ($items as $item) { + $agent = null; + if ($item['id_agent'] != 0) { + $agent = io_safe_output(agents_get_alias($item['id_agent'])); + } + + $return[$item['id']] = visual_map_create_internal_name_item( + $item['label'], + $item['type'], + $item['image'], + $agent, + $item['id_agente_modulo'], + $item['id'] + ); + } + + return $return; } + /** * Get the X axis coordinate of a layout item * * @param int Id of the layout to get. * - * @return int The X axis coordinate value. + * @return integer The X axis coordinate value. */ -function visual_map_get_layoutdata_x ($id_layoutdata) { - return (float) db_get_value ('pos_x', 'tlayout_data', 'id', (int) $id_layoutdata); +function visual_map_get_layoutdata_x($id_layoutdata) +{ + return (float) db_get_value('pos_x', 'tlayout_data', 'id', (int) $id_layoutdata); } + /** * Get the Y axis coordinate of a layout item * * @param int Id of the layout to get. * - * @return int The Y axis coordinate value. + * @return integer The Y axis coordinate value. */ -function visual_map_get_layoutdata_y ($id_layoutdata) { - return (float) db_get_value ('pos_y', 'tlayout_data', 'id', - (int)$id_layoutdata); -} - -function visual_map_type_in_js($type) { - switch ($type) { - case STATIC_GRAPH: - return 'static_graph'; - break; - case PERCENTILE_BAR: - return 'percentile_item'; - break; - case CIRCULAR_PROGRESS_BAR: - return 'percentile_item'; - break; - case CIRCULAR_INTERIOR_PROGRESS_BAR: - return 'percentile_item'; - break; - case MODULE_GRAPH: - return 'module_graph'; - break; - case BARS_GRAPH: - return 'bars_graph'; - break; - case AUTO_SLA_GRAPH: - return 'auto_sla_graph'; - break; - case SIMPLE_VALUE: - return 'simple_value'; - break; - case LABEL: - return 'label'; - break; - case ICON: - return 'icon'; - break; - case CLOCK: - return 'clock'; - break; - case SIMPLE_VALUE_MAX: - return 'simple_value'; - break; - case SIMPLE_VALUE_MIN: - return 'simple_value'; - break; - case SIMPLE_VALUE_AVG: - return 'simple_value'; - break; - case PERCENTILE_BUBBLE: - return 'percentile_item'; - break; - case SERVICE: - return 'service'; - break; - case GROUP_ITEM: - return 'group_item'; - break; - case BOX_ITEM: - return 'box_item'; - break; - case LINE_ITEM: - return 'line_item'; - break; - } -} - -function visual_map_macro($label,$module){ - $label = str_replace('_date_',strftime("%x"),$label); - $label = str_replace('_time_',strftime("%T"),$label); - $label = str_replace('_agent_',agents_get_alias(modules_get_agentmodule_agent($module)),$label); - $label = str_replace('_module_',modules_get_agentmodule_name($module),$label); - $label = str_replace('_agentdescription_',agents_get_description(modules_get_agentmodule_agent($module)),$label); - $label = str_replace('_address_',agents_get_address(modules_get_agentmodule_agent($module)),$label); - $label = str_replace('_moduledescription_',modules_get_agentmodule_descripcion($module),$label); - return $label; +function visual_map_get_layoutdata_y($id_layoutdata) +{ + return (float) db_get_value( + 'pos_y', + 'tlayout_data', + 'id', + (int) $id_layoutdata + ); } -?> \ No newline at end of file +function visual_map_type_in_js($type) +{ + switch ($type) { + case STATIC_GRAPH: + return 'static_graph'; + + break; + case PERCENTILE_BAR: + return 'percentile_item'; + + break; + case CIRCULAR_PROGRESS_BAR: + return 'percentile_item'; + + break; + case CIRCULAR_INTERIOR_PROGRESS_BAR: + return 'percentile_item'; + + break; + case MODULE_GRAPH: + return 'module_graph'; + + break; + case BARS_GRAPH: + return 'bars_graph'; + + break; + case AUTO_SLA_GRAPH: + return 'auto_sla_graph'; + + break; + case SIMPLE_VALUE: + return 'simple_value'; + + break; + case LABEL: + return 'label'; + + break; + case ICON: + return 'icon'; + + break; + case CLOCK: + return 'clock'; + + break; + case SIMPLE_VALUE_MAX: + return 'simple_value'; + + break; + case SIMPLE_VALUE_MIN: + return 'simple_value'; + + break; + case SIMPLE_VALUE_AVG: + return 'simple_value'; + + break; + case PERCENTILE_BUBBLE: + return 'percentile_item'; + + break; + case SERVICE: + return 'service'; + + break; + case GROUP_ITEM: + return 'group_item'; + + break; + case BOX_ITEM: + return 'box_item'; + + break; + case LINE_ITEM: + return 'line_item'; + + case COLOR_CLOUD: + return 'color_cloud'; + + break; + } +} + + +function visual_map_macro($label, $module) +{ + $label = str_replace('_date_', strftime('%x'), $label); + $label = str_replace('_time_', strftime('%T'), $label); + $label = str_replace('_agent_', agents_get_alias(modules_get_agentmodule_agent($module)), $label); + $label = str_replace('_module_', modules_get_agentmodule_name($module), $label); + $label = str_replace('_agentdescription_', agents_get_description(modules_get_agentmodule_agent($module)), $label); + $label = str_replace('_address_', agents_get_address(modules_get_agentmodule_agent($module)), $label); + $label = str_replace('_moduledescription_', modules_get_agentmodule_descripcion($module), $label); + return $label; +} + + +function visual_map_get_color_cloud_element($data) +{ + $id = (int) $data['id']; + $diameter = (int) $data['width']; + $dynamic_fields = []; + + try { + // Yes, the dynamic fields object is stored into the label field. ¯\_(ツ)_/¯ + if (!empty($data['label'])) { + $dynamic_fields = json_decode($data['label'], true); + } + } catch (Exception $ex) { + } + + $default_color = !empty($dynamic_fields['default_color']) ? $dynamic_fields['default_color'] : '#FFFFFF'; + $color = $default_color; + // The svg gradient needs a unique identifier + $gradient_id = 'grad_'.$id; + + // Color ranges + if (!empty($dynamic_fields['color_ranges']) + && !empty($data['id_agente_modulo']) + ) { + $node_id = null; + $node_connected = false; + // Connect to node + if (is_metaconsole() && !empty($data['id_metaconsole'])) { + $node_id = (int) $data['id_metaconsole']; + if (metaconsole_connect(null, $node_id) === NOERR) { + $node_connected = true; + } + } + + // Fetch module value + $value = (!$node_id || ($node_id && $node_connected)) ? modules_get_last_value($data['id_agente_modulo']) : false; + + // Restore connection + if ($node_connected) { + metaconsole_restore_db(); + } + + if ($value !== false) { + /* + TODO: It would be ok to give support to string values in the future? + * It can be done by matching the range value with the value if it is a + * string. I think the function to retrieve the value only supports + * numeric values. + */ + $value = (float) $value; + foreach ($dynamic_fields['color_ranges'] as $range) { + if ($range['from_value'] <= $value && $range['to_value'] >= $value) { + $color = $range['color']; + break; + } + } + } + } + + ob_start(); + ?> + + + + + + + + + + + '; - //----------------------------Hiden Form---------------------------- - ?> - - - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + +
        - __('Background'), - 'static_graph' => __('Static Graph'), - 'percentile_item' => __('Percentile Item'), - 'module_graph' => __('Graph'), - 'auto_sla_graph' => __('Auto SLA Graph'), - 'simple_value' => __('Simple value') . ui_print_help_tip(__("To use 'label'field, you should write - a text to replace '(_VALUE_)' and the value of the module will be printed at the end."), true), - 'label' => __('Label'), - 'icon' => __('Icon'), - 'clock' => __('Clock'), - 'group_item' => __('Group'), - 'box_item' => __('Box'), - 'line_item' => __('Line')); - - if (enterprise_installed()) { - enterprise_visual_map_editor_add_title_palette($titles); - } - - foreach ($titles as $item => $title) { - echo '
        Data Status change
        12:001No12:001No
        12:051No12:051No
        12:100No12:100No
        12:111No12:111No
        12:161No12:161No
        12:210No12:210No
        12:220Yes12:220Yes
        diff --git a/pandora_console/include/help/en/help_ff_timeout.php b/pandora_console/include/help/en/help_ff_timeout.php index 288c5b69a9..1e9049542b 100644 --- a/pandora_console/include/help/en/help_ff_timeout.php +++ b/pandora_console/include/help/en/help_ff_timeout.php @@ -17,34 +17,34 @@ For example, an asynchronous proc module with a FF threshold of 1 and a FF timeo Data Status change - 12:00 - 1 - No + 12:00 + 1 + No - 12:05 - 0 - No + 12:05 + 0 + No - 12:20 - 0 - No + 12:20 + 0 + No - 12:25
        - 1 - No + 12:25
        + 1 + No - 12:45 - 0 - No + 12:45 + 0 + No - 12:50 - 0 - Yes + 12:50 + 0 + Yes diff --git a/pandora_console/include/help/en/help_field_match_snmp.php b/pandora_console/include/help/en/help_field_match_snmp.php index 47ab269c0c..77d48b9089 100755 --- a/pandora_console/include/help/en/help_field_match_snmp.php +++ b/pandora_console/include/help/en/help_field_match_snmp.php @@ -1,7 +1,7 @@

        Variable bindings/Data #1-20

        @@ -11,26 +11,26 @@ -

        You can use up to 20 variables for doing the filtering (and reusing later for macros). But they doesnt need to follow a specific order. The position of the variable can be defined in the field preceding value. +

        You can use up to 20 variables for doing the filtering (and reusing later for macros). But they doesnt need to follow a specific order. The position of the variable can be defined in the field preceding value. That is, if we want to make an alert seeking values ​​"Uno" in the first variable received at the trap, "Tres" in the third variable received by the trap and the same for “Cinco” and “Siete”, is configured as you can see below:

        - + -

        We can use the value of the variables in macros _snmp_f1_ coincidence .. so _snmp_f7_ to define the alert, the alert action allows us to use these macros:

        +

        We can use the value of the variables in macros _snmp_f1_ coincidence .. so _snmp_f7_ to define the alert, the alert action allows us to use these macros:

        - + -

        Here's an example of SNMP trap that will trigger the alert:

        +

        Here's an example of SNMP trap that will trigger the alert:

        - + -

        Alert generated (an internal audit) will have this text:

        +

        Alert generated (an internal audit) will have this text:

        SNMP Alert of 192.168.5.2 with OID .1.3.6.1.4.1.2789.2005 Varbind 100: “cien” Varbind 3: “tres” Varbind 20: “veinte” Varbind 60: “sesenta”

        diff --git a/pandora_console/include/help/en/help_gis_map_builder.php b/pandora_console/include/help/en/help_gis_map_builder.php index 363d51fda4..ef666c7183 100644 --- a/pandora_console/include/help/en/help_gis_map_builder.php +++ b/pandora_console/include/help/en/help_gis_map_builder.php @@ -6,7 +6,7 @@

        GIS Map builder

        -This page shows a list of the defined maps, and let you edit, delete or view any of them. Also from this page is where the default Map of is set. +This page shows a list of the defined maps, and let you edit, delete or view any of them. Also from this page is where the default Map of is set.

        To create a map a connection to a map server is needed, the connections are created by the Adminstrator in the Setup menu.

        @@ -18,11 +18,11 @@ Options:

        Map name
        Click on the Map Name corresponding to the map you want edit the map
        -
        "View")); ?> View
        +
        'View']); ?> View
        Click on the view icon to view the map.
        Default radio button
        Click on the radio button corresponding to the map you want to make the default to set the default map
        -
        "Delete")); ?> Delete
        +
        'Delete']); ?> Delete
        Click on the delete icon to delete the map.
        Create Button
        Click on Create button to create a new map.
        diff --git a/pandora_console/include/help/en/help_gis_setup_map_connection.php b/pandora_console/include/help/en/help_gis_setup_map_connection.php index 0afe61a8e1..131431eb6d 100644 --- a/pandora_console/include/help/en/help_gis_setup_map_connection.php +++ b/pandora_console/include/help/en/help_gis_setup_map_connection.php @@ -11,7 +11,7 @@ This page is the place where the admin can configure a connection to a G

        Connection types

        -Currently support 3 differet kinds of connections: OpenStreetMap, Google Maps and Static Image. +Currently support 3 differet kinds of connections: OpenStreetMap, Google Maps and Static Image.

        Open Street Maps

        diff --git a/pandora_console/include/help/en/help_gis_tab.php b/pandora_console/include/help/en/help_gis_tab.php index cfa22a0013..cbb311bbab 100644 --- a/pandora_console/include/help/en/help_gis_tab.php +++ b/pandora_console/include/help/en/help_gis_tab.php @@ -1,6 +1,7 @@

        Agent GIS view

        diff --git a/pandora_console/include/help/en/help_graph_builder.php b/pandora_console/include/help/en/help_graph_builder.php index 6e7e9606c1..0a2e12a04a 100644 --- a/pandora_console/include/help/en/help_graph_builder.php +++ b/pandora_console/include/help/en/help_graph_builder.php @@ -1,7 +1,7 @@

        Graph builder

        diff --git a/pandora_console/include/help/en/help_graph_editor.php b/pandora_console/include/help/en/help_graph_editor.php index 79c9055cfc..2abee68b76 100644 --- a/pandora_console/include/help/en/help_graph_editor.php +++ b/pandora_console/include/help/en/help_graph_editor.php @@ -1,7 +1,7 @@

        Item editor

        diff --git a/pandora_console/include/help/en/help_graph_view.php b/pandora_console/include/help/en/help_graph_view.php index f5191cb214..4172d18c96 100644 --- a/pandora_console/include/help/en/help_graph_view.php +++ b/pandora_console/include/help/en/help_graph_view.php @@ -1,7 +1,7 @@

        Graph viewer

        diff --git a/pandora_console/include/help/en/help_graphs.php b/pandora_console/include/help/en/help_graphs.php index b1f51e0cb0..643caf7898 100644 --- a/pandora_console/include/help/en/help_graphs.php +++ b/pandora_console/include/help/en/help_graphs.php @@ -1,63 +1,63 @@ -

        INTERPRETING GRAPHS IN

        +

        INTERPRETING GRAPHS IN

        -

        In , graphs represent the values a module has had during a given period.

        -

        Due to the large amount of data that stores, two different types of functionality are offered

        +

        In , graphs represent the values a module has had during a given period.

        +

        Due to the large amount of data that stores, two different types of functionality are offered

        NORMAL GRAPHS

        -images/help/chart_normal_sample.png" alt="regular chart sample" /> +regular chart sample

        General characteristics

        These are graphs that represent the information stored by the module at a basic level.

        @@ -98,7 +98,7 @@ div.img_title {
        Shows indicator points with triggered alert information at the top.
        Show percentile
        -
        Adds a graph that indicates the percentile line (configurable in general visual options of ).
        +
        Adds a graph that indicates the percentile line (configurable in general visual options of ).
        Time comparison (superimposed)
        Displays the same graphic overlay, but in the period before the selected one. For example, if we request a period of one week and activate this option, the week before the chosen one will also be shown superimposed.
        @@ -107,7 +107,7 @@ div.img_title {
        Displays the same graph, but in the period before the selected one, in a separate area. For example, if we request a period of one week and activate this option, the week before the chosen one will also be shown.
        Display unknown graphic
        -
        It shows boxes in grey shading covering the periods in which cannot guarantee the module's status, either due to data loss, disconnection of a software agent, etc.
        +
        It shows boxes in grey shading covering the periods in which cannot guarantee the module's status, either due to data loss, disconnection of a software agent, etc.
        Show Full Scale Graph (TIP)
        Switches the creation mode from "normal" to "TIP". In this mode, the graphs will show real data rather than approximations, so the time it will take to generate them will be longer. More detailed information on this type of graphs can be found in the following section.
        @@ -122,7 +122,7 @@ div.img_title {

        TIP GRAPS

        -images/help/chart_tip_sample.png" alt="TIP chart sample" /> +TIP chart sample

        General characteristics

        These are graphs that represent real data.

        @@ -132,10 +132,10 @@ div.img_title {

        Examples of resolution offered by normal and TIP methods:

        Example of normal graph in unknown interval
        -images/help/chart_normal_detail.png" alt="TIP chart detail" /> +TIP chart detail
        Example of TIP graph in unknown interval
        -images/help/chart_tip_detail.png" alt="TIP chart detail" /> +TIP chart detail
        diff --git a/pandora_console/include/help/en/help_history_database.php b/pandora_console/include/help/en/help_history_database.php index 0859f49f3e..dd02965749 100644 --- a/pandora_console/include/help/en/help_history_database.php +++ b/pandora_console/include/help/en/help_history_database.php @@ -5,7 +5,7 @@ ?>

        History database

        -A history database is a database where old module data is moved to make the main database more responsive for everyday operations. That data will still be available seamlessly to the console when viewing reports, module charts etc. +A history database is a database where old module data is moved to make the main database more responsive for everyday operations. That data will still be available seamlessly to the console when viewing reports, module charts etc.

        SETTING UP A HISTORY DATABASE

        @@ -14,7 +14,7 @@ To configure a history database follow these simple steps:
        1. Create the new history database.

          -
        2. Create the necessary tables in the new database. You can use the DB Tool script provided with the console: +
        3. Create the necessary tables in the new database. You can use the DB Tool script provided with the console:

          cat pandoradb.sql | mysql -u user -p -D history_db

          @@ -22,10 +22,10 @@ To configure a history database follow these simple steps:

          Mysql Example: GRANT ALL PRIVILEGES ON pandora.* TO 'pandora'@'IP' IDENTIFIED BY 'password'

          -
        4. In your console navigate to Setup->History database and enter the host, port, database name, user and password of the new database. +
        5. In your console navigate to Setup->History database and enter the host, port, database name, user and password of the new database.


        - '550px')); ?> + '550px']); ?>

        Data older than Days days will be moved to the history database in blocks of Step rows, waiting Delay seconds between one block and the next to avoid overload.

        diff --git a/pandora_console/include/help/en/help_inventory_tab.php b/pandora_console/include/help/en/help_inventory_tab.php index 83150650ea..4c0b439b74 100644 --- a/pandora_console/include/help/en/help_inventory_tab.php +++ b/pandora_console/include/help/en/help_inventory_tab.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/en/help_ipam.php b/pandora_console/include/help/en/help_ipam.php index f26de991d8..549601f059 100755 --- a/pandora_console/include/help/en/help_ipam.php +++ b/pandora_console/include/help/en/help_ipam.php @@ -5,9 +5,9 @@ ?>

        IP Address Management (IPAM)


        -Using IPAM extension, we can manage, discover and get event on changes on hosts in a given network. We can know if a given IP address (IPv4 or IPv6) change it's availability (answer to a ping) or hostname (using dns resolution). We also can detect its OS and link a IP address to a current agent, adding the IP address to their currently assigned addresses. IPAM extension uses the recon server and a recon script on the low level, but you don't need to configure nothing, IPAM extension do everything for you. +Using IPAM extension, we can manage, discover and get event on changes on hosts in a given network. We can know if a given IP address (IPv4 or IPv6) change it's availability (answer to a ping) or hostname (using dns resolution). We also can detect its OS and link a IP address to a current agent, adding the IP address to their currently assigned addresses. IPAM extension uses the recon server and a recon script on the low level, but you don't need to configure nothing, IPAM extension do everything for you.

        -IP Management works in parallel to the monitoring you currently manage with agents, you can associate a IP address managed with IPAM extension or not, it depends on you. Managed IP addresses can optionally generate event on change. +IP Management works in parallel to the monitoring you currently manage with agents, you can associate a IP address managed with IPAM extension or not, it depends on you. Managed IP addresses can optionally generate event on change.

        IPs Detection

        We can setup a network (using a bit mask or a prefix), and this network will be automatically sweeped or setup to have a on-request manual execution. This will execute a recon script task, searching for active IP (using nmap for IPv4 and ping for IPv6). You see the progress on network sweep in the status view and also in the recon server view. @@ -76,7 +76,7 @@ When you click on the main icon, a modal window will be opened showing all the I

        Edition view

        If you have enought permission, you will have access to setup view, where IP address are shown as a list. You can filter to show only the IP's you are interested into, make changes and update all at once.

        -Some fields, are automatically filled by the recon script, like hostname, if it have a agent and the operating system. You can mark that fields as "manual" and edit them.

        +Some fields, are automatically filled by the recon script, like hostname, if it have a agent and the operating system. You can mark that fields as "manual" and edit them.

        diff --git a/pandora_console/include/help/en/help_linked_map_status_calc.php b/pandora_console/include/help/en/help_linked_map_status_calc.php index 96602eb262..a8221594de 100644 --- a/pandora_console/include/help/en/help_linked_map_status_calc.php +++ b/pandora_console/include/help/en/help_linked_map_status_calc.php @@ -7,30 +7,30 @@

        By Default

        - It calculates the status based on the status of all elements, as an agent would do. + It calculates the status based on the status of all elements, as an agent would do.

        By weight

        - It calculates the status of the elements that have a visual console, a module or an agent assigned in relation to a percentage of elements configured by the user. This percentage is the one that has to exceed the number of elements of a non-normal status with respect to the number of elements taken into account in the calculation for that status to change. + It calculates the status of the elements that have a visual console, a module or an agent assigned in relation to a percentage of elements configured by the user. This percentage is the one that has to exceed the number of elements of a non-normal status with respect to the number of elements taken into account in the calculation for that status to change.

        - For example, given an element with a percentage of 50% and a visual console linked with 5 elements: + For example, given an element with a percentage of 50% and a visual console linked with 5 elements:

          -
        • 1 critical, 1 warning y 3 normal -> Status normal.
        • -
        • 2 critical, 2 warning y 1 normal -> Status normal.
        • -
        • 1 critical, 3 warning y 1 normal -> Status warning.
        • -
        • 3 critical, 1 warning y 1 normal -> Status critical.
        • -
        • 1 critical, 1 warning y 3 unknown -> Status unknown.
        • +
        • 1 critical, 1 warning y 3 normal -> Status normal.
        • +
        • 2 critical, 2 warning y 1 normal -> Status normal.
        • +
        • 1 critical, 3 warning y 1 normal -> Status warning.
        • +
        • 3 critical, 1 warning y 1 normal -> Status critical.
        • +
        • 1 critical, 1 warning y 3 unknown -> Status unknown.

        - If several statuses exceed the weight, the priority is the same as in the rest of the status calculation (critical > warning > unknown). If there are no elements to perform the calculation, the status becomes unknown. + If several statuses exceed the weight, the priority is the same as in the rest of the status calculation (critical > warning > unknown). If there are no elements to perform the calculation, the status becomes unknown.

        By critical elements

        - It calculates the status using the elements in critical status and the percentages of the thresholds defined by the user. If the number of elements in critical status with respect to the number of elements taken into account in the calculation exceeds the percentage assigned as warning, the status becomes warning. The same applies to the percentage assigned as critical, which also has preference. + It calculates the status using the elements in critical status and the percentages of the thresholds defined by the user. If the number of elements in critical status with respect to the number of elements taken into account in the calculation exceeds the percentage assigned as warning, the status becomes warning. The same applies to the percentage assigned as critical, which also has preference.

        diff --git a/pandora_console/include/help/en/help_local_component.php b/pandora_console/include/help/en/help_local_component.php index 30eb475973..680c9531ce 100644 --- a/pandora_console/include/help/en/help_local_component.php +++ b/pandora_console/include/help/en/help_local_component.php @@ -1,9 +1,9 @@

        Local Component

        -

        Local Components are elements that can be applied to agents like templates. With Enterprise, this can be applied authomatically and remotely with policies or one by one.

        +

        Local Components are elements that can be applied to agents like templates. With Enterprise, this can be applied authomatically and remotely with policies or one by one.

        diff --git a/pandora_console/include/help/en/help_macros.php b/pandora_console/include/help/en/help_macros.php index 1c897c1f93..72e47cee63 100755 --- a/pandora_console/include/help/en/help_macros.php +++ b/pandora_console/include/help/en/help_macros.php @@ -9,9 +9,9 @@ Is possible configure macros in the module execution (module_exec) or in a plugi

        Each macro has 3 parameters:
          -
        • Description
        • -
        • Default value (optional)
        • -
        • Help (optional)
        • +
        • Description
        • +
        • Default value (optional)
        • +
        • Help (optional)
        In example, to configure a module that returns the apache's running process @@ -26,9 +26,9 @@ ps -A | grep _field1_ | wc -l And configure the parameters of the macro as:
          -
        • Description: Process
        • -
        • Default value: apache2
        • -
        • Help: Name of substring of the running processes counted by the module
        • +
        • Description: Process
        • +
        • Default value: apache2
        • +
        • Help: Name of substring of the running processes counted by the module
        When we configure the module from this component, will appear a text field "Process" diff --git a/pandora_console/include/help/en/help_macros_visual_maps.php b/pandora_console/include/help/en/help_macros_visual_maps.php index af01634f94..28f8e4e390 100644 --- a/pandora_console/include/help/en/help_macros_visual_maps.php +++ b/pandora_console/include/help/en/help_macros_visual_maps.php @@ -9,11 +9,11 @@ It is possible to enter a macro in the text box when editing an element of the v

        List of visual console's macros:
          -
        • _date_: Displays the date using the local PHP format.
        • -
        • _time_: Displays the time using the local PHP format.
        • -
        • _agent_: Displays the alias of the selected agent.
        • -
        • _module_: Displays the name of the selected module.
        • -
        • _agentdescription_: Displays the description of the selected agent.
        • -
        • _address_: Displays the ip address of the selected agent.
        • -
        • _moduledescription_: Displays the description of the selected module.
        • +
        • _date_: Displays the date using the local PHP format.
        • +
        • _time_: Displays the time using the local PHP format.
        • +
        • _agent_: Displays the alias of the selected agent.
        • +
        • _module_: Displays the name of the selected module.
        • +
        • _agentdescription_: Displays the description of the selected agent.
        • +
        • _address_: Displays the ip address of the selected agent.
        • +
        • _moduledescription_: Displays the description of the selected module.
        \ No newline at end of file diff --git a/pandora_console/include/help/en/help_main_help.php b/pandora_console/include/help/en/help_main_help.php index bfd5897efc..a86f636fa2 100644 --- a/pandora_console/include/help/en/help_main_help.php +++ b/pandora_console/include/help/en/help_main_help.php @@ -3,10 +3,10 @@ * @package Include/help/en */ ?> -

        - Help index

        +

        - Help index

        Introduction

        -This is the online help for console. This help is -in best cases- just a "brief" contextual help, not intented to teach you how to use . Official documentation of is large, and you probably don't need to read it entirely, but sure, you should download it and take a look. +This is the online help for console. This help is -in best cases- just a "brief" contextual help, not intented to teach you how to use . Official documentation of is large, and you probably don't need to read it entirely, but sure, you should download it and take a look.

        Download the official documentation diff --git a/pandora_console/include/help/en/help_manage_alert_list.php b/pandora_console/include/help/en/help_manage_alert_list.php index d46ac3abbf..406ef3ea01 100644 --- a/pandora_console/include/help/en/help_manage_alert_list.php +++ b/pandora_console/include/help/en/help_manage_alert_list.php @@ -6,7 +6,7 @@

        Alerts

        -Alerts in react to an "out of range" module value. The alert can consist of sending an e-mail or an SMS to the administrator, sending a SNMP trap, write the incident into the system log or into log file, etc. Basically, an alert can be anything that can be triggered by a script configured in the Operating System where Servers run. +Alerts in react to an "out of range" module value. The alert can consist of sending an e-mail or an SMS to the administrator, sending a SNMP trap, write the incident into the system log or into log file, etc. Basically, an alert can be anything that can be triggered by a script configured in the Operating System where Servers run.

        @@ -14,9 +14,9 @@ When a new alert is created the following fields must be filled in:

          -
        • Agent name: The name of the agent associated with the alert.
        • -
        • Module: Alert get module value and test if it is "out of range". In afirmative case it will raise an event (seding e-mail, etc.).
        • -
        • Template: Alerts width all parameters defined. They are used to do the administrator management easier.
        • -
        • Action: Allows to choose between all the alerts that have been configured. The selected action will be added to the action that is defined in the template.
        • -
        • Threshold: Defines the time interval in which it is guaranteed that an alert is not going to be fired more times than the number fixed in Maximum number of alerts. +
        • Agent name: The name of the agent associated with the alert.
        • +
        • Module: Alert get module value and test if it is "out of range". In afirmative case it will raise an event (seding e-mail, etc.).
        • +
        • Template: Alerts width all parameters defined. They are used to do the administrator management easier.
        • +
        • Action: Allows to choose between all the alerts that have been configured. The selected action will be added to the action that is defined in the template.
        • +
        • Threshold: Defines the time interval in which it is guaranteed that an alert is not going to be fired more times than the number fixed in Maximum number of alerts.
        diff --git a/pandora_console/include/help/en/help_manage_alerts.php b/pandora_console/include/help/en/help_manage_alerts.php index a2f379583c..c63236d578 100644 --- a/pandora_console/include/help/en/help_manage_alerts.php +++ b/pandora_console/include/help/en/help_manage_alerts.php @@ -5,25 +5,25 @@ ?>

        Alerts

        -Alerts in react to an "out of range" module value. The alert can consist of sending an e-mail or an SMS to the administrator, sending a SNMP trap, write the incident into the system log or into log file, etc. Basically, an alert can be anything that can be triggered by a script configured in the Operating System where Servers run. +Alerts in react to an "out of range" module value. The alert can consist of sending an e-mail or an SMS to the administrator, sending a SNMP trap, write the incident into the system log or into log file, etc. Basically, an alert can be anything that can be triggered by a script configured in the Operating System where Servers run.

        The values "_field1_", "_field2_" and "_field3_" of the customized alerts are used to build the command line that will be executed.

        When a new alert is created the following fields must be filled in:
          -
        • Alert name: The name of the alert. It is important to describe correctly its function, but briefly, for example: "Comm. log".
        • -
        • Command: Command that the alert will trigger, it is he most important field while defining an alert. Note that the macros _field1, _field2_, and _field3_ are used to replace the configured parameters at the alert definition. That way the execution of the command fired by the alert is built. While defining an alert, you should test the correct execution of the alert, and that the result is the expected (send an email, generate an entry in a log, etc) at the command line.
        • -
        • Description: Long description of the alert, optional.
        • +
        • Alert name: The name of the alert. It is important to describe correctly its function, but briefly, for example: "Comm. log".
        • +
        • Command: Command that the alert will trigger, it is he most important field while defining an alert. Note that the macros _field1, _field2_, and _field3_ are used to replace the configured parameters at the alert definition. That way the execution of the command fired by the alert is built. While defining an alert, you should test the correct execution of the alert, and that the result is the expected (send an email, generate an entry in a log, etc) at the command line.
        • +
        • Description: Long description of the alert, optional.
        The complete set of macros that can used within an alert is the following:
          -
        • _field1_: Usually used as username, phone number, file to send or e-mail destination.
        • -
        • _field2_: Usually used as short description of events, or subject line for e-mails.
        • -
        • _field3_: A full text explanation for the event, can be used as the text field for an email or SMS.
        • -
        • _agent_: Full agent name.
        • -
        • _timestamp_: A standard representation of date and time. Automatically replaced when the alert is executed.
        • -
        • _data_: The data value that triggered the alert.
        • +
        • _field1_: Usually used as username, phone number, file to send or e-mail destination.
        • +
        • _field2_: Usually used as short description of events, or subject line for e-mails.
        • +
        • _field3_: A full text explanation for the event, can be used as the text field for an email or SMS.
        • +
        • _agent_: Full agent name.
        • +
        • _timestamp_: A standard representation of date and time. Automatically replaced when the alert is executed.
        • +
        • _data_: The data value that triggered the alert.
        diff --git a/pandora_console/include/help/en/help_map_builder.php b/pandora_console/include/help/en/help_map_builder.php index 6f5e961e20..2d4997965f 100644 --- a/pandora_console/include/help/en/help_map_builder.php +++ b/pandora_console/include/help/en/help_map_builder.php @@ -7,23 +7,23 @@ To create a map, you must first fill the form providing:
          -
        • A name
        • -
        • A group
        • -
        • A background image
        • -
        • A size (width/height)
        • +
        • A name
        • +
        • A group
        • +
        • A background image
        • +
        • A size (width/height)
        One you have filled it, click on "Update" so the map will be loaded.

        To add items to the map, go to the form below the background image, and fill it, providing, for each element:
          -
        • A label and a color for it
        • -
        • A type: a static three color graph or a module graph
        • -
        • The Agent from where the data will come
        • -
        • The Module from the Agent
        • -
        • The update period
        • -
        • The image for the item
        • -
        • A parent, in case you want the item to be the child of another item
        • -
        • A linked map, in case you want to link the item with another map
        • +
        • A label and a color for it
        • +
        • A type: a static three color graph or a module graph
        • +
        • The Agent from where the data will come
        • +
        • The Module from the Agent
        • +
        • The update period
        • +
        • The image for the item
        • +
        • A parent, in case you want the item to be the child of another item
        • +
        • A linked map, in case you want to link the item with another map
        To edit the properties of an already created item, just drag the item to the form "MAP ELEMENT EDITOR" and drop it there, the form will load the element's properties.

        diff --git a/pandora_console/include/help/en/help_meta_access.php b/pandora_console/include/help/en/help_meta_access.php index 0129af6377..f9a02b6a8a 100644 --- a/pandora_console/include/help/en/help_meta_access.php +++ b/pandora_console/include/help/en/help_meta_access.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/en/help_metaconsole_agent_cache.php b/pandora_console/include/help/en/help_metaconsole_agent_cache.php index 8f8090bf5d..38a6ec1250 100644 --- a/pandora_console/include/help/en/help_metaconsole_agent_cache.php +++ b/pandora_console/include/help/en/help_metaconsole_agent_cache.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/en/help_module_interval.php b/pandora_console/include/help/en/help_module_interval.php index 23aa755538..f00e18f6c3 100644 --- a/pandora_console/include/help/en/help_module_interval.php +++ b/pandora_console/include/help/en/help_module_interval.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/en/help_module_interval_factor.php b/pandora_console/include/help/en/help_module_interval_factor.php index f75cb9d116..b0671bd855 100644 --- a/pandora_console/include/help/en/help_module_interval_factor.php +++ b/pandora_console/include/help/en/help_module_interval_factor.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/en/help_module_linking.php b/pandora_console/include/help/en/help_module_linking.php index 1cb3356cee..b43ad9b09a 100644 --- a/pandora_console/include/help/en/help_module_linking.php +++ b/pandora_console/include/help/en/help_module_linking.php @@ -1,7 +1,7 @@

        Linking modules

        diff --git a/pandora_console/include/help/en/help_module_macros.php b/pandora_console/include/help/en/help_module_macros.php index 705b6f92e9..3b61365492 100644 --- a/pandora_console/include/help/en/help_module_macros.php +++ b/pandora_console/include/help/en/help_module_macros.php @@ -5,29 +5,29 @@ ?>

        Module macros

        - Any number of custom module macros may be defined. The recommended format for macro names is: + Any number of custom module macros may be defined. The recommended format for macro names is:

        -	_macroname_
        +    _macroname_
         

        - For example: + For example:

          -
        1. - _technology_ -
        2. -
        3. - _modulepriority_ -
        4. -
        5. - _contactperson_ -
        6. +
        7. + _technology_ +
        8. +
        9. + _modulepriority_ +
        10. +
        11. + _contactperson_ +

        - This macros can be used in module alerts. + This macros can be used in module alerts.

        IF THE MODULE IS A WEB MODULE ANALYSIS TYPE:

        @@ -36,40 +36,40 @@ Dynamic macros will have a special format starting with @ and will have these possible substitutions:

          -
        1. - @DATE_FORMAT (current date/time with user-defined format) -
        2. -
        3. - @DATE_FORMAT_nh (hours) -
        4. -
        5. - @DATE_FORMAT_nm (minutes) -
        6. -
        7. - @DATE_FORMAT_nd (days) -
        8. -
        9. - @DATE_FORMAT_ns (seconds) -
        10. -
        11. - @DATE_FORMAT_nM (month) -
        12. -
        13. - @DATE_FORMAT_nY (years) -
        14. +
        15. + @DATE_FORMAT (current date/time with user-defined format) +
        16. +
        17. + @DATE_FORMAT_nh (hours) +
        18. +
        19. + @DATE_FORMAT_nm (minutes) +
        20. +
        21. + @DATE_FORMAT_nd (days) +
        22. +
        23. + @DATE_FORMAT_ns (seconds) +
        24. +
        25. + @DATE_FORMAT_nM (month) +
        26. +
        27. + @DATE_FORMAT_nY (years) +

        Where "n" can be a number without a sign (positive) or negative.

        And FORMAT follows the standard of perl's strftime: - http://search.cpan.org/~dexter/POSIX-strftime-GNU-0.02/lib/POSIX/strftime/GNU.pm + http://search.cpan.org/~dexter/POSIX-strftime-GNU-0.02/lib/POSIX/strftime/GNU.pm

        - Examples: + Examples:

        -	@DATE_%Y-%m-%d %H:%M:%S
        -	@DATE_%H:%M:%S_300s
        -	@DATE_%H:%M:%S_-1h
        +    @DATE_%Y-%m-%d %H:%M:%S
        +    @DATE_%H:%M:%S_300s
        +    @DATE_%H:%M:%S_-1h
         
        \ No newline at end of file diff --git a/pandora_console/include/help/en/help_module_tokens.php b/pandora_console/include/help/en/help_module_tokens.php index 8078c41e8d..f9f925f4db 100644 --- a/pandora_console/include/help/en/help_module_tokens.php +++ b/pandora_console/include/help/en/help_module_tokens.php @@ -1,5 +1,6 @@

        Modules definition

        @@ -21,7 +22,7 @@ module_end
        There are different kinds of modules, with different suboptions, but all modules have an structure similar to this. The parameters module_interval and module_description are optionals and the rest completely compulsories. We are going to see first the common elements.

        Common elements of all modules

        -

        +

        module_begin

        Defines the beginning of the module. @@ -96,7 +97,7 @@ The total of seconds, agent will wait for the execution of the module, so if it

        module_postprocess 'factor'

        -Same as in the definition of post processing of a module that is done from the console, here could be defined a numeric value of floating comma that will send this value to in order the server will use it to multiply the received (raw) by the agent. +Same as in the definition of post processing of a module that is done from the console, here could be defined a numeric value of floating comma that will send this value to in order the server will use it to multiply the received (raw) by the agent.

        module_save 'variable name'

        @@ -245,7 +246,7 @@ module_end

        Processes Watchdog

        -A Watchdog is a system that allows to act immediately when an agent is down, usually picking up the process that is down . The Windows agent could act as Watchdog when a process is down. This is called watchdog mode for the process: +A Watchdog is a system that allows to act immediately when an agent is down, usually picking up the process that is down . The Windows agent could act as Watchdog when a process is down. This is called watchdog mode for the process:

        Executing a process could need some parameters, so there are some additional configuration options for these kind of modules. It is important to say that the watchdog mode only works when the module type is asynchronous. Let's see an example of configuration of a module_proc with watchdog.

        @@ -268,7 +269,7 @@ This is the definition of the additional parameters for module_proc with watchdo

        module_startdelay: Number of milliseconds the module will wait before starting the process by first time. If the process takes lot of time at starting , then it will be a great idea to order the agent through this parameter that it "wait" until start checking again if the process has got up. In this example wait 3 seconds.

        - module_retrydelay: Similar to the previous one but for subsequent falls/reattempts, after having detect a fall. When detects a fall, relaunch the process, wait the nº of milliseconds pointed out in this parameter and check again if the process is already up. + module_retrydelay: Similar to the previous one but for subsequent falls/reattempts, after having detect a fall. When detects a fall, relaunch the process, wait the nº of milliseconds pointed out in this parameter and check again if the process is already up.

        module_cpuproc 'process'

        diff --git a/pandora_console/include/help/en/help_module_type.php b/pandora_console/include/help/en/help_module_type.php index 65aad4ce63..acb2c0a3e6 100644 --- a/pandora_console/include/help/en/help_module_type.php +++ b/pandora_console/include/help/en/help_module_type.php @@ -7,25 +7,25 @@ The following list describes the module types:
          -
        • async_data: Asynchronous numeric data
        • -
        • async_inc: Asynchronous incremental data
        • -
        • async_proc: Asynchronous proc data
        • -
        • async_string: Asynchronous string data
        • -
        • generic_data: Generic module to acquire numeric data
        • -
        • generic_data_inc: Generic module to acquire numeric incremental data
        • -
        • generic_data_string: Generic module to acquire alphanumeric data
        • -
        • generic_proc: Generic module to acquire boolean data
        • -
        • image_jpg: Image JPG data
        • -
        • image_png: Image PNG data
        • -
        • keep_alive: KeepAlive
        • -
        • remote_icmp: Remote ICMP network agent (latency)
        • -
        • remote_icmp_proc: Remote ICMP network agent, boolean data
        • -
        • remote_snmp: Remote SNMP network agent, numeric data
        • -
        • remote_snmp_inc: Remote SNMP network agent, incremental data
        • -
        • remote_snmp_proc: Remote SNMP network agent, boolean data
        • -
        • remote_snmp_string: Remote SNMP network agent, alphanumeric data
        • -
        • remote_tcp: Remote TCP network agent, numeric data
        • -
        • remote_tcp_inc: Remote TCP network agent, incremental data
        • -
        • remote_tcp_proc: Remote TCP network agent, boolean data
        • -
        • remote_tcp_string: Remote TCP network agent, alphanumeric data
        • +
        • async_data: Asynchronous numeric data
        • +
        • async_inc: Asynchronous incremental data
        • +
        • async_proc: Asynchronous proc data
        • +
        • async_string: Asynchronous string data
        • +
        • generic_data: Generic module to acquire numeric data
        • +
        • generic_data_inc: Generic module to acquire numeric incremental data
        • +
        • generic_data_string: Generic module to acquire alphanumeric data
        • +
        • generic_proc: Generic module to acquire boolean data
        • +
        • image_jpg: Image JPG data
        • +
        • image_png: Image PNG data
        • +
        • keep_alive: KeepAlive
        • +
        • remote_icmp: Remote ICMP network agent (latency)
        • +
        • remote_icmp_proc: Remote ICMP network agent, boolean data
        • +
        • remote_snmp: Remote SNMP network agent, numeric data
        • +
        • remote_snmp_inc: Remote SNMP network agent, incremental data
        • +
        • remote_snmp_proc: Remote SNMP network agent, boolean data
        • +
        • remote_snmp_string: Remote SNMP network agent, alphanumeric data
        • +
        • remote_tcp: Remote TCP network agent, numeric data
        • +
        • remote_tcp_inc: Remote TCP network agent, incremental data
        • +
        • remote_tcp_proc: Remote TCP network agent, boolean data
        • +
        • remote_tcp_string: Remote TCP network agent, alphanumeric data
        diff --git a/pandora_console/include/help/en/help_network_component.php b/pandora_console/include/help/en/help_network_component.php index 99fd49e7d5..62521ad5d2 100644 --- a/pandora_console/include/help/en/help_network_component.php +++ b/pandora_console/include/help/en/help_network_component.php @@ -9,6 +9,6 @@ The Network Component combo box allows you to select a template from a list of m

        To do so, select the template you want, click on "Get data" and wait few seconds until the information is filled. Depending on the template, some fields will be filled in and some others will not, for example:
          -
        • TCP port would be filled for "Check FTP Server" but not SNMP OID
        • -
        • TCP port would not be filled for "Catalyst CPU Usage (5min)" but SNMP OID will.
        • +
        • TCP port would be filled for "Check FTP Server" but not SNMP OID
        • +
        • TCP port would not be filled for "Catalyst CPU Usage (5min)" but SNMP OID will.
        diff --git a/pandora_console/include/help/en/help_network_map_enterprise.php b/pandora_console/include/help/en/help_network_map_enterprise.php index 4bf47e5790..60b9ebbe46 100644 --- a/pandora_console/include/help/en/help_network_map_enterprise.php +++ b/pandora_console/include/help/en/help_network_map_enterprise.php @@ -1,12 +1,12 @@

        Networkmap console

        -

        With Enterprise we have the possibility of create editable network maps that are more interactive comparing with the Open version that is currently on the "See agents" submenu.

        +

        With Enterprise we have the possibility of create editable network maps that are more interactive comparing with the Open version that is currently on the "See agents" submenu.

        On the contrary to the Open version, the Networkmap Enterprise provide us with more features, such as:

        @@ -38,7 +38,7 @@

        Minimap

        -

        This minimap gives us a global view that shows all the map extension, but in a smaller view, and besides, in contrast with the map view, all the nodes are shown, but without status and without relationships. Except the fictitious point, that is shown in green. And a red box is also shown of the part of the map that is being shown.

        +

        This minimap gives us a global view that shows all the map extension, but in a smaller view, and besides, in contrast with the map view, all the nodes are shown, but without status and without relationships. Except the fictitious point, that is shown in green. And a red box is also shown of the part of the map that is being shown.

        It's on the upper left corner, and could be hidden pressing on the arrow icon.

        @@ -49,7 +49,7 @@

        From the control panel you can do tasks more complex on the network map.

        t's hidden on the right upper corner. Same as with the minimap, it could be shown pressing on the arrow.

        - '550px')); ?> + '550px']); ?>

        And the available options are:

        @@ -67,12 +67,12 @@

        The detail view window is a visual view of one agent. It is refreshed at the same velocity that the map that has opened, and the windows are completely independents, so you can have several windows opened.

        - '550px')); ?>

        + '550px']); ?>

        It shows a box which rim will be of the same color that the agent status.
        - The agent name is a link to the agent page.
        + The agent name is a link to the agent page.
        Inside the box are all the modules that are not in unknown status, which, depending if the module status is green or red.
        It's possible to click on these modules and they shown a tooltip with the module main data.
        In the box rim are the modules kind SNMP Proc,that use to be for network interfaces when an agent related with network systems is monitored.

        @@ -81,7 +81,7 @@

        If you select see details on a fictitious point, this will show you a pop up window with a palette of options to modify the fictitious point

        - '550px')); ?>

        + '550px']); ?>

        We have a form with these options:

        @@ -107,7 +107,7 @@
      • Creating the network map from: option only available in the creation. It's the way to create the network map if we do it from the agents that are in the previously selected group, or on the contrary we want an empty network map.
      • Size of the network map: where it's possible to define the size of the network map, by default it's of 3000 width and 3000 high.
      • Method for creating of the network map: the method of distribution of the nodes that will make up the network map, by default it's radial, but there are the following ones:
      • -

        - Radial: In which all the nodes will be placed around the fictitious node that the represents.
        +

        - Radial: In which all the nodes will be placed around the fictitious node that the represents.
        - Circular: In which the nodes will be placed in concentric circles en el cual se dispondrá los nodos en círculos concentricos.
        - Flat: In which the nodes with tree shape will be placed.
        - spring1, spring2: are variations of the Flat.
        diff --git a/pandora_console/include/help/en/help_no_hierarchy.php b/pandora_console/include/help/en/help_no_hierarchy.php index 352f4ab318..5ab2e49425 100644 --- a/pandora_console/include/help/en/help_no_hierarchy.php +++ b/pandora_console/include/help/en/help_no_hierarchy.php @@ -13,17 +13,25 @@ We explained that the permissions of a group can be extended to the children by As a reference for the examples, we propose a configuration with two parent groups "Applications" and "Databases" with two children each, "Development_Apps" and "Management_Apps" for the former and "Databases_America" and "Databases_Asia" for the latter. Both parent groups are marked for ACL to spread.

        - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

        In the user edit view, if the following profiles are added:

        - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

        The user will have access to the groups named "Applications", "Development_Apps", "Management_Apps" and "Databases". @@ -33,9 +41,13 @@ The user will have access to the groups named "Applications", "Development_Apps" However, if a child of "Databases" is added:

        - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

        Now the user will have access to the groups named "Applications", "Development_Apps", "Management_Apps", "Databases" and "Databases_Asia", but not to "Databases_America". diff --git a/pandora_console/include/help/en/help_planned_downtime.php b/pandora_console/include/help/en/help_planned_downtime.php index d1d5bb844f..a400751740 100644 --- a/pandora_console/include/help/en/help_planned_downtime.php +++ b/pandora_console/include/help/en/help_planned_downtime.php @@ -12,5 +12,5 @@ This tool is used to plan non-monitoring periods of time. This is useful if you It's very easy to setup, you specify start date/time of a scheduled downtime and an end date/time. After setting the first fields you must save the Scheduled downtime and edit it, to set the agents which are going to be disconnected. You can also edit the rest of the fields once editing the Scheduled downtime entry.

        -When scheduled downtime starts, automatically disable all agents assigned to this downtime and no alerts or data are processed. When downtime ends, will be enable all agents assigned to this downtime. You cannot delete or modify a downtime instance when it's fired, you need to wait for ending before doing anything in this downtime instance. Of course you can manually, enable an agent using the agent configuration dialog. +When scheduled downtime starts, automatically disable all agents assigned to this downtime and no alerts or data are processed. When downtime ends, will be enable all agents assigned to this downtime. You cannot delete or modify a downtime instance when it's fired, you need to wait for ending before doing anything in this downtime instance. Of course you can manually, enable an agent using the agent configuration dialog.

        diff --git a/pandora_console/include/help/en/help_planned_downtime_time.php b/pandora_console/include/help/en/help_planned_downtime_time.php index aea7a0afa0..2d090a70cb 100644 --- a/pandora_console/include/help/en/help_planned_downtime_time.php +++ b/pandora_console/include/help/en/help_planned_downtime_time.php @@ -8,8 +8,8 @@

        Once execution

        - The date format must be year/month/day and the time format must be hour:minute:second. - It's possible to create a scheduled downtime with a past date, if that option aren't disabled by the admin of . + The date format must be year/month/day and the time format must be hour:minute:second. + It's possible to create a scheduled downtime with a past date, if that option aren't disabled by the admin of .

        Periodically execution

        @@ -17,15 +17,15 @@

        Monthly

        - The downtime will be executed every month, from the start day at the start time, to the end date at the end time selected. - The time format must be hour:minute:second and the start day can't be lower than the end day. - To reflect a downtime which ends away than the last day of the month, it's necessary to create two scheduled downtimes, the first should ends the day 31 at 23:59:59 and the other should start the day 1 at 00:00:00. + The downtime will be executed every month, from the start day at the start time, to the end date at the end time selected. + The time format must be hour:minute:second and the start day can't be lower than the end day. + To reflect a downtime which ends away than the last day of the month, it's necessary to create two scheduled downtimes, the first should ends the day 31 at 23:59:59 and the other should start the day 1 at 00:00:00.

        Weekly

        - The downtime will be executed every selected day, from the start time, to the end time selected. - The start time can't be lower than the end time. - To reflect a downtime which ends away than the last day time, it's necessary to create two scheduled downtimes, the first should end at 23:59:59 and the other should start at 00:00:00 on the next day. + The downtime will be executed every selected day, from the start time, to the end time selected. + The start time can't be lower than the end time. + To reflect a downtime which ends away than the last day time, it's necessary to create two scheduled downtimes, the first should end at 23:59:59 and the other should start at 00:00:00 on the next day.

        \ No newline at end of file diff --git a/pandora_console/include/help/en/help_plugin_definition.php b/pandora_console/include/help/en/help_plugin_definition.php index f6aeb4cd29..8f0d5bd1fe 100644 --- a/pandora_console/include/help/en/help_plugin_definition.php +++ b/pandora_console/include/help/en/help_plugin_definition.php @@ -5,20 +5,20 @@ ?>

        Plugin registration

        -Unlike with the rest of components, in a default way does not include any pre-configured complement, so first you should create and configure a complement to could after add it to the module of an agent. But includes plugins in the installation directories, but as have already been said, they are not configured in the database. +Unlike with the rest of components, in a default way does not include any pre-configured complement, so first you should create and configure a complement to could after add it to the module of an agent. But includes plugins in the installation directories, but as have already been said, they are not configured in the database.

        -To add a plugin that already exists to , go to the console administration section, and in it, click on Manage servers. After doing this, click on Manage plugins: +To add a plugin that already exists to , go to the console administration section, and in it, click on Manage servers. After doing this, click on Manage plugins:

        Once you are in the screen of the plugin management, click on Create a new plugin, so there will be no one.

        Fill in the plugin creation form with the following data: - '550px')); ?> + '550px']); ?>

        Name
        Name of the plugin, in this case Nmap.

        Plugin type
        -There are two kinds of plugins, the standard ones and the kind Nagios. The standard plugins are scripts that execute actions and accept parameters. The Nagios plugins are, as their name shows, Nagios plugins that could be being used in .The difference is mainly on that the Nagios plugins return an error level to show if the test has been successful or not. +There are two kinds of plugins, the standard ones and the kind Nagios. The standard plugins are scripts that execute actions and accept parameters. The Nagios plugins are, as their name shows, Nagios plugins that could be being used in .The difference is mainly on that the Nagios plugins return an error level to show if the test has been successful or not.

        If you want to use a plugin kind Nagios and you want to get a data, not an state (good/Bad), then you can use a plugin kind Nagios is the "Standard" mode.

        @@ -38,7 +38,7 @@ Plugin description. Write a short description, as for example:Test # UDP open po It is the path where the plugin command is. In a default way, if the installation has been an standard one, there will be in the directory /usr/share/pandora_server/util/plugin/. Though it could be any path of the system. For this case, writte /usr/share/pandora_server/util/plugin/udp_nmap_plugin.shin the field.

        - server will execute this script, so this should have permissions of access and execution on it. + server will execute this script, so this should have permissions of access and execution on it.

        Plug-in parameters
        @@ -56,8 +56,9 @@ Each macro has 3 fields:

        Example of a macro configuration:

        - '550px')); ?> + '550px']); ?>

        Example of this macro in the module editor:

        - '550px')); ?> + '550px']); diff --git a/pandora_console/include/help/en/help_plugin_macros.php b/pandora_console/include/help/en/help_plugin_macros.php index 1660c45e13..0bab3648a8 100644 --- a/pandora_console/include/help/en/help_plugin_macros.php +++ b/pandora_console/include/help/en/help_plugin_macros.php @@ -17,7 +17,7 @@ The following macros are available:
      • _modulegroup_ : Module group name.
      • _moduledescription_ : Description of the module.
      • _modulestatus_ : Status of the module.
      • -
      • _id_agent_ : Id of agent, useful to build direct URL to redirect to a console webpage.
      • +
      • _id_agent_ : Id of agent, useful to build direct URL to redirect to a console webpage.
      • _id_group_ : Id of agent group.
      • _policy_ : Name of the policy the module belongs to (if applies).
      • _interval_ : Execution interval of the module.
      • @@ -31,10 +31,10 @@ Hidden this macros because they cannot edit in the module form -->
      • _plugin_parameters_ : Plug-in Parameters of the module.
      • -
      • _name_tag_ : Nombre de los tags asociados al módulo.
      • -
      • _email_tag_ : Emails asociados a los tags de módulos.
      • -
      • _phone_tag_ : Teléfonos asociados a los tags de módulos.
      • -
      • _moduletags_ : Teléfonos asociados a los tags de módulos.
      • +
      • _name_tag_ : Names of the tags associated to the module.
      • +
      • _email_tag_ : Emails associated to module tags.
      • +
      • _phone_tag_ : Phone numbers associated to module tags.
      • +
      • _moduletags_ : URLs associated to module tags.
      • _agentcustomfield_n_: Agent custom field number n (eg. _agentcustomfield_9_).
      • diff --git a/pandora_console/include/help/en/help_plugin_parameters.php b/pandora_console/include/help/en/help_plugin_parameters.php index b3f1b289d4..c18b1191c0 100644 --- a/pandora_console/include/help/en/help_plugin_parameters.php +++ b/pandora_console/include/help/en/help_plugin_parameters.php @@ -9,9 +9,9 @@ This field reffers to all parameters that can be passed to a plugin and are not

        These parameters could be:

          -
        • An URL
        • -
        • A path
        • -
        • A file
        • -
        • Etc.
        • +
        • An URL
        • +
        • A path
        • +
        • A file
        • +
        • Etc.
        This field is optional and depends, completely, on the plugin. diff --git a/pandora_console/include/help/en/help_plugin_policy.php b/pandora_console/include/help/en/help_plugin_policy.php index 61afa6336d..693d491a04 100644 --- a/pandora_console/include/help/en/help_plugin_policy.php +++ b/pandora_console/include/help/en/help_plugin_policy.php @@ -1,7 +1,7 @@

        Agent Plugins

        diff --git a/pandora_console/include/help/en/help_policy_agent.php b/pandora_console/include/help/en/help_policy_agent.php index 90ea1c8809..59b98f3a3d 100644 --- a/pandora_console/include/help/en/help_policy_agent.php +++ b/pandora_console/include/help/en/help_policy_agent.php @@ -1,7 +1,7 @@

        Policy agent

        diff --git a/pandora_console/include/help/en/help_policy_queue.php b/pandora_console/include/help/en/help_policy_queue.php index 3e4bc4763c..210480a465 100644 --- a/pandora_console/include/help/en/help_policy_queue.php +++ b/pandora_console/include/help/en/help_policy_queue.php @@ -1,7 +1,7 @@

        Queue

        diff --git a/pandora_console/include/help/en/help_prediction_date.php b/pandora_console/include/help/en/help_prediction_date.php index b1cfb81efc..b55b13de2a 100644 --- a/pandora_console/include/help/en/help_prediction_date.php +++ b/pandora_console/include/help/en/help_prediction_date.php @@ -13,4 +13,4 @@

        For example, for the module disk_temp_free and choosing 2 months and searching for the date where the module reach the interval [5-0] the result will be 04 Dec 2011 18:36:23.

        This is a graphic vision of the explanation:

        - '210')); ?> + '210']); diff --git a/pandora_console/include/help/en/help_profile.php b/pandora_console/include/help/en/help_profile.php index 3e41970fbd..75a779cb2e 100644 --- a/pandora_console/include/help/en/help_profile.php +++ b/pandora_console/include/help/en/help_profile.php @@ -1,12 +1,12 @@

        Profile

        -

        is a Web management tool that allows multiple users to work with different permissions in multiple defined agent groups. The permissions an user can have are defined in profiles.

        +

        is a Web management tool that allows multiple users to work with different permissions in multiple defined agent groups. The permissions an user can have are defined in profiles.

        The following list defines what ACL control allows in each feature at the console:

        @@ -40,9 +40,9 @@
        @@ -297,7 +297,7 @@ + oeste de UTC es siempre negativo, y para las del este de UTC es siempre positivo. diff --git a/pandora_console/include/help/es/help_event_alert.php b/pandora_console/include/help/es/help_event_alert.php index 537deb47c7..5c326796dd 100644 --- a/pandora_console/include/help/es/help_event_alert.php +++ b/pandora_console/include/help/es/help_event_alert.php @@ -1,25 +1,25 @@

        Alerta de evento

        -Desde la versión 4.0 de se pueden definir alertas sobre los eventos, lo que permite trabajar desde una perspectiva completamente nueva y mucho más flexible. Esta es una característica Enterprise.

        +Desde la versión 4.0 de se pueden definir alertas sobre los eventos, lo que permite trabajar desde una perspectiva completamente nueva y mucho más flexible. Esta es una característica Enterprise.

        Las Alertas de evento nuevas se crean pinchando en el botón Create en el menú Event alerts en el menú de Administración.

        - '250px')); ?> + '250px']); ?>
        Una alerta de eventos está compuesta por distintas reglas, relacionadas entre sí por operadores lógicos (and, or, xor, nand, nor, nxor).

        - '550px')); ?> + '550px']); ?>
        Para hacer más fácil trabajar con ellas, los parámetros de configuración de una alerta de eventos son idénticos a los de una alerta de módulo. Aquí se puede encontrar una explicación detallada de cada uno de ellos. Únicamente existen dos parámetros específicos de las alertas de eventos: @@ -32,7 +32,7 @@ Cada regla se configura para saltar ante un determinado tipo de evento, cuando s

        - '550px')); ?> + '550px']); ?>
        @@ -56,9 +56,9 @@ Por ejemplo, podríamos configurar una regla que case con los eventos generados

        - '550px')); ?> + '550px']); ?>
        -

        Dado el elevado número de eventos que puede llegar a albergar la base de datos de , el servidor trabaja sobre una ventana de eventos que se define en el fichero de configuración pandora_server.conf mediante el parámetro event_window. Los eventos que se hayan generado fuera de esta ventana de tiempo no serán procesados por el servidor, de modo que no tiene sentido especificar en una regla una ventana de tiempo superior a la configurada en el servidor

        +

        Dado el elevado número de eventos que puede llegar a albergar la base de datos de , el servidor trabaja sobre una ventana de eventos que se define en el fichero de configuración pandora_server.conf mediante el parámetro event_window. Los eventos que se hayan generado fuera de esta ventana de tiempo no serán procesados por el servidor, de modo que no tiene sentido especificar en una regla una ventana de tiempo superior a la configurada en el servidor

        diff --git a/pandora_console/include/help/es/help_events_history.php b/pandora_console/include/help/es/help_events_history.php index 261e4c1622..fec450224d 100644 --- a/pandora_console/include/help/es/help_events_history.php +++ b/pandora_console/include/help/es/help_events_history.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_events_replication.php b/pandora_console/include/help/es/help_events_replication.php index 81a0ff9e20..3c5ec4e2cc 100644 --- a/pandora_console/include/help/es/help_events_replication.php +++ b/pandora_console/include/help/es/help_events_replication.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_eventview.php b/pandora_console/include/help/es/help_eventview.php index 94dc475b43..b6cd9d0173 100644 --- a/pandora_console/include/help/es/help_eventview.php +++ b/pandora_console/include/help/es/help_eventview.php @@ -9,26 +9,29 @@
        -

        Validar

        - "Validated event", "alt" => "Validated event", "width" => '10', "height" => '10')); ?> - Validar evento
        - "Event not validated", "alt" => "Event not validated", "width" => '10', "height" => '10')); ?>
        - Evento no validado +

        Validar

        + 'Validated event', 'alt' => 'Validated event', 'width' => '10', 'height' => '10']); ?> - Validar evento
        + "Event not validated", "alt" => "Event not validated", "width" => '10', "height" => '10')); + ?> +
        - Evento no validado
        -

        Severidad

        - "Maintenance event", "alt" => "Maintenance event")); ?> - Evento de mantenimiento
        - "Informational event", "alt" => "Informational event")); ?> - Evento informativo
        - "Normal event", "alt" => "Normal event")); ?> - Evento normal
        - "Warning event", "alt" => "Warning event")); ?> - Evento de alerta
        - "Critical event", "alt" => "Critical event")); ?> - Evento crítico
        +

        Severidad

        + 'Maintenance event', 'alt' => 'Maintenance event']); ?> - Evento de mantenimiento
        + 'Informational event', 'alt' => 'Informational event']); ?> - Evento informativo
        + 'Normal event', 'alt' => 'Normal event']); ?> - Evento normal
        + 'Warning event', 'alt' => 'Warning event']); ?> - Evento de alerta
        + 'Critical event', 'alt' => 'Critical event']); ?> - Evento crítico
        -

        Acciones

        - "Validate event", "alt" => "Validate event")); ?> - Validar evento
        - "Delete event", "alt" => "Delete event")); ?> - Borrar evento
        - "Mostrar más", "alt" => "Mostrar más")); ?> - Mostrar más
        - "En progreso", "alt" => "En progreso")); ?> - En progreso +

        Acciones

        + 'Validate event', 'alt' => 'Validate event']); ?> - Validar evento
        + 'Delete event', 'alt' => 'Delete event']); ?> - Borrar evento
        + 'Mostrar más', 'alt' => 'Mostrar más']); ?> - Mostrar más
        + 'En progreso', 'alt' => 'En progreso']); ?> - En progreso
         
        diff --git a/pandora_console/include/help/es/help_export_server.php b/pandora_console/include/help/es/help_export_server.php index 041d8d926c..cd48d8100c 100644 --- a/pandora_console/include/help/es/help_export_server.php +++ b/pandora_console/include/help/es/help_export_server.php @@ -5,10 +5,10 @@ ?>

        Servidor de exportación

        -

        La versión Enterprise de implementa, mediante el export server, un mecanismo de escalado de datos que permite virtualmente una implantación distribuida capaz de monitorizar un número ilimitado de información, siempre que se diseñe adecuadamente y se disgregue en diferentes perfiles de información.

        +

        La versión Enterprise de implementa, mediante el export server, un mecanismo de escalado de datos que permite virtualmente una implantación distribuida capaz de monitorizar un número ilimitado de información, siempre que se diseñe adecuadamente y se disgregue en diferentes perfiles de información.

          -
        • Nombre: El nombre del servidor de .
        • +
        • Nombre: El nombre del servidor de .
        • Servidor de exportacion: Combo donde se elige la instancia del servidor de export server que se usara para exporta los datos.
        • Prefijo: Prefijo que se usa para añadir al nombre del agente que envía los datos. Cuando se reenvían datos de un agente llamado "Farscape", por ejemplo y su prefijo en el servidor de exportación es "EU01", los datos del agente reenviado seran vistos en el servidor de destino con el nombre de agente EU01-Farscape.
        • Interval: Se define el intervalo de tiempo cada cuantos segundos se quieren enviar los datos que haya pendientes.
        • diff --git a/pandora_console/include/help/es/help_external_alert.php b/pandora_console/include/help/es/help_external_alert.php index 33c4f55437..fa7beba535 100644 --- a/pandora_console/include/help/es/help_external_alert.php +++ b/pandora_console/include/help/es/help_external_alert.php @@ -1,7 +1,7 @@

          Alertas externas

          diff --git a/pandora_console/include/help/es/help_ff_interval.php b/pandora_console/include/help/es/help_ff_interval.php index a661dca837..3134db2b6a 100644 --- a/pandora_console/include/help/es/help_ff_interval.php +++ b/pandora_console/include/help/es/help_ff_interval.php @@ -17,39 +17,39 @@ Por ejemplo, un módulo de ping con un intervalo de 5 minutos, un umbral de FF d
        - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + +
        SNMP Console viewingAR
        Validating trapsIW
        MessagesIW -
        Cron jobs PM -
        Tree view AR -
        Update Manager (operation and administration) PM +
        Cron jobs PM +
        Tree view AR +
        Update Manager (operation and administration) PM
        Extension Module GroupAR
        Agent ManagementAW
        Remote Agent Configuration Management AW @@ -51,7 +51,7 @@
        Group ManagementPM
        Creating inventory modulesPM
        Module Management (includes all suboptions)PM -
        Bulk Management Operations AW +
        Bulk Management Operations AW
        Creating agentsAW
        Duplicating remote configurationsAW
        Downtime ManagementAW diff --git a/pandora_console/include/help/en/help_projection_graph.php b/pandora_console/include/help/en/help_projection_graph.php index 8174793b63..4789eb7a47 100644 --- a/pandora_console/include/help/en/help_projection_graph.php +++ b/pandora_console/include/help/en/help_projection_graph.php @@ -1,7 +1,7 @@

        Projection graph

        - '210')); ?> + '210']); ?>

        Projection graphs make a projection of module data in the future. The projection is based on linear regressions. diff --git a/pandora_console/include/help/en/help_recontask.php b/pandora_console/include/help/en/help_recontask.php index 53424b850d..0223d66e5b 100644 --- a/pandora_console/include/help/en/help_recontask.php +++ b/pandora_console/include/help/en/help_recontask.php @@ -25,7 +25,7 @@ Network where you want to do the recognition. Use the network format/ bits mask. Interval
        -Repetition interval of systems search. Do not use intervals very shorts so Recon explores a network sending one Ping to each address. If you use recon networks very larges (for example a class A) combined with very short intervals (6 hours) you will be doing that will be always bomb the network with pings, overloading it and also unnecessarily.

        +Repetition interval of systems search. Do not use intervals very shorts so Recon explores a network sending one Ping to each address. If you use recon networks very larges (for example a class A) combined with very short intervals (6 hours) you will be doing that will be always bomb the network with pings, overloading it and also unnecessarily.

        Module template
        @@ -33,7 +33,7 @@ Plugins template to add to the discovered systems. When it detects a system that OS
        -Operative system to recognize. If you select one instead of any (Any) it will only be added the systems with this operative system.Consider that in some circumstances can make a mistake when detecting systems, so this kind of "guess" is done with statistic patterns, that depending on some other factors could fail (networks with filters, security software, modified versions of the systems).To could use this method with security, you should have installed Xprobe2 in your system.

        +Operative system to recognize. If you select one instead of any (Any) it will only be added the systems with this operative system.Consider that in some circumstances can make a mistake when detecting systems, so this kind of "guess" is done with statistic patterns, that depending on some other factors could fail (networks with filters, security software, modified versions of the systems).To could use this method with security, you should have installed Xprobe2 in your system.

        Ports
        diff --git a/pandora_console/include/help/en/help_reporting_global_tab.php b/pandora_console/include/help/en/help_reporting_global_tab.php index e93412b0ef..2b82406a0b 100644 --- a/pandora_console/include/help/en/help_reporting_global_tab.php +++ b/pandora_console/include/help/en/help_reporting_global_tab.php @@ -1,7 +1,7 @@

        Global

        diff --git a/pandora_console/include/help/en/help_reporting_item_editor_tab.php b/pandora_console/include/help/en/help_reporting_item_editor_tab.php index f7e3a53171..4c647cd882 100644 --- a/pandora_console/include/help/en/help_reporting_item_editor_tab.php +++ b/pandora_console/include/help/en/help_reporting_item_editor_tab.php @@ -1,7 +1,7 @@

        Report item editor

        diff --git a/pandora_console/include/help/en/help_reporting_list_items_tab.php b/pandora_console/include/help/en/help_reporting_list_items_tab.php index 7a3c6e7294..76877fb81f 100644 --- a/pandora_console/include/help/en/help_reporting_list_items_tab.php +++ b/pandora_console/include/help/en/help_reporting_list_items_tab.php @@ -1,7 +1,7 @@

        Report list items

        diff --git a/pandora_console/include/help/en/help_reporting_main_tab.php b/pandora_console/include/help/en/help_reporting_main_tab.php index 326f07523a..21ca873b9f 100644 --- a/pandora_console/include/help/en/help_reporting_main_tab.php +++ b/pandora_console/include/help/en/help_reporting_main_tab.php @@ -7,9 +7,9 @@ To create a report, you must first fill the form providing:
          -
        • A name
        • -
        • A group
        • -
        • A description
        • +
        • A name
        • +
        • A group
        • +
        • A description
        Then you must press the botton with the text Create.

        diff --git a/pandora_console/include/help/en/help_reporting_preview_tab.php b/pandora_console/include/help/en/help_reporting_preview_tab.php index ff5895ddd9..a185ce4a82 100644 --- a/pandora_console/include/help/en/help_reporting_preview_tab.php +++ b/pandora_console/include/help/en/help_reporting_preview_tab.php @@ -1,7 +1,7 @@

        Preview

        diff --git a/pandora_console/include/help/en/help_reporting_time_lapse.php b/pandora_console/include/help/en/help_reporting_time_lapse.php index df57594e42..1143ae61ca 100644 --- a/pandora_console/include/help/en/help_reporting_time_lapse.php +++ b/pandora_console/include/help/en/help_reporting_time_lapse.php @@ -1,8 +1,8 @@ - -

        Reports - Time lapse

        -
        -This is the range, or period of time over which the report renders the information for this report type. For example, a week means data from a week ago from now. \ No newline at end of file + +

        Reports - Time lapse

        +
        +This is the range, or period of time over which the report renders the information for this report type. For example, a week means data from a week ago from now. diff --git a/pandora_console/include/help/en/help_reporting_wizard_sla_tab.php b/pandora_console/include/help/en/help_reporting_wizard_sla_tab.php index bed414ce01..4513c80a19 100644 --- a/pandora_console/include/help/en/help_reporting_wizard_sla_tab.php +++ b/pandora_console/include/help/en/help_reporting_wizard_sla_tab.php @@ -1,9 +1,9 @@

        SLA Wizard

        -

        Allows to measure the service level (Service Level Agreement) of any monitor of . In this wizard you can create a SLA report of several agents.

        +

        Allows to measure the service level (Service Level Agreement) of any monitor of . In this wizard you can create a SLA report of several agents.

        diff --git a/pandora_console/include/help/en/help_reporting_wizard_tab.php b/pandora_console/include/help/en/help_reporting_wizard_tab.php index a3908e30b1..eb90e8269f 100644 --- a/pandora_console/include/help/en/help_reporting_wizard_tab.php +++ b/pandora_console/include/help/en/help_reporting_wizard_tab.php @@ -1,7 +1,7 @@

        Wizard

        diff --git a/pandora_console/include/help/en/help_reports_label_field.php b/pandora_console/include/help/en/help_reports_label_field.php index b9a553af85..d800d64808 100755 --- a/pandora_console/include/help/en/help_reports_label_field.php +++ b/pandora_console/include/help/en/help_reports_label_field.php @@ -7,19 +7,19 @@

        The following macros are also available:
        -

          +
          • _agent_ : Name of the agent that you selected in report item.
          • -
          • _agentdescription_ : Description of the agent that you selected in report item.
          • +
          • _agentdescription_ : Description of the agent that you selected in report item.
          • _agentgroup_ : Agent group name.
          • _address_ : Address of the agent that you selected in report item.
          • -
              -
              - -
                - Only if in form you can select a agent module.
                -
              • _module_ : Module name that you selected in report item.
              • -
              • _moduledescription_ : Description of the module that you selected in report item.
              • -
                  +
                    +
                    + +
                      + Only if in form you can select a agent module.
                      +
                    • _module_ : Module name that you selected in report item.
                    • +
                    • _moduledescription_ : Description of the module that you selected in report item.
                    • +
                        Example: Agent: _agent_ / module: _module_

                        diff --git a/pandora_console/include/help/en/help_response_macros.php b/pandora_console/include/help/en/help_response_macros.php index c5fe087ec7..38aae0eeab 100644 --- a/pandora_console/include/help/en/help_response_macros.php +++ b/pandora_console/include/help/en/help_response_macros.php @@ -18,7 +18,7 @@ The accepted macros are:
                      • Event ID: _event_id_
                      • Event instructions: _event_instruction_
                      • Event severity ID: _event_severity_id_
                      • -
                      • Event severity (translated by console): _event_severity_text_
                      • +
                      • Event severity (translated by console): _event_severity_text_
                      • Event source: _event_source_
                      • Event status (new, validated or event in process): _event_status_
                      • Event tags separated by commas: _event_tags_
                      • diff --git a/pandora_console/include/help/en/help_servers.php b/pandora_console/include/help/en/help_servers.php index f65b535f67..c3a0674309 100644 --- a/pandora_console/include/help/en/help_servers.php +++ b/pandora_console/include/help/en/help_servers.php @@ -1,16 +1,16 @@

                        Server management

                        -

                        The servers are the elements in charge of performing the existing checks. They verify them and change their status depending on the results. They are also in charge of triggering the alerts established to control the status of data.

                        +

                        The servers are the elements in charge of performing the existing checks. They verify them and change their status depending on the results. They are also in charge of triggering the alerts established to control the status of data.

                        -

                        's data server can work in high availability and/or load balancing modes. In a very large architecture, various servers can be used at the same time, in order to handle large volumes of functionally or geographically distributed information.

                        +

                        's data server can work in high availability and/or load balancing modes. In a very large architecture, various servers can be used at the same time, in order to handle large volumes of functionally or geographically distributed information.

                        -

                        servers are always on and permanently verify if any element has any problem. If there is any alert linked to the problem, then it'll run the pre-set action such as sending an SMS, an email, or activating a script execution.

                        +

                        servers are always on and permanently verify if any element has any problem. If there is any alert linked to the problem, then it'll run the pre-set action such as sending an SMS, an email, or activating a script execution.

                        • Data Server
                        • diff --git a/pandora_console/include/help/en/help_service_management_edit.php b/pandora_console/include/help/en/help_service_management_edit.php index 0634cf8252..87c473e4ef 100644 --- a/pandora_console/include/help/en/help_service_management_edit.php +++ b/pandora_console/include/help/en/help_service_management_edit.php @@ -1,7 +1,7 @@

                          Service edit

                          diff --git a/pandora_console/include/help/en/help_setup_gis_index.php b/pandora_console/include/help/en/help_setup_gis_index.php index 7f1b1cfd71..d5db84cdd7 100644 --- a/pandora_console/include/help/en/help_setup_gis_index.php +++ b/pandora_console/include/help/en/help_setup_gis_index.php @@ -9,5 +9,5 @@ This page is the place where the admin can configure connections to GIS Map Servers.

                          -Here it is possible to see the list of defined connections, edit any one of them by clicking on their name, delete any connection by clicking on the delete icon ( "delete icon")); ?>) or create new connections using the create button. +Here it is possible to see the list of defined connections, edit any one of them by clicking on their name, delete any connection by clicking on the delete icon ( 'delete icon']); ?>) or create new connections using the create button.

                          diff --git a/pandora_console/include/help/en/help_snmp_alert.php b/pandora_console/include/help/en/help_snmp_alert.php index d4d40d4ba3..519aa5e027 100644 --- a/pandora_console/include/help/en/help_snmp_alert.php +++ b/pandora_console/include/help/en/help_snmp_alert.php @@ -1,9 +1,9 @@

                          SNMP alert

                          -

                          It's possible to associate an alert to a trap, so warns us on arrival of a specific trap. SNMP traps have got nothing to do with the rest of the system alerts, even if both reuse the actions' system.

                          +

                          It's possible to associate an alert to a trap, so warns us on arrival of a specific trap. SNMP traps have got nothing to do with the rest of the system alerts, even if both reuse the actions' system.

                          diff --git a/pandora_console/include/help/en/help_snmp_alert_configuration.php b/pandora_console/include/help/en/help_snmp_alert_configuration.php index 290a98aaa6..5b0a4031cd 100644 --- a/pandora_console/include/help/en/help_snmp_alert_configuration.php +++ b/pandora_console/include/help/en/help_snmp_alert_configuration.php @@ -1,7 +1,7 @@

                          Alert configuration

                          diff --git a/pandora_console/include/help/en/help_snmp_alert_custom.php b/pandora_console/include/help/en/help_snmp_alert_custom.php index 8d21fc8941..b00b6f4dd8 100755 --- a/pandora_console/include/help/en/help_snmp_alert_custom.php +++ b/pandora_console/include/help/en/help_snmp_alert_custom.php @@ -1,13 +1,13 @@

                          Custom Value/OID

                          - This search in the trap "Value" fields, and also in the fields - "Variable bindings" and "Custom Value", that is, in - the rest of the TRAP fields. + This search in the trap "Value" fields, and also in the fields + "Variable bindings" and "Custom Value", that is, in + the rest of the TRAP fields.

                          diff --git a/pandora_console/include/help/en/help_snmp_alert_filters.php b/pandora_console/include/help/en/help_snmp_alert_filters.php index bb316eb4b2..c813efe7be 100644 --- a/pandora_console/include/help/en/help_snmp_alert_filters.php +++ b/pandora_console/include/help/en/help_snmp_alert_filters.php @@ -1,7 +1,7 @@

                          Alert filters

                          diff --git a/pandora_console/include/help/en/help_snmp_alert_position.php b/pandora_console/include/help/en/help_snmp_alert_position.php index f40fccbfc2..c2c698ac2c 100644 --- a/pandora_console/include/help/en/help_snmp_alert_position.php +++ b/pandora_console/include/help/en/help_snmp_alert_position.php @@ -1,7 +1,7 @@

                          Alert SNMP position

                          diff --git a/pandora_console/include/help/en/help_snmp_explorer.php b/pandora_console/include/help/en/help_snmp_explorer.php index e50437b092..72e5f140de 100644 --- a/pandora_console/include/help/en/help_snmp_explorer.php +++ b/pandora_console/include/help/en/help_snmp_explorer.php @@ -1,6 +1,7 @@ -

                          SNMP explorer

                          diff --git a/pandora_console/include/help/en/help_snmpoid.php b/pandora_console/include/help/en/help_snmpoid.php index 10fe9898fd..827a301907 100644 --- a/pandora_console/include/help/en/help_snmpoid.php +++ b/pandora_console/include/help/en/help_snmpoid.php @@ -5,4 +5,4 @@ ?>

                          SNMP OID

                          -Module's SNMP OID. If there is a MIB able to resolve the name in Network Server, then you can use alphanumeric OIDs (i.e. SNMPv2-MIB::sysDescr.0). Numeric OID can always be used (i.e. 3.1.3.1.3.5.12.4.0.1), even if there is no specific MIB. +Module's SNMP OID. If there is a MIB able to resolve the name in Network Server, then you can use alphanumeric OIDs (i.e. SNMPv2-MIB::sysDescr.0). Numeric OID can always be used (i.e. 3.1.3.1.3.5.12.4.0.1), even if there is no specific MIB. diff --git a/pandora_console/include/help/en/help_snmpwalk.php b/pandora_console/include/help/en/help_snmpwalk.php index 92a7c93556..ba6917c4f2 100644 --- a/pandora_console/include/help/en/help_snmpwalk.php +++ b/pandora_console/include/help/en/help_snmpwalk.php @@ -5,6 +5,6 @@ ?>

                          SNMP walk

                          - has also a simple SNMP browser that allows to walk the MIB of a remote device by a SNMP Walk. + has also a simple SNMP browser that allows to walk the MIB of a remote device by a SNMP Walk.

                          -Walking ("SNMP Walk") over a device will make all MIB variables available, so you can choose one. You can also enter a MIB using numerical OID or human understandable format, if you have the correct MIB installed in your Network Server. +Walking ("SNMP Walk") over a device will make all MIB variables available, so you can choose one. You can also enter a MIB using numerical OID or human understandable format, if you have the correct MIB installed in your Network Server. diff --git a/pandora_console/include/help/en/help_tags_config.php b/pandora_console/include/help/en/help_tags_config.php index cf2fbe240d..5f999bd6ef 100644 --- a/pandora_console/include/help/en/help_tags_config.php +++ b/pandora_console/include/help/en/help_tags_config.php @@ -3,7 +3,7 @@ * @package Include/help/en */ ?> -

                          Tags in

                          +

                          Tags in

                          The access to the modules can be configurated with a Tags system. A tags are configurated on the system, and be assigned to the choosed modules. In this way the access of the user can be limited to the modules with certain tags.

                          diff --git a/pandora_console/include/help/en/help_tcp_send.php b/pandora_console/include/help/en/help_tcp_send.php index 302deb2f13..ac988d18f4 100644 --- a/pandora_console/include/help/en/help_tcp_send.php +++ b/pandora_console/include/help/en/help_tcp_send.php @@ -38,7 +38,7 @@ If you type something, like "none" and press enter, they reply you the following

                          Protocol mismatch

                          -So to "code" this conversation in a TCP module, you need to put in TCP Send: +So to "code" this conversation in a TCP module, you need to put in TCP Send:

                          |none^M

                          diff --git a/pandora_console/include/help/en/help_template_tab.php b/pandora_console/include/help/en/help_template_tab.php index 55d7d587ba..1f23bf9c85 100644 --- a/pandora_console/include/help/en/help_template_tab.php +++ b/pandora_console/include/help/en/help_template_tab.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/en/help_timesource.php b/pandora_console/include/help/en/help_timesource.php index 9acceb5743..bb5e4cfd8d 100644 --- a/pandora_console/include/help/en/help_timesource.php +++ b/pandora_console/include/help/en/help_timesource.php @@ -9,9 +9,9 @@ What source to use for the time. This can be (for now) either the local system (System) or database (Database).

                          -This is useful when your database is not on the same system as your webserver or your servers. +This is useful when your database is not on the same system as your webserver or your servers. In that case any time difference will miscalculate the time differences and timestamps. -You should use NTP to sync all your servers and your MySQL server. +You should use NTP to sync all your servers and your MySQL server. By using these preferences you don't have to sync your webserver but it's still recommended.

                          @@ -30,28 +30,31 @@ var unixtime = parseInt(unixtime_ms / 1000);

                          "timestamp"); +$option = ['prominent' => 'timestamp']; ?> -Current System time: +Current System time:
                          Current Database time:
                          Your browser time: diff --git a/pandora_console/include/help/en/help_view_services.php b/pandora_console/include/help/en/help_view_services.php index ff2899c1bc..253ee1ba24 100644 --- a/pandora_console/include/help/en/help_view_services.php +++ b/pandora_console/include/help/en/help_view_services.php @@ -1,6 +1,6 @@ @@ -15,20 +15,20 @@ When you have all the devices monitored you can make group of them with the serv To create a new service just click on botton Create.

                          - '550px')); ?> + '550px']); ?>

                          At this moment we have a service created without items, so we have to add items to the service. To add a new item click on the oragne tool an the right top of Service Management tab and after in the botton Create. Then the form below will appear. In this form you must select a module of an agent to add. Also you must fill the fields related to the weight of this module inside the service for Normal, Warning and Critical status. The heavier a module the more important is within the service.

                          - '550px')); ?> + '550px']); ?>

                          When all fields are filled click on button create and the next picture will appear with the succesful message.

                          - '550px')); ?> + '550px']); ?>

                          You can add all items you need to monitor your service. For example we have added elements of this service with the proper weights and the result is like in the next picture.

                          - '550px')); ?> + '550px']); ?>

                          Then the service opeartion list will appear like the image below. This view is calculated in real time and the parameters showed are:

                          @@ -42,7 +42,7 @@ Then the service opeartion list will appear like the image below. This view is c

                        • Status: state of the service depending on its value and the critical and warning limits.


                        - '550px')); ?> + '550px']); ?>

                        If you click on a service name you will see the sepcific service view. As you know the value of a service is calculated as the addition of the weights associated to the state of each module. Services, same as modules, has associated an state depending on its value. This view shows the status of each service item and with following parameters:

                        @@ -58,7 +58,7 @@ If you click on a service name you will see the sepcific service view. As you kn

                        - '550px')); ?> + '550px']); ?>

                        It's also possible to create modules associated to services, with the advantages that this implies (calculation periodicity, integration with the alert system, etc). The way to associate one module to a service is to follow the following steps:

                        @@ -71,7 +71,7 @@ It's also possible to create modules associated to services, with the advantages
                      • If we want to associate alerts to the service, then we should do it on the module that is associated to the server. The server, as it is, has no possibilities of adding alerts, neither graphs or reports. All these has to be done through the monitor that is linked to the service, as we have described before.



                        - '550px')); ?> + '550px']); ?>

                        diff --git a/pandora_console/include/help/en/help_view_services_detail.php b/pandora_console/include/help/en/help_view_services_detail.php index 10f64d2518..995d3efe00 100644 --- a/pandora_console/include/help/en/help_view_services_detail.php +++ b/pandora_console/include/help/en/help_view_services_detail.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/en/help_visual_console_editor_data_tab.php b/pandora_console/include/help/en/help_visual_console_editor_data_tab.php index 86428c16db..36cf7da077 100644 --- a/pandora_console/include/help/en/help_visual_console_editor_data_tab.php +++ b/pandora_console/include/help/en/help_visual_console_editor_data_tab.php @@ -1,7 +1,7 @@

                        Editor

                        diff --git a/pandora_console/include/help/en/help_visual_console_editor_editor_tab.php b/pandora_console/include/help/en/help_visual_console_editor_editor_tab.php index 3cc211da66..73a691102b 100644 --- a/pandora_console/include/help/en/help_visual_console_editor_editor_tab.php +++ b/pandora_console/include/help/en/help_visual_console_editor_editor_tab.php @@ -1,7 +1,7 @@

                        Editor

                        @@ -13,9 +13,9 @@ your browser support correctly the javascript languaje. As you can see in the screen shot, the screen is divided in two areas that are well defined:
                          -
                        • the button box
                        • -
                        • the work area (where you will "draw" the visual console)
                        • -
                        • the option palette ( that is not visible in this screen shot)
                        • +
                        • the button box
                        • +
                        • the work area (where you will "draw" the visual console)
                        • +
                        • the option palette ( that is not visible in this screen shot)
                        You can set the label with a rich text. And the item "Simple value" you can use the macros to set inner the text diff --git a/pandora_console/include/help/en/help_visual_console_editor_list_elements_tab.php b/pandora_console/include/help/en/help_visual_console_editor_list_elements_tab.php index 9a0e59ebae..1e6897040e 100644 --- a/pandora_console/include/help/en/help_visual_console_editor_list_elements_tab.php +++ b/pandora_console/include/help/en/help_visual_console_editor_list_elements_tab.php @@ -1,7 +1,7 @@

                        List of elements

                        diff --git a/pandora_console/include/help/en/help_visual_console_editor_preview_tab.php b/pandora_console/include/help/en/help_visual_console_editor_preview_tab.php index cfe2355c5d..114ced63a8 100644 --- a/pandora_console/include/help/en/help_visual_console_editor_preview_tab.php +++ b/pandora_console/include/help/en/help_visual_console_editor_preview_tab.php @@ -1,9 +1,9 @@

                        Preview

                        -

                        This tab is useful to see the result of your work in a quick way, avoiding surfing between the Console menus. The visual console view is an static view, so, if the state of the elements contained there, they will not be drawing again as it happens with the visual console view that hangs on the Visual Console menu.

                        +

                        This tab is useful to see the result of your work in a quick way, avoiding surfing between the Console menus. The visual console view is an static view, so, if the state of the elements contained there, they will not be drawing again as it happens with the visual console view that hangs on the Visual Console menu.

                        diff --git a/pandora_console/include/help/en/help_visual_console_editor_wizard_tab.php b/pandora_console/include/help/en/help_visual_console_editor_wizard_tab.php index d526949a1f..196d012537 100644 --- a/pandora_console/include/help/en/help_visual_console_editor_wizard_tab.php +++ b/pandora_console/include/help/en/help_visual_console_editor_wizard_tab.php @@ -1,7 +1,7 @@

                        Wizard

                        diff --git a/pandora_console/include/help/en/help_web_checks.php b/pandora_console/include/help/en/help_web_checks.php index 5aad76468a..c7ea8b860c 100644 --- a/pandora_console/include/help/en/help_web_checks.php +++ b/pandora_console/include/help/en/help_web_checks.php @@ -6,7 +6,7 @@

                        WEB Monitoring

                        -Advanced WEB Monitoring is a feature done by the Goliat/WEB Server in Enterprise version. +Advanced WEB Monitoring is a feature done by the Goliat/WEB Server in Enterprise version.

                        This is a sample of GOLIAT Webcheck module:
                        @@ -43,12 +43,12 @@ The following macros are available:

                      • _moduledescription_ : Description of the module who fired the alert.
                      • _modulestatus_ : Status of the module.
                      • _moduletags_ : Tags associated to the module.
                      • -
                      • _id_agent_ : Id of agent, useful to build direct URL to redirect to a console webpage.
                      • +
                      • _id_agent_ : Id of agent, useful to build direct URL to redirect to a console webpage.
                      • _policy_ : Name of the policy the module belongs to (if applies).
                      • _interval_ : Execution interval of the module.
                      • _target_ip_ : IP address of the target of the module.
                      • _target_port_ : Port number of the target of the module.
                      • -
                      • _plugin_parameters_ : Plug-in Parameters of the module.
                      • +
                      • _plugin_parameters_ : Plug-in Parameters of the module.
                      • _email_tag_ : Emails associated to the module tags.
                      diff --git a/pandora_console/include/help/en/help_wux_console.php b/pandora_console/include/help/en/help_wux_console.php index 39ad49d70a..8404a1a3c1 100644 --- a/pandora_console/include/help/en/help_wux_console.php +++ b/pandora_console/include/help/en/help_wux_console.php @@ -2,155 +2,155 @@

                      Introducción

                      - WUX es un componente interno de que permite a los usuarios automatizar sus sesiones de navegación web. Genera en un informe con los resultados de las ejecuciones, tiempos empleados, y capturas con los posibles errores encontrados. Es capaz de dividir las sesiones de navegación en fases para simplificar la vista y depurar posibles cuellos de botella. + WUX es un componente interno de que permite a los usuarios automatizar sus sesiones de navegación web. Genera en un informe con los resultados de las ejecuciones, tiempos empleados, y capturas con los posibles errores encontrados. Es capaz de dividir las sesiones de navegación en fases para simplificar la vista y depurar posibles cuellos de botella.

                      - WUX utiliza el robot de navegación de (PWR - Web Robot) para automatizar las sesiones de navegación + WUX utiliza el robot de navegación de (PWR - Web Robot) para automatizar las sesiones de navegación

                      Grabar una sesión de navegación web

                      Grabar una sesión PWR

                      - Antes de monitorizar una experiencia de usuario debemos hacer la grabación. Dependiendo del tipo de tecnología que hayamos elegido utilizaremos un sistema de grabación u otro. + Antes de monitorizar una experiencia de usuario debemos hacer la grabación. Dependiendo del tipo de tecnología que hayamos elegido utilizaremos un sistema de grabación u otro.

                      - - Para realizar la grabación de una navegación con PWR necesitaremos: - + + Para realizar la grabación de una navegación con PWR necesitaremos: +

                        -
                      1. - Navegador web Firefox versión 47.0.1 (descargable en: - https://ftp.mozilla.org/pub/firefox/releases/47.0.1/). - .
                      2. -
                      3. - Extensión Selenium IDE (descargable en: - https://addons.mozilla.org/es/firefox/addon/selenium-ide/). -
                      4. +
                      5. + Navegador web Firefox versión 47.0.1 (descargable en: + https://ftp.mozilla.org/pub/firefox/releases/47.0.1/). + .
                      6. +
                      7. + Extensión Selenium IDE (descargable en: + https://addons.mozilla.org/es/firefox/addon/selenium-ide/). +

                      - Para instalar correctamente la versión 47.0.1 de Firefox hay que descargarla desde la URL proporcionada anteriormente. En sistemas Windows habrá que añadir el ejecutable al PATH del sistema. + Para instalar correctamente la versión 47.0.1 de Firefox hay que descargarla desde la URL proporcionada anteriormente. En sistemas Windows habrá que añadir el ejecutable al PATH del sistema.

                      - 'width: 90%;')); - ?> + 'width: 90%;']); + ?>

                      - Una vez descargado mostraremos el icono del entorno de grabación mediante las opciones de personalización de Firefox: + Una vez descargado mostraremos el icono del entorno de grabación mediante las opciones de personalización de Firefox:

                      - 'width:295px;')); - ?> + 'width:295px;']); + ?>

                      - 'width: 90%;')); - ?> + 'width: 90%;']); + ?>

                      - Una vez colocado el acceso iniciamos el grabador: + Una vez colocado el acceso iniciamos el grabador:

                      - 'width: 90%;')); - ?> + 'width: 90%;']); + ?>

                      - Desde este momento podremos navegar por el sitio web que queramos monitorizar y las diferentes acciones de cada paso que avancemos irán apareciendo en el grabador. + Desde este momento podremos navegar por el sitio web que queramos monitorizar y las diferentes acciones de cada paso que avancemos irán apareciendo en el grabador.

                      - Para detener la grabación utilizaremos el siguiente botón, situado en la parte superior derecha del grabador: + Para detener la grabación utilizaremos el siguiente botón, situado en la parte superior derecha del grabador:

                      - 'width:33px;')); - ?> + 'width:33px;']); + ?>

                      - Una vez completadas las acciones, podemos realizar comprobaciones sobre la página, por ejemplo verificar la existencia de un texto determinado para asegurarnos de que la página cargada es la correcta. Para ello haremos click derecho sobre una sección de texto en la ventana del navegador mientras continuamos grabando, y seleccionamos la opción verifyText: + Una vez completadas las acciones, podemos realizar comprobaciones sobre la página, por ejemplo verificar la existencia de un texto determinado para asegurarnos de que la página cargada es la correcta. Para ello haremos click derecho sobre una sección de texto en la ventana del navegador mientras continuamos grabando, y seleccionamos la opción verifyText:

                      - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                      - Aparecerá un nuevo paso en el grabador indicando la acción de comprobación de texto indicada: + Aparecerá un nuevo paso en el grabador indicando la acción de comprobación de texto indicada:

                      - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                      - Podemos reproducir la secuencia completa mediante el botón Play entire test suite y comprobar que finaliza correctamente: + Podemos reproducir la secuencia completa mediante el botón Play entire test suite y comprobar que finaliza correctamente:

                      - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                      - Una vez verificada la validez de la secuencia de navegación, la guardaremos (Archivo -> Save Test Case) para ejecutarla posteriormente con WUX. El fichero resultante será un documento HTML que WUX interpretará. + Una vez verificada la validez de la secuencia de navegación, la guardaremos (Archivo -> Save Test Case) para ejecutarla posteriormente con WUX. El fichero resultante será un documento HTML que WUX interpretará.

                      -

                      Grabar una sesión transaccional con WUX PWR

                      +

                      Grabar una sesión transaccional con WUX PWR

                      - WUX en modo PWR ( Web Robot) permite dividir la monitorización de la navegación de un sitio web en múltiples módulos, que representarán cada uno de los pasos realizados. + WUX en modo PWR ( Web Robot) permite dividir la monitorización de la navegación de un sitio web en múltiples módulos, que representarán cada uno de los pasos realizados.

                      - Para insertar un nuevo punto de control y generar los módulos de fase (hasta ese punto) haga clic derecho en el punto donde desea identificar el comienzo de fase. + Para insertar un nuevo punto de control y generar los módulos de fase (hasta ese punto) haga clic derecho en el punto donde desea identificar el comienzo de fase.

                      - 'width:436;')); - ?> + 'width:436;']); + ?>

                      - Como comentario pondremos el siguiente texto: + Como comentario pondremos el siguiente texto:

                      -	phase_start:nombre_de_fase
                      +    phase_start:nombre_de_fase
                       

                      - La fase englobará el tiempo y resultado de todos los comandos que se encuentren hasta el siguiente comentario: + La fase englobará el tiempo y resultado de todos los comandos que se encuentren hasta el siguiente comentario:

                      -	phase_end:nombre_de_fase
                      +    phase_end:nombre_de_fase
                       

                      - Todos los comandos que se ejecuten entre una etiqueta phase_start y phase_end se englobarán dentro de esa fase. + Todos los comandos que se ejecuten entre una etiqueta phase_start y phase_end se englobarán dentro de esa fase.

                      Visualización de los datos

                      @@ -166,9 +166,9 @@

                      - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                      @@ -176,9 +176,9 @@

                      - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                      Vista de consola WUX

                      @@ -186,55 +186,55 @@ En esta vista podemos encontrar toda la infomación que el sistema WUX ha obtenido de la sesión de navegación configurada:

                      - Nota: Si hemos definido fases en nuestra sesión de navegación, se mostrarán en esta vista de una forma sencilla y clara (ver apartado de grabación sesión transaccional con WUX PWR). + Nota: Si hemos definido fases en nuestra sesión de navegación, se mostrarán en esta vista de una forma sencilla y clara (ver apartado de grabación sesión transaccional con WUX PWR).

                      - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                      Sección Resultado Global:

                      - Muestra el estado general de nuestra transacción: + Muestra el estado general de nuestra transacción:

                        -
                      1. - Esta puede tener tres estados: -
                          - -
                        1. - Correcto: Cuando todas las fases de la transacción sean correctas. -
                        2. -
                        3. - Incorrecto: Si alguna de las fases de la transacción ha fallado. En ese caso, se mostrara una icono de una lupa que enlaza a la captura de pantalla del punto de la sesión de navegación en que se ha producido el fallo. -
                        4. -
                        5. - Desconocido: Si el servidor encuentra problemas para procesar la sesión o hay fallos de configuración. -
                        6. +
                        7. + Esta puede tener tres estados: +
                            + +
                          1. + Correcto: Cuando todas las fases de la transacción sean correctas. +
                          2. +
                          3. + Incorrecto: Si alguna de las fases de la transacción ha fallado. En ese caso, se mostrara una icono de una lupa que enlaza a la captura de pantalla del punto de la sesión de navegación en que se ha producido el fallo. +
                          4. +
                          5. + Desconocido: Si el servidor encuentra problemas para procesar la sesión o hay fallos de configuración. +
                        8. - Muestra el tiempo transcurrido desde la última ejecución de la sesión de navegación. + Muestra el tiempo transcurrido desde la última ejecución de la sesión de navegación.
                        9. - Muestra el tiempo total que ha tardado en realizarse dicha sesión de navegación, independientemente de su estado. + Muestra el tiempo total que ha tardado en realizarse dicha sesión de navegación, independientemente de su estado.

                        Sección Resultados de la ejecución de la transacción:

                          -
                        1. - Muestra el estado y el tiempo empleado en ejecutar la sesión de navegación. -
                        2. -
                        3. - En caso de fallo, se mostrará el icono que enlaza con la captura del momento del error. -
                        4. -
                        5. - Si hemos definido fases en nuestra sesión, entonces se mostrará el estado de cada una de las fases, asi como el tiempo que tarda en realizarse cada una de ellas y su contribución al tiempo global. -
                        6. +
                        7. + Muestra el estado y el tiempo empleado en ejecutar la sesión de navegación. +
                        8. +
                        9. + En caso de fallo, se mostrará el icono que enlaza con la captura del momento del error. +
                        10. +
                        11. + Si hemos definido fases en nuestra sesión, entonces se mostrará el estado de cada una de las fases, asi como el tiempo que tarda en realizarse cada una de ellas y su contribución al tiempo global. +

                        @@ -249,56 +249,56 @@

                        1. - - Stats_TT: - - Tiempo total en obtener el sitio web. + + Stats_TT: + + Tiempo total en obtener el sitio web.
                        2. - - Stats_TDNS: - - Tiempo total en resolver la dirección IP del objetivo. + + Stats_TDNS: + + Tiempo total en resolver la dirección IP del objetivo.
                        3. - - Stats_TTCP: - - Tiempo empleado en conectar vía TCP. + + Stats_TTCP: + + Tiempo empleado en conectar vía TCP.
                        4. - - Stats_TSSL: - - Tiempo empleado en establecer comunicación SSL. + + Stats_TSSL: + + Tiempo empleado en establecer comunicación SSL.
                        5. - - Stats_TST : - - Tiempo hasta que inició la transferencia de datos. + + Stats_TST : + + Tiempo hasta que inició la transferencia de datos.
                        6. - - Stats_TTC : - - Tiempo transfiriendo datos, agrupará todos los tiempos de transferencia de recursos. + + Stats_TTC : + + Tiempo transfiriendo datos, agrupará todos los tiempos de transferencia de recursos.
                        7. - - Stats_TTR : - - Tiempo empleado en transferir el recurso X, agrupando todas las imágenes en “image”. + + Stats_TTR : + + Tiempo empleado en transferir el recurso X, agrupando todas las imágenes en “image”.

                        Historial de trasacción:

                          -
                        1. - Muestra el histórico de las ejecuciones de la sesión de navegación web. -
                        2. - En el caso de haber ejecuciones fallidas, se mostrará un enlace donde consultar la imagen del error. + Muestra el histórico de las ejecuciones de la sesión de navegación web. +
                        3. +
                        4. + En el caso de haber ejecuciones fallidas, se mostrará un enlace donde consultar la imagen del error.
                        \ No newline at end of file diff --git a/pandora_console/include/help/es/help_agent_status.php b/pandora_console/include/help/es/help_agent_status.php index f62e66aeaa..d999cad8ff 100644 --- a/pandora_console/include/help/es/help_agent_status.php +++ b/pandora_console/include/help/es/help_agent_status.php @@ -23,13 +23,13 @@ Los valores posibles del estado de un agente son: - - - + + + - - + +
                        "At least one monitor fails", "alt" => "At least one monitor fails")); ?> "At least one monitor fails", "alt" => "At least one monitor fails")); ?>Al menos un monitor falla "Change between Green/Red state", "alt" => "Change between Green/Red state")); ?> "Change between Green/Red state", "alt" => "Change between Green/Red state")); ?>Cambia entre el estado Verde/Rojo "All Monitors OK", "alt" => "All Monitors OK")); ?> "All Monitors OK", "alt" => "All Monitors OK")); ?>Todos los monitores están OK 'At least one monitor fails', 'alt' => 'At least one monitor fails']); ?> 'At least one monitor fails', 'alt' => 'At least one monitor fails']); ?>Al menos un monitor falla 'Change between Green/Red state', 'alt' => 'Change between Green/Red state']); ?> 'Change between Green/Red state', 'alt' => 'Change between Green/Red state']); ?>Cambia entre el estado Verde/Rojo 'All Monitors OK', 'alt' => 'All Monitors OK']); ?> 'All Monitors OK', 'alt' => 'All Monitors OK']); ?>Todos los monitores están OK
                        "Agent without data", "alt" => "Agent without data")); ?> "Agent without data", "alt" => "Agent without data")); ?>Agente sin datos "Agent down", "alt" => "Agent down")); ?> "Agent down", "alt" => "Agent down")); ?>Agente caído 'Agent without data', 'alt' => 'Agent without data']); ?> 'Agent without data', 'alt' => 'Agent without data']); ?>Agente sin datos 'Agent down', 'alt' => 'Agent down']); ?> 'Agent down', 'alt' => 'Agent down']); ?>Agente caído
                        @@ -39,9 +39,9 @@ Los valores posibles del estado de alerta son:

                        - - - + + +
                        "Alert fired", "alt" => "Alert fired")); ?> "Alert fired", "alt" => "Alert fired")); ?>Alerta disparada "Alert disabled", "alt" => "Alert disabled")); ?> "Alert disabled", "alt" => "Alert disabled")); ?>Alerta desactivada "Alert not fired", "alt" => "Alert not fired")); ?> "Alert not fired", "alt" => "Alert not fired")); ?>Alerta no disparada 'Alert fired', 'alt' => 'Alert fired']); ?> 'Alert fired', 'alt' => 'Alert fired']); ?>Alerta disparada 'Alert disabled', 'alt' => 'Alert disabled']); ?> 'Alert disabled', 'alt' => 'Alert disabled']); ?>Alerta desactivada 'Alert not fired', 'alt' => 'Alert not fired']); ?> 'Alert not fired', 'alt' => 'Alert not fired']); ?>Alerta no disparada
                        diff --git a/pandora_console/include/help/es/help_alert_action.php b/pandora_console/include/help/es/help_alert_action.php index db673d076b..860fc34886 100644 --- a/pandora_console/include/help/es/help_alert_action.php +++ b/pandora_console/include/help/es/help_alert_action.php @@ -1,7 +1,7 @@

                        Acciones sobre alertas

                        diff --git a/pandora_console/include/help/es/help_alert_command.php b/pandora_console/include/help/es/help_alert_command.php index a2f19dc197..b4686010ca 100644 --- a/pandora_console/include/help/es/help_alert_command.php +++ b/pandora_console/include/help/es/help_alert_command.php @@ -1,9 +1,9 @@

                        Comando de alerta

                        -

                        La reacción de para un valor "fuera de rango" puede ser de diversos tipos: escribir en un syslog, envío de una mail o SMS, o bien la ejecucion de cualquier script que este alojado en la maquina de y pueda ser procesado.

                        +

                        La reacción de para un valor "fuera de rango" puede ser de diversos tipos: escribir en un syslog, envío de una mail o SMS, o bien la ejecucion de cualquier script que este alojado en la maquina de y pueda ser procesado.

                        diff --git a/pandora_console/include/help/es/help_alert_compound.php b/pandora_console/include/help/es/help_alert_compound.php index f1fc0ddc06..81306b5c18 100644 --- a/pandora_console/include/help/es/help_alert_compound.php +++ b/pandora_console/include/help/es/help_alert_compound.php @@ -1,10 +1,10 @@

                        Alerta correlación

                        -

                        Permite usar más de un módulo para generar una reacción en . Dichos módulos pueden pertenecer a un mismo agente o a varios.

                        +

                        Permite usar más de un módulo para generar una reacción en . Dichos módulos pueden pertenecer a un mismo agente o a varios.

                        diff --git a/pandora_console/include/help/es/help_alert_config.php b/pandora_console/include/help/es/help_alert_config.php index e26533ba9a..3c6d0b8e53 100644 --- a/pandora_console/include/help/es/help_alert_config.php +++ b/pandora_console/include/help/es/help_alert_config.php @@ -9,7 +9,7 @@ A continuación se detallan los campos que hay que rellenar:

                        Name: El nombre de la acción.
                        Group: El grupo de la acción.
                        - Command: En este campo se define el comando que se usará en el caso de que se ejecute la alerta. Se puede elegir entre los diferntes Comandos que hay definidos en . Dependiendo del comando elegido nos aparecerán unos campos a rellenar u otros.
                        + Command: En este campo se define el comando que se usará en el caso de que se ejecute la alerta. Se puede elegir entre los diferntes Comandos que hay definidos en . Dependiendo del comando elegido nos aparecerán unos campos a rellenar u otros.
                        Threshold: El umbral de ejecución de la acción.
                        Command Preview: En este campo, no editable, aparecerá automáticamente el comando que se va a ejecutar en el sistema.
                        Field X: En estos campos se define el valor de las macros _field1_ a _field10_, que se usarán en el comando, en caso de ser necesario. Estos campos pueden ser un campo de texto o un combo de selección si se configura. Dependiendo del comando seleccionado apareceran un numero de campos a rellenar según sea necesario o no. Por ejemplo:

                        @@ -18,7 +18,7 @@ Para el comando de los emails únicamente esta configurado el _field1_ (Destinat A la hora de crear la acción podemos definir únicamente estos 3 campos. Dentro de esos campos podemos configurar las macros que abajo se indican.

                        - '550px')); ?> + '550px']); ?>


                        @@ -50,7 +50,7 @@ Además de las macros de módulo definidas, las siguientes macros están disponi
                      2. _data_: Dato que hizo que la alerta se disparase.
                      3. _email_tag_: Emails asociados a los tags de módulos.
                      4. _event_cfX_: (Solo alertas de evento) Clave del campo personalizado del evento que disparó la alerta. Por ejemplo, si hay un campo personalizado cuya clave es IPAM, se puede obtener su valor usando la macro _event_cfIPAM_.
                      5. -
                      6. _event_description_ : (Solo alertas de evento) Descripción textual del evento de .
                      7. +
                      8. _event_description_ : (Solo alertas de evento) Descripción textual del evento de .
                      9. _event_extra_id_ : (Solo alertas de evento) Id extra.
                      10. _event_id_: (Solo alertas de evento) Id del evento que disparó la alerta.
                      11. _event_text_severity_: (Solo alertas de evento) Prioridad en texto de el evento que dispara la alerta (Maintenance, Informational, Normal Minor, Warning, Major, Critical).
                      12. @@ -73,7 +73,7 @@ Además de las macros de módulo definidas, las siguientes macros están disponi
                      13. _groupcustomid_: ID personalizado del grupo.
                      14. _groupother_: Otra información sobre el grupo. Se configura al crear el grupo.
                      15. _homeurl_: Es un enlace de la URL pública que debe configurarse en las opciones generales de la configuración.
                      16. -
                      17. _id_agent_: ID del agente, util para construir URL de acceso a la consola de .
                      18. +
                      19. _id_agent_: ID del agente, util para construir URL de acceso a la consola de .
                      20. _id_alert_: ID de la alerta, util para correlar la alerta en herramientas de terceros.
                      21. _id_group_ : ID del grupo de agente.
                      22. _id_module_: ID del módulo.
                      23. diff --git a/pandora_console/include/help/es/help_alert_macros.php b/pandora_console/include/help/es/help_alert_macros.php index 2817b32abb..de420b31c7 100644 --- a/pandora_console/include/help/es/help_alert_macros.php +++ b/pandora_console/include/help/es/help_alert_macros.php @@ -33,7 +33,7 @@ Además de las macros de módulo definidas, las siguientes macros están disponi
                      24. _data_: Dato que hizo que la alerta se disparase.
                      25. _email_tag_: Emails asociados a los tags de módulos.
                      26. _event_cfX_: (Solo alertas de evento) Clave del campo personalizado del evento que disparó la alerta. Por ejemplo, si hay un campo personalizado cuya clave es IPAM, se puede obtener su valor usando la macro _event_cfIPAM_
                      27. -
                      28. _event_description_ : (Solo alertas de evento) Descripción textual del evento de .
                      29. +
                      30. _event_description_ : (Solo alertas de evento) Descripción textual del evento de .
                      31. _event_extra_id_ : (Solo alertas de evento) Id extra.
                      32. _event_id_: (Solo alertas de evento) Id del evento que disparó la alerta.
                      33. _event_text_severity_:(Solo alertas de evento) Prioridad en texto de el evento que dispara la alerta (Maintenance, Informational, Normal Minor, Warning, Major, Critical).
                      34. @@ -56,7 +56,7 @@ Además de las macros de módulo definidas, las siguientes macros están disponi
                      35. _groupcustomid_: ID personalizado del grupo.
                      36. _groupother_: Otra información sobre el grupo. Se configura al crear el grupo.
                      37. _homeurl_: Es un enlace de la URL pública que debe configurarse en las opciones generales de la configuración.
                      38. -
                      39. _id_agent_: ID del agente, util para construir URL de acceso a la consola de .
                      40. +
                      41. _id_agent_: ID del agente, util para construir URL de acceso a la consola de .
                      42. _id_alert_: ID de la alerta, util para correlar la alerta en herramientas de terceros.
                      43. _id_group_ : ID del grupo de agente.
                      44. _id_module_: ID del módulo.
                      45. diff --git a/pandora_console/include/help/es/help_alert_recovery.php b/pandora_console/include/help/es/help_alert_recovery.php index 9c0addc685..85398ec6f8 100644 --- a/pandora_console/include/help/es/help_alert_recovery.php +++ b/pandora_console/include/help/es/help_alert_recovery.php @@ -5,4 +5,4 @@ ?>

                        Recuperación de alerta

                        -Define si lanza otra alerta cuando la condición de la alerta se recupera. Tiene el mismo «campo1» pero añade «[RECOVER]]» al «campo2» y al «campo3». De forma predeterminada está desactivada. +Define si lanza otra alerta cuando la condición de la alerta se recupera. Tiene el mismo «campo1» pero añade «[RECOVER]]» al «campo2» y al «campo3». De forma predeterminada está desactivada. diff --git a/pandora_console/include/help/es/help_alert_template.php b/pandora_console/include/help/es/help_alert_template.php index 4cdb6b523b..a9d26e0ef5 100644 --- a/pandora_console/include/help/es/help_alert_template.php +++ b/pandora_console/include/help/es/help_alert_template.php @@ -1,7 +1,7 @@

                        Plantilla de alerta

                        diff --git a/pandora_console/include/help/es/help_alert_type.php b/pandora_console/include/help/es/help_alert_type.php index 234531dd44..a2cd811a64 100644 --- a/pandora_console/include/help/es/help_alert_type.php +++ b/pandora_console/include/help/es/help_alert_type.php @@ -7,9 +7,9 @@ Existen algunas alertas predefinidas, las cuales es muy probable que tenga que configurar en caso de que su sistema no proporcione los comandos necesarios para ejecutarlas. El equipo de desarrollo ha probado estas alertas con Red Hat Enterprise Linux (RHEL), CentOS, Debian y Ubuntu Server.
                          -
                        • eMail: Envía un correo-e desde el servidor de . Usa el sendmail local. Si instaló otro tipo de servidor de correo o no tiene uno, debería instalar y configurar sendmail o cualquiera equivalente (y comprobar la sintaxis) para poder usar este servicio. depende de las herramientas del sistema para ejecutar prácticamente cada alerta, será necesario comprobar que esos comandos funcionan correctamente en su sistema.
                        • -
                        • Internal audit: Es la única alerta «interna», escribe un incidente en el sistema de auditoría interno de . Esto se almacena en la base de datos de y se puede revisar con el visor de auditoría de desde la consola Web.
                        • -
                        • Alertlog: Guarda información acerca de la alerta en un fichero de texto (.log). Use este tipo de alerta para generar ficheros log usando el formato que necesite. Para ello, deberá modificar el comando para que use el formato y fichero que usted quierd.a Note que no gestiona rotación de ficheros, y que el proceso del servidor de que ejecuta la alerta deberá poder acceder al fichero log para escribir en él.
                        • -
                        • Event: Esta alerta crea un evento especial en el gestor de eventos de .
                        • +
                        • eMail: Envía un correo-e desde el servidor de . Usa el sendmail local. Si instaló otro tipo de servidor de correo o no tiene uno, debería instalar y configurar sendmail o cualquiera equivalente (y comprobar la sintaxis) para poder usar este servicio. depende de las herramientas del sistema para ejecutar prácticamente cada alerta, será necesario comprobar que esos comandos funcionan correctamente en su sistema.
                        • +
                        • Internal audit: Es la única alerta «interna», escribe un incidente en el sistema de auditoría interno de . Esto se almacena en la base de datos de y se puede revisar con el visor de auditoría de desde la consola Web.
                        • +
                        • Alertlog: Guarda información acerca de la alerta en un fichero de texto (.log). Use este tipo de alerta para generar ficheros log usando el formato que necesite. Para ello, deberá modificar el comando para que use el formato y fichero que usted quierd.a Note que no gestiona rotación de ficheros, y que el proceso del servidor de que ejecuta la alerta deberá poder acceder al fichero log para escribir en él.
                        • +
                        • Event: Esta alerta crea un evento especial en el gestor de eventos de .
                        Estas alertas son predefinidas y no se pueden borrar, no obstante el usuario puede definir alertas nuevas que usen comandos personalizados y añadirlas al Gestor de alertas. \ No newline at end of file diff --git a/pandora_console/include/help/es/help_alerts.php b/pandora_console/include/help/es/help_alerts.php index 606d2b89d6..7089e420e7 100644 --- a/pandora_console/include/help/es/help_alerts.php +++ b/pandora_console/include/help/es/help_alerts.php @@ -12,26 +12,26 @@

                        El siguiente paso después de añadir un agente, habiendo configurado sus módulos y definido las alertas, es asignar esas alertas al agente. Este paso es necesario para establecer las condiciones de la alerta en los casos deseados. Se realiza pulsando en el agente que se quiere configurar en la opción «Gestionar agentes» del menú «Administración», o usando el modo de edición y seleccionando la solapa «Alertas», desde la vista del agennte.

                        Se deben rellenar los siguientes campos para asignar una alerta:


                        -
                      46. Tipo de alerta: Éste puede seleccionarse de la lista de alertas que hayan sido previamente generadas.
                      47. -
                      48. Valor máximo: Define el valor máximo para un módulo. Cualquier valor por encima de este umbral lanzará la alerta.
                      49. -
                      50. Valor mínimo: Define el valor mínimo para un módulo. Cualquier valor por debajo de este umbral disparará la alerta. La pareja de «maximo» y «minimo» son los valores clave en la definición de una alerta, ya que definen en qué rango de valores se ha de disparar una alerta. Los valores de máximo y mínimo definen «lo aceptable», valores que considera «válidos», fuera de estos valores, lo considerará como alerta candidata a ser disparada.
                      51. -
                      52. Texto de la alerta: En caso de módulos string, se puede definir una expresión regular o una subcadena para hacer disparar una alerta.
                      53. -
                      54. Hora desde / Hora hasta: Esto define un rango de tiempo «válido» para lanzar alertas.
                      55. -
                      56. Descripción: Describe la función de la alerta, y resulta útil para identificar la alerta entre otras en la vista general de alertas.
                      57. -
                      58. Campo #1 (Alias, nombre): Define el valor para la variable "_field1_".
                      59. -
                      60. Campo #2 (Línea sencilla): Define el valor para la variable "_field2_".
                      61. -
                      62. Campo #3 (Texto completo)): Define el valor para la variable "_field3_".
                      63. -
                      64. Umbral de tiempo: Define el intervalo de tiempo en el cual se garantiza que una alerta no se va a disparar más veces del número establecido en Numero máximo de alertas. Pasado el intervalo definido, una alerta se recupera si llega un valor correcto, salvo que esté activado el valor Recuperación de alerta, en cuyo caso se recupera inmediatamente después de recibir un valor correcto independientemente del umbral.
                      65. -
                      66. Número mínimo de alertas: Número mínimo de alertas que se necesitan para empezar a disparar una alerta. Funciona como un filtro, necesario para eliminar falsos positivos.
                      67. -
                      68. Número máximo de alertas: Máximo número de alertas que se pueden enviar consecutivamente en el mismo intervalo de tiempo.
                      69. -
                      70. Módulo asignado: Módulo que debe monitorizar la alerta.
                      71. +
                      72. Tipo de alerta: Éste puede seleccionarse de la lista de alertas que hayan sido previamente generadas.
                      73. +
                      74. Valor máximo: Define el valor máximo para un módulo. Cualquier valor por encima de este umbral lanzará la alerta.
                      75. +
                      76. Valor mínimo: Define el valor mínimo para un módulo. Cualquier valor por debajo de este umbral disparará la alerta. La pareja de «maximo» y «minimo» son los valores clave en la definición de una alerta, ya que definen en qué rango de valores se ha de disparar una alerta. Los valores de máximo y mínimo definen «lo aceptable», valores que considera «válidos», fuera de estos valores, lo considerará como alerta candidata a ser disparada.
                      77. +
                      78. Texto de la alerta: En caso de módulos string, se puede definir una expresión regular o una subcadena para hacer disparar una alerta.
                      79. +
                      80. Hora desde / Hora hasta: Esto define un rango de tiempo «válido» para lanzar alertas.
                      81. +
                      82. Descripción: Describe la función de la alerta, y resulta útil para identificar la alerta entre otras en la vista general de alertas.
                      83. +
                      84. Campo #1 (Alias, nombre): Define el valor para la variable "_field1_".
                      85. +
                      86. Campo #2 (Línea sencilla): Define el valor para la variable "_field2_".
                      87. +
                      88. Campo #3 (Texto completo)): Define el valor para la variable "_field3_".
                      89. +
                      90. Umbral de tiempo: Define el intervalo de tiempo en el cual se garantiza que una alerta no se va a disparar más veces del número establecido en Numero máximo de alertas. Pasado el intervalo definido, una alerta se recupera si llega un valor correcto, salvo que esté activado el valor Recuperación de alerta, en cuyo caso se recupera inmediatamente después de recibir un valor correcto independientemente del umbral.
                      91. +
                      92. Número mínimo de alertas: Número mínimo de alertas que se necesitan para empezar a disparar una alerta. Funciona como un filtro, necesario para eliminar falsos positivos.
                      93. +
                      94. Número máximo de alertas: Máximo número de alertas que se pueden enviar consecutivamente en el mismo intervalo de tiempo.
                      95. +
                      96. Módulo asignado: Módulo que debe monitorizar la alerta.
                      97. Se pueden ver todas las alertas de un agente usando la solapa «Alertas». A continuación se muestra un ejemplo:
                        «Quiero disparar una alerta cuando se caiga XXX, y no quiero que me moleste de nuevo durante, al menos, una hora. Después de ese tiempo, si sigue caído, que se dispare otra alerta y que espere otra hora».

                        Debe establecer:

                          -
                        • Umbral de tiempo 3600 (1 hora).
                        • -
                        • Número mínimo de alertas = 1.
                        • -
                        • Número máximo de alertas = 1.
                        • +
                        • Umbral de tiempo 3600 (1 hora).
                        • +
                        • Número mínimo de alertas = 1.
                        • +
                        • Número máximo de alertas = 1.
                        diff --git a/pandora_console/include/help/es/help_alerts_config.php b/pandora_console/include/help/es/help_alerts_config.php index 7a98cb2863..ca56acf4e4 100644 --- a/pandora_console/include/help/es/help_alerts_config.php +++ b/pandora_console/include/help/es/help_alerts_config.php @@ -1,23 +1,23 @@ -

                        Guía rápida de configuración de alertas para

                        +

                        Guía rápida de configuración de alertas para


                        Introducción al sistema de alertas actual

                        -Uno de los problemas más frecuentes y que ocasiona mayor número de quejas por parte de los usuarios es la complejidad de definir alertas en . Antes, hasta la version 2.0, las alertas eran bastante más sencillas de configurar.Para cada alerta, se definía la condición y lo que hacía cuando la acción no se cumplía, para cada caso. Era más intuitivo (aun así habia campos como el alert "threshold" que daban dolores de cabeza a más de uno). Era sencillo, pero ¿merecía la pena?.

                        +Uno de los problemas más frecuentes y que ocasiona mayor número de quejas por parte de los usuarios es la complejidad de definir alertas en . Antes, hasta la version 2.0, las alertas eran bastante más sencillas de configurar.Para cada alerta, se definía la condición y lo que hacía cuando la acción no se cumplía, para cada caso. Era más intuitivo (aun así habia campos como el alert "threshold" que daban dolores de cabeza a más de uno). Era sencillo, pero ¿merecía la pena?.

                        -Uno de nuestros mejores usuarios (cuando digo mejor, es porque tenía muchísimos agentes instalados, y además conocía muy bien el funcionamiento de ), nos comentó que crear una alerta en 2000 modulos, era enormemente complicado, especialmente cuando habia que modificar algo en todas ellas. Debido principalmente a este y otros problemas, modificamos el sistema de alertas para que fuera modular, para que se pudiera separar la definición de la condición de disparo de la alerta (Alert template), de la acción a ejecutar cuando esta se dispara (Alert action) y del comando que se ejecuta dentro de la acción (Alert comnmand). La combinación de una plantilla de alerta (Alert template) con un módulo desencadena la alerta en sí.

                        +Uno de nuestros mejores usuarios (cuando digo mejor, es porque tenía muchísimos agentes instalados, y además conocía muy bien el funcionamiento de ), nos comentó que crear una alerta en 2000 modulos, era enormemente complicado, especialmente cuando habia que modificar algo en todas ellas. Debido principalmente a este y otros problemas, modificamos el sistema de alertas para que fuera modular, para que se pudiera separar la definición de la condición de disparo de la alerta (Alert template), de la acción a ejecutar cuando esta se dispara (Alert action) y del comando que se ejecuta dentro de la acción (Alert comnmand). La combinación de una plantilla de alerta (Alert template) con un módulo desencadena la alerta en sí.

                        De esta forma, si yo tengo 1000 máquinas con un modulo llamado "Host alive" y todos ellas tienen asociada una plantilla de alerta llamada "Host down" que ejecuta por defecto una acción llamada "Avisar al operador", y quiero cambiar el número mínimo de alertas que se deben disparar antes de avisar al operador, sólo tengo que hacer un cambio en la definicion de la plantilla, no ir una por una, en las 1000 alertas para modificar esa condición.

                        -Muchos usuarios sólo gestionan algunas decenas de máquinas, pero existen usuarios con cientos, incluso miles de sistemas monitorizados con , y tenemos que intentar hacer posible que con se puedan gestionar todo tipo de entornos.



                        +Muchos usuarios sólo gestionan algunas decenas de máquinas, pero existen usuarios con cientos, incluso miles de sistemas monitorizados con , y tenemos que intentar hacer posible que con se puedan gestionar todo tipo de entornos.



                        Estructura de una alerta

                        - '550px')); ?> + '550px']); ?>
                        Las alertas se componen de:

                        @@ -39,11 +39,11 @@ En la plantilla se definen parámetros genéricos de la alertas que son: las con Al definir las acciones y las plantillas disponemos de unos campos genéricos llamados Field1, Field2 y Field3 que son los que se pasarán como parámetros de entrada en la ejecución del comando. Los valores de estos parámetros se propagan de plantilla a la acción y por último al comando. La propagación de la plantilla a la acción sólo se realiza si el campo correspondiente de la acción no tiene un valor asignado, si la acción tiene un valor asignado se conserva.

                        - '550px')); ?> + '550px']); ?>
                        Este seria un ejemplo de como se sobreescriben los valores de la plantilla usando los de la acción.

                        - '550px')); ?> + '550px']); ?>
                        Por ejemplo creamos una plantilla que dispara la alerta y envía un email con los siguientes campos:

                        @@ -69,32 +69,32 @@ Para los campos Field2 y Field3 se conservan los valores definidos en la plantil Bien, ahora vamos a ponernos en el caso anterior. Tenemos una necesidad: monitorizar un módulo que contiene valores numéricos. En nuestro caso, es un modulo que mide la CPU del sistema, en otro caso puede ser un sensor de temperatura, que engrega el valor en grados centígrados. Veamos primero que nuestro módulo recibe datos correctamente:

                        - '550px')); ?> + '550px']); ?>
                        Bien. En esta captura vemos que tenemos un modulo llamado sys_cpu con un valor actual de 7. En nuestro caso queremos que salte una alerta cuando supere los 20. Para ello vamos a configurar el módulo para que se ponga en estado CRITICAL cuando supere los 20. Para ello hacemos click en la llave inglesa para configurar el comportamiento del monitor:

                        - '550px')); ?> + '550px']); ?>
                        Para ello, modificamos el valor marcado en rojo en la captura siguiente:



                        - '550px')); ?> + '550px']); ?>
                        Aceptamos y grabamos la modificación. Ahora cuando el valor del módulo CPU sea 20 o mayor, cambiará su estado a CRITICAL y se verá en color rojo, tal y como vemos aquí.

                        - '550px')); ?> + '550px']); ?>
                        -Ya hemos hecho que el sistema sepa discriminar cuando algo está bien (OK, color VERDE) y cuando está mal (CRITICAL, color rojo). Ahora lo que debemos hacer es que nos envíe un email cuando el modulo se ponga en este estado. Para ello utilizaremos el sistema de alertas de .

                        +Ya hemos hecho que el sistema sepa discriminar cuando algo está bien (OK, color VERDE) y cuando está mal (CRITICAL, color rojo). Ahora lo que debemos hacer es que nos envíe un email cuando el modulo se ponga en este estado. Para ello utilizaremos el sistema de alertas de .

                        -Para esto, lo primero que debemos hacer es asegurarnos de que existe un comando que hace lo que necesitamos (enviar un email). Este ejemplo es fácil porque existe un comando predefinido en para enviar mails. Asi que ya lo tenemos.

                        +Para esto, lo primero que debemos hacer es asegurarnos de que existe un comando que hace lo que necesitamos (enviar un email). Este ejemplo es fácil porque existe un comando predefinido en para enviar mails. Asi que ya lo tenemos.

                        Configurando la acción

                        Ahora tenemos que crear una acción que sea "Enviar un email al operador". Vamos a ello: Vamos al menu de administracion -> Alertas -> Acciones y le damos al botón para crear una nueva acción:

                        - '550px')); ?> + '550px']); ?>
                        -Esta acción utiliza el comando "Enviar email", y es realmente sencillo, ya que sólo relleno un campo (Field 1) dejando los otros dos vacíos. Esta es una de las partes más confusas del sistema de alertas de : ¿Qué son los campos field1, field2, y field3?.

                        +Esta acción utiliza el comando "Enviar email", y es realmente sencillo, ya que sólo relleno un campo (Field 1) dejando los otros dos vacíos. Esta es una de las partes más confusas del sistema de alertas de : ¿Qué son los campos field1, field2, y field3?.

                        Esos campos son los que se usan para "pasar" la información de la plantilla de alerta al comando, y a su vez, de éste al comando. De forma que tanto Plantilla como Comando, puedan aportar diferente información al comando. En este caso el comando sólo establece el campo 1, y dejaremos el campo 2 y el campo 3 a la plantilla, como veremos a continuación.

                        @@ -104,7 +104,7 @@ El campo 1 es el que usamos para definir el email del operador, en este caso un Ahora tenemos que crear una plantilla de alerta lo más genérica posible (para poderla reutilizar más adelante, como veremos) que sea "Esto está mal, porque tengo un módulo en estado Crítico" y que por defecto, envíe un email al operador. Vamos a ello: Vamos al menu de administracion -> Alertas -> Templates y le damos al botón para crear una nueva plantilla (template) de alerta:

                        - '550px')); ?> + '550px']); ?>
                        Lo que define la condición es el campo "Condition", en este caso está marcado a "Estado crítico", de forma que esta plantilla, cuando se asocie a un módulo, se disparará cuando el modulo asociado esté en estado crítico. Antes hemos configurado el modulo "cpu_sys" para que entre en estado crítico cuando valga 20 o más.

                        @@ -112,7 +112,7 @@ La prioridad definida aqui "Critical" es la prioridad de la alerta, que no tiene Pasemos al paso 2, pulsando el boton "next":

                        - '550px')); ?> + '550px']); ?>
                        El paso 2 define todos los "valores" de configuración "finos" de la plantilla de alerta, de la condición de disparo. Algunos de ellos, los primeros, son bastante sencillos, restringen el momento de actuación de esta alerta a ciertos días entre diferentes horas.

                        @@ -120,7 +120,7 @@ Los parámetros más críticos aquí son los siguientes:

                        Time threshold: Por defecto es un día. Si un módulo permanece todo el rato caído, durante, por ejemplo un día, y tenemos aquí un valor de 5 minutos, significa que nos estaría mandando alertas cada 5 minutos. Si lo dejamos en un día (24 horas), sólo nos enviará la alerta una vez, cuando se caiga. Si el modulo se recupera, y luego se vuelve a caer, nos enviará una alerta de nuevo, pero si sigue caída desde la 2º caida, no enviará mas alertas hasta dentro de 24 horas.

                        - Min. Número de alertas: El nº mínimo de veces que se tendrá que dar la condición (en este caso, que el modulo esté en estado CRITICAL) antes de que me ejecute las acciones asociadas a la plantilla de alerta. Es una forma de evitar que falsos positivos me "inunden" a alertas, o que un comportamiento errático (ahora bien, ahora mal) haga que se disparen muchas alertas. Si ponemos aquí 1, significa que hasta que no ocurra al menos una vez, no lo tendré en cuenta. Si pongo 0, la primera vez que el modulo esté mal, disparará la alerta.

                        + Min. Número de alertas: El nº mínimo de veces que se tendrá que dar la condición (en este caso, que el modulo esté en estado CRITICAL) antes de que me ejecute las acciones asociadas a la plantilla de alerta. Es una forma de evitar que falsos positivos me "inunden" a alertas, o que un comportamiento errático (ahora bien, ahora mal) haga que se disparen muchas alertas. Si ponemos aquí 1, significa que hasta que no ocurra al menos una vez, no lo tendré en cuenta. Si pongo 0, la primera vez que el modulo esté mal, disparará la alerta.

                        Max. Numero de alertas: 1 significa que sólo ejecutará la acción una vez. Si tenemos aquí 10, ejecutará 10 veces la acción. Es una forma de limitar el número de veces que una alerta se puede ejecutar.

                        @@ -130,14 +130,14 @@ De nuevo volvemos a ver los campos: "campo1, campo2 y campo3". Ahora podemos ver Subject: [MONITORING] Farscape cpu_sys is in CRITICAL status with value 20
                        Texto email:

                        -This is an automated alert generated by
                        -Please contact your for more information. *DO NOT* reply this email.

                        +This is an automated alert generated by
                        +Please contact your for more information. *DO NOT* reply this email.

                        Dado que la acción por defecto es la que he definido previamente, todas las alertas que usen esta plantilla, usarán esa acción predeterminada por defecto, a no ser que la modifique.

                        En el caso 3, veremos que se puede configurar el sistema de alertas para que notifique cuando la alerta ha cesado.

                        - '550px')); ?> + '550px']); ?>
                        Es casi igual, pero el campo1 no está definido, porque se usará el mismo que venga definido en la acción ejecutada previamente (al disparar la alerta). En este caso solo enviará un mail con un subject que informa que la condición en el modulo cpu_sys se ha recuperado.

                        @@ -146,7 +146,7 @@ La recuperación de alertas es opcional. Es importante destacar que si en los da Ya tenemos todo lo que necesitábamos, ahora sólo tenemos que asociar la plantilla de alerta al módulo. Para ello vamos a la solapa de alertas dentro del agente donde está el módulo:

                        - '550px')); ?> + '550px']); ?>
                        Es sencillo, en esta captura vemos una alerta ya configurada para un módulo llamado "Last_Backup_Unixtime" asociado al mismo template que hemos definido antes "Module critical". Ahora en los controles que hay debajo, vamos a crear una asociación entre el modulo "cpu_sys" y la plantilla de alerta "Module critical". Por defecto mostrará la acción que tenemos definida en esa pantilla "Enviar email a Sancho Lerena".

                        Escalado de alertas

                        @@ -157,8 +157,8 @@ Ahora veremos que podemos añadir más acciones a la misma alerta, definiendo co Por ejemplo, podemos querer que mande un email a XXXXX la primera vez que ocurra, y si sigue caído el monitor, envíe un email a ZZZZ. Para ello, despues de asociar la alerta, en la tabla de alertas asignadas, puedo añadir mas acciones a una alerta ya definida, tal y como podemos ver en la siguiente captura:

                        - '550px')); ?> - '550px')); ?> + '550px']); ?> + '550px']); ?>
                        @@ -169,7 +169,7 @@ Las alertas pueden estar activadas, desactivadas o en standby. La diferencia ent Las alertas en standby son útiles para poder visualizarlas sin que molesten en otros aspectos.

                        Utilizando comandos de alertas distintos del email

                        -El email, como comando es interno a y no se puede configurar, es decir, field1, field2 y field3 son campos que están definidos que se usan como destinatario, subject y texto del mensaje. Pero, ¿que ocurre si yo quiero ejecutar una acción diferente, definida por mi?.

                        +El email, como comando es interno a y no se puede configurar, es decir, field1, field2 y field3 son campos que están definidos que se usan como destinatario, subject y texto del mensaje. Pero, ¿que ocurre si yo quiero ejecutar una acción diferente, definida por mi?.

                        Vamos a definir un nuevo comando, algo totalmente definido por nosotros. Imaginemos que queremos generar un fichero log con cada alerta que encontremos. El formato de ese fichero log tiene que ser algo como:

                        @@ -179,11 +179,11 @@ Donde VALOR es el valor del modulo en ese momento. Habrá varios ficheros log, d Para ello, primero vamos a crear un comando como sigue:

                        - '550px')); ?> + '550px']); ?>
                        Y vamos a definir una acción:

                        - '550px')); ?> + '550px']); ?>
                        Si vemos el fichero de log que hemos creado:

                        @@ -191,6 +191,6 @@ Si vemos el fichero de log que hemos creado:

                        La alerta se disparó a las 18:17:10 en el agente "farscape", en el modulo "cpu_sys" con un dato de "23.00" y con la descripción que pusimos al definir la acción.

                        -Dado que la ejecución del comando, el orden de los campos y otros asuntos pueden hacer que no entendamos bien cómo se ejecuta al final el comando, lo más sencillo es activar las trazas de debug del servidor de (verbose 10) en el fichero de configuración de server en /etc/pandora/pandora_server.conf, reiniciemos el servidor (/etc/init.d/pandora_server restart) y que miremos el fichero /var/log/pandora/pandora_server.log buscando la línea exacta con la ejecución del comando de la alerta que hemos definido, para ver como el servidor de está lanzando el comando.

                        +Dado que la ejecución del comando, el orden de los campos y otros asuntos pueden hacer que no entendamos bien cómo se ejecuta al final el comando, lo más sencillo es activar las trazas de debug del servidor de (verbose 10) en el fichero de configuración de server en /etc/pandora/pandora_server.conf, reiniciemos el servidor (/etc/init.d/pandora_server restart) y que miremos el fichero /var/log/pandora/pandora_server.log buscando la línea exacta con la ejecución del comando de la alerta que hemos definido, para ver como el servidor de está lanzando el comando.

                        diff --git a/pandora_console/include/help/es/help_cascade_protection.php b/pandora_console/include/help/es/help_cascade_protection.php index 56b4b06955..60e1da2d1b 100644 --- a/pandora_console/include/help/es/help_cascade_protection.php +++ b/pandora_console/include/help/es/help_cascade_protection.php @@ -4,11 +4,11 @@

                        Protección en cascada por agente


                        - +

                        -Esta opción se designa para evitar una "tormenta" de alertas que entren porque un grupo de agentes son inalcanzables. Este tipo de comportamiento ocurre cuando un dispositivo intermedio, como por ejemplo un router, está caido, y todos los dispositivos que están tras él no se pueden alcanzar. Probablemente estos dispositivos no estén caídos e incluso estos dispositivos estén trabajando junto con otro router, en modo HA. Pero si no hace nada, probablemente piense que estén caídos porque no los pueden testar con un Remote ICMP Proc Test (un ping). +Esta opción se designa para evitar una "tormenta" de alertas que entren porque un grupo de agentes son inalcanzables. Este tipo de comportamiento ocurre cuando un dispositivo intermedio, como por ejemplo un router, está caido, y todos los dispositivos que están tras él no se pueden alcanzar. Probablemente estos dispositivos no estén caídos e incluso estos dispositivos estén trabajando junto con otro router, en modo HA. Pero si no hace nada, probablemente piense que estén caídos porque no los pueden testar con un Remote ICMP Proc Test (un ping).

                        Cuando habilite cascade protection en un agente, esto significa que si cualquiera de sus padres tiene una alerta CRÍTICA disparada, entonces las alertas del agente NO SERÁN disparadas. Si el padre del agente tiene un módulo en CRITICAL o varias alertas con menor criticidad que CRITICAL, las alertas del agente serán disparadas si deben hacerlo. La protección en cascada comprueba las alertas padre con criticidad CRITICAL, incluyendo las alertas de correlación asignadas al padre.

                        @@ -19,11 +19,11 @@ Si quiere usar un sistema avanzado de protección en cascada, sólo tiene que us

                        Protección en cascada por módulo


                        - +

                        -Esta opción se designa para evitar una "tormenta" de alertas que entren porque un grupo de agentes son inalcanzables. Este tipo de comportamiento ocurre cuando un dispositivo intermedio, como por ejemplo un router, está caido, y todos los dispositivos que están tras él no se pueden alcanzar. Probablemente estos dispositivos no estén caídos e incluso estos dispositivos estén trabajando junto con otro router, en modo HA. Pero si no hace nada, probablemente piense que estén caídos porque no los pueden testar con un Remote ICMP Proc Test (un ping). +Esta opción se designa para evitar una "tormenta" de alertas que entren porque un grupo de agentes son inalcanzables. Este tipo de comportamiento ocurre cuando un dispositivo intermedio, como por ejemplo un router, está caido, y todos los dispositivos que están tras él no se pueden alcanzar. Probablemente estos dispositivos no estén caídos e incluso estos dispositivos estén trabajando junto con otro router, en modo HA. Pero si no hace nada, probablemente piense que estén caídos porque no los pueden testar con un Remote ICMP Proc Test (un ping).

                        Cuando habilite cascade protection en un módulo de un agente, esto significa que si este módulo del agente padre tiene una alerta CRÍTICA disparada, entonces las alertas del agente NO SERÁN disparadas.

                        diff --git a/pandora_console/include/help/es/help_categories.php b/pandora_console/include/help/es/help_categories.php index 1fbccc8961..33714c61c1 100644 --- a/pandora_console/include/help/es/help_categories.php +++ b/pandora_console/include/help/es/help_categories.php @@ -3,7 +3,7 @@ * @package Include/help/es */ ?> -

                        Categorías en

                        +

                        Categorías en

                        Se pueden configurar unas categorias en el sistema, se asignan a los módulos que se quiera.
                        El único usuario que tiene permisos para realizar la creación y configuración de categorias es el administrador y se pueden utilizar para la tarificación de modulos dependiendo de la categoría a la que pertenezcan. diff --git a/pandora_console/include/help/es/help_collection_tab.php b/pandora_console/include/help/es/help_collection_tab.php index 927840f8f9..4a5ff157d5 100644 --- a/pandora_console/include/help/es/help_collection_tab.php +++ b/pandora_console/include/help/es/help_collection_tab.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_collections.php b/pandora_console/include/help/es/help_collections.php index 1972edecc3..868e03575c 100644 --- a/pandora_console/include/help/es/help_collections.php +++ b/pandora_console/include/help/es/help_collections.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_component_groups.php b/pandora_console/include/help/es/help_component_groups.php index ea513907a4..17ac3c0124 100644 --- a/pandora_console/include/help/es/help_component_groups.php +++ b/pandora_console/include/help/es/help_component_groups.php @@ -1,7 +1,7 @@

                        Grupos de componentes

                        diff --git a/pandora_console/include/help/es/help_conf_alert_template.php b/pandora_console/include/help/es/help_conf_alert_template.php index f3de74e315..0d8a568a86 100644 --- a/pandora_console/include/help/es/help_conf_alert_template.php +++ b/pandora_console/include/help/es/help_conf_alert_template.php @@ -1,6 +1,6 @@ @@ -42,7 +42,7 @@ Al alegir la condición regular aparece la posibilidad de marcar la casilla Trig Una vez se han rellenado los campos se pincha en el botón “Next” y se accede a la siguiente pantalla . - '550px')); ?> + '550px']); ?>

                        A continuación se detallan los campos que hay que rellenar:

                        @@ -85,7 +85,7 @@ En este combo se define la acción por defecto que va a tener el template. Esta Una vez se han rellenado los campos se pincha en el botón “Next” y se accede a la siguiente pantalla .

                        - '550px')); ?> + '550px']); ?> A continuación se detallan los campos que hay que rellenar:

                        diff --git a/pandora_console/include/help/es/help_configure_gis_map.php b/pandora_console/include/help/es/help_configure_gis_map.php index 3b7bca232d..5e024f9285 100644 --- a/pandora_console/include/help/es/help_configure_gis_map.php +++ b/pandora_console/include/help/es/help_configure_gis_map.php @@ -10,16 +10,16 @@ Esta página es el lugar para configurar un Mapa GIS.

                        Nombre del Mapa

                        -Cada mapa tiene un nombre descriptivo que se utiliza para reconocer el mapa dentro de . +Cada mapa tiene un nombre descriptivo que se utiliza para reconocer el mapa dentro de .

                        Seleccionar Conexiones

                        -El primer paso es seleccionar la principal conexión empleada en este Mapa GIS. Al menos una conexión debe ser seleccionada para configurar el MAPA GIS, pero es posible añadir más presionando el icono(Add) "Add")); ?> +El primer paso es seleccionar la principal conexión empleada en este Mapa GIS. Al menos una conexión debe ser seleccionada para configurar el MAPA GIS, pero es posible añadir más presionando el icono(Add) 'Add']); ?>

                        -Cuando se configura la primera conexión, te pregunta si quiere utilizar los valores por defecto de la conexión para el mapa, para evitar tener que escribir de nuevo toda la información. También, si la conexión por defecto del mapa se ha cambiado (utilizando el radio button), te preguntará de nuevo si quiere usar los valores de la nueva conexión por defecto. +Cuando se configura la primera conexión, te pregunta si quiere utilizar los valores por defecto de la conexión para el mapa, para evitar tener que escribir de nuevo toda la información. También, si la conexión por defecto del mapa se ha cambiado (utilizando el radio button), te preguntará de nuevo si quiere usar los valores de la nueva conexión por defecto.

                        Parámetros del Mapa

                        diff --git a/pandora_console/include/help/es/help_create_agent.php b/pandora_console/include/help/es/help_create_agent.php index affd3d884a..53a6fe8a8c 100644 --- a/pandora_console/include/help/es/help_create_agent.php +++ b/pandora_console/include/help/es/help_create_agent.php @@ -12,5 +12,5 @@ Para crear un Agente, debes rellenar este formulario. Por favor rellena todos lo "Interval" se refiere al intervalo de ejecución del agente. El intervalo es cada cuanto el agente envía datos al servidor.

                        -"Server" se refiere al Servidor de que leerá los datos enviados por el agente. +"Server" se refiere al Servidor de que leerá los datos enviados por el agente.

                        diff --git a/pandora_console/include/help/es/help_cron.php b/pandora_console/include/help/es/help_cron.php index 5f911a8348..33e9c84cff 100644 --- a/pandora_console/include/help/es/help_cron.php +++ b/pandora_console/include/help/es/help_cron.php @@ -9,7 +9,7 @@ Mediante los grupos de parámetros de configuración Cron desde y Cron puede hacer que un módulo solo se ejecute durante ciertos periodos de tiempo. El modo en el que se configura es parecido a la sintaxis de cron. -Tal y como aparecen en la consola de , cada uno de los parámetros +Tal y como aparecen en la consola de , cada uno de los parámetros tiene tres opciones.

                        Cron desde: cualquiera

                        @@ -36,11 +36,11 @@ su intervalo de ejecución.

                        Ejemplos

                          -
                        • * * * * *: No hay cron configurado.
                        • -
                        • 15 20 * * *: Se ejecutará todos los días a las 20:15.
                        • -
                        • * 20 * * *: Se ejecutará todos los días durante las 20 horas, es decir, entre las 20:00 y las 20:59.
                        • -
                        • * 8-19 * * *: Se ejecutará todos los días entre las 8:00 y las 19:59.
                        • -
                        • 15-45 * 1-16 * *: Se ejecutará todos los primeros 16 días del mes a todas horas entre y cuarto y menos cuarto.
                        • -
                        • * * * 5 *: Se ejecutará solamente en mayo.
                        • +
                        • * * * * *: No hay cron configurado.
                        • +
                        • 15 20 * * *: Se ejecutará todos los días a las 20:15.
                        • +
                        • * 20 * * *: Se ejecutará todos los días durante las 20 horas, es decir, entre las 20:00 y las 20:59.
                        • +
                        • * 8-19 * * *: Se ejecutará todos los días entre las 8:00 y las 19:59.
                        • +
                        • 15-45 * 1-16 * *: Se ejecutará todos los primeros 16 días del mes a todas horas entre y cuarto y menos cuarto.
                        • +
                        • * * * 5 *: Se ejecutará solamente en mayo.
                          • diff --git a/pandora_console/include/help/es/help_custom_logo.php b/pandora_console/include/help/es/help_custom_logo.php index a1b26d4eed..2f39432fd7 100644 --- a/pandora_console/include/help/es/help_custom_logo.php +++ b/pandora_console/include/help/es/help_custom_logo.php @@ -5,7 +5,7 @@ ?>

                            Logo de Cliente (Marca comunitaria de empresa)

                            -Esta opción se utiliza para poder desplegar su propio logo en la cabecera de . Puede utilizar cualquier tipo de gráfica en formato PNG. Hay una ancho/alto para cualquier imagen desplegada aquí de 206x47 píxeles. +Esta opción se utiliza para poder desplegar su propio logo en la cabecera de . Puede utilizar cualquier tipo de gráfica en formato PNG. Hay una ancho/alto para cualquier imagen desplegada aquí de 206x47 píxeles.

                            diff --git a/pandora_console/include/help/es/help_date_format.php b/pandora_console/include/help/es/help_date_format.php index 495e3cf002..9818ffb1db 100644 --- a/pandora_console/include/help/es/help_date_format.php +++ b/pandora_console/include/help/es/help_date_format.php @@ -159,7 +159,7 @@
        o Número de año en ISO-8601. Esto tiene el mismo valor que - Y, excepto que si el número ISO de semana (W) pertenece al año anterior o siguiente, se usa ese año + Y, excepto que si el número ISO de semana (W) pertenece al año anterior o siguiente, se usa ese año en su lugar Ejemplo: 1999 o 2003
        Z Desplazamiento de la zona horaria en segundos. El desplazamiento para las zonas horarias del - oeste de UTC es siempre negativo, y para las del este de UTC es siempre positivo.-43200 a 50400
        Data Status change
        12:001No12:001No
        12:051No12:051No
        12:100No12:100No
        12:111No12:111No
        12:161No12:161No
        12:210No12:210No
        12:220Yes12:220Yes
        diff --git a/pandora_console/include/help/es/help_ff_timeout.php b/pandora_console/include/help/es/help_ff_timeout.php index d41f1751fe..cd0145a437 100644 --- a/pandora_console/include/help/es/help_ff_timeout.php +++ b/pandora_console/include/help/es/help_ff_timeout.php @@ -17,34 +17,34 @@ Por ejemplo, un módulo asíncrono de tipo proc con un umbral de FF de 1 y un ti Data Status change - 12:00 - 1 - No + 12:00 + 1 + No - 12:05 - 0 - No + 12:05 + 0 + No - 12:20 - 0 - No + 12:20 + 0 + No - 12:25 - 1 - No + 12:25 + 1 + No - 12:45 - 0 - No + 12:45 + 0 + No - 12:50 - 0 - Yes + 12:50 + 0 + Yes diff --git a/pandora_console/include/help/es/help_field_match_snmp.php b/pandora_console/include/help/es/help_field_match_snmp.php index b4332e70ae..ed20dc4771 100755 --- a/pandora_console/include/help/es/help_field_match_snmp.php +++ b/pandora_console/include/help/es/help_field_match_snmp.php @@ -1,7 +1,7 @@

        Variable bindings/Data #1-20

        @@ -10,25 +10,25 @@ -

        Como hemos visto, se pueden almacenar hasta 20 variables. Estas variables no tienen por qué seguir un órden consecutivo. La posición que ocupa la variable se puede definir en el campo que precede su valor. Es decir, si nosotros queremos hacer una alerta que busque los valores “Uno” en la primera variable recibida en el trap, “tres” en la tercera variable recibida por el trap y lo mismo para Cinco y Siete, se configuraría como se puede ver más abajo:

        +

        Como hemos visto, se pueden almacenar hasta 20 variables. Estas variables no tienen por qué seguir un órden consecutivo. La posición que ocupa la variable se puede definir en el campo que precede su valor. Es decir, si nosotros queremos hacer una alerta que busque los valores “Uno” en la primera variable recibida en el trap, “tres” en la tercera variable recibida por el trap y lo mismo para Cinco y Siete, se configuraría como se puede ver más abajo:

        - + -

        Podemos hacer uso del valor de las variables con coincidencia en las macros _snmp_f1_ .. _snmp_f7_ de forma que al definir la alerta, la acción nos permite usar esas macros:

        +

        Podemos hacer uso del valor de las variables con coincidencia en las macros _snmp_f1_ .. _snmp_f7_ de forma que al definir la alerta, la acción nos permite usar esas macros:

        - + -

        Aquí tenemos un ejemplo de trap con que el se disparará la alerta:

        +

        Aquí tenemos un ejemplo de trap con que el se disparará la alerta:

        - + -

        La alerta generada, un evento de auditoria tiene este texto:

        +

        La alerta generada, un evento de auditoria tiene este texto:

        SNMP Alert of 192.168.5.2 with OID .1.3.6.1.4.1.2789.2005 Varbind 100: “cien” Varbind 3: “tres” Varbind 20: “veinte” Varbind 60: “sesenta”

        diff --git a/pandora_console/include/help/es/help_gis_map_builder.php b/pandora_console/include/help/es/help_gis_map_builder.php index 3e303be97a..5abae44f56 100644 --- a/pandora_console/include/help/es/help_gis_map_builder.php +++ b/pandora_console/include/help/es/help_gis_map_builder.php @@ -7,7 +7,7 @@

        -Esta página muestra una lista de los mapas definidos, y le permite editar, borrar o ver cualquiera de ellos. También está instalado en está página el mapa por defecto de . +Esta página muestra una lista de los mapas definidos, y le permite editar, borrar o ver cualquiera de ellos. También está instalado en está página el mapa por defecto de .

        @@ -22,11 +22,11 @@ Opciones:
        Nombre del Mapa
        Haga click en elNombre del Mapa que se corresponda con el mapa que quiere editar
        -
        "View")); ?>Vista
        +
        'View']); ?>Vista
        Haga click en icono de visualizar para visualizar el mapa.
        Botón radio por defecto
        Haga click en el botón radio que se corresponda con el mapa que quiere por defecto para instalar mapa por defecto
        -
        "Delete")); ?> Eliminar
        +
        'Delete']); ?> Eliminar
        Haga click en el botón de eliminar para eliminar el mapa
        Crear botón
        Haga click en el Botón de Crear para crear un mapa nuevo
        diff --git a/pandora_console/include/help/es/help_gis_setup_map_connection.php b/pandora_console/include/help/es/help_gis_setup_map_connection.php index b7813269d9..fd9dd10106 100644 --- a/pandora_console/include/help/es/help_gis_setup_map_connection.php +++ b/pandora_console/include/help/es/help_gis_setup_map_connection.php @@ -11,7 +11,7 @@ En esta sección, es donde el administrador puede configurar una conexi

        Tipos de conexión

        -Ahora mismo, soporta tres tipos de conexiones: +Ahora mismo, soporta tres tipos de conexiones: OpenStreetMap, Google Maps e imágenes estáticas.

        Open Street Maps

        diff --git a/pandora_console/include/help/es/help_gis_tab.php b/pandora_console/include/help/es/help_gis_tab.php index 7968c7403e..af120e6995 100644 --- a/pandora_console/include/help/es/help_gis_tab.php +++ b/pandora_console/include/help/es/help_gis_tab.php @@ -1,6 +1,7 @@

        Agent GIS view

        diff --git a/pandora_console/include/help/es/help_graph_builder.php b/pandora_console/include/help/es/help_graph_builder.php index 659e564ff5..a1d6aafa17 100644 --- a/pandora_console/include/help/es/help_graph_builder.php +++ b/pandora_console/include/help/es/help_graph_builder.php @@ -1,7 +1,7 @@

        Editor gráficos

        diff --git a/pandora_console/include/help/es/help_graph_editor.php b/pandora_console/include/help/es/help_graph_editor.php index 68773cd925..c645c349a9 100644 --- a/pandora_console/include/help/es/help_graph_editor.php +++ b/pandora_console/include/help/es/help_graph_editor.php @@ -1,7 +1,7 @@

        Editor de items

        diff --git a/pandora_console/include/help/es/help_graph_view.php b/pandora_console/include/help/es/help_graph_view.php index abfe0b705d..f2f31b35a2 100644 --- a/pandora_console/include/help/es/help_graph_view.php +++ b/pandora_console/include/help/es/help_graph_view.php @@ -1,7 +1,7 @@

        Vista de graficas

        diff --git a/pandora_console/include/help/es/help_graphs.php b/pandora_console/include/help/es/help_graphs.php index af3f7ed9e9..485bf5ca1f 100644 --- a/pandora_console/include/help/es/help_graphs.php +++ b/pandora_console/include/help/es/help_graphs.php @@ -1,63 +1,63 @@ -

        Interpretar las gráficas en

        +

        Interpretar las gráficas en

        -

        Las gráficas en representan los valores que un módulo ha tenido a lo largo de un período.

        -

        Debido a la gran cantidad de datos que almacena, se ofrecen dos tipos diferentes de funcionalidad:

        +

        Las gráficas en representan los valores que un módulo ha tenido a lo largo de un período.

        +

        Debido a la gran cantidad de datos que almacena, se ofrecen dos tipos diferentes de funcionalidad:

        Gráficas Normales

        -images/help/chart_normal_sample.png" alt="regular chart sample" /> +regular chart sample

        Características generales

        Son gráficas que representan la información almacenada por el módulo a un nivel básico.

        @@ -98,7 +98,7 @@ div.img_title {
        Muestra puntos indicadores con la información de alertas disparadas en la parte superior.
        Mostrar percentil
        -
        Agrega una gráfica que indica la línea del percentil (configurable en opciones visuales generales de ).
        +
        Agrega una gráfica que indica la línea del percentil (configurable en opciones visuales generales de ).
        Comparación de tiempo (superpuesto)
        Muestra superpuesta la misma gráfica, pero en el período anterior al seleccionado. Por ejemplo, si solicitamos un período de una semana y activamos esta opción, la semana anterior a la elegida también se mostrará superpuesta.
        @@ -107,7 +107,7 @@ div.img_title {
        Muestra la misma gráfica, pero en el período anterior al seleccionado, en un area independiente. Por ejemplo, si solicitamos un período de una semana y activamos esta opción, la semana anterior a la elegida también se mostrará.
        Mostrar gráfica de desconocidos
        -
        Muestra cajas en sombreado gris cubriendo los períodos en que no puede garantizar el estado del módulo, ya sea por pérdida de datos, desconexión de un agente software, etc.
        +
        Muestra cajas en sombreado gris cubriendo los períodos en que no puede garantizar el estado del módulo, ya sea por pérdida de datos, desconexión de un agente software, etc.
        Mostrar gráfica de escala completa (TIP)
        Cambia el modo de pintado de "normal" a "TIP". En este modo, las gráficas mostrarán datos reales en vez de aproximaciones, por lo que el tiempo que emplearán para su generación será mayor. Podrá encontrar información más detallada de este tipo de gráficas en el siguiente apartado.
        @@ -122,7 +122,7 @@ div.img_title {

        Gráficas TIP

        -images/help/chart_tip_sample.png" alt="TIP chart sample" /> +TIP chart sample

        Características generales

        Son gráficas que representan datos reales.

        @@ -132,10 +132,10 @@ div.img_title {

        Ejemplos de resolución ofrecidas por metodos normal y TIP:

        Ejemplo de gráfica normal en intervalo desconocido
        -images/help/chart_normal_detail.png" alt="TIP chart detail" /> +TIP chart detail
        Ejemplo de gráfica TIP en intervalo desconocido
        -images/help/chart_tip_detail.png" alt="TIP chart detail" /> +TIP chart detail
        diff --git a/pandora_console/include/help/es/help_history_database.php b/pandora_console/include/help/es/help_history_database.php index 6741a9e3a1..bdca998a88 100644 --- a/pandora_console/include/help/es/help_history_database.php +++ b/pandora_console/include/help/es/help_history_database.php @@ -5,7 +5,7 @@ ?>

        Base de datos de histórico

        -Una base de datos de histórico es una base de datos a la que se mueven datos antiguos de módulos para mejorar la respuesta de la base de datos principal de . Estos datos seguirán estando disponibles para la consola de de forma transparente al ver informes, gráficas de módulos etc. +Una base de datos de histórico es una base de datos a la que se mueven datos antiguos de módulos para mejorar la respuesta de la base de datos principal de . Estos datos seguirán estando disponibles para la consola de de forma transparente al ver informes, gráficas de módulos etc.

        CONFIGURANDO UNA BASE DE DATOS DE HISTÓRICO

        @@ -14,18 +14,18 @@ Para configurar una base de datos de histórico siga los siguientes pasos:
        1. Cree la nueva base de datos de histórico.

          -
        2. Cree las tablas necesarias en la nueva base de datos. Puede utilizar el script DB Tool incluido en la consola de : +
        3. Cree las tablas necesarias en la nueva base de datos. Puede utilizar el script DB Tool incluido en la consola de :

          cat pandoradb.sql | mysql -u user -p -D history_db

          -
        4. Dar los permisos necesarios para que el usuario de tenga acceso a la base de datos de histórico +
        5. Dar los permisos necesarios para que el usuario de tenga acceso a la base de datos de histórico

          Mysql Example: GRANT ALL PRIVILEGES ON pandora.* TO 'pandora'@'IP' IDENTIFIED BY 'password'

          -
        6. En la consola de vaya a Setup->History database y configure el host, port, database name, user y password de la nueva base de datos. +
        7. En la consola de vaya a Setup->History database y configure el host, port, database name, user y password de la nueva base de datos.


        - '550px')); ?> + '550px']); ?>

        Los datos con más días de antigüedad se moverán a la base de datos de histórico en bloques de Step filas, esperando Delay segundos entre un bloque y el siguiente para evitar sobrecargas.

        diff --git a/pandora_console/include/help/es/help_inventory_tab.php b/pandora_console/include/help/es/help_inventory_tab.php index 6daaa25946..591c1654a0 100644 --- a/pandora_console/include/help/es/help_inventory_tab.php +++ b/pandora_console/include/help/es/help_inventory_tab.php @@ -1,5 +1,6 @@

        El inventario te permite tener una lista completa de todos los @@ -11,27 +12,27 @@ servidores.

        A continuación se describen los campos que hay que completar para añadir un módulo de inventario.

      • -
          - Module: Combo donde se elige el módulo de inventario que - se quiere añadir. Sólo aparecerán los módulos cuyo Sistema - Operativo coincide con el del agente. -
        -
          - Target: IP o nombre del servidor del que se quiere sacar - el inventario. -
        -
          - Interval: Combo donde se elige el intervalo de tiempo en - que se ejecutará el módulo de inventario. -
        -
          - Username: Usuario que se usara para ejecutar el módulo de - inventario. -
        -
          - Password: Password del usuario que se usara para ejecutar - el módulo de inventario. -
        +
          + Module: Combo donde se elige el módulo de inventario que + se quiere añadir. Sólo aparecerán los módulos cuyo Sistema + Operativo coincide con el del agente. +
        +
          + Target: IP o nombre del servidor del que se quiere sacar + el inventario. +
        +
          + Interval: Combo donde se elige el intervalo de tiempo en + que se ejecutará el módulo de inventario. +
        +
          + Username: Usuario que se usara para ejecutar el módulo de + inventario. +
        +
          + Password: Password del usuario que se usara para ejecutar + el módulo de inventario. +
      • Una vez completado el formulario se pulsa en “Add” para que el módulo se añada a los módulos de inventario.
        diff --git a/pandora_console/include/help/es/help_ipam.php b/pandora_console/include/help/es/help_ipam.php index afe1647d39..c03158f6ec 100755 --- a/pandora_console/include/help/es/help_ipam.php +++ b/pandora_console/include/help/es/help_ipam.php @@ -73,13 +73,13 @@ Cada dirección tendrá un icono grande que nos aportará información:

        Cada dirección tendrá en la parte inferior derecha un enlace para editarla, si disponemos de privilegios suficientes. Así mismo, en la parte inferior izquierda, tendrá un pequeño icono indicando el sistema operativo asociado. En el caso de las direcciones desactivadas, el icono del sistema operativo se verá sustituido por el siguiente icono:



        Si hacemos click en el icono principal, se abrirá una ventana modal con toda la información de la IP, incluyendo agente y sistema operativo asociados, configuración y el seguimiento de cuando se creó, editó por el usuario o fue chequeado por el servidor por última vez. En esta vista también se podrá hacer un ping a dicha dirección*.

        -* El ping se realiza desde la máquina donde esté instalada la consola de . +* El ping se realiza desde la máquina donde esté instalada la consola de .

        Vista de edición

        Si se tienen los permisos suficientes se podrá acceder a la vista de edición, donde las IPs aparecerán mostradas en forma de lista. Se podrá filtrar para mostrar las direcciones deseadas, hacer cambios en ellas y actualizar todas a la vez.

        -Algunos campos, se rellenan automáticamente por el script de reconocimiento, como el nombre de host, el agente de asociado y el sistema operativo. Podemos definir estos campos como manuales* y editarlos.

        +Algunos campos, se rellenan automáticamente por el script de reconocimiento, como el nombre de host, el agente de asociado y el sistema operativo. Podemos definir estos campos como manuales* y editarlos.

        diff --git a/pandora_console/include/help/es/help_linked_map_status_calc.php b/pandora_console/include/help/es/help_linked_map_status_calc.php index 40c5682d7a..d74b08991f 100644 --- a/pandora_console/include/help/es/help_linked_map_status_calc.php +++ b/pandora_console/include/help/es/help_linked_map_status_calc.php @@ -7,30 +7,30 @@

        Por defecto

        - Calcula el estado a partir del estado de todos los elementos, como lo haría un agente. + Calcula el estado a partir del estado de todos los elementos, como lo haría un agente.

        Por peso

        - Calcula el estado de los elementos que tienen asignados una consola visual, un módulo o un agente en relación a un porcentaje de elementos configurado por el usuario. Este porcentaje es el que tiene que superar el número de elementos de un estado no normal respecto al número de elementos tenidos en cuenta en el cálculo para que el ese estado cambie. + Calcula el estado de los elementos que tienen asignados una consola visual, un módulo o un agente en relación a un porcentaje de elementos configurado por el usuario. Este porcentaje es el que tiene que superar el número de elementos de un estado no normal respecto al número de elementos tenidos en cuenta en el cálculo para que el ese estado cambie.

        - Por ejemplo, dado un elemento con un porcentaje del 50% y una consola visual enlazada con 5 elementos: + Por ejemplo, dado un elemento con un porcentaje del 50% y una consola visual enlazada con 5 elementos:

          -
        • 1 critical, 1 warning y 3 normal -> Estado normal.
        • -
        • 2 critical, 2 warning y 1 normal -> Estado normal.
        • -
        • 1 critical, 3 warning y 1 normal -> Estado warning.
        • -
        • 3 critical, 1 warning y 1 normal -> Estado critical.
        • -
        • 1 critical, 1 warning y 3 unknown -> Estado unknown.
        • +
        • 1 critical, 1 warning y 3 normal -> Estado normal.
        • +
        • 2 critical, 2 warning y 1 normal -> Estado normal.
        • +
        • 1 critical, 3 warning y 1 normal -> Estado warning.
        • +
        • 3 critical, 1 warning y 1 normal -> Estado critical.
        • +
        • 1 critical, 1 warning y 3 unknown -> Estado unknown.

        - Si varios estados superan el peso, la prioridad es igual que en el resto de cálculo de estados (critical > warning > unknown). Si no hay elementos para realizar el cálculo, el estado pasa a ser unknown. + Si varios estados superan el peso, la prioridad es igual que en el resto de cálculo de estados (critical > warning > unknown). Si no hay elementos para realizar el cálculo, el estado pasa a ser unknown.

        Por elementos críticos

        - Calcula el estado usando los elementos en estado critical y los porcentajes de los umbrales definidos por el usuario. Si el número de los elementos en estado critical respecto al número de elementos tenidos en cuenta en el cálculo supera el porcentaje asignado como warning, el estado pasa a ser warning. Lo mismo para el porcentaje asignado como critical, que además tiene preferencia. + Calcula el estado usando los elementos en estado critical y los porcentajes de los umbrales definidos por el usuario. Si el número de los elementos en estado critical respecto al número de elementos tenidos en cuenta en el cálculo supera el porcentaje asignado como warning, el estado pasa a ser warning. Lo mismo para el porcentaje asignado como critical, que además tiene preferencia.

        diff --git a/pandora_console/include/help/es/help_local_component.php b/pandora_console/include/help/es/help_local_component.php index 06c8c3c888..9678a18158 100644 --- a/pandora_console/include/help/es/help_local_component.php +++ b/pandora_console/include/help/es/help_local_component.php @@ -1,7 +1,7 @@

        Componente local

        diff --git a/pandora_console/include/help/es/help_macros.php b/pandora_console/include/help/es/help_macros.php index 962b6b3445..293b3b0ad1 100755 --- a/pandora_console/include/help/es/help_macros.php +++ b/pandora_console/include/help/es/help_macros.php @@ -9,9 +9,9 @@ Se pueden configurar macros en la ejecución del módulo (module_exec) o los par

        Cada macro tiene 3 parámetros:
          -
        • Descripción
        • -
        • Valor por defecto (opcional)
        • -
        • Ayuda (opcional)
        • +
        • Descripción
        • +
        • Valor por defecto (opcional)
        • +
        • Ayuda (opcional)
        Por ejemplo, para configurar un módulo que devuelva el número de procesos @@ -26,9 +26,9 @@ ps -A | grep _field1_ | wc -l Y configurar los parámetros de la macro de la siguiente manera:
          -
        • Descripción: Proceso
        • -
        • Valor por defecto: apache2
        • -
        • Ayuda: Nombre o subcadena de los procesos en ejecución contados por el módulo
        • +
        • Descripción: Proceso
        • +
        • Valor por defecto: apache2
        • +
        • Ayuda: Nombre o subcadena de los procesos en ejecución contados por el módulo
        Cuando configuremos el módulo a partir de este componente, aparecerá un campo de texto "Proceso" diff --git a/pandora_console/include/help/es/help_macros_visual_maps.php b/pandora_console/include/help/es/help_macros_visual_maps.php index e373d7417b..ef6277b8fd 100644 --- a/pandora_console/include/help/es/help_macros_visual_maps.php +++ b/pandora_console/include/help/es/help_macros_visual_maps.php @@ -9,11 +9,11 @@ Es posible introducir una macro en el cuadro de texto al editar un elemento de l

        Lista de macros de consolas visuales:
          -
        • _date_ : Muestra la fecha usando el formato local del PHP.
        • -
        • _time_ : Muestra la hora usando el formato local del PHP.
        • -
        • _agent_ : Muestra el alias del agente seleccionado.
        • -
        • _module_ : Muestra el nombre del módulo seleccionado.
        • -
        • _agentdescription_ : Muestra la descripción del agente seleccionado.
        • -
        • _address_ : Muestra la dirección ip del agente seleccionado.
        • -
        • _moduledescription_ : Muestra la descripción del módulo seleccionado.
        • +
        • _date_ : Muestra la fecha usando el formato local del PHP.
        • +
        • _time_ : Muestra la hora usando el formato local del PHP.
        • +
        • _agent_ : Muestra el alias del agente seleccionado.
        • +
        • _module_ : Muestra el nombre del módulo seleccionado.
        • +
        • _agentdescription_ : Muestra la descripción del agente seleccionado.
        • +
        • _address_ : Muestra la dirección ip del agente seleccionado.
        • +
        • _moduledescription_ : Muestra la descripción del módulo seleccionado.
        \ No newline at end of file diff --git a/pandora_console/include/help/es/help_main_help.php b/pandora_console/include/help/es/help_main_help.php index b5b0e1da1d..91a37478c1 100644 --- a/pandora_console/include/help/es/help_main_help.php +++ b/pandora_console/include/help/es/help_main_help.php @@ -3,10 +3,10 @@ * @package Include/help/en */ ?> -

        - Índice de la ayuda

        +

        - Índice de la ayuda

        Introdución

        -Esta es la ayuda online para la consola de . Esta ayuda es -en el mejor de los casos-, simplemente una ayuda contextual breve, no pretende enseñar en detalle como usar . La documentación oficial de es larga, y probablemente no es necesario leerla entera, pero en cualquier caso, es importante echarle un buen vistazo. +Esta es la ayuda online para la consola de . Esta ayuda es -en el mejor de los casos-, simplemente una ayuda contextual breve, no pretende enseñar en detalle como usar . La documentación oficial de es larga, y probablemente no es necesario leerla entera, pero en cualquier caso, es importante echarle un buen vistazo.

        Descargue la documentación oficial diff --git a/pandora_console/include/help/es/help_manage_alert_list.php b/pandora_console/include/help/es/help_manage_alert_list.php index a3071d9408..483101f333 100644 --- a/pandora_console/include/help/es/help_manage_alert_list.php +++ b/pandora_console/include/help/es/help_manage_alert_list.php @@ -6,7 +6,7 @@

        Alerts

        -Las Alertas en reacionan a un valor "fuera de rango" de un módulo. La alerta consiste en enviar un e-mail o un SMS al administrador, enviando un trap SNMP, escribir el indcidenete en el log del sistema en el fichero de log de , etc. Basicamente, una alerta puede ser cualquier cosa que pueda ser disparada por un script configurado en el Sistema Operativo donde los servidores de se ejecutan. +Las Alertas en reacionan a un valor "fuera de rango" de un módulo. La alerta consiste en enviar un e-mail o un SMS al administrador, enviando un trap SNMP, escribir el indcidenete en el log del sistema en el fichero de log de , etc. Basicamente, una alerta puede ser cualquier cosa que pueda ser disparada por un script configurado en el Sistema Operativo donde los servidores de se ejecutan.

        @@ -14,10 +14,10 @@ Cuando una alerta es creada los siguiente campos deben de rellenarse:

          -
        • Agent name: El nombre del agente asociado a la alarma.
        • -
        • Module: La alerta recogerá el valor del módulo y comprobará si está "fuera de rango". En caso afirmativo creará un evento (sending, e-mail, etc.).
        • -
        • Template: Alertas con todos los parámetros predefinidos. Son usadas para hacer más sencilla la gestión de las alertas porel administrador.
        • -
        • Action: Permite elegir entre todas las alertas que están configuradas. La acción seleccionada será añadida a la acción definida por el template.
        • -
        • Threshold: Define el intervalo de tiempo en el que se garantiza que una alerta no va a ser disparada más veces que el número fijado en el número máximo de alertas. - +
        • Agent name: El nombre del agente asociado a la alarma.
        • +
        • Module: La alerta recogerá el valor del módulo y comprobará si está "fuera de rango". En caso afirmativo creará un evento (sending, e-mail, etc.).
        • +
        • Template: Alertas con todos los parámetros predefinidos. Son usadas para hacer más sencilla la gestión de las alertas porel administrador.
        • +
        • Action: Permite elegir entre todas las alertas que están configuradas. La acción seleccionada será añadida a la acción definida por el template.
        • +
        • Threshold: Define el intervalo de tiempo en el que se garantiza que una alerta no va a ser disparada más veces que el número fijado en el número máximo de alertas. +
        diff --git a/pandora_console/include/help/es/help_manage_alerts.php b/pandora_console/include/help/es/help_manage_alerts.php index 58cebfeff4..3f9358bc84 100644 --- a/pandora_console/include/help/es/help_manage_alerts.php +++ b/pandora_console/include/help/es/help_manage_alerts.php @@ -5,25 +5,25 @@ ?>

        Alertas

        -Las alertas en reaccionan ante un valor «fuera de rango». La alerta puede consistir del envío de un correo-e o un SMS al administrador, enviar un trap SNMP, escribir un incidente en el fichero log del sistema o en el log de , etc. Básicamente, una alerta puede ser cualquier cosa que se pueda dispoarar desde un script configurado en el Sistema Operativo donde se ejecuta. +Las alertas en reaccionan ante un valor «fuera de rango». La alerta puede consistir del envío de un correo-e o un SMS al administrador, enviar un trap SNMP, escribir un incidente en el fichero log del sistema o en el log de , etc. Básicamente, una alerta puede ser cualquier cosa que se pueda dispoarar desde un script configurado en el Sistema Operativo donde se ejecuta.

        Los valores «_field1_», «_field2_» y «_field3_» de las alertas personalizadsa se usan para construir el comando de línea que se ejecutará.

        Cuando se crea una nueva alerta, se deben rellenar los siguientes campos:
          -
        • Nombre de la alerta: El nombre de la alerta. Es importante describir correctamente su funcionalidad, pero brevemente, por ejemplo: «Log de comm.»".
        • -
        • Comando: Comando que la alerta ejecutará, es el campo más importante al definir la alerta. Note que se usan las macros _field1, _field2_, y _field3_ para reemplazar los parámetros configurados en la definición de la alerta. De esta manera se construye la ejecución del comando disparado por la alerta. Al definir una alerta, debería comprobar la ejecución correcta de la misma, y también que el resultado es el esperado (envío de correo-e, generación de una entrada en el fichero log, etc) en la línea de comandos.
        • -
        • Descripción: Descripción detallada de la alerta, opcional.
        • +
        • Nombre de la alerta: El nombre de la alerta. Es importante describir correctamente su funcionalidad, pero brevemente, por ejemplo: «Log de comm.»".
        • +
        • Comando: Comando que la alerta ejecutará, es el campo más importante al definir la alerta. Note que se usan las macros _field1, _field2_, y _field3_ para reemplazar los parámetros configurados en la definición de la alerta. De esta manera se construye la ejecución del comando disparado por la alerta. Al definir una alerta, debería comprobar la ejecución correcta de la misma, y también que el resultado es el esperado (envío de correo-e, generación de una entrada en el fichero log, etc) en la línea de comandos.
        • +
        • Descripción: Descripción detallada de la alerta, opcional.
        El conjunto completo de macros que se pueden usar en las alertas es el siguiente:
          -
        • _field1_: Generalmente usado como el nombre de usuario, el número de teléfono, campo para el destinatario del correo-e.
        • -
        • _field2_: Generalmente usado como una breve descripción de eventos, o el asunto para un correo-e.
        • -
        • _field3_: Una explicación completa para el evento, se puede usar como el campo de texto para un correo-e o un SMS.
        • -
        • _agent_: Nombre completo del agente.
        • -
        • _timestamp_: Una representación estándar de la fecha y hora. Automáticamente reemplazado cuando se ejecuta la alerta.
        • -
        • _data_: El valor del dato que dispara la alerta.
        • +
        • _field1_: Generalmente usado como el nombre de usuario, el número de teléfono, campo para el destinatario del correo-e.
        • +
        • _field2_: Generalmente usado como una breve descripción de eventos, o el asunto para un correo-e.
        • +
        • _field3_: Una explicación completa para el evento, se puede usar como el campo de texto para un correo-e o un SMS.
        • +
        • _agent_: Nombre completo del agente.
        • +
        • _timestamp_: Una representación estándar de la fecha y hora. Automáticamente reemplazado cuando se ejecuta la alerta.
        • +
        • _data_: El valor del dato que dispara la alerta.
        diff --git a/pandora_console/include/help/es/help_map_builder.php b/pandora_console/include/help/es/help_map_builder.php index 336823666d..d0d508b3a3 100644 --- a/pandora_console/include/help/es/help_map_builder.php +++ b/pandora_console/include/help/es/help_map_builder.php @@ -7,23 +7,23 @@ Para crear un mapa primero debe rellenar el formulario proporcionando:
          -
        • Un nombre
        • -
        • Un grupo
        • -
        • Una imagen de fondo
        • -
        • Un tamaño (anchura/altura)
        • +
        • Un nombre
        • +
        • Un grupo
        • +
        • Una imagen de fondo
        • +
        • Un tamaño (anchura/altura)
        Una vez que lo haya rellenado, pusle «Actualizar» para que se cargue el mapa.

        Para añadir elementos al mapa, vaya al formulario debajo de la imagen de fondo y rellénelo, proporcionando para cada elemento:
          -
        • Una etiqueta y un color para ella
        • -
        • Un tipo: una imagen estática de tres colores o un módulo de gráfico
        • -
        • El agente del que provvendrán los datos
        • -
        • El módulo del agente
        • -
        • El periodo de actualización
        • -
        • La imagen para el elemento
        • -
        • Un padre, en caso de que quiera que el elemento sea hijo (esté enlazado) con otro elemento
        • -
        • Un mapa enlazado, en caso de que quiera enlazar el mapa con otro.
        • +
        • Una etiqueta y un color para ella
        • +
        • Un tipo: una imagen estática de tres colores o un módulo de gráfico
        • +
        • El agente del que provvendrán los datos
        • +
        • El módulo del agente
        • +
        • El periodo de actualización
        • +
        • La imagen para el elemento
        • +
        • Un padre, en caso de que quiera que el elemento sea hijo (esté enlazado) con otro elemento
        • +
        • Un mapa enlazado, en caso de que quiera enlazar el mapa con otro.
        Para editar las propiedades de un elemento ya creado, simplemente arrastre el elemento al formulario «EDITOR DE ELEMENTOS» y suéltelo allí, el formulario cargará las propiedades del elemento.

        diff --git a/pandora_console/include/help/es/help_metaconsole_agent_cache.php b/pandora_console/include/help/es/help_metaconsole_agent_cache.php index 454934df50..658a29053b 100644 --- a/pandora_console/include/help/es/help_metaconsole_agent_cache.php +++ b/pandora_console/include/help/es/help_metaconsole_agent_cache.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_module_interval.php b/pandora_console/include/help/es/help_module_interval.php index e3b9b876f9..f8b1d2785d 100644 --- a/pandora_console/include/help/es/help_module_interval.php +++ b/pandora_console/include/help/es/help_module_interval.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_module_interval_factor.php b/pandora_console/include/help/es/help_module_interval_factor.php index d2902680bf..e961b1ca52 100644 --- a/pandora_console/include/help/es/help_module_interval_factor.php +++ b/pandora_console/include/help/es/help_module_interval_factor.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_module_linking.php b/pandora_console/include/help/es/help_module_linking.php index 9ecfff1275..d66c8c8183 100644 --- a/pandora_console/include/help/es/help_module_linking.php +++ b/pandora_console/include/help/es/help_module_linking.php @@ -1,7 +1,7 @@

        Modulos linkados

        diff --git a/pandora_console/include/help/es/help_module_macros.php b/pandora_console/include/help/es/help_module_macros.php index a65ebf7ee7..d546fc09c4 100644 --- a/pandora_console/include/help/es/help_module_macros.php +++ b/pandora_console/include/help/es/help_module_macros.php @@ -4,73 +4,73 @@ */ ?>

        Macros de módulo

        -

        - Se puede definir cualquier número de macros de módulo. El formato recomendado para los nombres de macros es el siguiente: +

        + Se puede definir cualquier número de macros de módulo. El formato recomendado para los nombres de macros es el siguiente:

        -	_macroname_
        +    _macroname_
         

        - Por ejemplo: + Por ejemplo:

          -
        1. - _technology_ -
        2. -
        3. - _modulepriority_ -
        4. -
        5. - _contactperson_ -
        6. +
        7. + _technology_ +
        8. +
        9. + _modulepriority_ +
        10. +
        11. + _contactperson_ +

        - Estas macros se pueden utilizar en las alertas de módulos. + Estas macros se pueden utilizar en las alertas de módulos.

        Si el módulo es de tipo analisis de módulo web:

        - Las macros dinámicas tendrán un formato especial que empieza por @ y tendrán estas posibles sustituciones: + Las macros dinámicas tendrán un formato especial que empieza por @ y tendrán estas posibles sustituciones:

          -
        1. - @DATE_FORMAT (fecha/hora actual con formato definido por el usuario) -
        2. -
        3. - @DATE_FORMAT_nh (horas) -
        4. -
        5. - @DATE_FORMAT_nm (minutos) -
        6. -
        7. - @DATE_FORMAT_nd (días) -
        8. -
        9. - @DATE_FORMAT_ns (segundos) -
        10. -
        11. - @DATE_FORMAT_nM (mes) -
        12. -
        13. - @DATE_FORMAT_nY (años) -
        14. +
        15. + @DATE_FORMAT (fecha/hora actual con formato definido por el usuario) +
        16. +
        17. + @DATE_FORMAT_nh (horas) +
        18. +
        19. + @DATE_FORMAT_nm (minutos) +
        20. +
        21. + @DATE_FORMAT_nd (días) +
        22. +
        23. + @DATE_FORMAT_ns (segundos) +
        24. +
        25. + @DATE_FORMAT_nM (mes) +
        26. +
        27. + @DATE_FORMAT_nY (años) +

        - Donde “n” puede ser un numero sin signo (positivo) o negativo. + Donde “n” puede ser un numero sin signo (positivo) o negativo.

        - Y FORMAT sigue el standard de strftime de perl: - http://search.cpan.org/~dexter/POSIX-strftime-GNU-0.02/lib/POSIX/strftime/GNU.pm + Y FORMAT sigue el standard de strftime de perl: + http://search.cpan.org/~dexter/POSIX-strftime-GNU-0.02/lib/POSIX/strftime/GNU.pm

        - Ejemplos: + Ejemplos:

        -	@DATE_%Y-%m-%d %H:%M:%S
        -	@DATE_%H:%M:%S_300s
        -	@DATE_%H:%M:%S_-1h
        +    @DATE_%Y-%m-%d %H:%M:%S
        +    @DATE_%H:%M:%S_300s
        +    @DATE_%H:%M:%S_-1h
         
        \ No newline at end of file diff --git a/pandora_console/include/help/es/help_module_tokens.php b/pandora_console/include/help/es/help_module_tokens.php index e48292734c..bbf4ac7e25 100644 --- a/pandora_console/include/help/es/help_module_tokens.php +++ b/pandora_console/include/help/es/help_module_tokens.php @@ -1,5 +1,6 @@

        Definición de los módulos

        @@ -21,7 +22,7 @@ module_end
        Existen diferentes tipos de módulos, con diferentes subopciones, pero todos los módulos tienen una estructura similar a esta. Los parámetros module_interval y module_description son opcionales, y el resto completamente obligatorios.

        Elementos comunes de todos los módulos

        -

        +

        module_begin

        Define el inicio del módulo. @@ -241,7 +242,7 @@ module_end

        Watchdog de procesos

        -Un Watchdog es un sistema que permite actuar inmediatamente ante la caída de un proceso, generalmente, levantando el proceso que se ha caído. El agente de Windows de , puede actuar como Watchdog ante la caída de un proceso, a esto le llamamos modo watchdog para procesos: +Un Watchdog es un sistema que permite actuar inmediatamente ante la caída de un proceso, generalmente, levantando el proceso que se ha caído. El agente de Windows de , puede actuar como Watchdog ante la caída de un proceso, a esto le llamamos modo watchdog para procesos:

        Dado que ejecutar un proceso puede requerir algunos parámetros, hay algunas opciones adicionales de configuración para este tipo de módulos. Es importante destacar que el modo watchdog solo funciona cuando el tipo de módulo es asíncrono. Veamos un ejemplo de configuración de un module_proc con watchdog:

        @@ -264,7 +265,7 @@ Esta es la definición de los parámetros adicionales para module_proc con watch

        module_startdelay: Número de milisegundos que el módulo esperará antes de lanzar el proceso por primera vez. Si el proceso tarda mucho en arrancar, es bueno decirle al agente por medio de este parámetro que "espere" antes de empezar a comprobar de nuevo si el proceso se ha levantado. En este ejemplo espera 3 segundos.

        - module_retrydelay: Similar al anterior pero para caídas/reintentos posteriores, después de detectar una caída. Cuando detecta una caída, relanza el proceso, espera el nº de milisegundos indicados en este parámetro y vuelve a comprobar si el proceso ya esta levantado. + module_retrydelay: Similar al anterior pero para caídas/reintentos posteriores, después de detectar una caída. Cuando detecta una caída, relanza el proceso, espera el nº de milisegundos indicados en este parámetro y vuelve a comprobar si el proceso ya esta levantado.

        module_cpuproc 'process'

        diff --git a/pandora_console/include/help/es/help_module_type.php b/pandora_console/include/help/es/help_module_type.php index d32f81b69c..947b8ddd5a 100644 --- a/pandora_console/include/help/es/help_module_type.php +++ b/pandora_console/include/help/es/help_module_type.php @@ -7,25 +7,25 @@ La siguiente lista describe los tipos de módulos:
          -
        • async_data: Datos numéricos asíncronos
        • -
        • async_inc: Datos incrementales asíncronos
        • -
        • async_proc: Datos asíncronos booleanos
        • -
        • async_string: Datos asíncronos tipo cadena
        • -
        • generic_data: Módulo genérico para adquirir datos numéricos
        • -
        • generic_data_inc: Módulo genérico para adquirir datos numéricos incrementales
        • -
        • generic_data_string: Módulo genérico para adquirir datos alfanuméricos
        • -
        • generic_proc: Módulo genérico para adquirir datos booleanos
        • -
        • image_jpg: Imagen JPG
        • -
        • image_png: Imagen PNG
        • -
        • keep_alive: KeepAlive
        • -
        • remote_icmp: Agente de red remoto ICMP (latencia)
        • -
        • remote_icmp_proc: Agente de red remoto ICMP, datos booleanos
        • -
        • remote_snmp: Agente de red remoto SNMP, datos numéricos
        • -
        • remote_snmp_inc: Agente de red remoto SNMP, datos incrementales
        • -
        • remote_snmp_proc: Agente de red remoto SNMP, datos booleanos
        • -
        • remote_snmp_string: Agente de red remoto SNMP, datos alfanuméricos
        • -
        • remote_tcp: Agente de red remoto TCP, datos numéricos
        • -
        • remote_tcp_inc: Agente de red remoto TCP, incremental data
        • -
        • remote_tcp_proc: Agente de red remoto TCP, datos booleanos
        • -
        • remote_tcp_string: Agente de red remoto TCP, datos alfanuméricos
        • +
        • async_data: Datos numéricos asíncronos
        • +
        • async_inc: Datos incrementales asíncronos
        • +
        • async_proc: Datos asíncronos booleanos
        • +
        • async_string: Datos asíncronos tipo cadena
        • +
        • generic_data: Módulo genérico para adquirir datos numéricos
        • +
        • generic_data_inc: Módulo genérico para adquirir datos numéricos incrementales
        • +
        • generic_data_string: Módulo genérico para adquirir datos alfanuméricos
        • +
        • generic_proc: Módulo genérico para adquirir datos booleanos
        • +
        • image_jpg: Imagen JPG
        • +
        • image_png: Imagen PNG
        • +
        • keep_alive: KeepAlive
        • +
        • remote_icmp: Agente de red remoto ICMP (latencia)
        • +
        • remote_icmp_proc: Agente de red remoto ICMP, datos booleanos
        • +
        • remote_snmp: Agente de red remoto SNMP, datos numéricos
        • +
        • remote_snmp_inc: Agente de red remoto SNMP, datos incrementales
        • +
        • remote_snmp_proc: Agente de red remoto SNMP, datos booleanos
        • +
        • remote_snmp_string: Agente de red remoto SNMP, datos alfanuméricos
        • +
        • remote_tcp: Agente de red remoto TCP, datos numéricos
        • +
        • remote_tcp_inc: Agente de red remoto TCP, incremental data
        • +
        • remote_tcp_proc: Agente de red remoto TCP, datos booleanos
        • +
        • remote_tcp_string: Agente de red remoto TCP, datos alfanuméricos
        diff --git a/pandora_console/include/help/es/help_network_component.php b/pandora_console/include/help/es/help_network_component.php index 90ffef2eab..c03c9e652a 100644 --- a/pandora_console/include/help/es/help_network_component.php +++ b/pandora_console/include/help/es/help_network_component.php @@ -12,6 +12,6 @@ La caja de selección del componente de red le permite seleccionar una plantilla Para ello, seleccione la plantilla que quiere, pulse en «Obtener datos» y espere unos segundos hasta que se rellene la información. Dependiendo de la plantilla, algunos campos se rellenarán y otros no, por ejemplo:

          -
        • «Puerto TCP» se rellenará para «Check FTP Server» pero «SNMP OID» no
        • -
        • «Puerto TCP» no se rellenará para «Catalyst CPU Usage (5min)» pero sí lo hará «SNMP OID».
        • +
        • «Puerto TCP» se rellenará para «Check FTP Server» pero «SNMP OID» no
        • +
        • «Puerto TCP» no se rellenará para «Catalyst CPU Usage (5min)» pero sí lo hará «SNMP OID».
        diff --git a/pandora_console/include/help/es/help_network_map_enterprise.php b/pandora_console/include/help/es/help_network_map_enterprise.php index 6465ff8e28..a575f0a85b 100644 --- a/pandora_console/include/help/es/help_network_map_enterprise.php +++ b/pandora_console/include/help/es/help_network_map_enterprise.php @@ -1,7 +1,7 @@

        Mapas de red

        @@ -35,7 +35,7 @@

        Minimapa

        -

        El minimapa nos provee de una vista global que muestra toda la extensión del mapa, pero en una vista mucho mas pequeña, además que frente a la vista del mapa se muestra completamente todos los nodos pero sin estado y sin las relaciones. Excepto el punto ficticio de que se muestra en verde. Y además se muestra un recuadro rojo de la parte del mapa que se esta mostrando.

        +

        El minimapa nos provee de una vista global que muestra toda la extensión del mapa, pero en una vista mucho mas pequeña, además que frente a la vista del mapa se muestra completamente todos los nodos pero sin estado y sin las relaciones. Excepto el punto ficticio de que se muestra en verde. Y además se muestra un recuadro rojo de la parte del mapa que se esta mostrando.

        Se encuentra en la esquina superior izquierda, y se puede ocultar pulsando en el icono de la flecha.

        @@ -46,7 +46,7 @@

        Desde el menú contextual del mapa de red puedes realizar tareas mas complejas sobre el.

        Se muestra si hacemos click derecho en alguna sección del mapa vacía.

        - '550px')); ?> + '550px']); ?>

        Y las opciones disponibles son:

        @@ -60,19 +60,19 @@

        Desde el menú contextual del nodo puedes realizar tareas mas complejas sobre el.

        Se muestra si hacemos click derecho en algún nodo.

        - '550px')); ?> + '550px']); ?>

        Y las opciones disponibles son:

      • Mostrar una vista en detalle con datos del nodo. Además en esta vista podremos consultar sus interfaces (si las tiene), editar su nombre y su forma o ver que enlaces tiene disponibles para editarlos o borrarlos.
      • - '550px')); ?> + '550px']); ?>
      • Añadir un enlace entre interfaces. Con esto podremos enlazar dos módulos de interfaz entre si, o uno de ellos con otro agente. Primero seleccionamos el hijo de la unión y posteriormente el padre
      • - '550px')); ?> - '550px')); ?> - '550px')); ?> + '550px']); ?> + '550px']); ?> + '550px']); ?>
      • Definir un enlace padre-hijo entre agentes, siguiendo la misma metodología que con los enlaces de interfaz, primero se seleccionaría el hijo, y posteriormente, el padre.
      • - '550px')); ?> - '550px')); ?> + '550px']); ?> + '550px']); ?>
      • Eliminar el nodo seleccionado (y todos sus enlaces).
      • Creación de un mapa de red

        @@ -80,9 +80,9 @@

        Para la creación de un mapa de red puedes hacerlo como:

      • Despliegue de todos los agentes contenidos en un grupo.
      • - '550px')); ?> + '550px']); ?>
      • Creación de un mapa de red en blanco.
      • - '550px')); ?> + '550px']); ?>

        Vamos a hacer una vista rápida de los campos que tiene el formulario de creación (habrá muchos menos valores para la creación de un mapa vacío):

        @@ -98,7 +98,7 @@
      • Tarea de reconocimiento de origen: Nos permite seleccionar la tarea de reconocimiento para generar el mapa.
      • IP: Nos permite seleccionar la IP generar el mapa (solo generación por máscara ip).
      • Método de generación del mapa de red: el método de distribución de los nodos que formarán el mapa de red, por defecto es spring2, pero existen los siguientes:
      • -

        - Radial: en el cual todos los nodos se dispondrán alrededor del nodo ficticio que simboliza el .
        +

        - Radial: en el cual todos los nodos se dispondrán alrededor del nodo ficticio que simboliza el .
        - Circular: en el cual se dispondrá los nodos en círculos concentricos.
        - Flat: en el cual se dispondrá los nodos de forma arborescente.
        - spring1, spring2: son variaciones del Flat.
        diff --git a/pandora_console/include/help/es/help_no_hierarchy.php b/pandora_console/include/help/es/help_no_hierarchy.php index 2597ace754..e7e39aa214 100644 --- a/pandora_console/include/help/es/help_no_hierarchy.php +++ b/pandora_console/include/help/es/help_no_hierarchy.php @@ -13,17 +13,25 @@ Los permisos de un grupo se pueden extender a los hijos mediante la opción de c Como referencia para los ejemplos, se plantea una configuración con dos grupos padre "Applications" y "Databases" con dos hijos cada uno, "Development_Apps" y "Management_Apps" para el primero y "Databases_America" y "Databases_Asia" para el segundo. Ambos grupos padre están marcados para que se propague el ACL.

        - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

        En la vista de edición de usuario, si se añaden los siguientes perfiles:

        - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

        El usuario tendrá acceso a los grupos "Applications", "Development_Apps", "Management_Apps" y "Databases". @@ -33,9 +41,13 @@ El usuario tendrá acceso a los grupos "Applications", "Development_Apps", "Mana En cambio, si se añade un hijo de "Databases":

        - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

        Ahora el usuario podrá acceder a los grupos "Applications", "Development_Apps", "Management_Apps", "Databases" y "Databases_Asia", pero no a "Databases_America". diff --git a/pandora_console/include/help/es/help_planned_downtime.php b/pandora_console/include/help/es/help_planned_downtime.php index dd1d65a5d8..423c865332 100644 --- a/pandora_console/include/help/es/help_planned_downtime.php +++ b/pandora_console/include/help/es/help_planned_downtime.php @@ -12,5 +12,5 @@ Esta herramienta se usa para planear periodos de desconexión de la monitorizaci Es muy fácil de configurar, especifique la fecha y hora de inicio de la desconexión programada y la fecha hora del final. Después de rellenar los primeros campos, debe guardar la Desconexión programada y editarla, para establecer los agentes que se van a desconectar. También pued eeditar el resto de campos al editar la Desconexión programada.

        -Cuando una desconexión programada se inicia, automáticamente desactiva todos los agentes asignados a esa desconexión y no se procesa ningún dato ni alerta. Cuando la desconexión finaliza, activará todos los agentes asignados a la desconexión.No puede borrar o modificar una instancia de desconexión cuando está activada, debe esperar a que finalice anes de hacer cualquier otra cosa en esa instancia. Por supuesto puede activar manualmente cualquier agente usando el diálogo de configuración del agente. +Cuando una desconexión programada se inicia, automáticamente desactiva todos los agentes asignados a esa desconexión y no se procesa ningún dato ni alerta. Cuando la desconexión finaliza, activará todos los agentes asignados a la desconexión.No puede borrar o modificar una instancia de desconexión cuando está activada, debe esperar a que finalice anes de hacer cualquier otra cosa en esa instancia. Por supuesto puede activar manualmente cualquier agente usando el diálogo de configuración del agente.

        diff --git a/pandora_console/include/help/es/help_planned_downtime_time.php b/pandora_console/include/help/es/help_planned_downtime_time.php index c44a49c7ce..0f575282cf 100644 --- a/pandora_console/include/help/es/help_planned_downtime_time.php +++ b/pandora_console/include/help/es/help_planned_downtime_time.php @@ -8,8 +8,8 @@

        Ejecución única

        - El formato de la fecha debe ser año/mes/día y el del tiempo hora:minuto:segundo. - Se pueden crear paradas planificadas en fechas pasadas, siempre que el administrador de no haya deshabilitado esa opción. + El formato de la fecha debe ser año/mes/día y el del tiempo hora:minuto:segundo. + Se pueden crear paradas planificadas en fechas pasadas, siempre que el administrador de no haya deshabilitado esa opción.

        Ejecución periódica

        @@ -17,15 +17,15 @@

        Mensual

        - La parada se ejecutará cada mes, desde el día de inicio a la hora de inicio, hasta el día final a la hora final indicados. - El formato del tiempo debe ser hora:minuto:segundo y el día de inicio no puede ser menor al día final. - Para reflejar una parada que va más allá del último día del mes, habría que crear dos paradas, una que terminase el día 31 a las 23:59:59 y otra que empezase el día 1 a las 00:00:00. + La parada se ejecutará cada mes, desde el día de inicio a la hora de inicio, hasta el día final a la hora final indicados. + El formato del tiempo debe ser hora:minuto:segundo y el día de inicio no puede ser menor al día final. + Para reflejar una parada que va más allá del último día del mes, habría que crear dos paradas, una que terminase el día 31 a las 23:59:59 y otra que empezase el día 1 a las 00:00:00.

        Semanal

        - La parada se ejecutará cada día seleccionado, desde la hora de inicio a la hora final indicadas. - La hora de inicio no puede ser superior a la hora final. - Para reflejar una parada que va más allá de la última hora del día, habría que crear dos paradas, una que terminase a las 23:59:59 y otra que empezase a las 00:00:00 del día siguiente. + La parada se ejecutará cada día seleccionado, desde la hora de inicio a la hora final indicadas. + La hora de inicio no puede ser superior a la hora final. + Para reflejar una parada que va más allá de la última hora del día, habría que crear dos paradas, una que terminase a las 23:59:59 y otra que empezase a las 00:00:00 del día siguiente.

        \ No newline at end of file diff --git a/pandora_console/include/help/es/help_plugin_definition.php b/pandora_console/include/help/es/help_plugin_definition.php index 78203ab89b..b63aa7f003 100644 --- a/pandora_console/include/help/es/help_plugin_definition.php +++ b/pandora_console/include/help/es/help_plugin_definition.php @@ -5,21 +5,21 @@ ?>

        Registro de complementos

        -A diferencia del resto de componentes, de forma predeterminada no incluye ningún complemento pre-configurado, por lo tanto primero se deberá crear y configurar un complemento, para después añadírselo al módulo de un agente. No obstante sí incluye complementos en los directorios de instalación, pero como ya se ha dicho no están configurados en la base de datos. +A diferencia del resto de componentes, de forma predeterminada no incluye ningún complemento pre-configurado, por lo tanto primero se deberá crear y configurar un complemento, para después añadírselo al módulo de un agente. No obstante sí incluye complementos en los directorios de instalación, pero como ya se ha dicho no están configurados en la base de datos.

        -Para añadir un complemento existente a , ir a la sección de administración de la consola, y en ella, pulsar sobre Manage servers; después pulsar Manage plugins: +Para añadir un complemento existente a , ir a la sección de administración de la consola, y en ella, pulsar sobre Manage servers; después pulsar Manage plugins:

        Una vez en la pantalla de gestión de los complementos, pulsar el botón Create para crear un nuevo complemento, ya que no habrá ninguno.

        Rellenar el formulario de creación de complementos con los siguientes datos:

        - '550px')); ?> + '550px']); ?>

        Name
        Nombre del plugin, en este caso Nmap.

        Plugin type
        -Hay dos tipos de complementos, los estándar (standard) y los de tipo Nagios. Los complementos estándar son scripts que ejecutan acciones y admiten parámetros. Los complementos de Nagios son, como su nombre indica, complementos de Nagios que se pueden usar en . La diferencia estriba principalmente en que los plugins de nagios devuelven un error level para indicar si la prueba ha tenido éxito o no. +Hay dos tipos de complementos, los estándar (standard) y los de tipo Nagios. Los complementos estándar son scripts que ejecutan acciones y admiten parámetros. Los complementos de Nagios son, como su nombre indica, complementos de Nagios que se pueden usar en . La diferencia estriba principalmente en que los plugins de nagios devuelven un error level para indicar si la prueba ha tenido éxito o no.

        Si quiere usar un plugin de tipo nagios y quiere obtener un dato, no un estado (Bien/Mal), puede utilizar un plugin de tipo nagios en el modo "Standard".

        @@ -39,7 +39,7 @@ Descripción del complemento. Escribir una breve descripción, como por ejemplo: Es la ruta a donde está el comando del complemento. De forma predeterminada, si la instalación ha sido estándar, estarán en el directorio /usr/share/pandora_server/util/plugin/. Aunque puede ser cualquier ruta del sistema. Para este caso, escribir /usr/share/pandora_server/util/plugin/udp_nmap_plugin.sh en el campo.

        -El servidor de ejecutará ese script, por lo que éste debe tener permisos de acceso y de ejecución sobre él. +El servidor de ejecutará ese script, por lo que éste debe tener permisos de acceso y de ejecución sobre él.

        Plug-in parameters
        @@ -57,8 +57,9 @@ Cada macro tiene 3 campos:

        Ejemplo de la configuración de macros:

        - '550px')); ?> + '550px']); ?>

        Ejemplo de esta misma macro en el editor del módulo:

        - '550px')); ?> + '550px']); diff --git a/pandora_console/include/help/es/help_plugin_macros.php b/pandora_console/include/help/es/help_plugin_macros.php index 701d15f35e..5b4977b700 100644 --- a/pandora_console/include/help/es/help_plugin_macros.php +++ b/pandora_console/include/help/es/help_plugin_macros.php @@ -17,7 +17,7 @@ Las siguientes macros están disponibles:
      • _modulegroup_ : Nombre del grupo del módulo.
      • _moduledescription_: Descripcion del modulo.
      • _modulestatus_ : Estado del módulo.
      • -
      • _id_agent_: ID del agente, util para construir URL de acceso a la consola de .
      • +
      • _id_agent_: ID del agente, util para construir URL de acceso a la consola de .
      • _policy_: Nombre de la política a la que pertenece el módulo (si aplica).
      • _interval_ : Intervalo de la ejecución del módulo.
      • @@ -30,9 +30,9 @@ Hidden this macros because they cannot edit in the module form -->
      • _plugin_parameters_ : Parámetros del Plug-in del módulo.
      • -
      • _name_tag_ : Names of the tags associated to the module.
      • -
      • _email_tag_ : Emails associated to the module tags.
      • -
      • _phone_tag_ : Phone numbers associated to the module tags.
      • -
      • _moduletags_ : URLs associated to the module tags.
      • +
      • _name_tag_ : Nombre de los tags asociados al módulo.
      • +
      • _email_tag_ : Emails asociados a los tags de módulos.
      • +
      • _phone_tag_ : Teléfonos asociados a los tags de módulos.
      • +
      • _moduletags_ : URLs asociadas a los tags de módulos.
      • _agentcustomfield_n_: Campo personalizado número n del agente (eg. _agentcustomfield_9_).
      • diff --git a/pandora_console/include/help/es/help_plugin_parameters.php b/pandora_console/include/help/es/help_plugin_parameters.php index 3a63b58a34..ce4e9a414c 100644 --- a/pandora_console/include/help/es/help_plugin_parameters.php +++ b/pandora_console/include/help/es/help_plugin_parameters.php @@ -9,9 +9,9 @@ Este campo hace referencia a todos los parámetros que se le pueden pasar al com

        Éstos parámetros pueden ser:
          -
        • Un URL
        • -
        • Una ruta
        • -
        • Un fichero
        • -
        • Etc.
        • +
        • Un URL
        • +
        • Una ruta
        • +
        • Un fichero
        • +
        • Etc.
        Este campo es opcional y depende completamente del complemento. diff --git a/pandora_console/include/help/es/help_plugin_policy.php b/pandora_console/include/help/es/help_plugin_policy.php index a4e190f7fe..d0d0aec84d 100644 --- a/pandora_console/include/help/es/help_plugin_policy.php +++ b/pandora_console/include/help/es/help_plugin_policy.php @@ -1,7 +1,7 @@

        Plugins de agente

        diff --git a/pandora_console/include/help/es/help_policy_agent.php b/pandora_console/include/help/es/help_policy_agent.php index 1c411de6a8..eb85895381 100644 --- a/pandora_console/include/help/es/help_policy_agent.php +++ b/pandora_console/include/help/es/help_policy_agent.php @@ -1,7 +1,7 @@

        Agentes de la politica

        diff --git a/pandora_console/include/help/es/help_policy_queue.php b/pandora_console/include/help/es/help_policy_queue.php index 168af443e8..3dbc546a14 100644 --- a/pandora_console/include/help/es/help_policy_queue.php +++ b/pandora_console/include/help/es/help_policy_queue.php @@ -1,7 +1,7 @@

        Cola

        diff --git a/pandora_console/include/help/es/help_prediction_date.php b/pandora_console/include/help/es/help_prediction_date.php index 03e43162f5..82eef89c0c 100644 --- a/pandora_console/include/help/es/help_prediction_date.php +++ b/pandora_console/include/help/es/help_prediction_date.php @@ -11,6 +11,6 @@

        Por ejemplo, para el modulo disk_temp_free y eligiendo un periodo de 2 meses si se busca la fecha en la que el modulo alcanzará el intervalo [5-0] el resultado sera 04 Dec 2011 18:36:23.

        -

        Visto de una manera grafica seria:

        - - '210')); ?> +

        Visto de una manera grafica seria:

        + + '210']); diff --git a/pandora_console/include/help/es/help_profile.php b/pandora_console/include/help/es/help_profile.php index 015d1b1157..1cdea0d09a 100644 --- a/pandora_console/include/help/es/help_profile.php +++ b/pandora_console/include/help/es/help_profile.php @@ -1,12 +1,12 @@

        Perfil

        -

        es una herramienta de gestión Web que permite que trabajen múltiples usuarios con diferentes permisos en múltiples grupos de agentes que hay definidos. En los perfiles se definen los permisos que puede tener un usuario.

        +

        es una herramienta de gestión Web que permite que trabajen múltiples usuarios con diferentes permisos en múltiples grupos de agentes que hay definidos. En los perfiles se definen los permisos que puede tener un usuario.

        Esta lista define qué habilita cada perfil:

        @@ -16,58 +16,58 @@
        +
        OperaciónBit de acceso -
        Ver datos agente (todas las vistas) AR -
        Vista táctica AR -
        Vista de grupos AR -
        Crear un visual console RW -
        Crear un informe RW -
        Crear una gráfica combinada RW -
        Ver informe, gráfica, etc RR +
        Ver datos agente (todas las vistas) AR +
        Vista táctica AR +
        Vista de grupos AR +
        Crear un visual console RW +
        Crear un informe RW +
        Crear una gráfica combinada RW +
        Ver informe, gráfica, etc RR
        Aplicar una plantilla de informeRR
        Crear una plantilla de informeRM -
        Crear incidente IW -
        Leer incidente IR -
        Borrar incidente IW -
        Incidente “Become owner” IM -
        Borrar incidente que no es tuyo IM -
        Ver evento ER -
        Validar/Comentar evento EW -
        Borrar evento EM +
        Crear incidente IW +
        Leer incidente IR +
        Borrar incidente IW +
        Incidente “Become owner” IM +
        Borrar incidente que no es tuyo IM +
        Ver evento ER +
        Validar/Comentar evento EW +
        Borrar evento EM
        Ejecutar respuestasEW -
        Crear incidencia a través del evento (Respuesta) EW&IW +
        Crear incidencia a través del evento (Respuesta) EW&IW
        Gestionar respuestasPM
        Gestionar filtrosEW
        Personalizar columnas de eventosPM -
        Cambiar propietario/Re-abrir evento EM -
        Ver usuarios AR -
        Ver Consola SNMP AR -
        Validar traps IW -
        Mensajes IW -
        Cron jobs PM -
        Tree view AR -
        Update manager (Operación y Administración) PM +
        Cambiar propietario/Re-abrir evento EM +
        Ver usuarios AR +
        Ver Consola SNMP AR +
        Validar traps IW +
        Mensajes IW +
        Cron jobs PM +
        Tree view AR +
        Update manager (Operación y Administración) PM
        Extension Module GroupAR -
        Vista de gestión agente AW -
        Edición del agente y de su .conf AW -
        Asignación de alertas ya creadas LW -
        Definir, modificar plantillas, comandos y acciones LM -
        Gestión de grupos PM -
        Crear módulos de inventario PM +
        Vista de gestión agente AW +
        Edición del agente y de su .conf AW +
        Asignación de alertas ya creadas LW +
        Definir, modificar plantillas, comandos y acciones LM +
        Gestión de grupos PM +
        Crear módulos de inventario PM
        Gestionar módulos (Incluidas todas las subopciones)PM -
        Operaciones masivas AW -
        Crear agente AW +
        Operaciones masivas AW +
        Crear agente AW
        Duplicar configuración remotaAW
        Gestión de paradas de servicioAW -
        Gestión de alertas LW -
        Gestión de usuarios UM +
        Gestión de alertas LW +
        Gestión de usuarios UM
        Gestión de consola SNMPPM
        Gestión de perfilesPM
        Gestión de servidoresPM
        Auditoría del sistema (edición y visualización)PM -
        Setup (todas las solapas inferiores incl) PM -
        Mantenimiento de la BBDD DM -
        Extensiones administración PM -
        Barra búsqueda AR +
        Setup (todas las solapas inferiores incl) PM +
        Mantenimiento de la BBDD DM +
        Extensiones administración PM +
        Barra búsqueda AR
        Gestión de PolíticasAW
        Desactivar agente/módulo/alertaAD
        Validar alertasLM&AR o AW&LW diff --git a/pandora_console/include/help/es/help_projection_graph.php b/pandora_console/include/help/es/help_projection_graph.php index f94a340c11..51d8c9ce54 100644 --- a/pandora_console/include/help/es/help_projection_graph.php +++ b/pandora_console/include/help/es/help_projection_graph.php @@ -1,7 +1,7 @@

        Projection graph

        - '210')); ?> + '210']); ?>

        Projection graphs hacen una proyección de los datos del modulo en el futuro. La proyeccion se basa en una regresion lineal. diff --git a/pandora_console/include/help/es/help_recontask.php b/pandora_console/include/help/es/help_recontask.php index d0dc85d823..d928675e9b 100644 --- a/pandora_console/include/help/es/help_recontask.php +++ b/pandora_console/include/help/es/help_recontask.php @@ -25,7 +25,7 @@ Red sobre la que realizar la exploración. Utiliza el formato de red / mascara d Intervalo
        -Intervalo de repetición de la búsqueda de equipos. No utilice intervalos muy cortos ya que recon explora una red enviando un Ping a cada dirección, si utiliza redes de exploracion muy amplias (por ejemplo una clase A) combinado con intervalos muy cortos (6 horas) estará provocando que esté constantemente bombardeando la red con pings, cargandola e innecesariamente sobre cargando .

        +Intervalo de repetición de la búsqueda de equipos. No utilice intervalos muy cortos ya que recon explora una red enviando un Ping a cada dirección, si utiliza redes de exploracion muy amplias (por ejemplo una clase A) combinado con intervalos muy cortos (6 horas) estará provocando que esté constantemente bombardeando la red con pings, cargandola e innecesariamente sobre cargando .

        Plantilla de módulos
        @@ -33,7 +33,7 @@ Plantilla de componentes que añadir a los equipos descubiertos. Cuando detecte SO
        -Sistema operativo para reconocer. Si se selecciona uno en lugar de cualquiera (Any) sólo se añadirán los equipos con ese sistema operativo. Piense que en determiandas situaciones puede equivocarse a la hora de detectar sistemas, ya que este tipo de "adivinación" se realiza con patrones estadísticos que en función de algunos factores ajenos pueden fallar (redes con filtrados, software de seguridad, versiones modificadas de los sistemas). Para poder utilizar con seguridad este método debe tener instalado Xprobe2 en su sistema.

        +Sistema operativo para reconocer. Si se selecciona uno en lugar de cualquiera (Any) sólo se añadirán los equipos con ese sistema operativo. Piense que en determiandas situaciones puede equivocarse a la hora de detectar sistemas, ya que este tipo de "adivinación" se realiza con patrones estadísticos que en función de algunos factores ajenos pueden fallar (redes con filtrados, software de seguridad, versiones modificadas de los sistemas). Para poder utilizar con seguridad este método debe tener instalado Xprobe2 en su sistema.

        Puertos
        diff --git a/pandora_console/include/help/es/help_reporting_global_tab.php b/pandora_console/include/help/es/help_reporting_global_tab.php index b84b2db340..2b4fc51056 100644 --- a/pandora_console/include/help/es/help_reporting_global_tab.php +++ b/pandora_console/include/help/es/help_reporting_global_tab.php @@ -1,7 +1,7 @@

        Global

        diff --git a/pandora_console/include/help/es/help_reporting_item_editor_tab.php b/pandora_console/include/help/es/help_reporting_item_editor_tab.php index 6bbe12a57f..8aa67bbe7c 100644 --- a/pandora_console/include/help/es/help_reporting_item_editor_tab.php +++ b/pandora_console/include/help/es/help_reporting_item_editor_tab.php @@ -1,7 +1,7 @@

        Editor de elementos

        diff --git a/pandora_console/include/help/es/help_reporting_list_items_tab.php b/pandora_console/include/help/es/help_reporting_list_items_tab.php index cbe18a79cf..0a1286072a 100644 --- a/pandora_console/include/help/es/help_reporting_list_items_tab.php +++ b/pandora_console/include/help/es/help_reporting_list_items_tab.php @@ -1,7 +1,7 @@

        Report list items

        diff --git a/pandora_console/include/help/es/help_reporting_main_tab.php b/pandora_console/include/help/es/help_reporting_main_tab.php index 12dfaa722c..495e59a55d 100644 --- a/pandora_console/include/help/es/help_reporting_main_tab.php +++ b/pandora_console/include/help/es/help_reporting_main_tab.php @@ -7,9 +7,9 @@ Para crear un informe, primero debe llenar el formulario proporcionando:
          -
        • Un nombre
        • -
        • Un grupo
        • -
        • Una descripción
        • +
        • Un nombre
        • +
        • Un grupo
        • +
        • Una descripción
        Luego se debe presionar el boton con el texto Crear.

        diff --git a/pandora_console/include/help/es/help_reporting_preview_tab.php b/pandora_console/include/help/es/help_reporting_preview_tab.php index f54323351c..41f7b4c63a 100644 --- a/pandora_console/include/help/es/help_reporting_preview_tab.php +++ b/pandora_console/include/help/es/help_reporting_preview_tab.php @@ -1,7 +1,7 @@

        Preview

        diff --git a/pandora_console/include/help/es/help_reporting_time_lapse.php b/pandora_console/include/help/es/help_reporting_time_lapse.php index 4f6305b9a6..e3c8b79d1c 100644 --- a/pandora_console/include/help/es/help_reporting_time_lapse.php +++ b/pandora_console/include/help/es/help_reporting_time_lapse.php @@ -1,8 +1,8 @@ - -

        Reports - Time lapse

        -
        -Este es el lapso de tiempo que refleja el informe. Si es una semana, por ejemplo, el informe mostrará los datos desde hace una semana hasta ahora \ No newline at end of file + +

        Reports - Time lapse

        +
        +Este es el lapso de tiempo que refleja el informe. Si es una semana, por ejemplo, el informe mostrará los datos desde hace una semana hasta ahora diff --git a/pandora_console/include/help/es/help_reporting_wizard_sla_tab.php b/pandora_console/include/help/es/help_reporting_wizard_sla_tab.php index 9e80d42a3e..fecf9ca2fa 100644 --- a/pandora_console/include/help/es/help_reporting_wizard_sla_tab.php +++ b/pandora_console/include/help/es/help_reporting_wizard_sla_tab.php @@ -1,10 +1,10 @@

        Wizard SLA

        -

        Permite medir el nivel del servicio (Service Level Agreement) de todos los moduloes de . En es este wizard puedes crear un informe SLA de muchas agentes.

        +

        Permite medir el nivel del servicio (Service Level Agreement) de todos los moduloes de . En es este wizard puedes crear un informe SLA de muchas agentes.

        diff --git a/pandora_console/include/help/es/help_reporting_wizard_tab.php b/pandora_console/include/help/es/help_reporting_wizard_tab.php index e49bc84b27..2e1d20d76c 100644 --- a/pandora_console/include/help/es/help_reporting_wizard_tab.php +++ b/pandora_console/include/help/es/help_reporting_wizard_tab.php @@ -1,9 +1,9 @@

        Wizard

        -

        Esta pestaña pertenece a la versión Enterprise de . Esta pestaña nos permite realizar de una forma automática con unos pocos click, y de una vez multitud de items para un informe, con configuraciones comunes pero aplicadas a multitud de agentes y o módulos.

        +

        Esta pestaña pertenece a la versión Enterprise de . Esta pestaña nos permite realizar de una forma automática con unos pocos click, y de una vez multitud de items para un informe, con configuraciones comunes pero aplicadas a multitud de agentes y o módulos.

        diff --git a/pandora_console/include/help/es/help_reports_label_field.php b/pandora_console/include/help/es/help_reports_label_field.php index e1f32dc8ed..5fe83976bf 100755 --- a/pandora_console/include/help/es/help_reports_label_field.php +++ b/pandora_console/include/help/es/help_reports_label_field.php @@ -7,19 +7,19 @@

        Lista de las macros admitidas en este campo:
        -

          +
          • _agent_ : Nombre del agente que ha seleccionado en el elemento del informe.
          • -
          • _agentdescription_ : Descripción del agente que ha seleccionado en el elemento del informe.
          • +
          • _agentdescription_ : Descripción del agente que ha seleccionado en el elemento del informe.
          • _agentgroup_ : Grupo del agente que ha seleccionado en el elemento del informe
          • _address_ : Dirección del agente que ha seleccionado en el elemento del informe
          • -
              -
              - -
                - Solamente si ha podido o puede seleccionar un módulo de agente en el elemento del informe.
                -
              • _module_ : Nombre del módulo de agente que ha seleccionado en el elemento del informe.
              • -
              • _moduledescription_ : Descripción del módulo de agente que ha seleccionado en el elemento del informe.
              • -
                  +
                    +
                    + +
                      + Solamente si ha podido o puede seleccionar un módulo de agente en el elemento del informe.
                      +
                    • _module_ : Nombre del módulo de agente que ha seleccionado en el elemento del informe.
                    • +
                    • _moduledescription_ : Descripción del módulo de agente que ha seleccionado en el elemento del informe.
                    • +
                        Ejemplo: Agente: _agent_ / Módulo: _module_

                        diff --git a/pandora_console/include/help/es/help_response_macros.php b/pandora_console/include/help/es/help_response_macros.php index 8f88dca7f7..adc43b4f48 100644 --- a/pandora_console/include/help/es/help_response_macros.php +++ b/pandora_console/include/help/es/help_response_macros.php @@ -1,7 +1,7 @@

                        Macros en Respuestas de eventos

                        @@ -19,7 +19,7 @@ Las macros aceptadas son las siguientes:
                      • Id del evento: _event_id_
                      • Instrucciones del evento: _event_instruction_
                      • Id de la criticidad del evento: _event_severity_id_
                      • -
                      • Gravedad del evento (traducido por la consola de ): _event_severity_text_
                      • +
                      • Gravedad del evento (traducido por la consola de ): _event_severity_text_
                      • Procedencia del evento: _event_source_
                      • Estado del evento (Nuevo, validado o evento en proceso): _event_status_
                      • Etiquetas del evento separadas por comas: _event_tags_
                      • diff --git a/pandora_console/include/help/es/help_response_parameters.php b/pandora_console/include/help/es/help_response_parameters.php index 1e8375e7a1..046e90151a 100644 --- a/pandora_console/include/help/es/help_response_parameters.php +++ b/pandora_console/include/help/es/help_response_parameters.php @@ -1,7 +1,7 @@

                        Parámetros de respuestas de eventos

                        diff --git a/pandora_console/include/help/es/help_servers.php b/pandora_console/include/help/es/help_servers.php index c5ce08c1a3..c0f11979be 100644 --- a/pandora_console/include/help/es/help_servers.php +++ b/pandora_console/include/help/es/help_servers.php @@ -1,16 +1,16 @@

                        Gestion de servidores

                        -

                        Los servidores de son los elementos encargados de realizar las comprobaciones existentes. Ellos las verifican y cambian el estado de las mismas en funcion de los resultados obtenidos. Tambien son los encargados de disparar las alertas que se establezcan para controlar el estado de los datos.

                        +

                        Los servidores de son los elementos encargados de realizar las comprobaciones existentes. Ellos las verifican y cambian el estado de las mismas en funcion de los resultados obtenidos. Tambien son los encargados de disparar las alertas que se establezcan para controlar el estado de los datos.

                        -

                        El servidor de datos de puede trabajar con alta disponibilidad y/o balanceo de carga. En una arquitectura muy grande, se pueden usar varios servidores de a la vez, para poder manejar grandes volumenes de informacion distribuida por zonas geograficas o funcionales.

                        +

                        El servidor de datos de puede trabajar con alta disponibilidad y/o balanceo de carga. En una arquitectura muy grande, se pueden usar varios servidores de a la vez, para poder manejar grandes volumenes de informacion distribuida por zonas geograficas o funcionales.

                        -

                        Los servidores de están siempre en funcionamiento y verifican permanentemente si algún elemento tiene algún problema. Si existe alguna alerta asociada al problema, esta ejecuta la acción definida, como por ejemplo enviar un SMS, un correo electrónico, o activar la ejecución de un script.

                        +

                        Los servidores de están siempre en funcionamiento y verifican permanentemente si algún elemento tiene algún problema. Si existe alguna alerta asociada al problema, esta ejecuta la acción definida, como por ejemplo enviar un SMS, un correo electrónico, o activar la ejecución de un script.

                        • Servidor datos
                        • Servidor de red
                        • diff --git a/pandora_console/include/help/es/help_service_management_edit.php b/pandora_console/include/help/es/help_service_management_edit.php index e1ce822559..e398488d19 100644 --- a/pandora_console/include/help/es/help_service_management_edit.php +++ b/pandora_console/include/help/es/help_service_management_edit.php @@ -1,7 +1,7 @@

                          Edición de servicios

                          diff --git a/pandora_console/include/help/es/help_snmp_alert.php b/pandora_console/include/help/es/help_snmp_alert.php index 9276a12896..e35a626143 100644 --- a/pandora_console/include/help/es/help_snmp_alert.php +++ b/pandora_console/include/help/es/help_snmp_alert.php @@ -1,10 +1,10 @@

                          Alertas SNMP

                          -

                          Es posible asociar una alerta a un trap, asi P puede avisarnos de la llegada de un trap expecifico. Los traps SNMP no tienen relacion con el resto de sistema de alertas, aunque reulticen el sistema de alertas.

                          +

                          Es posible asociar una alerta a un trap, asi P puede avisarnos de la llegada de un trap expecifico. Los traps SNMP no tienen relacion con el resto de sistema de alertas, aunque reulticen el sistema de alertas.

                          diff --git a/pandora_console/include/help/es/help_snmp_alert_configuration.php b/pandora_console/include/help/es/help_snmp_alert_configuration.php index bb3c08203a..a8f8fad51f 100644 --- a/pandora_console/include/help/es/help_snmp_alert_configuration.php +++ b/pandora_console/include/help/es/help_snmp_alert_configuration.php @@ -1,7 +1,7 @@

                          Alert configuration

                          diff --git a/pandora_console/include/help/es/help_snmp_alert_custom.php b/pandora_console/include/help/es/help_snmp_alert_custom.php index 400cca44ad..157a44011e 100644 --- a/pandora_console/include/help/es/help_snmp_alert_custom.php +++ b/pandora_console/include/help/es/help_snmp_alert_custom.php @@ -1,7 +1,7 @@

                          Custom Value/OID

                          diff --git a/pandora_console/include/help/es/help_snmp_alert_filters.php b/pandora_console/include/help/es/help_snmp_alert_filters.php index 1ee32f5bf3..e9062e8c5e 100644 --- a/pandora_console/include/help/es/help_snmp_alert_filters.php +++ b/pandora_console/include/help/es/help_snmp_alert_filters.php @@ -1,7 +1,7 @@

                          Alert filters

                          diff --git a/pandora_console/include/help/es/help_snmp_alert_position.php b/pandora_console/include/help/es/help_snmp_alert_position.php index 2ac458d016..1f41edc8f0 100644 --- a/pandora_console/include/help/es/help_snmp_alert_position.php +++ b/pandora_console/include/help/es/help_snmp_alert_position.php @@ -1,7 +1,7 @@

                          Alert SNMP position

                          diff --git a/pandora_console/include/help/es/help_snmp_explorer.php b/pandora_console/include/help/es/help_snmp_explorer.php index 2f51f58a57..c44491396b 100644 --- a/pandora_console/include/help/es/help_snmp_explorer.php +++ b/pandora_console/include/help/es/help_snmp_explorer.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_snmpoid.php b/pandora_console/include/help/es/help_snmpoid.php index fb095bb10d..54a4ab7a53 100644 --- a/pandora_console/include/help/es/help_snmpoid.php +++ b/pandora_console/include/help/es/help_snmpoid.php @@ -5,4 +5,4 @@ ?>

                          OID SNMP

                          -La OID SNMP del módulo. Si existe una MIB capaz de resolver el nombre en el servidor de red de , entonces puede usar OID alfanumércias (ej. SNMPv2-MIB::sysDescr.0). Siempre se pueden usar OID numéricas (ej. 3.1.3.1.3.5.12.4.0.1), incluso si no hay una MIB específica. \ No newline at end of file +La OID SNMP del módulo. Si existe una MIB capaz de resolver el nombre en el servidor de red de , entonces puede usar OID alfanumércias (ej. SNMPv2-MIB::sysDescr.0). Siempre se pueden usar OID numéricas (ej. 3.1.3.1.3.5.12.4.0.1), incluso si no hay una MIB específica. \ No newline at end of file diff --git a/pandora_console/include/help/es/help_snmpwalk.php b/pandora_console/include/help/es/help_snmpwalk.php index 6e77a6807f..3ce1f100cd 100644 --- a/pandora_console/include/help/es/help_snmpwalk.php +++ b/pandora_console/include/help/es/help_snmpwalk.php @@ -5,6 +5,6 @@ ?>

                          SNMP walk

                          - también tiene un examinador SNMP simple que permite hacer un «walk» de un dispositivo remoto a través de un SNMP walk. + también tiene un examinador SNMP simple que permite hacer un «walk» de un dispositivo remoto a través de un SNMP walk.

                          -Hacer un «walk» («SNMP Walk») sobre un dispositivo hará que todas sus variables MIB estén disponibles, para que pueda elegir una. También puede introducir una MIB usando un OID numérico o un formato comprensible por humanos, si tiene la MIB correcta instalada en su servidor de red de . +Hacer un «walk» («SNMP Walk») sobre un dispositivo hará que todas sus variables MIB estén disponibles, para que pueda elegir una. También puede introducir una MIB usando un OID numérico o un formato comprensible por humanos, si tiene la MIB correcta instalada en su servidor de red de . diff --git a/pandora_console/include/help/es/help_tags_config.php b/pandora_console/include/help/es/help_tags_config.php index 72006b2743..e760a38d96 100644 --- a/pandora_console/include/help/es/help_tags_config.php +++ b/pandora_console/include/help/es/help_tags_config.php @@ -3,7 +3,7 @@ * @package Include/help/es */ ?> -

                          Tags en

                          +

                          Tags en

                          El acceso a los módulos se puede configurar con un sistema de Etiquetas o Tags. Se configuran unos tags en el sistema, se asignan a los módulos que se quiera. De esta forma se puede limitar el acceso a un usuario a los módulos con determinados tags.

                          diff --git a/pandora_console/include/help/es/help_template_tab.php b/pandora_console/include/help/es/help_template_tab.php index 957e5d02bd..87546784d0 100644 --- a/pandora_console/include/help/es/help_template_tab.php +++ b/pandora_console/include/help/es/help_template_tab.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_timesource.php b/pandora_console/include/help/es/help_timesource.php index db2ea3a8e5..a53ff48927 100644 --- a/pandora_console/include/help/es/help_timesource.php +++ b/pandora_console/include/help/es/help_timesource.php @@ -9,9 +9,9 @@ Qué origen de tiempo usar. Esto puede ser (por el momento) el sistema local («Sistema») o la base de datos («Base de datos»).

                          -Esto es útil cuando su base de datos no está en el mismo sistema que su servidor Web o los servidores de su . +Esto es útil cuando su base de datos no está en el mismo sistema que su servidor Web o los servidores de su . En ese caso cualquier diferencia de tiempo calculará de forma errónea las diferencias de tiempo y marcas de tiempo. -Debería usar NTP para sincronizar todos sus servidores de y su servidor de MySQL. +Debería usar NTP para sincronizar todos sus servidores de y su servidor de MySQL. Usando estas preferencias no tendrá que sincronizar su servidor web, aún así se recomienda.

                          @@ -30,28 +30,31 @@ var unixtime = parseInt(unixtime_ms / 1000);

                          "timestamp"); +$option = ['prominent' => 'timestamp']; ?> -Hora actual del sistema: +Hora actual del sistema:
                          Hora actual de la base de datos:
                          Hora de su navegador: diff --git a/pandora_console/include/help/es/help_view_services.php b/pandora_console/include/help/es/help_view_services.php index e0a412872d..52a03ef181 100644 --- a/pandora_console/include/help/es/help_view_services.php +++ b/pandora_console/include/help/es/help_view_services.php @@ -1,6 +1,6 @@ @@ -15,20 +15,20 @@ Una vez que tiene todos los dispositivos monitorizados puede crear un grupo con Para crear una nuevo servicio simplemente haga click en el boton Create, y entonces puede crear el servicio rellenando el formulario que aparece en la imagen de abajo.

                          - '550px')); ?> + '550px']); ?>

                          En este punto hemos creado un servidor sin items, así que tenemos que añadir los items que componen el servicio. Para añadir un nuevo item pulse en la herramienta naranja de la esquina superior derecha del tab Gestión de Servicio y luego en el botón Crear. Aparecerá el siguiente formulario. En este formulario debe elegir el módulo de agente que quiere añadir. Además debe rellenar los campos pesos, que dictan los pesos que tiene el módulo dentro del servicio para los estados Normal, Advertencia y Crítico. Cuanto más peso tenga el módulo más importante es dentro del servicio.

                          - '550px')); ?> + '550px']); ?>

                          Cuando todos los campos están rellenos pulse en el botón Crear y aparecerá una imagen parecida a la inferior mostrando que el módulo se añadió con éxito.

                          - '550px')); ?> + '550px']); ?>

                          Puede añadir todos los elementos que necesite para monitorizar sus servicios. En este ejemplo hemos añadido todos los elementos necesarios para monitorizar el servicio con los pesos correspondientes, y el resultado queda como puede ver en la siguiente imagen.

                          - '550px')); ?> + '550px']); ?>

                          Aparecerá la lista con todos los servicios en el modo operación, parecida a la imagen inferior. Estos datos son calculados en tiempo real mostrando los siguientes parámetros:

                          @@ -42,7 +42,7 @@ Aparecerá la lista con todos los servicios en el modo operación, parecida a la

                        • *Status: Estado del servicio en función del valor y los límites critical y warning. .


                        - '550px')); ?> + '550px']); ?>

                        Si hace click en el nombre de un servicio verá la vista específica de ese servicio. Como sabe el estado del servicio se calcula como la suma de los pesos asociados a cada módulo. Los servicios, al igual que los módulos, tienen asociado un estado dependiendo de su valor. Esta vista muestra el estado de cada item del servicio con los siguientes parámetros:

                        @@ -58,7 +58,7 @@ Si hace click en el nombre de un servicio verá la vista específica de ese serv

                        - '550px')); ?> + '550px']); ?>

                        También se pueden crear módulos asociados a servicios con las ventajas que esto implica (periodicidad de cálculo, integración con el sistema de alertas etc.) La forma de asociar un módulo a un servicio es seguir los siguientes pasos:

                        @@ -71,7 +71,7 @@ También se pueden crear módulos asociados a servicios con las ventajas que est
                      • Si queremos asociar alertas al servicio, debemos hacerlo sobre el modulo asociado al servicio. El servicio como tal no tiene posibilidad de agregar alertas, ni gráficas ni informes, todo debe ser hecho a través del monitor vinculado al servicio, tal y como se ha descrito.



                        - '550px')); ?> + '550px']); ?>

                        diff --git a/pandora_console/include/help/es/help_view_services_detail.php b/pandora_console/include/help/es/help_view_services_detail.php index b191605477..d94149d5a9 100644 --- a/pandora_console/include/help/es/help_view_services_detail.php +++ b/pandora_console/include/help/es/help_view_services_detail.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/es/help_visual_console_editor_data_tab.php b/pandora_console/include/help/es/help_visual_console_editor_data_tab.php index 9c857a7c94..7ec963f467 100644 --- a/pandora_console/include/help/es/help_visual_console_editor_data_tab.php +++ b/pandora_console/include/help/es/help_visual_console_editor_data_tab.php @@ -1,7 +1,7 @@

                        Editor

                        diff --git a/pandora_console/include/help/es/help_visual_console_editor_editor_tab.php b/pandora_console/include/help/es/help_visual_console_editor_editor_tab.php index 544e2d4287..bfc772d1d4 100644 --- a/pandora_console/include/help/es/help_visual_console_editor_editor_tab.php +++ b/pandora_console/include/help/es/help_visual_console_editor_editor_tab.php @@ -1,7 +1,7 @@

                        Editor

                        diff --git a/pandora_console/include/help/es/help_visual_console_editor_list_elements_tab.php b/pandora_console/include/help/es/help_visual_console_editor_list_elements_tab.php index 76e7d0f9cd..6697ed3e07 100644 --- a/pandora_console/include/help/es/help_visual_console_editor_list_elements_tab.php +++ b/pandora_console/include/help/es/help_visual_console_editor_list_elements_tab.php @@ -1,7 +1,7 @@

                        List of elements

                        diff --git a/pandora_console/include/help/es/help_visual_console_editor_preview_tab.php b/pandora_console/include/help/es/help_visual_console_editor_preview_tab.php index 3cf27b539e..36ce8c599c 100644 --- a/pandora_console/include/help/es/help_visual_console_editor_preview_tab.php +++ b/pandora_console/include/help/es/help_visual_console_editor_preview_tab.php @@ -1,7 +1,7 @@

                        Previsualizacion

                        diff --git a/pandora_console/include/help/es/help_visual_console_editor_wizard_tab.php b/pandora_console/include/help/es/help_visual_console_editor_wizard_tab.php index 8101a9a4d2..ddb2c035d4 100644 --- a/pandora_console/include/help/es/help_visual_console_editor_wizard_tab.php +++ b/pandora_console/include/help/es/help_visual_console_editor_wizard_tab.php @@ -1,7 +1,7 @@

                        Wizard

                        diff --git a/pandora_console/include/help/es/help_web_checks.php b/pandora_console/include/help/es/help_web_checks.php index 48c277c076..a27c46be59 100644 --- a/pandora_console/include/help/es/help_web_checks.php +++ b/pandora_console/include/help/es/help_web_checks.php @@ -6,7 +6,7 @@

                        Monitorización WEB

                        -La monitorización WEB avanzada es una funcionalidad que realiza el Servidor WEB de Goliat en la versión Enterprise de . +La monitorización WEB avanzada es una funcionalidad que realiza el Servidor WEB de Goliat en la versión Enterprise de .

                        Este es un ejemplo del modulo Webcheck de GOLIAT: diff --git a/pandora_console/include/help/es/help_wux_console.php b/pandora_console/include/help/es/help_wux_console.php index 39ad49d70a..8404a1a3c1 100644 --- a/pandora_console/include/help/es/help_wux_console.php +++ b/pandora_console/include/help/es/help_wux_console.php @@ -2,155 +2,155 @@

                        Introducción

                        - WUX es un componente interno de que permite a los usuarios automatizar sus sesiones de navegación web. Genera en un informe con los resultados de las ejecuciones, tiempos empleados, y capturas con los posibles errores encontrados. Es capaz de dividir las sesiones de navegación en fases para simplificar la vista y depurar posibles cuellos de botella. + WUX es un componente interno de que permite a los usuarios automatizar sus sesiones de navegación web. Genera en un informe con los resultados de las ejecuciones, tiempos empleados, y capturas con los posibles errores encontrados. Es capaz de dividir las sesiones de navegación en fases para simplificar la vista y depurar posibles cuellos de botella.

                        - WUX utiliza el robot de navegación de (PWR - Web Robot) para automatizar las sesiones de navegación + WUX utiliza el robot de navegación de (PWR - Web Robot) para automatizar las sesiones de navegación

                        Grabar una sesión de navegación web

                        Grabar una sesión PWR

                        - Antes de monitorizar una experiencia de usuario debemos hacer la grabación. Dependiendo del tipo de tecnología que hayamos elegido utilizaremos un sistema de grabación u otro. + Antes de monitorizar una experiencia de usuario debemos hacer la grabación. Dependiendo del tipo de tecnología que hayamos elegido utilizaremos un sistema de grabación u otro.

                        - - Para realizar la grabación de una navegación con PWR necesitaremos: - + + Para realizar la grabación de una navegación con PWR necesitaremos: +

                          -
                        1. - Navegador web Firefox versión 47.0.1 (descargable en: - https://ftp.mozilla.org/pub/firefox/releases/47.0.1/). - .
                        2. -
                        3. - Extensión Selenium IDE (descargable en: - https://addons.mozilla.org/es/firefox/addon/selenium-ide/). -
                        4. +
                        5. + Navegador web Firefox versión 47.0.1 (descargable en: + https://ftp.mozilla.org/pub/firefox/releases/47.0.1/). + .
                        6. +
                        7. + Extensión Selenium IDE (descargable en: + https://addons.mozilla.org/es/firefox/addon/selenium-ide/). +

                        - Para instalar correctamente la versión 47.0.1 de Firefox hay que descargarla desde la URL proporcionada anteriormente. En sistemas Windows habrá que añadir el ejecutable al PATH del sistema. + Para instalar correctamente la versión 47.0.1 de Firefox hay que descargarla desde la URL proporcionada anteriormente. En sistemas Windows habrá que añadir el ejecutable al PATH del sistema.

                        - 'width: 90%;')); - ?> + 'width: 90%;']); + ?>

                        - Una vez descargado mostraremos el icono del entorno de grabación mediante las opciones de personalización de Firefox: + Una vez descargado mostraremos el icono del entorno de grabación mediante las opciones de personalización de Firefox:

                        - 'width:295px;')); - ?> + 'width:295px;']); + ?>

                        - 'width: 90%;')); - ?> + 'width: 90%;']); + ?>

                        - Una vez colocado el acceso iniciamos el grabador: + Una vez colocado el acceso iniciamos el grabador:

                        - 'width: 90%;')); - ?> + 'width: 90%;']); + ?>

                        - Desde este momento podremos navegar por el sitio web que queramos monitorizar y las diferentes acciones de cada paso que avancemos irán apareciendo en el grabador. + Desde este momento podremos navegar por el sitio web que queramos monitorizar y las diferentes acciones de cada paso que avancemos irán apareciendo en el grabador.

                        - Para detener la grabación utilizaremos el siguiente botón, situado en la parte superior derecha del grabador: + Para detener la grabación utilizaremos el siguiente botón, situado en la parte superior derecha del grabador:

                        - 'width:33px;')); - ?> + 'width:33px;']); + ?>

                        - Una vez completadas las acciones, podemos realizar comprobaciones sobre la página, por ejemplo verificar la existencia de un texto determinado para asegurarnos de que la página cargada es la correcta. Para ello haremos click derecho sobre una sección de texto en la ventana del navegador mientras continuamos grabando, y seleccionamos la opción verifyText: + Una vez completadas las acciones, podemos realizar comprobaciones sobre la página, por ejemplo verificar la existencia de un texto determinado para asegurarnos de que la página cargada es la correcta. Para ello haremos click derecho sobre una sección de texto en la ventana del navegador mientras continuamos grabando, y seleccionamos la opción verifyText:

                        - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                        - Aparecerá un nuevo paso en el grabador indicando la acción de comprobación de texto indicada: + Aparecerá un nuevo paso en el grabador indicando la acción de comprobación de texto indicada:

                        - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                        - Podemos reproducir la secuencia completa mediante el botón Play entire test suite y comprobar que finaliza correctamente: + Podemos reproducir la secuencia completa mediante el botón Play entire test suite y comprobar que finaliza correctamente:

                        - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                        - Una vez verificada la validez de la secuencia de navegación, la guardaremos (Archivo -> Save Test Case) para ejecutarla posteriormente con WUX. El fichero resultante será un documento HTML que WUX interpretará. + Una vez verificada la validez de la secuencia de navegación, la guardaremos (Archivo -> Save Test Case) para ejecutarla posteriormente con WUX. El fichero resultante será un documento HTML que WUX interpretará.

                        -

                        Grabar una sesión transaccional con WUX PWR

                        +

                        Grabar una sesión transaccional con WUX PWR

                        - WUX en modo PWR ( Web Robot) permite dividir la monitorización de la navegación de un sitio web en múltiples módulos, que representarán cada uno de los pasos realizados. + WUX en modo PWR ( Web Robot) permite dividir la monitorización de la navegación de un sitio web en múltiples módulos, que representarán cada uno de los pasos realizados.

                        - Para insertar un nuevo punto de control y generar los módulos de fase (hasta ese punto) haga clic derecho en el punto donde desea identificar el comienzo de fase. + Para insertar un nuevo punto de control y generar los módulos de fase (hasta ese punto) haga clic derecho en el punto donde desea identificar el comienzo de fase.

                        - 'width:436;')); - ?> + 'width:436;']); + ?>

                        - Como comentario pondremos el siguiente texto: + Como comentario pondremos el siguiente texto:

                        -	phase_start:nombre_de_fase
                        +    phase_start:nombre_de_fase
                         

                        - La fase englobará el tiempo y resultado de todos los comandos que se encuentren hasta el siguiente comentario: + La fase englobará el tiempo y resultado de todos los comandos que se encuentren hasta el siguiente comentario:

                        -	phase_end:nombre_de_fase
                        +    phase_end:nombre_de_fase
                         

                        - Todos los comandos que se ejecuten entre una etiqueta phase_start y phase_end se englobarán dentro de esa fase. + Todos los comandos que se ejecuten entre una etiqueta phase_start y phase_end se englobarán dentro de esa fase.

                        Visualización de los datos

                        @@ -166,9 +166,9 @@

                        - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                        @@ -176,9 +176,9 @@

                        - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                        Vista de consola WUX

                        @@ -186,55 +186,55 @@ En esta vista podemos encontrar toda la infomación que el sistema WUX ha obtenido de la sesión de navegación configurada:

                        - Nota: Si hemos definido fases en nuestra sesión de navegación, se mostrarán en esta vista de una forma sencilla y clara (ver apartado de grabación sesión transaccional con WUX PWR). + Nota: Si hemos definido fases en nuestra sesión de navegación, se mostrarán en esta vista de una forma sencilla y clara (ver apartado de grabación sesión transaccional con WUX PWR).

                        - 'width:90%;')); - ?> + 'width:90%;']); + ?>

                        Sección Resultado Global:

                        - Muestra el estado general de nuestra transacción: + Muestra el estado general de nuestra transacción:

                          -
                        1. - Esta puede tener tres estados: -
                            - -
                          1. - Correcto: Cuando todas las fases de la transacción sean correctas. -
                          2. -
                          3. - Incorrecto: Si alguna de las fases de la transacción ha fallado. En ese caso, se mostrara una icono de una lupa que enlaza a la captura de pantalla del punto de la sesión de navegación en que se ha producido el fallo. -
                          4. -
                          5. - Desconocido: Si el servidor encuentra problemas para procesar la sesión o hay fallos de configuración. -
                          6. +
                          7. + Esta puede tener tres estados: +
                              + +
                            1. + Correcto: Cuando todas las fases de la transacción sean correctas. +
                            2. +
                            3. + Incorrecto: Si alguna de las fases de la transacción ha fallado. En ese caso, se mostrara una icono de una lupa que enlaza a la captura de pantalla del punto de la sesión de navegación en que se ha producido el fallo. +
                            4. +
                            5. + Desconocido: Si el servidor encuentra problemas para procesar la sesión o hay fallos de configuración. +
                          8. - Muestra el tiempo transcurrido desde la última ejecución de la sesión de navegación. + Muestra el tiempo transcurrido desde la última ejecución de la sesión de navegación.
                          9. - Muestra el tiempo total que ha tardado en realizarse dicha sesión de navegación, independientemente de su estado. + Muestra el tiempo total que ha tardado en realizarse dicha sesión de navegación, independientemente de su estado.

                          Sección Resultados de la ejecución de la transacción:

                            -
                          1. - Muestra el estado y el tiempo empleado en ejecutar la sesión de navegación. -
                          2. -
                          3. - En caso de fallo, se mostrará el icono que enlaza con la captura del momento del error. -
                          4. -
                          5. - Si hemos definido fases en nuestra sesión, entonces se mostrará el estado de cada una de las fases, asi como el tiempo que tarda en realizarse cada una de ellas y su contribución al tiempo global. -
                          6. +
                          7. + Muestra el estado y el tiempo empleado en ejecutar la sesión de navegación. +
                          8. +
                          9. + En caso de fallo, se mostrará el icono que enlaza con la captura del momento del error. +
                          10. +
                          11. + Si hemos definido fases en nuestra sesión, entonces se mostrará el estado de cada una de las fases, asi como el tiempo que tarda en realizarse cada una de ellas y su contribución al tiempo global. +

                          @@ -249,56 +249,56 @@

                          1. - - Stats_TT: - - Tiempo total en obtener el sitio web. + + Stats_TT: + + Tiempo total en obtener el sitio web.
                          2. - - Stats_TDNS: - - Tiempo total en resolver la dirección IP del objetivo. + + Stats_TDNS: + + Tiempo total en resolver la dirección IP del objetivo.
                          3. - - Stats_TTCP: - - Tiempo empleado en conectar vía TCP. + + Stats_TTCP: + + Tiempo empleado en conectar vía TCP.
                          4. - - Stats_TSSL: - - Tiempo empleado en establecer comunicación SSL. + + Stats_TSSL: + + Tiempo empleado en establecer comunicación SSL.
                          5. - - Stats_TST : - - Tiempo hasta que inició la transferencia de datos. + + Stats_TST : + + Tiempo hasta que inició la transferencia de datos.
                          6. - - Stats_TTC : - - Tiempo transfiriendo datos, agrupará todos los tiempos de transferencia de recursos. + + Stats_TTC : + + Tiempo transfiriendo datos, agrupará todos los tiempos de transferencia de recursos.
                          7. - - Stats_TTR : - - Tiempo empleado en transferir el recurso X, agrupando todas las imágenes en “image”. + + Stats_TTR : + + Tiempo empleado en transferir el recurso X, agrupando todas las imágenes en “image”.

                          Historial de trasacción:

                            -
                          1. - Muestra el histórico de las ejecuciones de la sesión de navegación web. -
                          2. - En el caso de haber ejecuciones fallidas, se mostrará un enlace donde consultar la imagen del error. + Muestra el histórico de las ejecuciones de la sesión de navegación web. +
                          3. +
                          4. + En el caso de haber ejecuciones fallidas, se mostrará un enlace donde consultar la imagen del error.
                          \ No newline at end of file diff --git a/pandora_console/include/help/ja/help_ad_advanced_permision.php b/pandora_console/include/help/ja/help_ad_advanced_permision.php index 4adf9955ec..3aaa141099 100644 --- a/pandora_console/include/help/ja/help_ad_advanced_permision.php +++ b/pandora_console/include/help/ja/help_ad_advanced_permision.php @@ -9,15 +9,15 @@ - +
                          新たなパーミッションを追加する場合、次のようにテキストを追加する必要があります。 - - "プロファイルの名前, グループの名前, [グループ AD n1 の名前|グループ AD n2 の名前| - - グループ AD n3 の名前|...],[名前タグ1|名前タグ2|名前タグN|...]" - - グループとタグの間は、上記の例のように "|" で区切る必要があります。 - 新たなパーミッションを追加する場合、次のようにテキストを追加する必要があります。 + + "プロファイルの名前, グループの名前, [グループ AD n1 の名前|グループ AD n2 の名前| + + グループ AD n3 の名前|...],[名前タグ1|名前タグ2|名前タグN|...]" + + グループとタグの間は、上記の例のように "|" で区切る必要があります。 +
                          diff --git a/pandora_console/include/help/ja/help_agent_status.php b/pandora_console/include/help/ja/help_agent_status.php index 5ac2f46219..37e99ce4aa 100644 --- a/pandora_console/include/help/ja/help_agent_status.php +++ b/pandora_console/include/help/ja/help_agent_status.php @@ -10,19 +10,19 @@

                          - - - + + + - - + + - + - - - - + + + + - -
                          "すべての監視項目が正常", "alt" => "すべての監視項目が正常")); ?>すべての監視項目が正常 "1つ以上の監視項目で障害", "alt" => "1つ以上の監視項目で障害")); ?>1つ以上の監視項目で障害 "緑/赤 の状態変化発生", "alt" => "緑/赤 の状態変化発生")); ?>緑/赤 の状態変化発生 'すべての監視項目が正常', 'alt' => 'すべての監視項目が正常']); ?>すべての監視項目が正常 '1つ以上の監視項目で障害', 'alt' => '1つ以上の監視項目で障害']); ?>1つ以上の監視項目で障害 '緑/赤 の状態変化発生', 'alt' => '緑/赤 の状態変化発生']); ?>緑/赤 の状態変化発生 "アラート発生中", "alt" => "アラート発生中")); ?>アラート発生中 "アラートが無効", "alt" => "アラートが無効")); ?>アラートが無効 'アラート発生中', 'alt' => 'アラート発生中']); ?>アラート発生中 'アラートが無効', 'alt' => 'アラートが無効']); ?>アラートが無効
                          "データ収集対象外エージェント", "alt" => "データ収集対象外エージェント")); ?>データ収集対象外エージェント "エージェント停止中", "alt" => "エージェント停止中")); ?>エージェント停止中 "アラート未発生", "alt" => "アラート未発生")); ?>アラート未発生 'データ収集対象外エージェント', 'alt' => 'データ収集対象外エージェント']); ?>データ収集対象外エージェント 'エージェント停止中', 'alt' => 'エージェント停止中']); ?>エージェント停止中 'アラート未発生', 'alt' => 'アラート未発生']); ?>アラート未発生
                          +
        diff --git a/pandora_console/include/help/ja/help_alert_action.php b/pandora_console/include/help/ja/help_alert_action.php index de75fe5a3f..e81e273a5c 100644 --- a/pandora_console/include/help/ja/help_alert_action.php +++ b/pandora_console/include/help/ja/help_alert_action.php @@ -1,7 +1,7 @@

        アラートアクション

        diff --git a/pandora_console/include/help/ja/help_alert_command.php b/pandora_console/include/help/ja/help_alert_command.php index b8eeeedee5..d32975e388 100644 --- a/pandora_console/include/help/ja/help_alert_command.php +++ b/pandora_console/include/help/ja/help_alert_command.php @@ -1,9 +1,9 @@

        アラートコマンド

        -

        "しきい値を越えた場合"の の動作には、syslog への記録、e-mail、SMS 送信や、 が動作するマシンでの任意のスクリプトの実行など、さまざまな種類があります。

        +

        "しきい値を越えた場合"の の動作には、syslog への記録、e-mail、SMS 送信や、 が動作するマシンでの任意のスクリプトの実行など、さまざまな種類があります。

        diff --git a/pandora_console/include/help/ja/help_alert_compound.php b/pandora_console/include/help/ja/help_alert_compound.php index 691a5853ca..90a9bd624c 100644 --- a/pandora_console/include/help/ja/help_alert_compound.php +++ b/pandora_console/include/help/ja/help_alert_compound.php @@ -1,9 +1,9 @@

        関連付けアラート

        -

        一つ以上のモジュールを使って の動作をさせることができます。これらのモジュールは、同一エージェントや異なるエージェントからのどちらでも可能です。

        +

        一つ以上のモジュールを使って の動作をさせることができます。これらのモジュールは、同一エージェントや異なるエージェントからのどちらでも可能です。

        diff --git a/pandora_console/include/help/ja/help_alert_config.php b/pandora_console/include/help/ja/help_alert_config.php index 5e2790dc76..21e12b1baf 100644 --- a/pandora_console/include/help/ja/help_alert_config.php +++ b/pandora_console/include/help/ja/help_alert_config.php @@ -9,7 +9,7 @@ 名前(Name): アクションの名前。
        グループ(Group): アクションのグループ。
        -
        コマンド(Command): アラートが実行された時に利用されるコマンドの定義です。 で定義されたコマンドを選択することができます。選択するコマンドによって、入力が必要なフィールドが異なります。
        +
        コマンド(Command): アラートが実行された時に利用されるコマンドの定義です。 で定義されたコマンドを選択することができます。選択するコマンドによって、入力が必要なフィールドが異なります。
        閾値(Threshold): アクション実行の閾値。
        コマンドプレビュー(Command Preview): このフィールドには、システムが実行するコマンドが表示されます。編集はできません。
        フィールドX(Field X): このフィールドでは、マクロ _field1_ から _field10_ までのマクロの値を定義します。これらは、必要に応じてコマンドで利用されます。これらのフィールドは、設定によりテキスト入力または選択となります。選択したコマンドに応じて、表示されるフィールドの数が変化します。以下に例を示します。

        @@ -18,7 +18,7 @@ email アクションを設定するには、_field1_ (送信先アドレス)、 アクション作成時には 3つのフィールドのみ設定できます。これらのフィールド内では、以下のマクロを利用できます。

        - '550px')); ?> + '550px']); ?>


        @@ -49,7 +49,7 @@ email アクションを設定するには、_field1_ (送信先アドレス)、
      • _data_ : アラート発生時のモジュールのデータ(値)
      • _email_tag_ : モジュールタグに関連付けられた Email。
      • _event_cfX_ : (イベントアラートのみ) アラートを発報したイベントのカスタムフィールドのキー。 例えば、キーが IPAM のカスタムフィールドがある場合、_event_cfIPAM_ マクロにて値を得ることができます。
      • -
      • _event_description_ : (イベントアラートのみ) イベントの説明 です
      • +
      • _event_description_ : (イベントアラートのみ) イベントの説明 です
      • _event_extra_id_: (イベントアラートのみ) 拡張 ID
      • _event_id_ : (イベントアラートのみ) アラート発生元のイベントID
      • _event_text_severity_ : (イベントアラートのみ) イベント(アラートの発生元)のテキストでの重要度 (Maintenance, Informational, Normal Minor, Warning, Major, Critical)
      • diff --git a/pandora_console/include/help/ja/help_alert_macros.php b/pandora_console/include/help/ja/help_alert_macros.php index 1a7fd69680..73ca00126e 100644 --- a/pandora_console/include/help/ja/help_alert_macros.php +++ b/pandora_console/include/help/ja/help_alert_macros.php @@ -33,7 +33,7 @@
      • _data_ : アラート発生時のモジュールのデータ(値)
      • _email_tag_ : モジュールタグに関連付けられた Email。
      • _event_cfX_ : (イベントアラートのみ) アラートを発報したイベントのカスタムフィールドのキー。 For example, if there is a custom field whose key is IPAM, its value can be obtained using the _event_cfIPAM_ macro.
      • -
      • _event_description_ : (イベントアラートのみ) イベントの説明 です
      • +
      • _event_description_ : (イベントアラートのみ) イベントの説明 です
      • _event_extra_id_: (Only event alerts) Extra id.
      • _event_id_ : (イベントアラートのみ) アラート発生元のイベントID
      • _event_text_severity_ : (イベントアラートのみ) イベント(アラートの発生元)のテキストでの重要度 (Maintenance, Informational, Normal Minor, Warning, Major, Critical)
      • @@ -75,7 +75,7 @@
      • _plugin_parameters_ : モジュールのプラグインパラメータ
      • _policy_ : モジュールが属するポリシー名 (存在する場合)
      • _prevdata_ : アラートを発報する前のモジュールデータ
      • -
      • _rca_: Root cause analysis chain (only for services).
      • +
      • _rca_: Root cause analysis chain (only for services).
      • _server_ip_ : エージェントが割り当てられているサーバ IP。
      • _server_name_ : エージェントが割り当てられているサーバ名。
      • _target_ip_ : モジュールの対象IPアドレス
      • diff --git a/pandora_console/include/help/ja/help_alert_recovery.php b/pandora_console/include/help/ja/help_alert_recovery.php index b603045937..2b6383e68d 100644 --- a/pandora_console/include/help/ja/help_alert_recovery.php +++ b/pandora_console/include/help/ja/help_alert_recovery.php @@ -5,5 +5,5 @@ ?>

        アラートリカバリ

        -アラート状態がリカバーした時に、 が別のアラートを上げるかどうかを定義します。フィールド 1 は同じで、フィールド 2 とフィールド 3 に "[RECOVER]" が追加されます。 +アラート状態がリカバーした時に、 が別のアラートを上げるかどうかを定義します。フィールド 1 は同じで、フィールド 2 とフィールド 3 に "[RECOVER]" が追加されます。 デフォルトでは無効に設定されています。 diff --git a/pandora_console/include/help/ja/help_alert_template.php b/pandora_console/include/help/ja/help_alert_template.php index c0f133a5b3..6f077173b1 100644 --- a/pandora_console/include/help/ja/help_alert_template.php +++ b/pandora_console/include/help/ja/help_alert_template.php @@ -1,7 +1,7 @@

        アラートテンプレート

        diff --git a/pandora_console/include/help/ja/help_alerts_config.php b/pandora_console/include/help/ja/help_alerts_config.php index 36f2e51ff4..2fc8331342 100644 --- a/pandora_console/include/help/ja/help_alerts_config.php +++ b/pandora_console/include/help/ja/help_alerts_config.php @@ -3,21 +3,21 @@ * @package Include/help/ja */ ?> -

        アラート設定クイックガイド

        +

        アラート設定クイックガイド


        アラートシステムの概要

        - のアラート定義は複雑だと良く言われます。バージョン 2.0 以前は、アラートの設定は簡単でした。個々のアラートで状態を定義し、それぞれの場合においてアクションが実施されなかった時に何をするかを定義していました。これは "直感的" です (しかし、それぞれが閾値の設定を持っており、多くの人の頭痛の種になっていました)。シンプルではありますが、良くは無いのではないでしょうか。

        + のアラート定義は複雑だと良く言われます。バージョン 2.0 以前は、アラートの設定は簡単でした。個々のアラートで状態を定義し、それぞれの場合においてアクションが実施されなかった時に何をするかを定義していました。これは "直感的" です (しかし、それぞれが閾値の設定を持っており、多くの人の頭痛の種になっていました)。シンプルではありますが、良くは無いのではないでしょうか。

        -一人のユーザ (たくさんのエージェントをインストールし、 を良く利用していました) が、2000 のモジュール全てに対して、アラートを 設定 しなくてはいけないという点でとても大変であるということを言及しました。この点とその他問題のために、我々はアラートシステムをモジュール化し、アラートが発生したときに実行するアクション (アラートアクション) および、アクションによって実行されるコマンド (アラートコマンド) から、アラートを発生させる定義 (アラートテンプレート) を分割するよう改変を行いました。モジュールとアラートテンプレートの組み合わせにより、アラートが発生します。

        +一人のユーザ (たくさんのエージェントをインストールし、 を良く利用していました) が、2000 のモジュール全てに対して、アラートを 設定 しなくてはいけないという点でとても大変であるということを言及しました。この点とその他問題のために、我々はアラートシステムをモジュール化し、アラートが発生したときに実行するアクション (アラートアクション) および、アクションによって実行されるコマンド (アラートコマンド) から、アラートを発生させる定義 (アラートテンプレート) を分割するよう改変を行いました。モジュールとアラートテンプレートの組み合わせにより、アラートが発生します。

        この方法で、"Host alive" というモジュールを持ち、"Host down" というアラートテンプレートが関連付けられた 1000 のシステムがあったとします。このとき、"Call to the operator" というアラートがデフォルトで実行されます。そして、オペレータへ通知する前に何回のアラート検知までを許容するか(何回目まではオペレータへ通知しないか)を変更したいと考えたとき、テンプレートの定義を変更するだけで実現できます。1000個のアラート設定を一つ一つ設定変更する必要はありません。

        - で、何人かのユーザは、数十のマシンのみを管理していますが、数百を管理しているユーザもいます。また、数千ものシステムをモニタしているユーザもいます。我々は、 で、すべての種類の環境の管理を可能にしなければいけません。



        + で、何人かのユーザは、数十のマシンのみを管理していますが、数百を管理しているユーザもいます。また、数千ものシステムをモニタしているユーザもいます。我々は、 で、すべての種類の環境の管理を可能にしなければいけません。



        アラートの仕組み

        - '550px')); ?> + '550px']); ?> アラートは次の組み合わせです。

        @@ -39,11 +39,11 @@ アクションとテンプレートを定義するとき、フィールド1、フィールド2、フィールド3というフィールドがあります。これらはコマンド実行時にパラメータとして渡されます。このパラメータの値は、テンプレートからアクションへ、そしてコマンドへ引き渡されます。テンプレートからアクションへの引き渡しは、アクションでフィールドが定義されていない場合のみ実行されます。アクションで定義されている場合はそれが使われます。

        - '550px')); ?> + '550px']); ?> これは、テンプレートの値がどのようにアクションの値で上書きされるかの例です。

        - '550px')); ?> + '550px']); ?> 例として、次のフィールド設定で、アラート発生時にメールを送信するテンプレートを作成します。

        @@ -68,33 +68,33 @@ ここで、上記のような例を仮定すると、まずは数値データのモジュールを一つモニタします。以下の例では、system CPU 使用率をモニタするモジュールをとりあげます。温度を返す温度センサーなどでも良いです。まず最初に、モジュールがデータを正しく受け取っているかを見てみましょう。

        - '550px')); ?> + '550px']); ?> このスクリーンショットでは、sys_cpu というモジュールがあり、現在の値が 7 であるということが解ります。この例では、この値が 20以上になったらアラートを上げたいと考えます。そのためには、20以上の値になったら、障害状態になるようにモジュールを設定します。設定するには、スパナアイコンをクリックします。

        - '550px')); ?> + '550px']); ?> 以下の画面の赤で囲っている部分の値を設定します。



        - '550px')); ?> + '550px']); ?> 設定を反映させます。これで、CPU モジュールの値が 20以上になるとステータスが障害状態になり、次のように赤い表示になります。

        - '550px')); ?> + '550px']); ?> -以上で、どのような時が正常 (正常で緑表示) で、どのような時が異常 (障害で赤表示) かをシステムが認識するようになりました。次のすべきは、モジュールが障害状態になったときにメール通知する設定です。そのためには、 アラートシステムを利用します。

        +以上で、どのような時が正常 (正常で緑表示) で、どのような時が異常 (障害で赤表示) かをシステムが認識するようになりました。次のすべきは、モジュールが障害状態になったときにメール通知する設定です。そのためには、 アラートシステムを利用します。

        -この設定をするには、まずは、必要なコマンド (メールを送る) が一つあるということを認識する必要があります。この例では、 にあらかじめ定義されているメール送信コマンドを利用するので簡単です。

        +この設定をするには、まずは、必要なコマンド (メールを送る) が一つあるということを認識する必要があります。この例では、 にあらかじめ定義されているメール送信コマンドを利用するので簡単です。

        アラートの設定

        まずは、"Send an email to the operator" というアクションを作成しないといけません。新たなアクションを作成するには、システム管理メニューから、アラート管理 -> アクションの順にクリックします。

        - '550px')); ?> + '550px']); ?> -このアクションでは、eMail というメールを送信するコマンドを使います。これはとても簡単で、一つのフィールド (フィールド 1) だけ設定すれば良く、他の 2つの設定は不要です。フィールド1、2、3 は何かというのは、 のアラートシステムの中で最もわかりにくい部分の一つです。

        +このアクションでは、eMail というメールを送信するコマンドを使います。これはとても簡単で、一つのフィールド (フィールド 1) だけ設定すれば良く、他の 2つの設定は不要です。フィールド1、2、3 は何かというのは、 のアラートシステムの中で最もわかりにくい部分の一つです。

        これらのフィールドは、アラートテンプレートの情報をコマンド設定へ "渡す" ために利用されます。また、そこから、実際に実行されるコマンドに渡されます。つまり、テンプレートとコマンド設定の両方から、異なる情報を実行されるコマンドに与えることができます。この場合、コマンドに対してフィールド 1のみを指定し、フィールド 2 と 3 は設定していません。

        @@ -104,7 +104,7 @@ 次に、後から使えるように可能な限り一般的な内容で、アラートテンプレートを作成する必要があります。これは、"モジュールが障害状態であることを認識" し、デフォルトとして、オペレータにメールを送信します。システム管理メニューから、「アラート管理」->「テンプレート」をクリックして、「作成」ボタンをクリックしてください。

        - '550px')); ?> + '550px']); ?> "条件種別(Condition)" フィールドにて状態を定義します。この場合、"障害状態(Critical stateus)" を選択しています。これにより、モジュールが障害状態になった時にアラートが通知されます。ここで、"cpu sys" モジュールに対して、20以上の値になった場合に障害状態となるように設定しています。

        @@ -112,7 +112,7 @@ ステップ2 へ進むために、"次(next)" ボタンをクリックします。

        - '550px')); ?> + '550px']); ?> ステップ2 では、アラートテンプレートのアラート通知に関する全ての設定を行います。最初のいくつかはとても簡単で、アラートを発生させる日や時間を定義します。

        @@ -121,7 +121,7 @@ 再通知間隔(Time threshhold): デフォルトでは 1日です。例では 1日ですが、5分に設定すると、モジュールが常にダウン状態の場合、5分間隔でアラート通知されます。もし、1日 (24時間) に設定すると、ダウンしたときに、まず一度アラート通知します。モジュールが復旧し、再びダウンすると、再びアラート通知します。しかし、二度目のダウンからダウン状態が続いても、24時間以内であればアラートを通知しません。

        - 最小アラート数(Min. Number of alerts): がアラートテンプレートで定義したアクションを実行する状態変化 (この例では、モジュールの障害状態) の回数です。この設定により、正常状態と障害状態を繰り返す大量のアラートが発生を避けることができます。ここに 1を設定すると、モジュールの一度の障害状態は無視します。0 を設定すると、モジュールの初回の障害状態でアラート通知がされます。

        + 最小アラート数(Min. Number of alerts): がアラートテンプレートで定義したアクションを実行する状態変化 (この例では、モジュールの障害状態) の回数です。この設定により、正常状態と障害状態を繰り返す大量のアラートが発生を避けることができます。ここに 1を設定すると、モジュールの一度の障害状態は無視します。0 を設定すると、モジュールの初回の障害状態でアラート通知がされます。

        最大アラート数(Max. Number of alerts): 1 は、アクションを一度だけ実行することを意味します。もし、ここに 10 を設定すると、アクションを 10回実行します。この設定により、アラートの実行回数を制限することができます。

        @@ -131,14 +131,14 @@ Subject: [MONITORING] Farscape cpu_sys is in CRITICAL status with value 20
        Texto email:

        -This is an automated alert generated by
        -Please contact your for more information. *DO NOT* reply this email.

        +This is an automated alert generated by
        +Please contact your for more information. *DO NOT* reply this email.

        下に、前もって定義したデフォルトのアクションが表示されます。このテンプレートを利用する全てのアラートは、設定を変更しなければデフォルトでこの定義済アクションを利用します。

        次のステップ3では、障害状態が復旧したときの通知に関する設定をみていきます。

        - '550px')); ?> + '550px']); ?> ほとんど一緒ですが、フィールド1(field1)がありません。なぜなら、(アラート通知時に) 実行されたアクションと同じだからです。この例では、cpu-syst モジュールが復旧したということを示す件名のメールを送るだけです。

        @@ -148,7 +148,7 @@ Please contact your for more information. *DO N 以上で、必要な設定が完了しました。あとは、アラートテンプレートをモジュールに関連づけるだけです。そのためには、エージェントのモジュールのアラートタブへいきます。

        - '550px')); ?> + '550px']); ?> 設定は簡単です。この画面ショットでは、 "Last_Backup_Unixtime" というモジュールに対して、事前に定義した "Module critical" というアラートが設定されています。加えて、ここでは下の画面を操作して、モジュール "cpu-sys" と、アラートテンプレート "Module critical" を関連づけようとしています。デフォルトで、このテンプレートで設定した "Sancho Lerena へメールを送信する" というアクションが表示されています。

        @@ -160,8 +160,8 @@ Please contact your for more information. *DO N 例えば、最初の障害発生時は XXXXX にメールを送り、障害状態が継続している場合は ZZZZ にメールを送信したい場合があったとします。そのためには、アラートの関連付のあとに、割り当てられたアラートに定義済のアクションを追加することができます。以下に画面ショットを示します。

        - '550px')); ?> - '550px')); ?> + '550px']); ?> + '550px']); ?> @@ -173,7 +173,7 @@ Please contact your for more information. *DO N メール送信以外のアラートコマンドの利用

        -メール送信は、 の内部コマンドであり、フィールド1、フィールド2、フィールド3 はそれぞれメール送信先、件名、本文として使うように定義されており変更することはできません。では、別のアクションを自分で定義したい時はどうすれば良いでしょうか。

        +メール送信は、 の内部コマンドであり、フィールド1、フィールド2、フィールド3 はそれぞれメール送信先、件名、本文として使うように定義されており変更することはできません。では、別のアクションを自分で定義したい時はどうすれば良いでしょうか。

        この場合は、新たなコマンドの定義画面へ行き、自分で定義を行います。検知したアラートそれぞれのログファイルを作成したいとします。ログファイルのフォーマットは次のようなものを想定します。

        @@ -184,11 +184,11 @@ Please contact your for more information. *DO N そのためには、次のようにコマンドの作成へ行きます。

        - '550px')); ?> + '550px']); ?> そして、アクションを定義します。

        - '550px')); ?> + '550px']); ?> 作成したログを見ると次のようになっています。

        @@ -196,4 +196,4 @@ Please contact your for more information. *DO N アラートは、"farscape" エージェントの "cpu_sys" モジュールで、18:17:10 に発生したこと、また、現在のデータは "23.00" であり、アクションで設定した説明が含まれていることがわかります。

        -コマンド実行時に、フィールドやその他がどのように引き渡されて実行されたかは簡単にはわかりません。それを確認する簡単な方法は、pandora サーバの設定ファイル /etc/pandora/pandora_server.conf にて、デバッグトレースを有効にする (verbose 10) ことです。 そして、 サーバがどのようにコマンドを実行しているか確認するには、サーバを再起動し (/etc/init.d/pandora_server restart)、/var/log/pandora/pandora_server.log に出力されている定義されたアラートの実行ログを探します。

        +コマンド実行時に、フィールドやその他がどのように引き渡されて実行されたかは簡単にはわかりません。それを確認する簡単な方法は、pandora サーバの設定ファイル /etc/pandora/pandora_server.conf にて、デバッグトレースを有効にする (verbose 10) ことです。 そして、 サーバがどのようにコマンドを実行しているか確認するには、サーバを再起動し (/etc/init.d/pandora_server restart)、/var/log/pandora/pandora_server.log に出力されている定義されたアラートの実行ログを探します。

        diff --git a/pandora_console/include/help/ja/help_cascade_protection.php b/pandora_console/include/help/ja/help_cascade_protection.php index f8d28a6fc6..70ab52576d 100644 --- a/pandora_console/include/help/ja/help_cascade_protection.php +++ b/pandora_console/include/help/ja/help_cascade_protection.php @@ -4,13 +4,13 @@

        エージェント関連障害検知抑制


        - +

        このオプションは、あるエージェントの障害により他のエージェントの状態が確認できなくなった時に、大量のアラートが上がるのを避けるために利用します。 たとえば、途中のルータがダウンしたことにより、その先の機器が実際には正常稼働していたとしても疎通が取れなくなったような場合です。 -何も設定を行わないと、 は ICMP(ping)疎通確認を実施し、疎通が取れなくなった全てのエージェントをダウン状態と認識します。 +何も設定を行わないと、 は ICMP(ping)疎通確認を実施し、疎通が取れなくなった全てのエージェントをダウン状態と認識します。

        エージェントで関連障害検知抑制を有効にすると、いずれかの親のエージェントで「障害」アラートが上がった場合は、その配下のエージェントではアラートは上がらなくなります。 親エージェントが「障害」状態よりレベルの低いアラート状態の場合は、配下のエージェントのアラートも上がります。 @@ -23,13 +23,13 @@

        モジュール関連障害検知抑制


        - +

        このオプションは、あるエージェントの障害により他のエージェントの状態が確認できなくなった時に、大量のアラートが上がるのを避けるために利用します。 たとえば、途中のルータがダウンしたことにより、その先の機器が実際には正常稼働していたとしても疎通が取れなくなったような場合です。 -何も設定を行わないと、 は ICMP(ping)疎通確認を実施し、疎通が取れなくなった全てのエージェントをダウン状態と認識します。 +何も設定を行わないと、 は ICMP(ping)疎通確認を実施し、疎通が取れなくなった全てのエージェントをダウン状態と認識します。

        モジュールで関連障害検知抑制を有効にすると、いずれかの親のエージェントのモジュールで「障害」アラートが上がった場合は、その配下のエージェントではアラートは上がらなくなります。

        diff --git a/pandora_console/include/help/ja/help_categories.php b/pandora_console/include/help/ja/help_categories.php index 678f9f72a1..5d56e764ff 100644 --- a/pandora_console/include/help/ja/help_categories.php +++ b/pandora_console/include/help/ja/help_categories.php @@ -3,7 +3,7 @@ * @package Include/help/ja */ ?> -

        におけるカテゴリ

        +

        におけるカテゴリ

        カテゴリはシステム上で設定され、選択されたモジュールに割り当てられます。
        管理者のみが、カテゴリを作成したり編集したりできます。属するカテゴリに応じてモジュールを操作するのに利用できます。 diff --git a/pandora_console/include/help/ja/help_collection_tab.php b/pandora_console/include/help/ja/help_collection_tab.php index b70becb178..54ded31c25 100644 --- a/pandora_console/include/help/ja/help_collection_tab.php +++ b/pandora_console/include/help/ja/help_collection_tab.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_collections.php b/pandora_console/include/help/ja/help_collections.php index b1ef729ee5..aab34cc021 100644 --- a/pandora_console/include/help/ja/help_collections.php +++ b/pandora_console/include/help/ja/help_collections.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_component_groups.php b/pandora_console/include/help/ja/help_component_groups.php index 5b301d02d5..bb60913294 100644 --- a/pandora_console/include/help/ja/help_component_groups.php +++ b/pandora_console/include/help/ja/help_component_groups.php @@ -1,7 +1,7 @@

        コンポーネントグループ

        diff --git a/pandora_console/include/help/ja/help_conf_alert_template.php b/pandora_console/include/help/ja/help_conf_alert_template.php index e1dc7cdc5b..adef563d41 100644 --- a/pandora_console/include/help/ja/help_conf_alert_template.php +++ b/pandora_console/include/help/ja/help_conf_alert_template.php @@ -44,7 +44,7 @@ 入力が完了したら、"次" ボタンをクリックし、次の画面に行きます。 - '550px')); ?> + '550px']); ?>

        次に、入力するフィールドの詳細を説明します。

        @@ -85,7 +85,7 @@ テンプレートがデフォルトで持つアクションをメニューから選択します。テンプレートをモジュールに割り当てた時、このアクションが自動的に設定されます。"なし"か、いずれか一つを選択することができますが、デフォルトとしては複数のアクションは選択できません。 - '550px')); ?> + '550px']); ?> 次の入力フィールは以下の通りです。

        diff --git a/pandora_console/include/help/ja/help_configure_gis_map.php b/pandora_console/include/help/ja/help_configure_gis_map.php index 93d5ec1e43..431390e448 100644 --- a/pandora_console/include/help/ja/help_configure_gis_map.php +++ b/pandora_console/include/help/ja/help_configure_gis_map.php @@ -10,17 +10,17 @@

        マップ名

        -それぞれのマップには 内で区別するための名前を定義します。 +それぞれのマップには 内で区別するための名前を定義します。

        利用マップの選択

        最初のステップは、GIS マップで利用するメインのマップを定義することです。 GIS マップを設定するためには、少なくとも一つ選択されている必要があります。 - "Add")); ?>(追加)アイコンをクリックして、追加することも可能です。 + 'Add']); ?>(追加)アイコンをクリックして、追加することも可能です。

        -意図しない設定情報の再入力を防ぐために、利用マップが設定されると、それを はデフォルトのマップとして利用するかどうか尋ねます。 -(ラジオボタンによって)デフォルトの利用マップが変更された場合は、それで良いか は再度尋ねます。 +意図しない設定情報の再入力を防ぐために、利用マップが設定されると、それを はデフォルトのマップとして利用するかどうか尋ねます。 +(ラジオボタンによって)デフォルトの利用マップが変更された場合は、それで良いか は再度尋ねます。

        マップパラメータ

        @@ -57,7 +57,7 @@ GIS マップを設定するためには、少なくとも一つ選択されて

        レイヤは、表示非表示の設定ができ、グループを選択やエージェントの追加ができます。 一度レイヤが定義されると、左側の定義済レイヤに移ります。(定義は、マップ全体が保存されるまでは保存されません。) -ここでは、再度、順番の変更 ( "move up icon")); ?>、 "move down icon")); ?>)、削除 ( "delete icon")); ?>)、編集 ( "edit icon")); ?>) ができます。 +ここでは、再度、順番の変更 ( 'move up icon']); ?>、 'move down icon']); ?>)、削除 ( 'delete icon']); ?>)、編集 ( 'edit icon']); ?>) ができます。


        1 デフォルトマップでは、エージェント名で一つのレイヤしか表示しない場合は、レイヤを持たない設定も可能です。 diff --git a/pandora_console/include/help/ja/help_context_module_unknow.php b/pandora_console/include/help/ja/help_context_module_unknow.php index 1590bc118e..addaa36919 100644 --- a/pandora_console/include/help/ja/help_context_module_unknow.php +++ b/pandora_console/include/help/ja/help_context_module_unknow.php @@ -3,7 +3,7 @@ * @package Include/help/ja */ ?> -

        における不明モジュール

        +

        における不明モジュール

        さまざまな理由で不明モジュールが発生することがあります。不明モジュールは、モジュールにおける特別な状態で、"直近で監視結果があるべきなのに、それが無い" ということを意味します。監視間隔の 2倍を超えて監視データを受信できない場合に不明になります。例えば、5分間隔の監視であれば、10分データを受信できないと不明になります。

        @@ -11,13 +11,13 @@ 不明モジュールの発生にはいくつかのケースがあります。

          -
        • サーバがダウンしている場合。それを再起動してくください。なぜダウンしたかを確認するために /var/log/pandora/pandora_server.log をチェックするのを忘れないようにしてください。
        • -
        • tentacle サーバがダウンしている場合で、リモートサーバにインストールしている からデータを取得できない場合。
        • -
        • エージェントとサーバの間でネットワークの問題が発生している場合。
        • -
        • エージェントが停止していて、サーバに情報を送信していない場合。
        • -
        • ネットワークがダウンしているか、監視対象のリモートデバイスがダウンしているか IP アドレスが変わった場合(例えば、SNMP のクエリなど)。
        • -
        • エージェントが間違った日時を報告していたり、過去の日時でデータを送っている場合。
        • -
        • スクリプトやモジュールが動作する前に、エージェント自体で何らかの問題が発生している場合。この場合はエージェントを確認してください。
        • +
        • サーバがダウンしている場合。それを再起動してくください。なぜダウンしたかを確認するために /var/log/pandora/pandora_server.log をチェックするのを忘れないようにしてください。
        • +
        • tentacle サーバがダウンしている場合で、リモートサーバにインストールしている からデータを取得できない場合。
        • +
        • エージェントとサーバの間でネットワークの問題が発生している場合。
        • +
        • エージェントが停止していて、サーバに情報を送信していない場合。
        • +
        • ネットワークがダウンしているか、監視対象のリモートデバイスがダウンしているか IP アドレスが変わった場合(例えば、SNMP のクエリなど)。
        • +
        • エージェントが間違った日時を報告していたり、過去の日時でデータを送っている場合。
        • +
        • スクリプトやモジュールが動作する前に、エージェント自体で何らかの問題が発生している場合。この場合はエージェントを確認してください。

        不明状態は、時には監視することが有用です。上記のような状態を警告するために、不明状態にアラートを設定することができます。 diff --git a/pandora_console/include/help/ja/help_context_pandora_server_email.php b/pandora_console/include/help/ja/help_context_pandora_server_email.php index 4acd60e574..7761b26406 100755 --- a/pandora_console/include/help/ja/help_context_pandora_server_email.php +++ b/pandora_console/include/help/ja/help_context_pandora_server_email.php @@ -3,14 +3,14 @@ * @package Include/help/ja */ ?> -

        email アラートのための サーバ設定

        -

        " サーバ設定ファイル"を編集する必要があります。通常は以下にあります。 +

        email アラートのための サーバ設定

        +

        " サーバ設定ファイル"を編集する必要があります。通常は以下にあります。

        -	/etc/pandora_server/pandora_server.conf
        +    /etc/pandora_server/pandora_server.conf
         
        次の値を設定します。
        -# mta_address: External Mailer (MTA) IP Address to be used by  internal email capabilities
        +# mta_address: External Mailer (MTA) IP Address to be used by  internal email capabilities
         
         mta_address localhost
         
        @@ -33,6 +33,6 @@ mta_auth LOGIN
         # mta_from Email address that sends the mail, by default is pandora@localhost 
         #           probably you need to change it to avoid problems with your antispam
         
        -mta_from  <monitoring@mydomain.com>
        +mta_from  <monitoring@mydomain.com>
         

        diff --git a/pandora_console/include/help/ja/help_create_agent.php b/pandora_console/include/help/ja/help_create_agent.php index 0d8ac45555..77a5cfb52b 100644 --- a/pandora_console/include/help/ja/help_create_agent.php +++ b/pandora_console/include/help/ja/help_create_agent.php @@ -12,5 +12,5 @@ "間隔" は、エージェントの実行間隔です。どの程度の頻度でエージェントがサーバにデータを送るかです。

        -"サーバ" は、 サーバで、エージェントから送られるデータを受け取ります。 +"サーバ" は、 サーバで、エージェントから送られるデータを受け取ります。

        diff --git a/pandora_console/include/help/ja/help_cron.php b/pandora_console/include/help/ja/help_cron.php index f6a5d02be5..af825b9383 100644 --- a/pandora_console/include/help/ja/help_cron.php +++ b/pandora_console/include/help/ja/help_cron.php @@ -7,7 +7,7 @@ 設定パラメータ Cron from および Cron to を用いることにより、特定の時間にのみモジュールを実行するようにできます。 設定のための書式は、cron に似ています。 - コンソールに表示され、それぞれのパラメータには 3つのオプションがあります。 + コンソールに表示され、それぞれのパラメータには 3つのオプションがあります。

        Cron from: any

        @@ -29,10 +29,10 @@ cron 条件が満たされている限り、エージェントは実行間隔に

          -
        • * * * * *: cron 設定なし。
        • -
        • 15 20 * * *: 毎日 20:15 に実行します。
        • -
        • * 20 * * *: 毎日 20時台、20:00 から 20:59 の間に実行します。
        • -
        • * 8-19 * * *: 毎日 8:00 から 19:59 の間に実行します。
        • -
        • 15-45 * 1-16 * *: 毎月 1日から 16日まで、毎時 15分から 45分の間で実行します。
        • -
        • * * * 5 *: 5月にのみ実行します。
        • +
        • * * * * *: cron 設定なし。
        • +
        • 15 20 * * *: 毎日 20:15 に実行します。
        • +
        • * 20 * * *: 毎日 20時台、20:00 から 20:59 の間に実行します。
        • +
        • * 8-19 * * *: 毎日 8:00 から 19:59 の間に実行します。
        • +
        • 15-45 * 1-16 * *: 毎月 1日から 16日まで、毎時 15分から 45分の間で実行します。
        • +
        • * * * 5 *: 5月にのみ実行します。
          • diff --git a/pandora_console/include/help/ja/help_custom_logo.php b/pandora_console/include/help/ja/help_custom_logo.php index 1fca279a7a..f9863b7e15 100644 --- a/pandora_console/include/help/ja/help_custom_logo.php +++ b/pandora_console/include/help/ja/help_custom_logo.php @@ -5,7 +5,7 @@ ?>

            カスタムロゴ

            -ここに指定した画像ファイルを、オリジナルロゴとして のヘッダーに表示することができます。 +ここに指定した画像ファイルを、オリジナルロゴとして のヘッダーに表示することができます。 表示可能な画像ファイルは PNG 形式です。 画像サイズは、206x47ピクセルに修正されます。

            diff --git a/pandora_console/include/help/ja/help_date_format.php b/pandora_console/include/help/ja/help_date_format.php index 5b510cb504..8f9cf89932 100644 --- a/pandora_console/include/help/ja/help_date_format.php +++ b/pandora_console/include/help/ja/help_date_format.php @@ -360,7 +360,7 @@ -D M j G:i:s T Y Sat Mar 10 15:16:08 MST 2001 +D M j G:i:s T Y Sat Mar 10 15:16:08 MST 2001 H:i:s17:16:17 diff --git a/pandora_console/include/help/ja/help_event_alert.php b/pandora_console/include/help/ja/help_event_alert.php index 927fbf6ecc..8894d57d50 100644 --- a/pandora_console/include/help/ja/help_event_alert.php +++ b/pandora_console/include/help/ja/help_event_alert.php @@ -1,7 +1,7 @@

            イベントアラート

            @@ -12,14 +12,14 @@

            - '250px')); ?> + '250px']); ?>
            イベントアラートは、論理式(and、or、xor、nand、nor、nxor)で結合されたルールで組 み立てられます。

            - '550px')); ?> + '550px']); ?>
            簡単に言うと、イベントアラートの設定パラメータは、モジュールアラートと同じです。イベントアラート特有のパラメータは2つだけです。 @@ -32,7 +32,7 @@

            - '550px')); ?> + '550px']); ?>
            @@ -56,8 +56,8 @@

            - '550px')); ?> + '550px']); ?> -

            * データベースに保存できるイベント数に関しては、pandora_server.conf ファイルの event_window パラメータにて定義します。この時間範囲を越えるイベントが発生した場合は、サーバは処理を行いません。そのため、サーバの設定よりも大きな時間間隔を設定しても意味がありません。

            +

            * データベースに保存できるイベント数に関しては、pandora_server.conf ファイルの event_window パラメータにて定義します。この時間範囲を越えるイベントが発生した場合は、サーバは処理を行いません。そのため、サーバの設定よりも大きな時間間隔を設定しても意味がありません。

            diff --git a/pandora_console/include/help/ja/help_events_history.php b/pandora_console/include/help/ja/help_events_history.php index eed3001724..ce8e386503 100644 --- a/pandora_console/include/help/ja/help_events_history.php +++ b/pandora_console/include/help/ja/help_events_history.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_events_replication.php b/pandora_console/include/help/ja/help_events_replication.php index 1158077edc..6298a4a8d8 100644 --- a/pandora_console/include/help/ja/help_events_replication.php +++ b/pandora_console/include/help/ja/help_events_replication.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_eventview.php b/pandora_console/include/help/ja/help_eventview.php index 1a8284e271..248c6a1849 100644 --- a/pandora_console/include/help/ja/help_eventview.php +++ b/pandora_console/include/help/ja/help_eventview.php @@ -9,25 +9,25 @@
            -

            承諾

            - "承諾済", "alt" => "承諾済", "width" => '10', "height" => '10')); ?> - 承諾済
            - "未承諾", "alt" => "未承諾", "width" => '10', "height" => '10')); ?> - 未承諾 +

            承諾

            + '承諾済', 'alt' => '承諾済', 'width' => '10', 'height' => '10']); ?> - 承諾済
            + '未承諾', 'alt' => '未承諾', 'width' => '10', 'height' => '10']); ?> - 未承諾
            -

            重要度

            - "メンテナンス", "alt" => "メンテナンス")); ?> - メンテナンス
            - "情報", "alt" => "情報")); ?> - 情報
            - "正常", "alt" => "正常")); ?> - 正常
            - "警告", "alt" => "警告")); ?> - 警告
            - "障害", "alt" => "障害")); ?> - 障害
            +

            重要度

            + 'メンテナンス', 'alt' => 'メンテナンス']); ?> - メンテナンス
            + '情報', 'alt' => '情報']); ?> - 情報
            + '正常', 'alt' => '正常']); ?> - 正常
            + '警告', 'alt' => '警告']); ?> - 警告
            + '障害', 'alt' => '障害']); ?> - 障害
            -

            アクション

            - "承諾する", "alt" => "承諾する")); ?> - 承諾する
            - "削除する", "alt" => "削除する")); ?> - 削除する
            - "インシデントを作成する", "alt" => "インシデントを作成する")); ?> - インシデントを作成する +

            アクション

            + '承諾する', 'alt' => '承諾する']); ?> - 承諾する
            + '削除する', 'alt' => '削除する']); ?> - 削除する
            + 'インシデントを作成する', 'alt' => 'インシデントを作成する']); ?> - インシデントを作成する
             
            diff --git a/pandora_console/include/help/ja/help_export_server.php b/pandora_console/include/help/ja/help_export_server.php index 1f98e92ec5..a541efd0ab 100644 --- a/pandora_console/include/help/ja/help_export_server.php +++ b/pandora_console/include/help/ja/help_export_server.php @@ -5,10 +5,10 @@ ?>

            エクスポートサーバ

            -

            エンタープライズ版の実装では、さまざまな情報をプロファイルに分割するように設計すれば、データスケーリング機能のエクスポートサーバで仮想的に無限のモニタリング情報を配布することができます。

            +

            エンタープライズ版の実装では、さまざまな情報をプロファイルに分割するように設計すれば、データスケーリング機能のエクスポートサーバで仮想的に無限のモニタリング情報を配布することができます。

              -
            • 名前: サーバ名。
            • +
            • 名前: サーバ名。
            • エクスポートサーバ: データをエクスポートするのに使うエクスポートサーバを選択します。
            • プレフィックス: 送信するデータのエージェント名に追加するプレフィックスです。例えば、"Farscape" という名前のエージェントがあり、エクスポートサーバのプレフィックスが "EU04" であれば、送信先のサーバでのエージェント名は、EU01-Farscape となります。
            • 間隔: 時間間隔および未解決のデータを送信する頻度(秒)を定義します。
            • diff --git a/pandora_console/include/help/ja/help_external_alert.php b/pandora_console/include/help/ja/help_external_alert.php index 0c3c8362fd..5c3cf9cb94 100644 --- a/pandora_console/include/help/ja/help_external_alert.php +++ b/pandora_console/include/help/ja/help_external_alert.php @@ -1,7 +1,7 @@

              外部アラート

              diff --git a/pandora_console/include/help/ja/help_ff_interval.php b/pandora_console/include/help/ja/help_ff_interval.php index e3083cf398..4951b2241d 100644 --- a/pandora_console/include/help/ja/help_ff_interval.php +++ b/pandora_console/include/help/ja/help_ff_interval.php @@ -17,39 +17,39 @@ データ 状態変化 - 12:00 - 1 - No + 12:00 + 1 + No - 12:05 - 1 - No + 12:05 + 1 + No - 12:10 - 0 - No + 12:10 + 0 + No - 12:11 - 1 - No + 12:11 + 1 + No - 12:16 - 1 - No + 12:16 + 1 + No - 12:21 - 0 - No + 12:21 + 0 + No - 12:22 - 0 - Yes + 12:22 + 0 + Yes diff --git a/pandora_console/include/help/ja/help_ff_timeout.php b/pandora_console/include/help/ja/help_ff_timeout.php index 3866a40253..3e07741875 100644 --- a/pandora_console/include/help/ja/help_ff_timeout.php +++ b/pandora_console/include/help/ja/help_ff_timeout.php @@ -18,34 +18,34 @@ データ 状態変化 - 12:00 - 1 - No + 12:00 + 1 + No - 12:05 - 0 - No + 12:05 + 0 + No - 12:20 - 0 - No + 12:20 + 0 + No - 12:25 - 1 - No + 12:25 + 1 + No - 12:45 - 0 - No + 12:45 + 0 + No - 12:50 - 0 - Yes + 12:50 + 0 + Yes diff --git a/pandora_console/include/help/ja/help_field_match_snmp.php b/pandora_console/include/help/ja/help_field_match_snmp.php index 13e20c8fd1..dae06b1484 100644 --- a/pandora_console/include/help/ja/help_field_match_snmp.php +++ b/pandora_console/include/help/ja/help_field_match_snmp.php @@ -1,7 +1,7 @@

              カスタム OID/データ #1-10(Custom OID/Data #1-10)

              @@ -11,7 +11,7 @@ -

              フィルタリング(および結果のマクロ)には最大 20の変数を利用できます。しかし、特定の順番に従う必要はありません。変数の位置は、フィールドの前の値で定義することができます。 +

              フィルタリング(および結果のマクロ)には最大 20の変数を利用できます。しかし、特定の順番に従う必要はありません。変数の位置は、フィールドの前の値で定義することができます。 つまり、もしトラップで受信した最初の値から <80><8B><80><8B>"Uno" という値を検索し、トラップで受信した 3番目の値の "Tres" 、同様に、<80><9C>Cinco<80><9D> and <80><9C>Siete<80><9D> でアラートを上げたい場合、次のように設定します。

              diff --git a/pandora_console/include/help/ja/help_gis_map_builder.php b/pandora_console/include/help/ja/help_gis_map_builder.php index 9274d12f15..1deb2e2d0f 100644 --- a/pandora_console/include/help/ja/help_gis_map_builder.php +++ b/pandora_console/include/help/ja/help_gis_map_builder.php @@ -8,7 +8,7 @@

              このページでは定義済のマップ一覧を表示しています。 それらの編集や削除、参照ができます。 -また、このページで、デフォルトマップが定義されています。 +また、このページで、デフォルトマップが定義されています。

              マップを作成するためには、利用マップの設定が必要です。 利用マップの設定は、設定メニューで管理者権限にて実施してください。 @@ -21,11 +21,11 @@
              マップ名
              マップ名をクリックすると、そのマップを編集できます。
              -
              "View")); ?> View
              +
              'View']); ?> View
              表示アイコンをクリックすると、マップを参照できます。
              デフォルトラジオボタン
              ラジオボタンをクリックすると、そのマップがデフォルトマップに設定されます。
              -
              "Delete")); ?> 削除
              +
              'Delete']); ?> 削除
              削除アイコンをクリックすると、そのマップを削除します。
              作成ボタン
              作成ボタンをクリックすると、新しいマップを作成できます。
              diff --git a/pandora_console/include/help/ja/help_gis_setup_map_connection.php b/pandora_console/include/help/ja/help_gis_setup_map_connection.php index eb42b7a2a8..c524b8663e 100644 --- a/pandora_console/include/help/ja/help_gis_setup_map_connection.php +++ b/pandora_console/include/help/ja/help_gis_setup_map_connection.php @@ -11,7 +11,7 @@

              マップの種類

              -現在、 は、OpenStreetマップ、Google マップ、静的画像の 3種類のマップをサポートしています。 +現在、 は、OpenStreetマップ、Google マップ、静的画像の 3種類のマップをサポートしています。

              Open Street マップ

              diff --git a/pandora_console/include/help/ja/help_gis_tab.php b/pandora_console/include/help/ja/help_gis_tab.php index 422ff83567..ea401dcc80 100644 --- a/pandora_console/include/help/ja/help_gis_tab.php +++ b/pandora_console/include/help/ja/help_gis_tab.php @@ -1,6 +1,7 @@

              エージェントの GIS 表示

              diff --git a/pandora_console/include/help/ja/help_graph_builder.php b/pandora_console/include/help/ja/help_graph_builder.php index 887d28dd79..e05de4a091 100644 --- a/pandora_console/include/help/ja/help_graph_builder.php +++ b/pandora_console/include/help/ja/help_graph_builder.php @@ -1,7 +1,7 @@

              グラフビルダー

              diff --git a/pandora_console/include/help/ja/help_graph_editor.php b/pandora_console/include/help/ja/help_graph_editor.php index 0244b178b7..55e5d1c98e 100644 --- a/pandora_console/include/help/ja/help_graph_editor.php +++ b/pandora_console/include/help/ja/help_graph_editor.php @@ -1,7 +1,7 @@

              アイテムエディタ

              diff --git a/pandora_console/include/help/ja/help_graph_view.php b/pandora_console/include/help/ja/help_graph_view.php index 6327dbd9b9..dc52da6027 100644 --- a/pandora_console/include/help/ja/help_graph_view.php +++ b/pandora_console/include/help/ja/help_graph_view.php @@ -1,7 +1,7 @@

              グラフビューワ

              diff --git a/pandora_console/include/help/ja/help_graphs.php b/pandora_console/include/help/ja/help_graphs.php index f95773d983..df193efd1b 100644 --- a/pandora_console/include/help/ja/help_graphs.php +++ b/pandora_console/include/help/ja/help_graphs.php @@ -1,61 +1,61 @@ -

              におけるグラフ処理

              +

              におけるグラフ処理

              -

              では、グラフは指定した期間においてモジュールが持つ値を表現します。

              -

              には、大量のデータが保存されるため、2つの異なるタイプの機能を提供しています。

              +

              では、グラフは指定した期間においてモジュールが持つ値を表現します。

              +

              には、大量のデータが保存されるため、2つの異なるタイプの機能を提供しています。

              通常グラフ

              -images/help/chart_normal_sample.png" alt="regular chart sample" /> +regular chart sample

              一般的な特性

              基本的なレベルでモジュールに保存された情報を表現するグラフがあります。

              @@ -96,7 +96,7 @@ div.img_title {
              一番上に発生したアラートの情報をポイント表示します。
              パーセント表示
              -
              グラフにパーセント表示の線を追加します。( の表示オプションで設定できます)
              +
              グラフにパーセント表示の線を追加します。( の表示オプションで設定できます)
              時間比較 (重ね合わせ)
              同一のグラフを重ね合わせて表示します。ただし、選択した期間より前との重ね合わせです。例えば、期間として 1週間を選択し、このオプションをチェックすると、選択した期間の前の 1週間が重ねあわされて表示されます。
              @@ -105,7 +105,7 @@ div.img_title {
              同一のグラフを表示します。ただし、選択した期間より前のグラフを別々に表示します。例えば、期間として 1週間を選択し、このオプションをチェックすると、選択した期間の前の 1週間のグラフも表示されます。
              不明グラフ表示
              -
              がモジュールの状態を把握していない、データ欠損、ソフトウエアエージェントの接続断などがあった期間を、グレーの箱で表示します。
              +
              がモジュールの状態を把握していない、データ欠損、ソフトウエアエージェントの接続断などがあった期間を、グレーの箱で表示します。
              詳細グラフ表示 (TIP)
              生成モードを "通常" から "TIP" へ切り替えます。このモードでは、グラフを近似値ではなく実データで表示します。そのため、生成にかかる時間は長くなります。このグラフでは、次に説明するより詳細の情報が参照できます。
              @@ -120,7 +120,7 @@ div.img_title {

              詳細グラフ

              -images/help/chart_tip_sample.png" alt="TIP chart sample" /> +TIP chart sample

              一般的な特性

              実データを表現するグラフです。

              @@ -130,10 +130,10 @@ div.img_title {

              通常と TIP グラフで提供される表示例:

              不明期間の通常グラフの例
              -images/help/chart_normal_detail.png" alt="Normal chart detail" /> +Normal chart detail
              不明期間の TIP グラフの例
              -images/help/chart_tip_detail.png" alt="TIP chart detail" /> +TIP chart detail
              diff --git a/pandora_console/include/help/ja/help_history_database.php b/pandora_console/include/help/ja/help_history_database.php index 9ece6b5070..a428e5e56e 100644 --- a/pandora_console/include/help/ja/help_history_database.php +++ b/pandora_console/include/help/ja/help_history_database.php @@ -5,7 +5,7 @@ ?>

              ヒストリデータベース

              -ヒストリデータベースは、メインの データベースの応答速度を確保するために、古いモジュールデータを毎日移動させるためのデータベースです。データは、 コンソールでレポートやグラフを表示するときにシームレスに参照できます。 +ヒストリデータベースは、メインの データベースの応答速度を確保するために、古いモジュールデータを毎日移動させるためのデータベースです。データは、 コンソールでレポートやグラフを表示するときにシームレスに参照できます。

              ヒストリデータベースの設定

              @@ -14,7 +14,7 @@
              1. 新たなヒストリデータベースの作成

                -
              2. 新たなデータベースに必要なテーブルを作成します。 コンソールと共に提供されている DB Tool スクリプトが利用できます。 +
              3. 新たなデータベースに必要なテーブルを作成します。 コンソールと共に提供されている DB Tool スクリプトが利用できます。

                cat pandoradb.sql | mysql -u user -p -D history_db

                @@ -22,10 +22,10 @@

                Mysql Example: GRANT ALL PRIVILEGES ON pandora.* TO 'pandora'@'IP' IDENTIFIED BY 'password'

                -
              4. コンソールの 設定(Setup) -> ヒストリデータベース(History database) のメニューへ行き、ホスト名、ポート番号、データベース名および、新たなデータベースのユーザ名とパスワードを入力します。 +
              5. コンソールの 設定(Setup) -> ヒストリデータベース(History database) のメニューへ行き、ホスト名、ポート番号、データベース名および、新たなデータベースのユーザ名とパスワードを入力します。


              - '550px')); ?> + '550px']); ?>

              "日間"に指定した日数より古いデータが、"ステップ"に指定したブロックサイズでヒストリデータベースに移動されます。負荷上昇を避けるために、"遅延"に指定した秒数だけブロック間の転送を待ちます。

              diff --git a/pandora_console/include/help/ja/help_inventory_tab.php b/pandora_console/include/help/ja/help_inventory_tab.php index ea08848839..c851f8f8a5 100644 --- a/pandora_console/include/help/ja/help_inventory_tab.php +++ b/pandora_console/include/help/ja/help_inventory_tab.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_ipam.php b/pandora_console/include/help/ja/help_ipam.php index e06a6654ae..28cac820b8 100644 --- a/pandora_console/include/help/ja/help_ipam.php +++ b/pandora_console/include/help/ja/help_ipam.php @@ -5,9 +5,9 @@ ?>

              IP アドレス管理 (IPAM)


              -IPAM 拡張を利用して、指定したネットワークのホストの管理、検出、変更イベントの検出をすることができます。IP アドレス(IPv4 または IPv6)が変更された場合、ホスト(ping応答)やホスト名(DNS名前解決の利用)が存在するかどうかを知ることができます。また、OS の検出および、現在割り当てられている IP アドレスを追加することにより、現在の エージェントに IP アドレスをリンクすることができます。IPAM 拡張は、ベースに自動検出サーバおよび自動検出スクリプトを利用します。ただし、何の設定も要りません。IPAM 拡張は全てを自動実行します。 +IPAM 拡張を利用して、指定したネットワークのホストの管理、検出、変更イベントの検出をすることができます。IP アドレス(IPv4 または IPv6)が変更された場合、ホスト(ping応答)やホスト名(DNS名前解決の利用)が存在するかどうかを知ることができます。また、OS の検出および、現在割り当てられている IP アドレスを追加することにより、現在の エージェントに IP アドレスをリンクすることができます。IPAM 拡張は、ベースに自動検出サーバおよび自動検出スクリプトを利用します。ただし、何の設定も要りません。IPAM 拡張は全てを自動実行します。

              -IP 管理は、 エージェントで設定している監視と並行して動作します。IP アドレス管理を IPAM 拡張と関連づけることも、そうしないことも、好きにできます。管理された IP アドレスは、変化時にオプションでイベントを生成することができます。 +IP 管理は、 エージェントで設定している監視と並行して動作します。IP アドレス管理を IPAM 拡張と関連づけることも、そうしないことも、好きにできます。管理された IP アドレスは、変化時にオプションでイベントを生成することができます。

              IP 検出

              ネットワークを設定する(ネットマスクまたはプレフィックスを利用)ことができ、ネットワークは、自動的に検出するかまたは、手動実行する設定ができます。これは、自動検出タスクを実行し、(IPv4 では nmap、IPv6 では ping を利用し)応答のある IP を検索します。ネットワーク検出の進捗、はステータス画面および自動検出サーバ画面でも見ることができます。 @@ -77,7 +77,7 @@ IP 管理は、 エージェントで設定し

              編集画面

              権限があれば、編集画面にアクセスできます。ここでは、IP アドレスが一覧で表示されます。必要な IP のみを表示するようにフィルタすることができます。すべて一度に変更および更新ができます。

              - エージェントおよび OS がある場合、ホスト名などいくつかのフィールドは、自動検出スクリプトによって自動的に入力されています。これらのフィールドは "手動" に設定して編集することができます。

              + エージェントおよび OS がある場合、ホスト名などいくつかのフィールドは、自動検出スクリプトによって自動的に入力されています。これらのフィールドは "手動" に設定して編集することができます。

              diff --git a/pandora_console/include/help/ja/help_local_component.php b/pandora_console/include/help/ja/help_local_component.php index 0b4621c626..68f675be42 100644 --- a/pandora_console/include/help/ja/help_local_component.php +++ b/pandora_console/include/help/ja/help_local_component.php @@ -1,9 +1,9 @@

              ローカルコンポーネント

              -

              ローカルコンポーネントは、テンプレートのようにエージェントに適用できる要素です。 エンタープライズ版では、これはポリシーを使ってリモートから自動的に適用できます。

              +

              ローカルコンポーネントは、テンプレートのようにエージェントに適用できる要素です。 エンタープライズ版では、これはポリシーを使ってリモートから自動的に適用できます。

              diff --git a/pandora_console/include/help/ja/help_macros.php b/pandora_console/include/help/ja/help_macros.php index 303cd410a8..2e25a69a76 100644 --- a/pandora_console/include/help/ja/help_macros.php +++ b/pandora_console/include/help/ja/help_macros.php @@ -9,9 +9,9 @@

              マクロには次の 3つのパラメータがあります。
                -
              • 説明
              • -
              • デフォルト値 (オプション)
              • -
              • ヘルプ (オプション)
              • +
              • 説明
              • +
              • デフォルト値 (オプション)
              • +
              • ヘルプ (オプション)
              例えば、サーバで動作している apache のプロセス数を返すモジュールの設定では、次のコマンドを実行します。 @@ -25,9 +25,9 @@ ps -A | grep _field1_ | wc -l マクロのパラメータは次のように設定します。
                -
              • 説明: Process
              • -
              • デフォルト値: apache2
              • -
              • ヘルプ: 指定した文字列の実行プロセス数をカウントします
              • +
              • 説明: Process
              • +
              • デフォルト値: apache2
              • +
              • ヘルプ: 指定した文字列の実行プロセス数をカウントします
              このコンポーネントのモジュールを設定すると、デフォルトの値が "apache2" のテキストフィールド "Process" が表示され編集することができます。また、詳細としてヘルプの内容が表示されます。 diff --git a/pandora_console/include/help/ja/help_main_help.php b/pandora_console/include/help/ja/help_main_help.php index 18f40f3afc..467ffd829f 100644 --- a/pandora_console/include/help/ja/help_main_help.php +++ b/pandora_console/include/help/ja/help_main_help.php @@ -3,10 +3,10 @@ * @package Include/help/ja */ ?> -

              - ヘルプ

              +

              - ヘルプ

              概要

              -これは、 コンソールのオンラインヘルプです。このヘルプは簡単に説明することを目的としたもので、 の使い方を教えることを意図しているわけではありません。 の公式ドキュメントは約 900ページにも及びます。全体を読む必要はありませんが、参照できるようにダウンロードしておくことをお勧めします。 +これは、 コンソールのオンラインヘルプです。このヘルプは簡単に説明することを目的としたもので、 の使い方を教えることを意図しているわけではありません。 の公式ドキュメントは約 900ページにも及びます。全体を読む必要はありませんが、参照できるようにダウンロードしておくことをお勧めします。

              公式ドキュメントのダウンロード diff --git a/pandora_console/include/help/ja/help_manage_alert_list.php b/pandora_console/include/help/ja/help_manage_alert_list.php index 254094f552..1c115a9361 100644 --- a/pandora_console/include/help/ja/help_manage_alert_list.php +++ b/pandora_console/include/help/ja/help_manage_alert_list.php @@ -6,9 +6,9 @@

              アラート

              - のアラートは、モジュールの値がしきい値を超えると動作します。アラート + のアラートは、モジュールの値がしきい値を超えると動作します。アラート では、管理者への e-mail や SMS 送信、SNMP トラップ送信、インシデント登録や Pando -ra FMS ログファイルへの記録等ができます。基本的に、 サーバを実行して +ra FMS ログファイルへの記録等ができます。基本的に、 サーバを実行して いる OS 上で実行できるスクリプトは何でも実行することができます。

              @@ -17,9 +17,9 @@ ra FMS ログファイルへの記録等ができます。基本的に、
                -
              • エージェント名: アラートを関連付けるエージェントの名前です。
              • -
              • モジュール: しきい値を超えたかどうかを確認するモジュールです。条件に合致すると、(e-mail 送信などの) イベントが発生します。 -
              • テンプレート: パラメータが定義されたアラートです。管理者が簡単に設定するために利用します。
              • -
              • アクション: 設定されたアラートで選択すします。テンプレートで定義されたアクションを選択できます。
              • -
              • 閾値: 最大回数を超えてアラートが発報されないことを保障する時間間隔を定義します。 +
              • エージェント名: アラートを関連付けるエージェントの名前です。
              • +
              • モジュール: しきい値を超えたかどうかを確認するモジュールです。条件に合致すると、(e-mail 送信などの) イベントが発生します。 +
              • テンプレート: パラメータが定義されたアラートです。管理者が簡単に設定するために利用します。
              • +
              • アクション: 設定されたアラートで選択すします。テンプレートで定義されたアクションを選択できます。
              • +
              • 閾値: 最大回数を超えてアラートが発報されないことを保障する時間間隔を定義します。
              diff --git a/pandora_console/include/help/ja/help_manage_alerts.php b/pandora_console/include/help/ja/help_manage_alerts.php index c667e2bd2d..c6606297d2 100644 --- a/pandora_console/include/help/ja/help_manage_alerts.php +++ b/pandora_console/include/help/ja/help_manage_alerts.php @@ -5,25 +5,25 @@ ?>

              アラート

              - のアラートは、モジュールの値がしきい値を超えると動作します。アラートでは、管理者への e-mail や SMS 送信、SNMP トラップ送信、インシデント登録や ログファイルへの記録等ができます。基本的に、 サーバを実行している OS 上で実行できるスクリプトは何でも実行することができます。 + のアラートは、モジュールの値がしきい値を超えると動作します。アラートでは、管理者への e-mail や SMS 送信、SNMP トラップ送信、インシデント登録や ログファイルへの記録等ができます。基本的に、 サーバを実行している OS 上で実行できるスクリプトは何でも実行することができます。

              実行するコマンドを作成する場合、"_field1_", "_field2_", "_field3_" という値を利用できます。

              新規アラートを作成するときは、以下のフィールドを入力する必要があります。
                -
              • アラート名: アラートの名前です。機能を説明するのに重要ですが、簡潔に書きます。例えば、"Comm. log" などです。
              • -
              • コマンド: アラートで実行するコマンドです。これは、アラート定義における一番重要なフィールドです。_field1_, _field2_ および _field3_ というマクロが利用でき、アラート定義のパラメータに置き換えられます。これにより、アラートで実行されるコマンド定義がされます。アラート定義では、アラートが正しく実行でき、期待した動作 (メール送信、ログの記録など) をするかコマンドラインからテストをしてください。
              • -
              • 説明: アラートの詳細の説明です。入力必須項目ではありません。
              • +
              • アラート名: アラートの名前です。機能を説明するのに重要ですが、簡潔に書きます。例えば、"Comm. log" などです。
              • +
              • コマンド: アラートで実行するコマンドです。これは、アラート定義における一番重要なフィールドです。_field1_, _field2_ および _field3_ というマクロが利用でき、アラート定義のパラメータに置き換えられます。これにより、アラートで実行されるコマンド定義がされます。アラート定義では、アラートが正しく実行でき、期待した動作 (メール送信、ログの記録など) をするかコマンドラインからテストをしてください。
              • +
              • 説明: アラートの詳細の説明です。入力必須項目ではありません。
              アラートで利用できるマクロの詳細は次の通りです。
                -
              • _field1_: 通常は、ユーザ名、電話番号、送信するファイル、または、メールの送信先アドレスに利用します。
              • -
              • _field2_: 通常は、イベントの短い説明やメールの件名に利用します。
              • -
              • _field3_: イベントの詳細説明に利用します。メールや SMS の本文に利用できます。
              • -
              • _agent_: エージェント名になります
              • -
              • _timestamp_: 日時情報になります。アラートが実行された日時に置き換えられます。
              • -
              • _data_: アラートのきっかけとなったモジュールの値になります。
              • +
              • _field1_: 通常は、ユーザ名、電話番号、送信するファイル、または、メールの送信先アドレスに利用します。
              • +
              • _field2_: 通常は、イベントの短い説明やメールの件名に利用します。
              • +
              • _field3_: イベントの詳細説明に利用します。メールや SMS の本文に利用できます。
              • +
              • _agent_: エージェント名になります
              • +
              • _timestamp_: 日時情報になります。アラートが実行された日時に置き換えられます。
              • +
              • _data_: アラートのきっかけとなったモジュールの値になります。
              diff --git a/pandora_console/include/help/ja/help_map_builder.php b/pandora_console/include/help/ja/help_map_builder.php index 5ca2a9b3f4..519151892e 100644 --- a/pandora_console/include/help/ja/help_map_builder.php +++ b/pandora_console/include/help/ja/help_map_builder.php @@ -7,28 +7,28 @@ マップを作成するには、最初に次の項目を入力します。
                -
              • 名前
              • -
              • グループ
              • -
              • 背景画像
              • +
              • 名前
              • +
              • グループ
              • +
              • 背景画像
              入力が完了したら「追加」をクリックします。するとマップがロードされます。

              マップにアイテムを追加するには、背景画像の下の「マップアイテム編集」フォームに入力します。 フォームには次の内容を入力します。
                -
              • ラベルと色
              • -
              • 種類:
                +
              • ラベルと色
              • +
              • 種類:
                ・状態を表すアイコン - 対象の状態に応じて色が変化するアイコンを表示します
                ・モジュールデータのグラフ - モジュールが収集しているデータをグラフで表示します
                ・値 - モジュールが収集している現在の値を表示します
                ・パーセント(バー) - モジュールが収集している現在の値を棒グラフでパーセント表示します
                -
              • -
              • マップに表示するエージェント
              • -
              • マップに表示するモジュール
              • -
              • 更新間隔
              • -
              • 画像
              • -
              • 親クラス - 他のアイテムの子アイテムとして定義したい場合に指定します。
              • -
              • リンク先マップ - アイテムを他のマップへリンクしたい場合に指定します
              • + +
              • マップに表示するエージェント
              • +
              • マップに表示するモジュール
              • +
              • 更新間隔
              • +
              • 画像
              • +
              • 親クラス - 他のアイテムの子アイテムとして定義したい場合に指定します。
              • +
              • リンク先マップ - アイテムを他のマップへリンクしたい場合に指定します
              作成済みアイテムのプロパティを編集するには、マップ上のアイテムを「マップアイテム編集」にドラッグ&ドロップします。

              diff --git a/pandora_console/include/help/ja/help_meta_access.php b/pandora_console/include/help/ja/help_meta_access.php index 550d4b2faa..48ca9054ae 100644 --- a/pandora_console/include/help/ja/help_meta_access.php +++ b/pandora_console/include/help/ja/help_meta_access.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_metaconsole_agent_cache.php b/pandora_console/include/help/ja/help_metaconsole_agent_cache.php index 28e65b0b3b..8bf50f48a3 100644 --- a/pandora_console/include/help/ja/help_metaconsole_agent_cache.php +++ b/pandora_console/include/help/ja/help_metaconsole_agent_cache.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_module_interval.php b/pandora_console/include/help/ja/help_module_interval.php index 1a22e089bd..49bfe28914 100644 --- a/pandora_console/include/help/ja/help_module_interval.php +++ b/pandora_console/include/help/ja/help_module_interval.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_module_interval_factor.php b/pandora_console/include/help/ja/help_module_interval_factor.php index 1db1104db8..5ef70c530c 100644 --- a/pandora_console/include/help/ja/help_module_interval_factor.php +++ b/pandora_console/include/help/ja/help_module_interval_factor.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_module_linking.php b/pandora_console/include/help/ja/help_module_linking.php index 1e4dc95ea9..8dbbe33786 100644 --- a/pandora_console/include/help/ja/help_module_linking.php +++ b/pandora_console/include/help/ja/help_module_linking.php @@ -1,7 +1,7 @@

              モジュールのリンク

              diff --git a/pandora_console/include/help/ja/help_module_type.php b/pandora_console/include/help/ja/help_module_type.php index bfc95fd01f..a618513196 100644 --- a/pandora_console/include/help/ja/help_module_type.php +++ b/pandora_console/include/help/ja/help_module_type.php @@ -7,25 +7,25 @@ モジュールの種類一覧:
                -
              • async_data: Asynchronous numeric data / 非同期数値データ
              • -
              • async_inc: Asynchronous incremental data / 非同期インクリメンタルデータ
              • -
              • async_proc: Asynchronous proc data / 非同期booleanデータ
              • -
              • async_string: Asynchronous string data / 非同期文字列データ
              • -
              • generic_data: Generic module to acquire numeric data / 数値データ取得の一般モジュール
              • -
              • generic_data_inc: Generic module to acquire numeric incremental data / インクリメンタルデータ取得の一般モジュール
              • -
              • generic_data_string: Generic module to acquire alphanumeric data / 文字列取得の一般モジュール
              • -
              • generic_proc: Generic module to acquire boolean data / booleanデータ取得の一般モジュール
              • -
              • image_jpg: Image JPG data / JPG画像データ
              • -
              • image_png: Image PNG data / PNG画像データ
              • -
              • keep_alive: KeepAlive
              • -
              • remote_icmp: Remote ICMP network agent (latency) / リモート ICMP エージェント(レガシィ)
              • -
              • remote_icmp_proc: Remote ICMP network agent, boolean data / リモート ICMP エージェント(booleanデータ)
              • -
              • remote_snmp: Remote SNMP network agent, numeric data / リモート SNMP エージェント(数値データ)
              • -
              • remote_snmp_inc: Remote SNMP network agent, incremental data / リモート SNMP エージェント(インクリメンタルデータ)
              • -
              • remote_snmp_proc: Remote SNMP network agent, boolean data / リモート SNMP エージェント(booleanデータ)
              • -
              • remote_snmp_string: Remote SNMP network agent, alphanumeric data / リモート SNMP エージェント(文字列データ)
              • -
              • remote_tcp: Remote TCP network agent, numeric data / リモート TCP エージェント(数値データ)
              • -
              • remote_tcp_inc: Remote TCP network agent, incremental data / リモート TCP エージェント(インクリメンタルデータ)
              • -
              • remote_tcp_proc: Remote TCP network agent, boolean data / リモート TCP エージェント(booleanデータ)
              • -
              • remote_tcp_string: Remote TCP network agent, alphanumeric data / リモート TCP エージェント(文字列データ)
              • +
              • async_data: Asynchronous numeric data / 非同期数値データ
              • +
              • async_inc: Asynchronous incremental data / 非同期インクリメンタルデータ
              • +
              • async_proc: Asynchronous proc data / 非同期booleanデータ
              • +
              • async_string: Asynchronous string data / 非同期文字列データ
              • +
              • generic_data: Generic module to acquire numeric data / 数値データ取得の一般モジュール
              • +
              • generic_data_inc: Generic module to acquire numeric incremental data / インクリメンタルデータ取得の一般モジュール
              • +
              • generic_data_string: Generic module to acquire alphanumeric data / 文字列取得の一般モジュール
              • +
              • generic_proc: Generic module to acquire boolean data / booleanデータ取得の一般モジュール
              • +
              • image_jpg: Image JPG data / JPG画像データ
              • +
              • image_png: Image PNG data / PNG画像データ
              • +
              • keep_alive: KeepAlive
              • +
              • remote_icmp: Remote ICMP network agent (latency) / リモート ICMP エージェント(レガシィ)
              • +
              • remote_icmp_proc: Remote ICMP network agent, boolean data / リモート ICMP エージェント(booleanデータ)
              • +
              • remote_snmp: Remote SNMP network agent, numeric data / リモート SNMP エージェント(数値データ)
              • +
              • remote_snmp_inc: Remote SNMP network agent, incremental data / リモート SNMP エージェント(インクリメンタルデータ)
              • +
              • remote_snmp_proc: Remote SNMP network agent, boolean data / リモート SNMP エージェント(booleanデータ)
              • +
              • remote_snmp_string: Remote SNMP network agent, alphanumeric data / リモート SNMP エージェント(文字列データ)
              • +
              • remote_tcp: Remote TCP network agent, numeric data / リモート TCP エージェント(数値データ)
              • +
              • remote_tcp_inc: Remote TCP network agent, incremental data / リモート TCP エージェント(インクリメンタルデータ)
              • +
              • remote_tcp_proc: Remote TCP network agent, boolean data / リモート TCP エージェント(booleanデータ)
              • +
              • remote_tcp_string: Remote TCP network agent, alphanumeric data / リモート TCP エージェント(文字列データ)
              diff --git a/pandora_console/include/help/ja/help_network_map_enterprise.php b/pandora_console/include/help/ja/help_network_map_enterprise.php index 94a887cdb4..abf221ab8a 100644 --- a/pandora_console/include/help/ja/help_network_map_enterprise.php +++ b/pandora_console/include/help/ja/help_network_map_enterprise.php @@ -1,12 +1,12 @@

              ネットワークマップコンソール

              -

              Enterprise では、編集可能なネットワークマップを作成することができます。ネットワーク参照メニューにあるオープンソース版のものと比べるとより対話形式になっています。

              +

              Enterprise では、編集可能なネットワークマップを作成することができます。ネットワーク参照メニューにあるオープンソース版のものと比べるとより対話形式になっています。

              オープンソース版に対して Enterprise 版のネットワークマップでは、次のような機能があります。

              @@ -48,7 +48,7 @@

              コントロールパネルからは、ネットワークマップのより複雑な操作ができます。

              これは右上に隠れています。ミニマップと同様に、矢印をクリックすることで表示できます。

              - '550px')); ?> + '550px']); ?>

              操作オプションは次の通りです。

              @@ -66,12 +66,12 @@

              詳細表示ウインドウは、一つのエージェントのビジュアル表示です。開いたマップと同じ頻度で更新されます。個々のウインドウは完全に独立しているため、複数のウインドウを開くことができます。

              - '550px')); ?>

              + '550px']); ?>

              エージェントの状態と同じ色の枠で表示されます。
              - エージェント名は、 のエージェントのページへのリンクになっています。
              + エージェント名は、 のエージェントのページへのリンクになっています。
              ウインドウ内には、不明状態ではないすべてのモジュールが、緑や赤といったモジュールの状態に応じて表示されます。
              モジュールをクリックすると、モジュールのメインデータと共に簡単な説明が表示されます。
              枠の中には、SNMP Proc のモジュールがあります。ネットワーク機器関連のエージェントで、ネットワークインタフェースの監視に使われます。

              @@ -80,7 +80,7 @@

              仮想ポイントの詳細を表示すると、仮想ポイントを編集するためのオプションパレットをポップアップウインドウで表示します。

              - '550px')); ?>

              + '550px']); ?>

              次のオプションのフォームがあります。

              diff --git a/pandora_console/include/help/ja/help_no_hierarchy.php b/pandora_console/include/help/ja/help_no_hierarchy.php index 1970c9865a..6119f113c7 100644 --- a/pandora_console/include/help/ja/help_no_hierarchy.php +++ b/pandora_console/include/help/ja/help_no_hierarchy.php @@ -13,17 +13,25 @@ We explained that the permissions of a group can be extended to the children by As a reference for the examples, we propose a configuration with two parent groups "Applications" and "Databases" with two children each, "Development_Apps" and "Management_Apps" for the former and "Databases_America" and "Databases_Asia" for the latter. Both parent groups are marked for ACL to spread.

              - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

              In the user edit view, if the following profiles are added:

              - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

              The user will have access to the groups named "Applications", "Development_Apps", "Management_Apps" and "Databases". @@ -33,9 +41,13 @@ The user will have access to the groups named "Applications", "Development_Apps" However, if a child of "Databases" is added:

              - "max-width:100%" -)); ?> + 'max-width:100%' ] +); +?>

              Now the user will have access to the groups named "Applications", "Development_Apps", "Management_Apps", "Databases" and "Databases_Asia", but not to "Databases_America". diff --git a/pandora_console/include/help/ja/help_planned_downtime.php b/pandora_console/include/help/ja/help_planned_downtime.php index 22eb78b6d9..1f8e416d36 100644 --- a/pandora_console/include/help/ja/help_planned_downtime.php +++ b/pandora_console/include/help/ja/help_planned_downtime.php @@ -14,7 +14,7 @@ 説明には任意の文章を入力できます。

              -計画停止時間が来ると、 は自動的に該当するすべてのエージェントのアラートやデータ収集を停止します。 +計画停止時間が来ると、 は自動的に該当するすべてのエージェントのアラートやデータ収集を停止します。 その時間が終了すると、該当する全てのエージェントを有効に戻します。 計画停止時間になると、該当する設定は削除や編集ができなくなります。 削除・編集には、計画停止時間の終了を待つ必要があります。 diff --git a/pandora_console/include/help/ja/help_plugin_definition.php b/pandora_console/include/help/ja/help_plugin_definition.php index 6e536c32c8..2e7ab2a9e2 100644 --- a/pandora_console/include/help/ja/help_plugin_definition.php +++ b/pandora_console/include/help/ja/help_plugin_definition.php @@ -5,20 +5,20 @@ ?>

              プラグイン登録

              -他のコンポーネントとは異なり、デフォルトでは にあらかじめ設定されたコンポーネントが存在しません。そのため、エージェントのモジュールに追加できるよ、作成する必要があります。 のインストールディレクトリにはいくつかのプラグインが含まれていますが、前述の通りデータベースに設定はされていません。 +他のコンポーネントとは異なり、デフォルトでは にあらかじめ設定されたコンポーネントが存在しません。そのため、エージェントのモジュールに追加できるよ、作成する必要があります。 のインストールディレクトリにはいくつかのプラグインが含まれていますが、前述の通りデータベースに設定はされていません。

              - にすでに存在するプラグインを追加するには、コンソールの管理メニューで、サーバ管理をクリックします。その後、プラグイン管理をクリックします。 + にすでに存在するプラグインを追加するには、コンソールの管理メニューで、サーバ管理をクリックします。その後、プラグイン管理をクリックします。

              プラグイン管理画面に行ったら、追加ボタンをクリックします。それ以外のメニューはありません。

              次のように、プラグイン作成のフォームを入力します。 - '550px')); ?> + '550px']); ?>

              名前(Name)
              プラグイン名です。ここでは、Nmap です。

              プラグインタイプ(Plugin type)
              -プラグインは、標準と Nagios の 2種類があります。標準プラグインは、処理を実行し値を取得するものです。Nagios プラグインは、その名の通り で Nagios プラグインを利用できるようにするものです。Nagios プラグインの主な違いは、実行結果の成功・失敗を戻値で返すことです。 +プラグインは、標準と Nagios の 2種類があります。標準プラグインは、処理を実行し値を取得するものです。Nagios プラグインは、その名の通り で Nagios プラグインを利用できるようにするものです。Nagios プラグインの主な違いは、実行結果の成功・失敗を戻値で返すことです。

              Nagios プラグインを利用して正常・異常の状態ではなくデータを取得したい場合は、Nagios プラグインを "標準" モードで利用します。

              @@ -38,7 +38,7 @@ Nagios プラグインを利用して正常・異常の状態ではなくデー プラグインコマンドのパスを設定します。デフォルトのディレクトリは、標準のインストールをした場合、/usr/share/pandora_server/util/plugin/ です。システム上の任意のパスを指定することができます。この例では、/usr/share/pandora_server/util/plugin/udp_nmap_plugin.shin を設定しています。

              - サーバは、このスクリプトを実行します。このファイルは、アクセスし実行できるパーミッションになっている必要があります。 + サーバは、このスクリプトを実行します。このファイルは、アクセスし実行できるパーミッションになっている必要があります。

              プラグインパラメータ(Plug-in parameters)
              @@ -56,8 +56,9 @@ Nagios プラグインを利用して正常・異常の状態ではなくデー

              マクロ設定例:

              - '550px')); ?> + '550px']); ?>

              モジュールの編集画面におけるこのマクロの例:

              - '550px')); ?> + '550px']); diff --git a/pandora_console/include/help/ja/help_plugin_parameters.php b/pandora_console/include/help/ja/help_plugin_parameters.php index 38582d6cf3..8917dcdf48 100644 --- a/pandora_console/include/help/ja/help_plugin_parameters.php +++ b/pandora_console/include/help/ja/help_plugin_parameters.php @@ -9,9 +9,9 @@

              例えば次のようなものです。
                -
              • URL
              • -
              • パス
              • -
              • ファイル
              • -
              • Etc.
              • +
              • URL
              • +
              • パス
              • +
              • ファイル
              • +
              • Etc.
              このフィールドはオプションで、プラグインの仕様に依存します。 diff --git a/pandora_console/include/help/ja/help_plugin_policy.php b/pandora_console/include/help/ja/help_plugin_policy.php index 0fb9333395..1a2b52b35e 100644 --- a/pandora_console/include/help/ja/help_plugin_policy.php +++ b/pandora_console/include/help/ja/help_plugin_policy.php @@ -1,7 +1,7 @@

              エージェントプラグイン

              diff --git a/pandora_console/include/help/ja/help_policy_agent.php b/pandora_console/include/help/ja/help_policy_agent.php index 243898ba3b..67a0c07995 100644 --- a/pandora_console/include/help/ja/help_policy_agent.php +++ b/pandora_console/include/help/ja/help_policy_agent.php @@ -1,7 +1,7 @@

              ポリシーエージェント

              diff --git a/pandora_console/include/help/ja/help_policy_queue.php b/pandora_console/include/help/ja/help_policy_queue.php index 603232e46b..e5cffd98e5 100644 --- a/pandora_console/include/help/ja/help_policy_queue.php +++ b/pandora_console/include/help/ja/help_policy_queue.php @@ -1,7 +1,7 @@

              キュー

              diff --git a/pandora_console/include/help/ja/help_prediction_date.php b/pandora_console/include/help/ja/help_prediction_date.php index 597d2a3627..259aa2a197 100644 --- a/pandora_console/include/help/ja/help_prediction_date.php +++ b/pandora_console/include/help/ja/help_prediction_date.php @@ -13,4 +13,4 @@

              以下の例では、disk_temp_free というモジュールで、二か月間を選択しデータ範囲を [5-0] として、04 Dec 2011 18:36:23 が出力されています。

              これはグラフ表示バージョンです。

              - '210')); ?> + '210']); diff --git a/pandora_console/include/help/ja/help_profile.php b/pandora_console/include/help/ja/help_profile.php index 0c97704f3f..0915b51aba 100644 --- a/pandora_console/include/help/ja/help_profile.php +++ b/pandora_console/include/help/ja/help_profile.php @@ -1,7 +1,7 @@

              プロファイル

              diff --git a/pandora_console/include/help/ja/help_projection_graph.php b/pandora_console/include/help/ja/help_projection_graph.php index f4b586777e..7cf7163afc 100644 --- a/pandora_console/include/help/ja/help_projection_graph.php +++ b/pandora_console/include/help/ja/help_projection_graph.php @@ -1,7 +1,7 @@

              予想グラフ

              - '210')); ?> + '210']); ?>

              予想グラフは将来のモジュールデータを予想します。予想は線形回帰を利用しています。 diff --git a/pandora_console/include/help/ja/help_recontask.php b/pandora_console/include/help/ja/help_recontask.php index f70113674a..790c2cdb48 100644 --- a/pandora_console/include/help/ja/help_recontask.php +++ b/pandora_console/include/help/ja/help_recontask.php @@ -26,7 +26,7 @@ 間隔(Interval)
              -検出処理の間隔です。自動検出処理では、ネットワーク上にそれぞれの IP アドレスに対して ping を送信するため、短い間隔は設定しないでください。自動検出対象ネットワークが非常に大きく(例えばクラスAのネットワーク)、間隔が短い(6時間)と、 はネットワークに大量の ping を投げ続け、ネットワークおよび が高負荷になります。

              +検出処理の間隔です。自動検出処理では、ネットワーク上にそれぞれの IP アドレスに対して ping を送信するため、短い間隔は設定しないでください。自動検出対象ネットワークが非常に大きく(例えばクラスAのネットワーク)、間隔が短い(6時間)と、 はネットワークに大量の ping を投げ続け、ネットワークおよび が高負荷になります。

              モジュールテンプレート(Module template)
              @@ -34,7 +34,7 @@ OS
              -認識するオペレーティングシステムです。任意(Any)の OS ではなく特定の OS を選択した場合、該当の OS のシステムのみ追加されます。静的なパラメータを元に実施されるため、(ネットワークがフィルタリングされている、セキュリティソフトウエアが導入されている、システムのバージョンが編集されているなど)特定の条件下では、システム検出時に が誤認識する可能性があることに注意してください。この機能を利用するには、Xprobe2 がインストールされている必要があります。

              +認識するオペレーティングシステムです。任意(Any)の OS ではなく特定の OS を選択した場合、該当の OS のシステムのみ追加されます。静的なパラメータを元に実施されるため、(ネットワークがフィルタリングされている、セキュリティソフトウエアが導入されている、システムのバージョンが編集されているなど)特定の条件下では、システム検出時に が誤認識する可能性があることに注意してください。この機能を利用するには、Xprobe2 がインストールされている必要があります。

              ポート(Ports)
              diff --git a/pandora_console/include/help/ja/help_reporting_global_tab.php b/pandora_console/include/help/ja/help_reporting_global_tab.php index ee077ab4cb..7bb4b4d140 100644 --- a/pandora_console/include/help/ja/help_reporting_global_tab.php +++ b/pandora_console/include/help/ja/help_reporting_global_tab.php @@ -1,7 +1,7 @@

              グローバル

              diff --git a/pandora_console/include/help/ja/help_reporting_item_editor_tab.php b/pandora_console/include/help/ja/help_reporting_item_editor_tab.php index 632620dd54..038458eecf 100644 --- a/pandora_console/include/help/ja/help_reporting_item_editor_tab.php +++ b/pandora_console/include/help/ja/help_reporting_item_editor_tab.php @@ -1,7 +1,7 @@

              レポートアイテムエディタ

              diff --git a/pandora_console/include/help/ja/help_reporting_list_items_tab.php b/pandora_console/include/help/ja/help_reporting_list_items_tab.php index 37715e885d..bbb83c0ee3 100644 --- a/pandora_console/include/help/ja/help_reporting_list_items_tab.php +++ b/pandora_console/include/help/ja/help_reporting_list_items_tab.php @@ -1,7 +1,7 @@

              レポートのアイテム一覧

              diff --git a/pandora_console/include/help/ja/help_reporting_main_tab.php b/pandora_console/include/help/ja/help_reporting_main_tab.php index 02f438e98d..7c71fa3b70 100644 --- a/pandora_console/include/help/ja/help_reporting_main_tab.php +++ b/pandora_console/include/help/ja/help_reporting_main_tab.php @@ -7,9 +7,9 @@ レポートを作成するには、最初に次のフォームを入力します。
                -
              • 名前
              • -
              • グループ
              • -
              • 説明
              • +
              • 名前
              • +
              • グループ
              • +
              • 説明
              次に、作成をクリックします。

              diff --git a/pandora_console/include/help/ja/help_reporting_preview_tab.php b/pandora_console/include/help/ja/help_reporting_preview_tab.php index 6e56c9572e..5b64ae1425 100644 --- a/pandora_console/include/help/ja/help_reporting_preview_tab.php +++ b/pandora_console/include/help/ja/help_reporting_preview_tab.php @@ -1,7 +1,7 @@

              プレビュー

              diff --git a/pandora_console/include/help/ja/help_reporting_wizard_sla_tab.php b/pandora_console/include/help/ja/help_reporting_wizard_sla_tab.php index f3c11069d0..37087570e3 100644 --- a/pandora_console/include/help/ja/help_reporting_wizard_sla_tab.php +++ b/pandora_console/include/help/ja/help_reporting_wizard_sla_tab.php @@ -1,9 +1,9 @@

              SLA ウィザード

              -

              でモニタリングしているサービスレベル (Service Level Agreement) を計測できます。このウィザードでは、複数のエージェントの SLA レポートを作成することができます。

              +

              でモニタリングしているサービスレベル (Service Level Agreement) を計測できます。このウィザードでは、複数のエージェントの SLA レポートを作成することができます。

              diff --git a/pandora_console/include/help/ja/help_reporting_wizard_tab.php b/pandora_console/include/help/ja/help_reporting_wizard_tab.php index 2de57bd694..eb4eaa275e 100644 --- a/pandora_console/include/help/ja/help_reporting_wizard_tab.php +++ b/pandora_console/include/help/ja/help_reporting_wizard_tab.php @@ -1,7 +1,7 @@

              ウィザード

              diff --git a/pandora_console/include/help/ja/help_reports_label_field.php b/pandora_console/include/help/ja/help_reports_label_field.php index c8a23d6983..e3e719d562 100755 --- a/pandora_console/include/help/ja/help_reports_label_field.php +++ b/pandora_console/include/help/ja/help_reports_label_field.php @@ -7,20 +7,20 @@

              次のマクロも使えます:
              -

                - エージェントごとに一つのグラフを選択した場合のみ
                +
                  + エージェントごとに一つのグラフを選択した場合のみ
                • _agent_ : レポートアイテムで選択したエージェント名。
                • -
                • _agentdescription_ : レポートアイテムで選択したエージェントの説明。
                • +
                • _agentdescription_ : レポートアイテムで選択したエージェントの説明。
                • _agentgroup_ : エージェントグループ名。
                • _address_ : レポートアイテムで選択したエージェントのアドレス。
                • -
                    -
                    - -
                      - エージェントモジュールのフォームで利用可能なもの
                      -
                    • _module_ : レポートアイテムで選択したモジュール名。
                    • -
                    • _moduledescription_ : レポートアイテムで選択したモジュールの説明。
                    • -
                        +
                          +
                          + +
                            + エージェントモジュールのフォームで利用可能なもの
                            +
                          • _module_ : レポートアイテムで選択したモジュール名。
                          • +
                          • _moduledescription_ : レポートアイテムで選択したモジュールの説明。
                          • +
                              例: エージェント: _agent_ / モジュール: _module_

                              diff --git a/pandora_console/include/help/ja/help_response_macros.php b/pandora_console/include/help/ja/help_response_macros.php index f5ae7ee4e1..1aa60b38a4 100644 --- a/pandora_console/include/help/ja/help_response_macros.php +++ b/pandora_console/include/help/ja/help_response_macros.php @@ -18,7 +18,7 @@
                            • イベントID: _event_id_
                            • Event instructions: _event_instruction_
                            • Event severity ID: _event_severity_id_
                            • -
                            • Event severity (translated by console): _event_severity_text_
                            • +
                            • Event severity (translated by console): _event_severity_text_
                            • Event source: _event_source_
                            • Event status (new, validated or event in process): _event_status_
                            • Event tags separated by commas: _event_tags_
                            • diff --git a/pandora_console/include/help/ja/help_servers.php b/pandora_console/include/help/ja/help_servers.php index 6bd01880a1..7dcdc5292e 100644 --- a/pandora_console/include/help/ja/help_servers.php +++ b/pandora_console/include/help/ja/help_servers.php @@ -1,16 +1,16 @@

                              サーバ管理

                              -

                              サーバは、定義された監視を実行する要素です。監視をし結果に応じて状態を変更します。また、データの状態に応じてアラートを生成します。

                              +

                              サーバは、定義された監視を実行する要素です。監視をし結果に応じて状態を変更します。また、データの状態に応じてアラートを生成します。

                              -

                              のデータサーバは、冗長化および負荷分散が可能です。大きなシステムでは、大量の機能を扱ったり物理的に分散した情報を扱うために、さまざまな Pandora FMS サーバを同時に利用可能です。

                              +

                              のデータサーバは、冗長化および負荷分散が可能です。大きなシステムでは、大量の機能を扱ったり物理的に分散した情報を扱うために、さまざまな Pandora FMS サーバを同時に利用可能です。

                              -

                              サーバは、各要素に問題が無いか、また、アラートが定義されているかを常に確認します。何かあると、アラームに定義された SMS 送信、e-mail 送信、スクリプトの実行など、アクションを実行します。l

                              +

                              サーバは、各要素に問題が無いか、また、アラートが定義されているかを常に確認します。何かあると、アラームに定義された SMS 送信、e-mail 送信、スクリプトの実行など、アクションを実行します。l

                              • データサーバ(Data Server)
                              • diff --git a/pandora_console/include/help/ja/help_service_management_edit.php b/pandora_console/include/help/ja/help_service_management_edit.php index 5c58db2ea5..4be110f719 100644 --- a/pandora_console/include/help/ja/help_service_management_edit.php +++ b/pandora_console/include/help/ja/help_service_management_edit.php @@ -1,7 +1,7 @@

                                サービスの編集

                                diff --git a/pandora_console/include/help/ja/help_setup_gis_index.php b/pandora_console/include/help/ja/help_setup_gis_index.php index 9e6872f02c..181ca6cf43 100644 --- a/pandora_console/include/help/ja/help_setup_gis_index.php +++ b/pandora_console/include/help/ja/help_setup_gis_index.php @@ -11,6 +11,6 @@

                                設定済の利用マップ定義一覧の参照できます。 編集するにはマップ名をクリックします。 -削除するには削除アイコン( "delete icon")) ?> )をクリックします。 +削除するには削除アイコン( 'delete icon']); ?> )をクリックします。 また、新たな設定を作成するには、「作成」ボタンをクリックします。

                                diff --git a/pandora_console/include/help/ja/help_snmp_alert.php b/pandora_console/include/help/ja/help_snmp_alert.php index 0d93311d22..c30bbfcec5 100644 --- a/pandora_console/include/help/ja/help_snmp_alert.php +++ b/pandora_console/include/help/ja/help_snmp_alert.php @@ -1,9 +1,9 @@

                                SNMPアラート

                                -

                                アラートとトラップを関連付けることができます。それにより、 は、特定のトラップ受信で警告を上げることができます。SNMPトラップは、アクションで再利用したとしても、システムアラートとは関係がありません。

                                +

                                アラートとトラップを関連付けることができます。それにより、 は、特定のトラップ受信で警告を上げることができます。SNMPトラップは、アクションで再利用したとしても、システムアラートとは関係がありません。

                                diff --git a/pandora_console/include/help/ja/help_snmp_alert_configuration.php b/pandora_console/include/help/ja/help_snmp_alert_configuration.php index ee99930452..a0ce07aa81 100644 --- a/pandora_console/include/help/ja/help_snmp_alert_configuration.php +++ b/pandora_console/include/help/ja/help_snmp_alert_configuration.php @@ -1,7 +1,7 @@

                                アラート設定

                                diff --git a/pandora_console/include/help/ja/help_snmp_alert_custom.php b/pandora_console/include/help/ja/help_snmp_alert_custom.php index 2080cbfdb1..dfb56de53d 100644 --- a/pandora_console/include/help/ja/help_snmp_alert_custom.php +++ b/pandora_console/include/help/ja/help_snmp_alert_custom.php @@ -1,7 +1,7 @@

                                全体マッチング

                                diff --git a/pandora_console/include/help/ja/help_snmp_alert_position.php b/pandora_console/include/help/ja/help_snmp_alert_position.php index fbbfba2f89..298304afe2 100644 --- a/pandora_console/include/help/ja/help_snmp_alert_position.php +++ b/pandora_console/include/help/ja/help_snmp_alert_position.php @@ -1,7 +1,7 @@

                                SNMP アラート順位

                                diff --git a/pandora_console/include/help/ja/help_snmp_explorer.php b/pandora_console/include/help/ja/help_snmp_explorer.php index 47aaa5832f..bd07d4e4af 100644 --- a/pandora_console/include/help/ja/help_snmp_explorer.php +++ b/pandora_console/include/help/ja/help_snmp_explorer.php @@ -1,6 +1,7 @@ -

                                SNMPエクスプローラ

                                diff --git a/pandora_console/include/help/ja/help_snmp_trap_types.php b/pandora_console/include/help/ja/help_snmp_trap_types.php index c85854926e..d011203a70 100755 --- a/pandora_console/include/help/ja/help_snmp_trap_types.php +++ b/pandora_console/include/help/ja/help_snmp_trap_types.php @@ -5,11 +5,11 @@ ?>

                                トラップのタイプ

                                  -
                                • Cold start (0): エージェントが(再)起動したことを示します。
                                • -
                                • Warm start (1): エージェントの設定が変更されたことを示します。
                                • -
                                • Link down (2): ネットワークインタフェースがダウンしたことを示します。
                                • -
                                • Link up (3): ネットワークインタフェースがアップしたことを示します。
                                • -
                                • Authentication failure (4): エージェントが許可されていない発信元からのリクエストを受けたことを示します。(通常はコミュニティで制限されています)
                                • -
                                • EGP neighbor loss (5): EGP プロトコルを利用しているルータで、隣接ホストとの通信が切れたことを示します。
                                • -
                                • Enterprise (6): このカテゴリに含まれるものは、ベンダー独自のトラップです。
                                • +
                                • Cold start (0): エージェントが(再)起動したことを示します。
                                • +
                                • Warm start (1): エージェントの設定が変更されたことを示します。
                                • +
                                • Link down (2): ネットワークインタフェースがダウンしたことを示します。
                                • +
                                • Link up (3): ネットワークインタフェースがアップしたことを示します。
                                • +
                                • Authentication failure (4): エージェントが許可されていない発信元からのリクエストを受けたことを示します。(通常はコミュニティで制限されています)
                                • +
                                • EGP neighbor loss (5): EGP プロトコルを利用しているルータで、隣接ホストとの通信が切れたことを示します。
                                • +
                                • Enterprise (6): このカテゴリに含まれるものは、ベンダー独自のトラップです。
                                diff --git a/pandora_console/include/help/ja/help_snmpoid.php b/pandora_console/include/help/ja/help_snmpoid.php index f09c620a8c..5ce3cfffab 100644 --- a/pandora_console/include/help/ja/help_snmpoid.php +++ b/pandora_console/include/help/ja/help_snmpoid.php @@ -5,5 +5,5 @@ ?>

                                SNMP OID

                                - ネットワークサーバにて MIB の名前解決が可能の場合は、その名前で表示されます。(例: SNMPv2-MIB::sysDescr.0) + ネットワークサーバにて MIB の名前解決が可能の場合は、その名前で表示されます。(例: SNMPv2-MIB::sysDescr.0) MIB が無ければ、数字で表示されます。(例:3.1.3.1.3.5.12.4.0.1) diff --git a/pandora_console/include/help/ja/help_snmpwalk.php b/pandora_console/include/help/ja/help_snmpwalk.php index fe9c6344f5..438df9a381 100644 --- a/pandora_console/include/help/ja/help_snmpwalk.php +++ b/pandora_console/include/help/ja/help_snmpwalk.php @@ -5,7 +5,7 @@ ?>

                                snmpwalk

                                - は、簡易 SNMP ブラウザがあり、リモートノードに対して snmpwalk を実行することができます。 + は、簡易 SNMP ブラウザがあり、リモートノードに対して snmpwalk を実行することができます。

                                snmpwalk は全 MIB データを取得しますが、その中から一つを選択できます。 -また、OID を数値で入力したり、 ネットワークサーバに MIB がインストールされていれば、名称で入力することも可能です。 +また、OID を数値で入力したり、 ネットワークサーバに MIB がインストールされていれば、名称で入力することも可能です。 diff --git a/pandora_console/include/help/ja/help_tags_config.php b/pandora_console/include/help/ja/help_tags_config.php index f7845c394b..1e5095c8ea 100644 --- a/pandora_console/include/help/ja/help_tags_config.php +++ b/pandora_console/include/help/ja/help_tags_config.php @@ -3,7 +3,7 @@ * @package Include/help/ja */ ?> -

                                におけるタグ

                                +

                                におけるタグ

                                モジュールへのアクセス権をタグシステムにより設定することができます。タグはシステムで設定し、選択したモジュールに割り当てられます。これにより、ユーザのアクセスを特定のタグがついたモジュールに限定することができます。

                                diff --git a/pandora_console/include/help/ja/help_template_tab.php b/pandora_console/include/help/ja/help_template_tab.php index b34c4523ed..f981ee3120 100644 --- a/pandora_console/include/help/ja/help_template_tab.php +++ b/pandora_console/include/help/ja/help_template_tab.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_timesource.php b/pandora_console/include/help/ja/help_timesource.php index 90c858d781..978abcac6b 100644 --- a/pandora_console/include/help/ja/help_timesource.php +++ b/pandora_console/include/help/ja/help_timesource.php @@ -9,8 +9,8 @@ 日時データソースに、システムの日時データかデータベースに記録されているデータかどちらをを利用するかを定義します。

                                -これは、データベースがウェブサーバや サーバと異なるサーバで動作している場合で、時刻にずれが生じている場合に便利です。 -すべての サーバと MySQL サーバの時刻は NTP により同期すべきですが、この設定を利用することにより、必ずしもそうする必要がなくなります。 +これは、データベースがウェブサーバや サーバと異なるサーバで動作している場合で、時刻にずれが生じている場合に便利です。 +すべての サーバと MySQL サーバの時刻は NTP により同期すべきですが、この設定を利用することにより、必ずしもそうする必要がなくなります。

                                注: データベースではクエリがキャッシュされますが、内部関数が呼ばれるかどうかに関わらずその時点のシステムタイムが返されますので、日時データは若干異なる場合があります。 @@ -25,28 +25,31 @@ var unixtime = parseInt(unixtime_ms / 1000);

                                "timestamp"); +$option = ['prominent' => 'timestamp']; ?> -現在のシステムの時刻: +現在のシステムの時刻:
                                現在のデータベースの時刻:
                                あなたのブラウザの時刻: diff --git a/pandora_console/include/help/ja/help_view_services.php b/pandora_console/include/help/ja/help_view_services.php index b333ea1e26..596c9d6e65 100644 --- a/pandora_console/include/help/ja/help_view_services.php +++ b/pandora_console/include/help/ja/help_view_services.php @@ -15,20 +15,20 @@ 新たなサービスを作成するには、「作成」ボタンをクリックします。

                                - '550px')); ?> + '550px']); ?>

                                この時点では、アイテムが無い状態でサービスが作成されています。そのため、サービスにアイテムを追加する必要があります。新たなアイテムを追加するには、右上のサービス管理タブのオレンジ色のツールアイコンをクリックし、作成をクリックします。すると、以下のようなフォームが表示されます。このフォームでは、追加したいエージェントのモジュールを選択します。また、サービスにおける、そのモジュールの正常、警告、障害状態に対するウエイトを入力します。サービス内で重要なモジュールほどウエイトは大きくします。

                                - '550px')); ?> + '550px']); ?>

                                全てのフィールドに入力し作成ボタンをクリックすると、処理が実行されたメッセージと共に次のような画面が表示されます。

                                - '550px')); ?> + '550px']); ?>

                                サービスを監視するために必要な全てのアイテムを追加できます。例えば、このサービスに適切な重みを持たせた要素を追加すると、次のようになります。

                                - '550px')); ?> + '550px']); ?>

                                すると、下に示すようなサービス一覧が表示されます。画面にはリアルタイムで計算された値が表示され、表示されるパラメータは次の通りです。

                                @@ -42,7 +42,7 @@

                              • 状態(Status): 値および障害・警告の閾値に応じたサービスの状態。


                              - '550px')); ?> + '550px']); ?>

                              サービス名をクリックするとサービスビューが表示されます。前述の通り、サービスの値は、それぞれのモジュールの状態に関連した重み付け(ウエイト)を計算したものです。モジュールと同様に、サービスの状態はその値に依存しています。この画面では、それぞれのサービスアイテムの状態を次のパラメータと共に表示します。

                              @@ -58,7 +58,7 @@

                              - '550px')); ?> + '550px']); ?>

                              サービスに関連付けするモジュールを作成することも可能です。これには、定期的な状態計算、アラートシステムの統合などの利点があります。モジュールをサービスに関連付けるには、次の手順を実施します。

                              @@ -72,5 +72,5 @@



                              - '550px')); ?> + '550px']); ?>

                              diff --git a/pandora_console/include/help/ja/help_view_services_detail.php b/pandora_console/include/help/ja/help_view_services_detail.php index 31e68016f2..4cf7f90ef1 100644 --- a/pandora_console/include/help/ja/help_view_services_detail.php +++ b/pandora_console/include/help/ja/help_view_services_detail.php @@ -1,5 +1,6 @@ diff --git a/pandora_console/include/help/ja/help_visual_console_editor_data_tab.php b/pandora_console/include/help/ja/help_visual_console_editor_data_tab.php index 1ab0c6fa96..4a14d3c21e 100644 --- a/pandora_console/include/help/ja/help_visual_console_editor_data_tab.php +++ b/pandora_console/include/help/ja/help_visual_console_editor_data_tab.php @@ -1,7 +1,7 @@

                              エディタ

                              diff --git a/pandora_console/include/help/ja/help_visual_console_editor_editor_tab.php b/pandora_console/include/help/ja/help_visual_console_editor_editor_tab.php index 9397ddaf48..626268c876 100644 --- a/pandora_console/include/help/ja/help_visual_console_editor_editor_tab.php +++ b/pandora_console/include/help/ja/help_visual_console_editor_editor_tab.php @@ -1,7 +1,7 @@

                              エディタ

                              @@ -12,5 +12,5 @@
                            • ワークエリア (ここで、ビジュアルコンソールを作成します)
                            • オプションパレット (画面ショットでは表示されていません)
                            - バージョン 5.0.1 では、テキストのラベルを設定できます。また、テキスト内に (_VALUE_) マクロを使って値を定義することができます。 + バージョン 5.0.1 では、テキストのラベルを設定できます。また、テキスト内に (_VALUE_) マクロを使って値を定義することができます。

                            diff --git a/pandora_console/include/help/ja/help_visual_console_editor_list_elements_tab.php b/pandora_console/include/help/ja/help_visual_console_editor_list_elements_tab.php index 315fcb4f10..948dc2ddb1 100644 --- a/pandora_console/include/help/ja/help_visual_console_editor_list_elements_tab.php +++ b/pandora_console/include/help/ja/help_visual_console_editor_list_elements_tab.php @@ -1,7 +1,7 @@

                            要素一覧

                            diff --git a/pandora_console/include/help/ja/help_visual_console_editor_preview_tab.php b/pandora_console/include/help/ja/help_visual_console_editor_preview_tab.php index 46983fcd4d..5b1d2c71be 100644 --- a/pandora_console/include/help/ja/help_visual_console_editor_preview_tab.php +++ b/pandora_console/include/help/ja/help_visual_console_editor_preview_tab.php @@ -1,9 +1,9 @@

                            プレビュー

                            -

                            このタブは、 コンソールのメニューをたどらずに作業結果を確認するのに便利です。ビジュアルコンソールビューは静的な表示です。そのため、要素に状態を含んでいたとしても、ビジュアルコンソールメニューから表示されるのと違い、それらは表示されません。

                            +

                            このタブは、 コンソールのメニューをたどらずに作業結果を確認するのに便利です。ビジュアルコンソールビューは静的な表示です。そのため、要素に状態を含んでいたとしても、ビジュアルコンソールメニューから表示されるのと違い、それらは表示されません。

                            diff --git a/pandora_console/include/help/ja/help_visual_console_editor_wizard_tab.php b/pandora_console/include/help/ja/help_visual_console_editor_wizard_tab.php index 3d784180db..20169d9bea 100644 --- a/pandora_console/include/help/ja/help_visual_console_editor_wizard_tab.php +++ b/pandora_console/include/help/ja/help_visual_console_editor_wizard_tab.php @@ -1,7 +1,7 @@

                            ウィザード

                            diff --git a/pandora_console/include/help/ja/help_web_checks.php b/pandora_console/include/help/ja/help_web_checks.php index f63831c01f..e5a413fa74 100644 --- a/pandora_console/include/help/ja/help_web_checks.php +++ b/pandora_console/include/help/ja/help_web_checks.php @@ -6,7 +6,7 @@

                            ウェブモニタリング

                            -拡張ウェブモニタリングは、 エンタープライズ版の Goliat で動作する機能です。 +拡張ウェブモニタリングは、 エンタープライズ版の Goliat で動作する機能です。

                            以下に、GOLIAT ウェブチェックモジュールのサンプルを示します。
                            diff --git a/pandora_console/include/include_graph_dependencies.php b/pandora_console/include/include_graph_dependencies.php index 37dc34ef11..947f8a5f6f 100644 --- a/pandora_console/include/include_graph_dependencies.php +++ b/pandora_console/include/include_graph_dependencies.php @@ -4,33 +4,30 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +// Function that includes all graph dependencies +function include_graphs_dependencies($home_url='', $serialize_ttl=1) +{ + global $config; + global $ttl; + global $homeurl; -/* Function that includes all graph dependencies */ -function include_graphs_dependencies($home_url = '', $serialize_ttl = 1) { - global $config; - global $ttl; - global $homeurl; + $ttl = $serialize_ttl; + $homeurl = $home_url; + include_once $homeurl.'include/functions_io.php'; + include_once $homeurl.'include/functions.php'; + include_once $homeurl.'include/functions_html.php'; - $ttl = $serialize_ttl; - $homeurl = $home_url; - include_once($homeurl . 'include/functions_io.php'); - include_once($homeurl . 'include/functions.php'); - include_once($homeurl . 'include/functions_html.php'); + if (!defined('AJAX') && !get_parameter('static_graph', 0)) { + include_once $homeurl.'include/graphs/functions_flot.php'; + } - if (!defined('AJAX') && !get_parameter('static_graph',0)) { - include_once($homeurl . 'include/graphs/functions_flot.php'); - } - include_once($homeurl . 'include/graphs/functions_gd.php'); - include_once($homeurl . 'include/graphs/functions_utils.php'); + include_once $homeurl.'include/graphs/functions_gd.php'; + include_once $homeurl.'include/graphs/functions_utils.php'; } - -?> diff --git a/pandora_console/include/javascript/clippy.js b/pandora_console/include/javascript/clippy.js index f7624e3638..044825cb08 100644 --- a/pandora_console/include/javascript/clippy.js +++ b/pandora_console/include/javascript/clippy.js @@ -1,8 +1,8 @@ function clippy_set_help(help_section) { - document.cookie = 'clippy=' + help_section; + document.cookie = "clippy=" + help_section; } function clippy_go_link_show_help(link, help_section) { - document.cookie = 'clippy=' + help_section; - window.location.href = link; -} \ No newline at end of file + document.cookie = "clippy=" + help_section; + window.location.href = link; +} diff --git a/pandora_console/include/javascript/encode_decode_base64.js b/pandora_console/include/javascript/encode_decode_base64.js index d5992ebb38..71432daa75 100644 --- a/pandora_console/include/javascript/encode_decode_base64.js +++ b/pandora_console/include/javascript/encode_decode_base64.js @@ -1,147 +1,136 @@ -/** +/** * Javascript functions for encoding /decoding in base 64 codification */ /** -* -* Base64 encode / decode -* http://www.webtoolkit.info/ -* -**/ + * + * Base64 encode / decode + * http://www.webtoolkit.info/ + * + **/ var Base64 = { + // private property + _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", - // private property - _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + // public method for encoding + encode: function(input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; - // public method for encoding - encode : function (input) { - var output = ""; - var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0; + input = Base64._utf8_encode(input); - input = Base64._utf8_encode(input); + while (i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); - while (i < input.length) { + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - enc4 = chr3 & 63; + output = + output + + this._keyStr.charAt(enc1) + + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + + this._keyStr.charAt(enc4); + } - if (isNaN(chr2)) { - enc3 = enc4 = 64; - } else if (isNaN(chr3)) { - enc4 = 64; - } + return output; + }, - output = output + - this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + - this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); + // public method for decoding + decode: function(input) { + var output = ""; + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0; - } + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - return output; - }, + while (i < input.length) { + enc1 = this._keyStr.indexOf(input.charAt(i++)); + enc2 = this._keyStr.indexOf(input.charAt(i++)); + enc3 = this._keyStr.indexOf(input.charAt(i++)); + enc4 = this._keyStr.indexOf(input.charAt(i++)); - // public method for decoding - decode : function (input) { - var output = ""; - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0; + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + output = output + String.fromCharCode(chr1); - while (i < input.length) { + if (enc3 != 64) { + output = output + String.fromCharCode(chr2); + } + if (enc4 != 64) { + output = output + String.fromCharCode(chr3); + } + } - enc1 = this._keyStr.indexOf(input.charAt(i++)); - enc2 = this._keyStr.indexOf(input.charAt(i++)); - enc3 = this._keyStr.indexOf(input.charAt(i++)); - enc4 = this._keyStr.indexOf(input.charAt(i++)); + output = Base64._utf8_decode(output); - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; + return output; + }, - output = output + String.fromCharCode(chr1); + // private method for UTF-8 encoding + _utf8_encode: function(string) { + string = string.replace(/\r\n/g, "\n"); + var utftext = ""; - if (enc3 != 64) { - output = output + String.fromCharCode(chr2); - } - if (enc4 != 64) { - output = output + String.fromCharCode(chr3); - } + for (var n = 0; n < string.length; n++) { + var c = string.charCodeAt(n); - } + if (c < 128) { + utftext += String.fromCharCode(c); + } else if (c > 127 && c < 2048) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + } - output = Base64._utf8_decode(output); + return utftext; + }, - return output; + // private method for UTF-8 decoding + _utf8_decode: function(utftext) { + var string = ""; + var i = 0; + var c = (c1 = c2 = 0); - }, + while (i < utftext.length) { + c = utftext.charCodeAt(i); - // private method for UTF-8 encoding - _utf8_encode : function (string) { - string = string.replace(/\r\n/g,"\n"); - var utftext = ""; - - for (var n = 0; n < string.length; n++) { - - var c = string.charCodeAt(n); - - if (c < 128) { - utftext += String.fromCharCode(c); - } - else if((c > 127) && (c < 2048)) { - utftext += String.fromCharCode((c >> 6) | 192); - utftext += String.fromCharCode((c & 63) | 128); - } - else { - utftext += String.fromCharCode((c >> 12) | 224); - utftext += String.fromCharCode(((c >> 6) & 63) | 128); - utftext += String.fromCharCode((c & 63) | 128); - } - - } - - return utftext; - }, - - // private method for UTF-8 decoding - _utf8_decode : function (utftext) { - var string = ""; - var i = 0; - var c = c1 = c2 = 0; - - while ( i < utftext.length ) { - - c = utftext.charCodeAt(i); - - if (c < 128) { - string += String.fromCharCode(c); - i++; - } - else if((c > 191) && (c < 224)) { - c2 = utftext.charCodeAt(i+1); - string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } - else { - c2 = utftext.charCodeAt(i+1); - c3 = utftext.charCodeAt(i+2); - string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - - } - - return string; - } - -} + if (c < 128) { + string += String.fromCharCode(c); + i++; + } else if (c > 191 && c < 224) { + c2 = utftext.charCodeAt(i + 1); + string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = utftext.charCodeAt(i + 1); + c3 = utftext.charCodeAt(i + 2); + string += String.fromCharCode( + ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63) + ); + i += 3; + } + } + return string; + } +}; diff --git a/pandora_console/include/javascript/fixed-bottom-box.js b/pandora_console/include/javascript/fixed-bottom-box.js index 7fc622e498..7ea5b803b3 100644 --- a/pandora_console/include/javascript/fixed-bottom-box.js +++ b/pandora_console/include/javascript/fixed-bottom-box.js @@ -6,345 +6,334 @@ // This module has an Universal Module Definition pattern and its scope is private -(function (name, factory) { - // AMD - if (typeof define === 'function' && define.amd) { - define(['jquery'], factory); - } - // Node (CommonJS) - else if (typeof exports === 'object') { - module.exports = factory(require('jquery')); - } - // Assign to the jQuery namespace - else { - (this.jQuery || this.$)[name] = factory(this.jQuery || this.$); - } -} ('fixedBottomBox', function ($) { - // jQuery required - if (typeof $ === 'undefined') - return; - // Module definition - return fixedBottomBox = function (params) { - var self = new Object(); - - self._rendered = false; - - self.isRendered = function (state) { - if (typeof state === 'boolean') - self._rendered = state; - - return self._rendered; - } - - params = params || {}; - self._debug = params.debug || false; - self._target = params.target || 'body'; - self._opened = params.opened || false; - self._head = params.head || ''; - self._content = params.content || ''; - self._animationDuration = params.animationDuration || 200; - - self._width = params.width || 300; - self._height = params.height || 400; - - self.setWidth = function (width) { - if (typeof width !== 'number' || width <= 0) - throw new TypeError('Invalid width'); - self._width = width; - - if (typeof self._box !== 'undefined') { - self._box.head.css('width', width + 'px'); - self._box.content.css('width', width + 'px'); - } - - return self; - } - - self.getWidth = function (width) { - return self._width; - } - - self.setHeight = function (height) { - if (typeof height !== 'number' || height <= 0) - throw new TypeError('Invalid height'); - self._heigth = height; - - var headHeight = self._box.head.height() || 30; - - if (typeof self._box !== 'undefined') { - self._box.content.css('max-height', (height - headHeight) + 'px'); - } - - return self; - } - - self.getHeight = function (height) { - return self._height; - } - - self.resize = function (width, height) { - try { - self.setWidth(width); - self.setHeight(height); - self.emit('resized', { width: width, height: height }); - } - catch (error) { - if (self._debug) - console.error(error); - } - - return self; - } - - self.render = function (head, content) { - self._createBox(head, content); - - return self; - } - - self._renderHead = function (head) { - head = head || self._head; - - var headBody = $('

                            '); - headBody - .addClass('fixed-bottom-box-head-body') - .click(function(event) { - self.toggle(); - }); - var headClose = $(''); - headClose - .addClass('fixed-bottom-box-head-close') - .click(function(event) { - self.close(); - }); - - self._box.head = $('
                            '); - self._box.head - .addClass('fixed-bottom-box-head') - .append(headClose, headBody); - self._box.append(self._box.head); - - self.emit('head-rendered', { headRef: self._box.head, headContent: head }); - } - - self._renderContent = function (content) { - content = content || self._content; - - self._box.content = $('
                            '); - self._box.content - .addClass('fixed-bottom-box-content') - .append(content); - self._box.append(self._box.content); - - self.emit('content-rendered', { contentRef: self._box.content, content: content }); - } - - self._createBox = function (head, content) { - head = head || self._head; - content = content || self._content; - - if (self.isRendered()) - self._destroyBox(); - - try { - self._box = $('
                            '); - self._box - .addClass('fixed-bottom-box') - .css('position', 'fixed') - .css('bottom', '0px') - .css('right', '20px'); - - self._renderHead(head); - self._renderContent(content); - - self.resize(self._width, self._height); - - if (!self.isOpen()) - self._box.content.hide(); - - $(self._target).append(self._box); - - self.isRendered(true); - - self.emit('rendered', { boxRef: self._box, headContent: head, content: content }); - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - self._destroyBox = function () { - try { - if (self.isRendered()) { - self._box.hide(); - - self._box.content.remove(); - delete self._box.content; - - self._box.head.remove(); - delete self._box.head; - - self._box.remove(); - delete self._box; - - self.isRendered(false); - } - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - - self.isOpen = function (state) { - if (typeof state === 'boolean') - self._opened = state; - - return self._opened; - } - - self.setHead = function (head) { - if (typeof head === 'undefined' || head.length <= 0) - throw new TypeError('Invalid head'); - self._head = head; - - return self; - } - - self.setContent = function (content) { - if (typeof content === 'undefined' || content.length <= 0) - throw new TypeError('Invalid content'); - self._content = content; - - return self; - } - - self.open = function () { - try { - if (!self.isOpen()) { - self._box.content.slideDown(self._animationDuration, function() { - self.isOpen(true); - $(this) - .removeClass('fixed-bottom-box-hided') - .addClass('fixed-bottom-box-opened'); - self.emit('open', { ref: self }); - }); - } - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - self.hide = function () { - try { - if (self.isOpen()) { - - self._box.content.slideUp(self._animationDuration, function() { - self.isOpen(false); - $(this) - .removeClass('fixed-bottom-box-opened') - .addClass('fixed-bottom-box-hided'); - self.emit('hide', { ref: self }); - }); - } - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - self.toggle = function () { - if (self.isOpen()) - self.hide(); - else - self.open(); - } - - self.close = function () { - try { - self._head = ''; - self._content = ''; - self.isOpen(false); - self._destroyBox(); - - self.emit('close', {}); - } - catch (error) { - if (self._debug) - console.error(error); - } - } - - - //-- Event handlers --// - - // Populate the observers - var eventsList = ['open', 'hide', 'close', 'rendered', 'head-rendered', 'content-rendered', 'resized']; - self._observers = {} - eventsList.forEach(function(eventName) { - self._observers[eventName] = []; - }); - - self.emit = function (eventName, payload) { - if (typeof eventName === 'undefined' || eventName.length <= 0) - throw new TypeError('Invalid event name'); - if (typeof self._observers[eventName] === 'undefined') - throw new TypeError('The introduced event does not exists'); - payload = payload || {}; - - var observers = self._observers[eventName]; - - observers.forEach(function(callback) { - if (typeof callback === 'function') - callback(payload); - }); - } - - self.on = function (eventName, callback) { - if (typeof eventName === 'undefined' || eventName.length <= 0) - throw new TypeError('Invalid event name'); - if (typeof callback === 'function') - throw new TypeError('The callback should be a function'); - - var res = false; - if (typeof self._observers[eventName] !== 'undefined') { - var length = self._observers[eventName].push(callback); - res = length - 1; - } - - return res; - } - - // Should receive - self.onOpen = function (callback) { - self.on('open', callback); - } - // Should receive - self.onHide = function (callback) { - self.on('hide', callback); - } - // Should receive - self.onClose = function (callback) { - self.on('close', callback); - } - // Should receive - self.onHeadRender = function (callback) { - self.on('head-rendered', callback); - } - // Should receive - self.onContentRender = function (callback) { - self.on('content-rendered', callback); - } - // Should receive - self.onResize = function (callback) { - self.on('resized', callback); - } - - return self; - } -})); \ No newline at end of file +(function(name, factory) { + // AMD + if (typeof define === "function" && define.amd) { + define(["jquery"], factory); + } + // Node (CommonJS) + else if (typeof exports === "object") { + module.exports = factory(require("jquery")); + } + // Assign to the jQuery namespace + else { + (this.jQuery || this.$)[name] = factory(this.jQuery || this.$); + } +})("fixedBottomBox", function($) { + // jQuery required + if (typeof $ === "undefined") return; + // Module definition + return (fixedBottomBox = function(params) { + var self = new Object(); + + self._rendered = false; + + self.isRendered = function(state) { + if (typeof state === "boolean") self._rendered = state; + + return self._rendered; + }; + + params = params || {}; + self._debug = params.debug || false; + self._target = params.target || "body"; + self._opened = params.opened || false; + self._head = params.head || ""; + self._content = params.content || ""; + self._animationDuration = params.animationDuration || 200; + + self._width = params.width || 300; + self._height = params.height || 400; + + self.setWidth = function(width) { + if (typeof width !== "number" || width <= 0) + throw new TypeError("Invalid width"); + self._width = width; + + if (typeof self._box !== "undefined") { + self._box.head.css("width", width + "px"); + self._box.content.css("width", width + "px"); + } + + return self; + }; + + self.getWidth = function(width) { + return self._width; + }; + + self.setHeight = function(height) { + if (typeof height !== "number" || height <= 0) + throw new TypeError("Invalid height"); + self._heigth = height; + + var headHeight = self._box.head.height() || 30; + + if (typeof self._box !== "undefined") { + self._box.content.css("max-height", height - headHeight + "px"); + } + + return self; + }; + + self.getHeight = function(height) { + return self._height; + }; + + self.resize = function(width, height) { + try { + self.setWidth(width); + self.setHeight(height); + self.emit("resized", { width: width, height: height }); + } catch (error) { + if (self._debug) console.error(error); + } + + return self; + }; + + self.render = function(head, content) { + self._createBox(head, content); + + return self; + }; + + self._renderHead = function(head) { + head = head || self._head; + + var headBody = $("
                            "); + headBody.addClass("fixed-bottom-box-head-body").click(function(event) { + self.toggle(); + }); + var headClose = $(""); + headClose.addClass("fixed-bottom-box-head-close").click(function(event) { + self.close(); + }); + + self._box.head = $("
                            "); + self._box.head + .addClass("fixed-bottom-box-head") + .append(headClose, headBody); + self._box.append(self._box.head); + + self.emit("head-rendered", { + headRef: self._box.head, + headContent: head + }); + }; + + self._renderContent = function(content) { + content = content || self._content; + + self._box.content = $("
                            "); + self._box.content.addClass("fixed-bottom-box-content").append(content); + self._box.append(self._box.content); + + self.emit("content-rendered", { + contentRef: self._box.content, + content: content + }); + }; + + self._createBox = function(head, content) { + head = head || self._head; + content = content || self._content; + + if (self.isRendered()) self._destroyBox(); + + try { + self._box = $("
                            "); + self._box + .addClass("fixed-bottom-box") + .css("position", "fixed") + .css("bottom", "0px") + .css("right", "20px"); + + self._renderHead(head); + self._renderContent(content); + + self.resize(self._width, self._height); + + if (!self.isOpen()) self._box.content.hide(); + + $(self._target).append(self._box); + + self.isRendered(true); + + self.emit("rendered", { + boxRef: self._box, + headContent: head, + content: content + }); + } catch (error) { + if (self._debug) console.error(error); + } + }; + + self._destroyBox = function() { + try { + if (self.isRendered()) { + self._box.hide(); + + self._box.content.remove(); + delete self._box.content; + + self._box.head.remove(); + delete self._box.head; + + self._box.remove(); + delete self._box; + + self.isRendered(false); + } + } catch (error) { + if (self._debug) console.error(error); + } + }; + + self.isOpen = function(state) { + if (typeof state === "boolean") self._opened = state; + + return self._opened; + }; + + self.setHead = function(head) { + if (typeof head === "undefined" || head.length <= 0) + throw new TypeError("Invalid head"); + self._head = head; + + return self; + }; + + self.setContent = function(content) { + if (typeof content === "undefined" || content.length <= 0) + throw new TypeError("Invalid content"); + self._content = content; + + return self; + }; + + self.open = function() { + try { + if (!self.isOpen()) { + self._box.content.slideDown(self._animationDuration, function() { + self.isOpen(true); + $(this) + .removeClass("fixed-bottom-box-hided") + .addClass("fixed-bottom-box-opened"); + self.emit("open", { ref: self }); + }); + } + } catch (error) { + if (self._debug) console.error(error); + } + }; + + self.hide = function() { + try { + if (self.isOpen()) { + self._box.content.slideUp(self._animationDuration, function() { + self.isOpen(false); + $(this) + .removeClass("fixed-bottom-box-opened") + .addClass("fixed-bottom-box-hided"); + self.emit("hide", { ref: self }); + }); + } + } catch (error) { + if (self._debug) console.error(error); + } + }; + + self.toggle = function() { + if (self.isOpen()) self.hide(); + else self.open(); + }; + + self.close = function() { + try { + self._head = ""; + self._content = ""; + self.isOpen(false); + self._destroyBox(); + + self.emit("close", {}); + } catch (error) { + if (self._debug) console.error(error); + } + }; + + //-- Event handlers --// + + // Populate the observers + var eventsList = [ + "open", + "hide", + "close", + "rendered", + "head-rendered", + "content-rendered", + "resized" + ]; + self._observers = {}; + eventsList.forEach(function(eventName) { + self._observers[eventName] = []; + }); + + self.emit = function(eventName, payload) { + if (typeof eventName === "undefined" || eventName.length <= 0) + throw new TypeError("Invalid event name"); + if (typeof self._observers[eventName] === "undefined") + throw new TypeError("The introduced event does not exists"); + payload = payload || {}; + + var observers = self._observers[eventName]; + + observers.forEach(function(callback) { + if (typeof callback === "function") callback(payload); + }); + }; + + self.on = function(eventName, callback) { + if (typeof eventName === "undefined" || eventName.length <= 0) + throw new TypeError("Invalid event name"); + if (typeof callback === "function") + throw new TypeError("The callback should be a function"); + + var res = false; + if (typeof self._observers[eventName] !== "undefined") { + var length = self._observers[eventName].push(callback); + res = length - 1; + } + + return res; + }; + + // Should receive + self.onOpen = function(callback) { + self.on("open", callback); + }; + // Should receive + self.onHide = function(callback) { + self.on("hide", callback); + }; + // Should receive + self.onClose = function(callback) { + self.on("close", callback); + }; + // Should receive + self.onHeadRender = function(callback) { + self.on("head-rendered", callback); + }; + // Should receive + self.onContentRender = function(callback) { + self.on("content-rendered", callback); + }; + // Should receive + self.onResize = function(callback) { + self.on("resized", callback); + }; + + return self; + }); +}); diff --git a/pandora_console/include/javascript/functions_pandora_networkmap.js b/pandora_console/include/javascript/functions_pandora_networkmap.js index 8871950f3e..4c9f5b61b7 100644 --- a/pandora_console/include/javascript/functions_pandora_networkmap.js +++ b/pandora_console/include/javascript/functions_pandora_networkmap.js @@ -1,1070 +1,1157 @@ - function draw_minimap() { - //Clean the canvas - context_minimap.clearRect(0, 0, minimap_w, minimap_h); + //Clean the canvas + context_minimap.clearRect(0, 0, minimap_w, minimap_h); - context_minimap.beginPath(); - context_minimap.globalAlpha = 0.8; - context_minimap.fillStyle = "#ddd"; - context_minimap.fillRect(0, 0, minimap_w, minimap_h); + context_minimap.beginPath(); + context_minimap.globalAlpha = 0.8; + context_minimap.fillStyle = "#ddd"; + context_minimap.fillRect(0, 0, minimap_w, minimap_h); - var relation_min_nodes = minimap_relation; - var relation_minimap_w = 2; - var relation_minimap_h = 2; - if (graph.nodes.length > 100) { - relation_min_nodes = 0.01; - relation_minimap_w = (graph.nodes.length / 100) * 2.5; - relation_minimap_h = 1.5; - } + var relation_min_nodes = minimap_relation; + var relation_minimap_w = 2; + var relation_minimap_h = 2; + if (graph.nodes.length > 100) { + relation_min_nodes = 0.01; + relation_minimap_w = (graph.nodes.length / 100) * 2.5; + relation_minimap_h = 1.5; + } - //Draw the items and lines - jQuery.each(graph.nodes, function (key, value) { - if (typeof (value) == 'undefined') return; + //Draw the items and lines + jQuery.each(graph.nodes, function(key, value) { + if (typeof value == "undefined") return; - context_minimap.beginPath(); - //Paint the item - if (graph.nodes.length > 100) { - center_orig_x = (value.x + value.image_width / 4) * relation_min_nodes + minimap_w / relation_minimap_w; - center_orig_y = (value.y + value.image_height / 4) * relation_min_nodes + minimap_h / relation_minimap_h; - } - else { - center_orig_x = (value.x + value.image_width / 2) * relation_min_nodes; - center_orig_y = (value.y + value.image_height / 2) * relation_min_nodes; - } + context_minimap.beginPath(); + //Paint the item + if (graph.nodes.length > 100) { + center_orig_x = + (value.x + value.image_width / 4) * relation_min_nodes + + minimap_w / relation_minimap_w; + center_orig_y = + (value.y + value.image_height / 4) * relation_min_nodes + + minimap_h / relation_minimap_h; + } else { + center_orig_x = (value.x + value.image_width / 2) * relation_min_nodes; + center_orig_y = (value.y + value.image_height / 2) * relation_min_nodes; + } - context_minimap.arc(center_orig_x, - center_orig_y, 2, 0, Math.PI * 2, false); - //Check if the pandora point - if (value.id_agent == -1) { - context_minimap.fillStyle = "#364D1F"; - } - else { - context_minimap.fillStyle = "#000"; - } - context_minimap.fill(); - }); + context_minimap.arc(center_orig_x, center_orig_y, 2, 0, Math.PI * 2, false); + //Check if the pandora point + if (value.id_agent == -1) { + context_minimap.fillStyle = "#364D1F"; + } else { + context_minimap.fillStyle = "#000"; + } + context_minimap.fill(); + }); - if (graph.nodes.length > 100) { - //Draw the rect of viewport - context_minimap.beginPath(); - context_minimap.strokeStyle = "#3f3f3f"; - context_minimap.strokeRect( - (-translation[0] / scale) * relation_min_nodes + minimap_w / relation_minimap_w, - (-translation[1] / scale) * relation_min_nodes + minimap_h / relation_minimap_h, - width_svg * relation_min_nodes / scale, - height_svg * relation_min_nodes / scale); - } - else { - //Draw the rect of viewport - context_minimap.beginPath(); - context_minimap.strokeStyle = "#f00"; - context_minimap.strokeRect( - (-translation[0] / scale) * relation_min_nodes, - (-translation[1] / scale) * relation_min_nodes, - width_svg * relation_min_nodes / scale, - height_svg * relation_min_nodes / scale); - } + if (graph.nodes.length > 100) { + //Draw the rect of viewport + context_minimap.beginPath(); + context_minimap.strokeStyle = "#3f3f3f"; + context_minimap.strokeRect( + (-translation[0] / scale) * relation_min_nodes + + minimap_w / relation_minimap_w, + (-translation[1] / scale) * relation_min_nodes + + minimap_h / relation_minimap_h, + (width_svg * relation_min_nodes) / scale, + (height_svg * relation_min_nodes) / scale + ); + } else { + //Draw the rect of viewport + context_minimap.beginPath(); + context_minimap.strokeStyle = "#f00"; + context_minimap.strokeRect( + (-translation[0] / scale) * relation_min_nodes, + (-translation[1] / scale) * relation_min_nodes, + (width_svg * relation_min_nodes) / scale, + (height_svg * relation_min_nodes) / scale + ); + } - context_minimap.beginPath(); - context_minimap.strokeStyle = "#82B92E"; - context_minimap.strokeRect( - (networkmap_dimensions[0] + node_radius - holding_area_dimensions[0]) * minimap_relation, - (networkmap_dimensions[1] + node_radius - holding_area_dimensions[1]) * minimap_relation, - holding_area_dimensions[0] * minimap_relation, - holding_area_dimensions[1] * minimap_relation) + context_minimap.beginPath(); + context_minimap.strokeStyle = "#82B92E"; + context_minimap.strokeRect( + (networkmap_dimensions[0] + node_radius - holding_area_dimensions[0]) * + minimap_relation, + (networkmap_dimensions[1] + node_radius - holding_area_dimensions[1]) * + minimap_relation, + holding_area_dimensions[0] * minimap_relation, + holding_area_dimensions[1] * minimap_relation + ); - context_minimap.globalAlpha = 1; + context_minimap.globalAlpha = 1; } function inner_minimap_box(param_x, param_y) { - if ((param_x + translation[0] * minimap_relation >= 0) - && (param_x + translation[0] * minimap_relation <= width_svg * minimap_relation) - && (param_y + translation[1] * minimap_relation >= 0) - && (param_y + translation[1] * minimap_relation <= height_svg * minimap_relation)) { - return true; - } + if ( + param_x + translation[0] * minimap_relation >= 0 && + param_x + translation[0] * minimap_relation <= + width_svg * minimap_relation && + param_y + translation[1] * minimap_relation >= 0 && + param_y + translation[1] * minimap_relation <= height_svg * minimap_relation + ) { + return true; + } - return false; + return false; } function set_center(id, event) { - pos_x = (width_svg / 2) - (translation[0] / scale); - pos_y = (height_svg / 2) - (translation[1] / scale); + pos_x = width_svg / 2 - translation[0] / scale; + pos_y = height_svg / 2 - translation[1] / scale; - var params = []; - params.push("set_center=1"); - params.push("id=" + id); - params.push("x=" + pos_x); - params.push("y=" + pos_y); - params.push("scale=" + scale); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - } - } - }); + var params = []; + params.push("set_center=1"); + params.push("id=" + id); + params.push("x=" + pos_x); + params.push("y=" + pos_y); + params.push("scale=" + scale); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + } + } + }); } function get_relations(node_param) { - var return_links = []; - var links_id_db = []; - - jQuery.each(graph.links, function (i, link_each) { - if (node_param.id == link_each.source.id || node_param.id == link_each.target.id) { - if(links_id_db.length > 0){ - if(links_id_db.indexOf(link_each.id_db) == -1){ - return_links.push(link_each); - links_id_db.push(link_each.id_db); - } - } else { - return_links.push(link_each); - links_id_db.push(link_each.id_db); - } - } - }); - - return return_links; + var return_links = []; + var links_id_db = []; + + jQuery.each(graph.links, function(i, link_each) { + if ( + node_param.id == link_each.source.id || + node_param.id == link_each.target.id + ) { + if (links_id_db.length > 0) { + if (links_id_db.indexOf(link_each.id_db) == -1) { + return_links.push(link_each); + links_id_db.push(link_each.id_db); + } + } else { + return_links.push(link_each); + links_id_db.push(link_each.id_db); + } + } + }); + + return return_links; } -function delete_link(source_id, source_module_id, target_id, target_module_id, id_link) { - if (enterprise_installed) { - var params = []; - params.push("delete_link=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("source_id=" + source_id); - params.push("source_module_id=" + source_module_id); - params.push("target_id=" + target_id); - params.push("target_module_id=" + target_module_id); - params.push("id_link=" + id_link); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - var found = -1; - jQuery.each(graph.links, function (i, element) { - if (element.id_db == id_link) { - found = i; - } - }); - if (found != -1) { - graph.links.splice(found, 1); - } +function delete_link( + source_id, + source_module_id, + target_id, + target_module_id, + id_link +) { + if (enterprise_installed) { + var params = []; + params.push("delete_link=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("source_id=" + source_id); + params.push("source_module_id=" + source_module_id); + params.push("target_id=" + target_id); + params.push("target_module_id=" + target_module_id); + params.push("id_link=" + id_link); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + var found = -1; + jQuery.each(graph.links, function(i, element) { + if (element.id_db == id_link) { + found = i; + } + }); + if (found != -1) { + graph.links.splice(found, 1); + } - $("#layer_graph_links_" + networkmap_id).remove(); - $("#layer_graph_nodes_" + networkmap_id).remove(); + $("#layer_graph_links_" + networkmap_id).remove(); + $("#layer_graph_nodes_" + networkmap_id).remove(); - window.layer_graph_links = window.layer_graph - .append("g") - .attr("id", "layer_graph_links_" + networkmap_id); - window.layer_graph_nodes = window.layer_graph - .append("g") - .attr("id", "layer_graph_nodes_" + networkmap_id); + window.layer_graph_links = window.layer_graph + .append("g") + .attr("id", "layer_graph_links_" + networkmap_id); + window.layer_graph_nodes = window.layer_graph + .append("g") + .attr("id", "layer_graph_nodes_" + networkmap_id); - force.nodes(graph.nodes) - .links(graph.links) - .start(); + force + .nodes(graph.nodes) + .links(graph.links) + .start(); - window.node = layer_graph_nodes.selectAll(".node"); - window.link = layer_graph_links.selectAll(".link"); + window.node = layer_graph_nodes.selectAll(".node"); + window.link = layer_graph_links.selectAll(".link"); - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } - $("#dialog_node_edit").dialog("close"); - } - }); - } + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } + $("#dialog_node_edit").dialog("close"); + } + }); + } } function update_fictional_node(id_db_node) { - if (enterprise_installed) { - var name = $("input[name='edit_name_fictional_node']").val(); - var networkmap_to_link = $("#edit_networkmap_to_link").val(); + if (enterprise_installed) { + var name = $("input[name='edit_name_fictional_node']").val(); + var networkmap_to_link = $("#edit_networkmap_to_link").val(); - var params = []; - params.push("update_fictional_node=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("node_id=" + id_db_node); - params.push("name=" + name); - params.push("networkmap_to_link=" + networkmap_to_link); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("update_fictional_node=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("node_id=" + id_db_node); + params.push("name=" + name); + params.push("networkmap_to_link=" + networkmap_to_link); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#dialog_node_edit").dialog("close"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#dialog_node_edit").dialog("close"); - jQuery.each(graph.nodes, function (i, element) { - if (element.id_db == id_db_node) { - graph.nodes[i].text = name; - graph.nodes[i].networkmap_id = networkmap_to_link; + jQuery.each(graph.nodes, function(i, element) { + if (element.id_db == id_db_node) { + graph.nodes[i].text = name; + graph.nodes[i].networkmap_id = networkmap_to_link; - $("#id_node_" + i + networkmap_id + " title").html(name); - $("#id_node_" + i + networkmap_id + " tspan").html(ellipsize(name, 30)); - } - }); + $("#id_node_" + i + networkmap_id + " title").html(name); + $("#id_node_" + i + networkmap_id + " tspan").html( + ellipsize(name, 30) + ); + } + }); - draw_elements_graph(); - set_positions_graph(); - } - } - }); - } + draw_elements_graph(); + set_positions_graph(); + } + } + }); + } } function update_node_name(id_db_node) { - if (enterprise_installed) { - var name = $("input[name='edit_name_node']").val(); + if (enterprise_installed) { + var name = $("input[name='edit_name_node']").val(); - var params = []; - params.push("update_node_name=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("node_id=" + id_db_node); - params.push("name=" + name); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("update_node_name=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("node_id=" + id_db_node); + params.push("name=" + name); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#dialog_node_edit").dialog("close"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#dialog_node_edit").dialog("close"); - jQuery.each(graph.nodes, function (i, element) { - if (element.id_db == id_db_node) { - graph.nodes[i]['text'] = data['text']; - graph.nodes[i]['raw_text'] = data['raw_text']; + jQuery.each(graph.nodes, function(i, element) { + if (element.id_db == id_db_node) { + graph.nodes[i]["text"] = data["text"]; + graph.nodes[i]["raw_text"] = data["raw_text"]; - $("#id_node_" + i + networkmap_id + " title").html(data['raw_text']); - $("#id_node_" + i + networkmap_id + " tspan").html(ellipsize(data['raw_text'], 30)); - } - }); + $("#id_node_" + i + networkmap_id + " title").html( + data["raw_text"] + ); + $("#id_node_" + i + networkmap_id + " tspan").html( + ellipsize(data["raw_text"], 30) + ); + } + }); - draw_elements_graph(); - set_positions_graph(); - } - } - }); - } + draw_elements_graph(); + set_positions_graph(); + } + } + }); + } } function change_shape(id_db_node) { - if (enterprise_installed) { - var shape = $("select[name='shape']").val(); + if (enterprise_installed) { + var shape = $("select[name='shape']").val(); - var params = []; - params.push("change_shape=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("id=" + id_db_node); - params.push("shape=" + shape); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("change_shape=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("id=" + id_db_node); + params.push("shape=" + shape); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - $("#shape_icon_correct").css("display", "none"); - $("#shape_icon_fail").css("display", "none"); - $("#shape_icon_in_progress").css("display", ""); + $("#shape_icon_correct").css("display", "none"); + $("#shape_icon_fail").css("display", "none"); + $("#shape_icon_in_progress").css("display", ""); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - $("#shape_icon_in_progress").css("display", "none"); - if (data['correct']) { - $("#shape_icon_correct").css("display", ""); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + $("#shape_icon_in_progress").css("display", "none"); + if (data["correct"]) { + $("#shape_icon_correct").css("display", ""); - count = graph.nodes.length; + count = graph.nodes.length; - jQuery.each(graph.nodes, function (i, element) { - if (element.id_db == id_db_node) { - graph.nodes[i].shape = shape; + jQuery.each(graph.nodes, function(i, element) { + if (element.id_db == id_db_node) { + graph.nodes[i].shape = shape; - $("#id_node_" + element.id + networkmap_id + " rect").remove(); - $("#id_node_" + element.id + networkmap_id + " circle").remove(); - $("#id_node_" + element.id + networkmap_id + " image").remove(); + $("#id_node_" + element.id + networkmap_id + " rect").remove(); + $("#id_node_" + element.id + networkmap_id + " circle").remove(); + $("#id_node_" + element.id + networkmap_id + " image").remove(); - if (shape == 'circle') { - d3.select("#id_node_" + element.id + networkmap_id) - .insert("circle", "title") - .attr("r", node_radius) - .attr("class", "node_shape node_shape_circle") - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverCircleFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutCircleFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + if (shape == "circle") { + d3.select("#id_node_" + element.id + networkmap_id) + .insert("circle", "title") + .attr("r", node_radius) + .attr("class", "node_shape node_shape_circle") + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverCircleFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutCircleFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - d3.select("#id_node_" + element.id + networkmap_id) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverCircleFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutCircleFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + d3.select("#id_node_" + element.id + networkmap_id) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverCircleFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutCircleFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); + } else if (shape == "square") { + d3.select("#id_node_" + element.id + networkmap_id) + .insert("rect", "title") + .attr("width", node_radius * 2) + .attr("height", node_radius * 2) + .attr("class", "node_shape node_shape_square") + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverSquareFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutSquareFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + d3.select("#id_node_" + element.id + networkmap_id) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverSquareFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutSquareFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); + } else if (shape == "rhombus") { + d3.select("#id_node_" + element.id + networkmap_id) + .insert("rect", "title") + .attr("transform", "") + .attr("width", node_radius * 1.5) + .attr("height", node_radius * 1.5) + .attr("class", "node_shape node_shape_rhombus") + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverRhombusFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutRhombusFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - } - else if (shape == 'square') { - d3.select("#id_node_" + element.id + networkmap_id) - .insert("rect", "title") - .attr("width", node_radius * 2) - .attr("height", node_radius * 2) - .attr("class", "node_shape node_shape_square") - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverSquareFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutSquareFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + d3.select("#id_node_" + element.id + networkmap_id) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverRhombusFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutRhombusFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); + } + } - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - d3.select("#id_node_" + element.id + networkmap_id) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverSquareFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutSquareFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - } - else if (shape == 'rhombus') { - d3.select("#id_node_" + element.id + networkmap_id) - .insert("rect", "title") - .attr("transform", - "") - .attr("width", node_radius * 1.5) - .attr("height", node_radius * 1.5) - .attr("class", "node_shape node_shape_rhombus") - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverRhombusFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutRhombusFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - d3.select("#id_node_" + element.id + networkmap_id) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverRhombusFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutRhombusFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - } - - } - - count = count - 1; - if (count == 0) { - draw_elements_graph(); - set_positions_graph(); - } - }); - } - else { - $("#shape_icon_fail").css("display", ""); - } - } - }); - } + count = count - 1; + if (count == 0) { + draw_elements_graph(); + set_positions_graph(); + } + }); + } else { + $("#shape_icon_fail").css("display", ""); + } + } + }); + } } function update_link(row_index, id_link) { - var interface_source = parseInt( - $("select[name='interface_source_" + row_index + "']") - .val() - ); + var interface_source = parseInt( + $("select[name='interface_source_" + row_index + "']").val() + ); - var text_source_interface = ""; - if (interface_source != 0) { - text_source_interface = $("select[name='interface_source_" + - row_index + "'] option:selected").text(); - } + var text_source_interface = ""; + if (interface_source != 0) { + text_source_interface = $( + "select[name='interface_source_" + row_index + "'] option:selected" + ).text(); + } - var interface_target = parseInt( - $("select[name='interface_target_" + row_index + "']") - .val() - ); + var interface_target = parseInt( + $("select[name='interface_target_" + row_index + "']").val() + ); - var text_target_interface = ""; - if (interface_target != 0) { - text_target_interface = $("select[name='interface_target_" + - row_index + "'] option:selected").text(); - } + var text_target_interface = ""; + if (interface_target != 0) { + text_target_interface = $( + "select[name='interface_target_" + row_index + "'] option:selected" + ).text(); + } - $(".edit_icon_progress_" + row_index).css("display", ""); - $(".edit_icon_" + row_index).css("display", "none"); + $(".edit_icon_progress_" + row_index).css("display", ""); + $(".edit_icon_" + row_index).css("display", "none"); - var params = []; - params.push("update_link=1"); - params.push("networkmap_id=" + networkmap_id); - params.push("id_link=" + id_link); - params.push("interface_source=" + interface_source); - params.push("interface_target=" + interface_target); - params.push("source_text=" + text_source_interface); - params.push("target_text=" + text_target_interface); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("update_link=1"); + params.push("networkmap_id=" + networkmap_id); + params.push("id_link=" + id_link); + params.push("interface_source=" + interface_source); + params.push("interface_target=" + interface_target); + params.push("source_text=" + text_source_interface); + params.push("target_text=" + text_target_interface); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - $(".edit_icon_progress_" + row_index).css("display", "none"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + $(".edit_icon_progress_" + row_index).css("display", "none"); - if (data['correct']) { - $(".edit_icon_correct_" + row_index).css("display", ""); + if (data["correct"]) { + $(".edit_icon_correct_" + row_index).css("display", ""); - $("select[name='interface_source_" + row_index + "'] option[value='" + interface_source + "']") - .prop("selected", true); - $("select[name='interface_target_" + row_index + "'] option[value='" + interface_target + "']") - .prop("selected", true); + $( + "select[name='interface_source_" + + row_index + + "'] option[value='" + + interface_source + + "']" + ).prop("selected", true); + $( + "select[name='interface_target_" + + row_index + + "'] option[value='" + + interface_target + + "']" + ).prop("selected", true); - var id = ""; - var index = -1; - $.each(graph.links, function (j, link) { - if (link['id_db'] == id_link) { - index = j; - id = String(id_link); - } - }); + var id = ""; + var index = -1; + $.each(graph.links, function(j, link) { + if (link["id_db"] == id_link) { + index = j; + id = String(id_link); + } + }); - delete_link_from_id(index); + delete_link_from_id(index); - var temp_link = {}; - temp_link["status_start"] = "0"; - temp_link["status_end"] = "0"; - - temp_link["id_db"] = String(data['id_db_link']); - - if (data['type_source'] == 1) { - temp_link["arrow_start"] = "module"; - temp_link["id_module_start"] = interface_source; - temp_link["status_start"] = data['status']; - temp_link["link_color"] = (data['status'] == "1") ? "#FC4444" : "#999"; - } - else { - temp_link["arrow_start"] = ""; - temp_link["id_agent_start"] = interface_source; - temp_link["id_module_start"] = 0; - } - if (data['type_target'] == 1) { - temp_link["arrow_end"] = "module"; - temp_link["id_module_end"] = interface_target; - temp_link["status_end"] = data['status']; - temp_link["link_color"] = (data['status'] == "1") ? "#FC4444" : "#999"; - } - else { - temp_link["arrow_end"] = ""; - temp_link["id_agent_end"] = interface_target; - temp_link["id_module_end"] = 0; - } - - temp_link["text_start"] = data["text_start"]; - temp_link["text_end"] = data["text_end"]; + var temp_link = {}; + temp_link["status_start"] = "0"; + temp_link["status_end"] = "0"; - $.each(graph.nodes, function (k, node) { - if (node['id_agent'] == data['id_db_target']) { - temp_link["target"] = graph.nodes[k]; - } - if (node['id_agent'] == data['id_db_source']) { - temp_link["source"] = graph.nodes[k]; - } - }); + temp_link["id_db"] = String(data["id_db_link"]); - add_new_link(temp_link); + if (data["type_source"] == 1) { + temp_link["arrow_start"] = "module"; + temp_link["id_module_start"] = interface_source; + temp_link["status_start"] = data["status"]; + temp_link["link_color"] = data["status"] == "1" ? "#FC4444" : "#999"; + } else { + temp_link["arrow_start"] = ""; + temp_link["id_agent_start"] = interface_source; + temp_link["id_module_start"] = 0; + } + if (data["type_target"] == 1) { + temp_link["arrow_end"] = "module"; + temp_link["id_module_end"] = interface_target; + temp_link["status_end"] = data["status"]; + temp_link["link_color"] = data["status"] == "1" ? "#FC4444" : "#999"; + } else { + temp_link["arrow_end"] = ""; + temp_link["id_agent_end"] = interface_target; + temp_link["id_module_end"] = 0; + } - $("#layer_graph_links_" + networkmap_id).remove(); - $("#layer_graph_nodes_" + networkmap_id).remove(); + temp_link["text_start"] = data["text_start"]; + temp_link["text_end"] = data["text_end"]; - window.layer_graph_links = window.layer_graph - .append("g") - .attr("id", "layer_graph_links_" + networkmap_id); - window.layer_graph_nodes = window.layer_graph - .append("g") - .attr("id", "layer_graph_nodes_" + networkmap_id); + $.each(graph.nodes, function(k, node) { + if (node["id_agent"] == data["id_db_target"]) { + temp_link["target"] = graph.nodes[k]; + } + if (node["id_agent"] == data["id_db_source"]) { + temp_link["source"] = graph.nodes[k]; + } + }); - force.nodes(graph.nodes) - .links(graph.links) - .start(); + add_new_link(temp_link); - window.node = layer_graph_nodes.selectAll(".node"); - window.link = layer_graph_links.selectAll(".link"); + $("#layer_graph_links_" + networkmap_id).remove(); + $("#layer_graph_nodes_" + networkmap_id).remove(); - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } - else { - $(".edit_icon_fail_" + row_index).css("display", ""); - } - } - }); + window.layer_graph_links = window.layer_graph + .append("g") + .attr("id", "layer_graph_links_" + networkmap_id); + window.layer_graph_nodes = window.layer_graph + .append("g") + .attr("id", "layer_graph_nodes_" + networkmap_id); + + force + .nodes(graph.nodes) + .links(graph.links) + .start(); + + window.node = layer_graph_nodes.selectAll(".node"); + window.link = layer_graph_links.selectAll(".link"); + + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } else { + $(".edit_icon_fail_" + row_index).css("display", ""); + } + } + }); } function delete_link_from_id(index) { - graph.links.splice(index, 1); + graph.links.splice(index, 1); } function add_new_link(new_link) { - graph.links.push(new_link); + graph.links.push(new_link); } -function move_to_networkmap (node) { - var params = []; - params.push("get_networkmap_from_fictional=1"); - params.push("id=" + node.id_db); - params.push("id_map=" + node.map_id); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); +function move_to_networkmap(node) { + var params = []; + params.push("get_networkmap_from_fictional=1"); + params.push("id=" + node.id_db); + params.push("id_map=" + node.map_id); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax ({ - data: params.join ("&"), - dataType: 'json', - type: 'POST', - url: action="ajax.php", - success: function (data) { - if (data['correct']) { - window.location="index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=" + data['id_networkmap']; - } - else { - edit_node(node, true); - } - } - }); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + window.location = + "index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=" + + data["id_networkmap"]; + } else { + edit_node(node, true); + } + } + }); } - function edit_node(data_node, dblClick) { - if (enterprise_installed) { - var flag_edit_node = true; - var edit_node = null + if (enterprise_installed) { + var flag_edit_node = true; + var edit_node = null; - //Only select one node - var selection = d3.selectAll('.node_selected'); + //Only select one node + var selection = d3.selectAll(".node_selected"); - if (selection[0].length == 1) { - edit_node = selection[0].pop(); - } - else if (selection[0].length > 1) { - edit_node = selection[0].pop(); - } - else if (dblClick) { - edit_node = d3.select("#id_node_" + data_node['id'] + networkmap_id); - edit_node = edit_node[0][0]; - } - else { - flag_edit_node = false; - } + if (selection[0].length == 1) { + edit_node = selection[0].pop(); + } else if (selection[0].length > 1) { + edit_node = selection[0].pop(); + } else if (dblClick) { + edit_node = d3.select("#id_node_" + data_node["id"] + networkmap_id); + edit_node = edit_node[0][0]; + } else { + flag_edit_node = false; + } - if (flag_edit_node) { - d3.selectAll('.node_selected') - .classed("node_selected", false); - d3.select(edit_node) - .classed("node_selected", true); + if (flag_edit_node) { + d3.selectAll(".node_selected").classed("node_selected", false); + d3.select(edit_node).classed("node_selected", true); - id = d3.select(edit_node).attr("id").replace("id_node_", ""); - id_networkmap_lenght = networkmap_id.toString().length; - id_node_length = id.length - id_networkmap_lenght; - id = id.substring(0, id_node_length); - node_selected = graph.nodes[id]; + id = d3 + .select(edit_node) + .attr("id") + .replace("id_node_", ""); + id_networkmap_lenght = networkmap_id.toString().length; + id_node_length = id.length - id_networkmap_lenght; + id = id.substring(0, id_node_length); + node_selected = graph.nodes[id]; - selected_links = get_relations(node_selected); + selected_links = get_relations(node_selected); - $("select[name='shape'] option[value='" + node_selected.shape + "']") - .prop("selected", true); - $("select[name='shape']").attr("onchange", - "javascript: change_shape(" + node_selected.id_db + ");"); - $("#node_options-fictional_node_update_button-1 input") - .attr("onclick", "update_fictional_node(" + node_selected.id_db + ");"); + $( + "select[name='shape'] option[value='" + node_selected.shape + "']" + ).prop("selected", true); + $("select[name='shape']").attr( + "onchange", + "javascript: change_shape(" + node_selected.id_db + ");" + ); + $("#node_options-fictional_node_update_button-1 input").attr( + "onclick", + "update_fictional_node(" + node_selected.id_db + ");" + ); - $("#node_options-node_name-2 input") - .attr("onclick", "update_node_name(" + node_selected.id_db + ");"); + $("#node_options-node_name-2 input").attr( + "onclick", + "update_node_name(" + node_selected.id_db + ");" + ); - var params = []; - params.push("get_agent_info=1"); - params.push("id_agent=" + node_selected["id_agent"]); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("get_agent_info=1"); + params.push("id_agent=" + node_selected["id_agent"]); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - $("#node_details-0-1").html('' + data['alias'] + ''); - - var addresses = ""; - if (data['adressess'] instanceof Array) { - for (var i; i < data['adressess'].length; i++) { - addresses += data['adressess'][i] + "
                            "; - } - } else { - for (address in data['adressess']) { - addresses += address + "
                            "; - } - } - $("#node_details-1-1").html(addresses); - $("#node_details-2-1").html(data["os"]); - $("#node_details-3-1").html(data["group"]); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + $("#node_details-0-1").html( + '' + + data["alias"] + + "" + ); - $('[aria-describedby=dialog_node_edit]').css({ 'top': '200px' }); - $('#foot').css({ 'top': parseInt($("[aria-describedby=dialog_node_edit]").css('height') + $("[aria-describedby=dialog_node_edit]").css('top')), 'position': 'relative' }); + var addresses = ""; + if (data["adressess"] instanceof Array) { + for (var i; i < data["adressess"].length; i++) { + addresses += data["adressess"][i] + "
                            "; + } + } else { + for (address in data["adressess"]) { + addresses += address + "
                            "; + } + } + $("#node_details-1-1").html(addresses); + $("#node_details-2-1").html(data["os"]); + $("#node_details-3-1").html(data["group"]); - get_interface_data_to_table(node_selected, selected_links); - } - }); + $("[aria-describedby=dialog_node_edit]").css({ top: "200px" }); + $("#foot").css({ + top: parseInt( + $("[aria-describedby=dialog_node_edit]").css("height") + + $("[aria-describedby=dialog_node_edit]").css("top") + ), + position: "relative" + }); - $("#dialog_node_edit") - .dialog("option", "title", - dialog_node_edit_title.replace("%s", ellipsize(node_selected['text'], 40))); // It doesn't eval the possible XSS so it's ok - $("#dialog_node_edit").dialog("open"); + get_interface_data_to_table(node_selected, selected_links); + } + }); - if (node_selected.id_agent == undefined || node_selected.id_agent == -2) { - //Fictional node - $("#node_options-fictional_node_name") - .css("display", ""); - $("input[name='edit_name_fictional_node']") - .val(node_selected.text); // It doesn't eval the possible XSS so it's ok - $("#node_options-fictional_node_networkmap_link") - .css("display", ""); - $("#edit_networkmap_to_link") - .val(node_selected.networkmap_id); - $("#node_options-fictional_node_update_button") - .css("display", ""); - $("#node_options-node_name") - .css("display", "none"); - $("#node_options-node_update_button") - .css("display", "none"); - } - else { - $("input[name='edit_name_node']") - .val(node_selected.text); // It doesn't eval the possible XSS so it's ok - $("#node_options-fictional_node_name") - .css("display", "none"); - $("#node_options-fictional_node_networkmap_link") - .css("display", "none"); - $("#node_options-fictional_node_update_button") - .css("display", "none"); - $("#node_options-node_name") - .css("display", ""); - } + $("#dialog_node_edit").dialog( + "option", + "title", + dialog_node_edit_title.replace( + "%s", + ellipsize(node_selected["text"], 40) + ) + ); // It doesn't eval the possible XSS so it's ok + $("#dialog_node_edit").dialog("open"); - //Clean - $("#relations_table .relation_link_row").remove(); - //Show the no relations - $("#relations_table-loading").css('display', 'none'); - $("#relations_table-no_relations").css('display', ''); - } - } + if (node_selected.id_agent == undefined || node_selected.id_agent == -2) { + //Fictional node + $("#node_options-fictional_node_name").css("display", ""); + $("input[name='edit_name_fictional_node']").val(node_selected.text); // It doesn't eval the possible XSS so it's ok + $("#node_options-fictional_node_networkmap_link").css("display", ""); + $("#edit_networkmap_to_link").val(node_selected.networkmap_id); + $("#node_options-fictional_node_update_button").css("display", ""); + $("#node_options-node_name").css("display", "none"); + $("#node_options-node_update_button").css("display", "none"); + } else { + $("input[name='edit_name_node']").val(node_selected.text); // It doesn't eval the possible XSS so it's ok + $("#node_options-fictional_node_name").css("display", "none"); + $("#node_options-fictional_node_networkmap_link").css( + "display", + "none" + ); + $("#node_options-fictional_node_update_button").css("display", "none"); + $("#node_options-node_name").css("display", ""); + } + + //Clean + $("#relations_table .relation_link_row").remove(); + //Show the no relations + $("#relations_table-loading").css("display", "none"); + $("#relations_table-no_relations").css("display", ""); + } + } } function get_interface_data_to_table(node_selected, selected_links) { - $("#interface_information").find("tr:gt(0)").remove(); + $("#interface_information") + .find("tr:gt(0)") + .remove(); - var params = []; - params.push("get_interface_info=1"); - params.push("id_agent=" + node_selected["id_agent"]); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data.length == 0) { - $("#interface_information").find('tbody') - .append($('
              ').html("

              It has no interface to display

              ")); - } - else { - jQuery.each(data, function (j, interface) { - if (interface['graph'] == "") { - var interf_graph = "--"; - } - else { - var interf_graph = interface['graph']; - } - $("#interface_information").find('tbody') - .append($('') - .append($('").html( + '

              It has no interface to display

              ' + ) + ); + } else { + jQuery.each(data, function(j, interface) { + if (interface["graph"] == "") { + var interf_graph = "--"; + } else { + var interf_graph = interface["graph"]; + } + $("#interface_information") + .find("tbody") + .append( + $("") + .append($("'); + $("#" + id_table).append( + '' + ); } // Get an event response from db function get_response_target(event_id, response_id, server_id) { - var ajax_file = $('#hidden-ajax_file').val(); + var ajax_file = $("#hidden-ajax_file").val(); - var target = ''; - - // Replace the main macros - var params = []; - params.push("page=include/ajax/events"); - params.push("get_response_target=1"); - params.push("event_id="+event_id); - params.push("response_id="+response_id); - params.push("server_id="+server_id); - - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: action=ajax_file, - async: false, - timeout: 10000, - dataType: 'html', - success: function (data) { - target = data; - } - }); - - // Replace the custom params macros - var response_params = get_response_params(response_id); - - if (response_params.length > 1 || response_params[0] != '') { - for (i = 0; i < response_params.length; i++) { - target = target.replace('_'+response_params[i]+'_',$('#'+response_params[i]).val()); - } - } - - return target; + var target = ""; + + // Replace the main macros + var params = []; + params.push("page=include/ajax/events"); + params.push("get_response_target=1"); + params.push("event_id=" + event_id); + params.push("response_id=" + response_id); + params.push("server_id=" + server_id); + + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: (action = ajax_file), + async: false, + timeout: 10000, + dataType: "html", + success: function(data) { + target = data; + } + }); + + // Replace the custom params macros + var response_params = get_response_params(response_id); + + if (response_params.length > 1 || response_params[0] != "") { + for (i = 0; i < response_params.length; i++) { + target = target.replace( + "_" + response_params[i] + "_", + $("#" + response_params[i]).val() + ); + } + } + + return target; } // Perform a response and put the output into a div function perform_response(target, response_id) { - var ajax_file = $('#hidden-ajax_file').val(); - - $('#re_exec_command').hide(); - $('#response_loading_command').show(); - $('#response_out').html(''); - - var finished = 0; - var time = Math.round(+new Date()/1000); - var timeout = time + 10; - - var params = []; - params.push("page=include/ajax/events"); - params.push("perform_event_response=1"); - params.push("target="+target); - params.push("response_id="+response_id) - - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: action=ajax_file, - async: true, - timeout: 10000, - dataType: 'html', - success: function (data) { - var out = data.replace(/[\n|\r]/g, "
              "); - $('#response_out').html(out); - $('#response_loading_command').hide(); - $('#re_exec_command').show(); - } - }); + var ajax_file = $("#hidden-ajax_file").val(); - return false; + $("#re_exec_command").hide(); + $("#response_loading_command").show(); + $("#response_out").html(""); + + var finished = 0; + var time = Math.round(+new Date() / 1000); + var timeout = time + 10; + + var params = []; + params.push("page=include/ajax/events"); + params.push("perform_event_response=1"); + params.push("target=" + target); + params.push("response_id=" + response_id); + + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: (action = ajax_file), + async: true, + timeout: 10000, + dataType: "html", + success: function(data) { + var out = data.replace(/[\n|\r]/g, "
              "); + $("#response_out").html(out); + $("#response_loading_command").hide(); + $("#re_exec_command").show(); + } + }); + + return false; +} + +// Perform a response and put the output into a div +function perform_response_massive(target, response_id, out_iterator) { + var ajax_file = $("#hidden-ajax_file").val(); + + $("#re_exec_command").hide(); + $("#response_loading_command_" + out_iterator).show(); + $("#response_out_" + out_iterator).html(""); + + var finished = 0; + var time = Math.round(+new Date() / 1000); + var timeout = time + 10; + + var params = []; + params.push("page=include/ajax/events"); + params.push("perform_event_response=1"); + params.push("target=" + target); + params.push("response_id=" + response_id); + + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: (action = ajax_file), + async: true, + timeout: 10000, + dataType: "html", + success: function(data) { + var out = data.replace(/[\n|\r]/g, "
              "); + $("#response_out_" + out_iterator).html(out); + $("#response_loading_command_" + out_iterator).hide(); + $("#re_exec_command_" + out_iterator).show(); + } + }); + + return false; } // Change the status of an event to new, in process or validated function event_change_status(event_ids) { - var ajax_file = $('#hidden-ajax_file').val(); + var ajax_file = $("#hidden-ajax_file").val(); - var new_status = $('#estado').val(); - var event_id = $('#hidden-id_event').val(); - var meta = $('#hidden-meta').val(); - var history = $('#hidden-history').val(); - - var params = []; - params.push("page=include/ajax/events"); - params.push("change_status=1"); - params.push("event_ids="+event_ids); - params.push("new_status="+new_status); - params.push("meta="+meta); - params.push("history="+history); - - $('#button-status_button').attr('disabled','disabled'); - $('#response_loading').show(); - - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: action=ajax_file, - async: true, - timeout: 10000, - dataType: 'html', - success: function (data) { - $('#button-status_button').removeAttr('disabled'); - $('#response_loading').hide(); - show_event_dialog(event_id, $('#hidden-group_rep').val(), 'responses', data); - if (data == 'status_ok') { - } - else { - } - } - }); - return false; + var new_status = $("#estado").val(); + var event_id = $("#hidden-id_event").val(); + var meta = $("#hidden-meta").val(); + var history = $("#hidden-history").val(); + + var params = []; + params.push("page=include/ajax/events"); + params.push("change_status=1"); + params.push("event_ids=" + event_ids); + params.push("new_status=" + new_status); + params.push("meta=" + meta); + params.push("history=" + history); + + $("#button-status_button").attr("disabled", "disabled"); + $("#response_loading").show(); + + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: (action = ajax_file), + async: true, + timeout: 10000, + dataType: "html", + success: function(data) { + $("#button-status_button").removeAttr("disabled"); + $("#response_loading").hide(); + show_event_dialog( + event_id, + $("#hidden-group_rep").val(), + "responses", + data + ); + if (data == "status_ok") { + } else { + } + } + }); + return false; } // Change te owner of an event to one user of empty function event_change_owner() { - var ajax_file = $('#hidden-ajax_file').val(); + var ajax_file = $("#hidden-ajax_file").val(); - var event_id = $('#hidden-id_event').val(); - var new_owner = $('#id_owner').val(); - var meta = $('#hidden-meta').val(); - var history = $('#hidden-history').val(); - - var params = []; - params.push("page=include/ajax/events"); - params.push("change_owner=1"); - params.push("event_id="+event_id); - params.push("new_owner="+new_owner); - params.push("meta="+meta); - params.push("history="+history); - - $('#button-owner_button').attr('disabled','disabled'); - $('#response_loading').show(); + var event_id = $("#hidden-id_event").val(); + var new_owner = $("#id_owner").val(); + var meta = $("#hidden-meta").val(); + var history = $("#hidden-history").val(); - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: action=ajax_file, - async: true, - timeout: 10000, - dataType: 'html', - success: function (data) { - $('#button-owner_button').removeAttr('disabled'); - $('#response_loading').hide(); - - show_event_dialog(event_id, $('#hidden-group_rep').val(), 'responses', data); - } - }); - - return false; + var params = []; + params.push("page=include/ajax/events"); + params.push("change_owner=1"); + params.push("event_id=" + event_id); + params.push("new_owner=" + new_owner); + params.push("meta=" + meta); + params.push("history=" + history); + + $("#button-owner_button").attr("disabled", "disabled"); + $("#response_loading").show(); + + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: (action = ajax_file), + async: true, + timeout: 10000, + dataType: "html", + success: function(data) { + $("#button-owner_button").removeAttr("disabled"); + $("#response_loading").hide(); + + show_event_dialog( + event_id, + $("#hidden-group_rep").val(), + "responses", + data + ); + } + }); + + return false; } // Save a comment into an event function event_comment() { - var ajax_file = $('#hidden-ajax_file').val(); - - var event_id = $('#hidden-id_event').val(); - var comment = $('#textarea_comment').val(); - var meta = $('#hidden-meta').val(); - var history = $('#hidden-history').val(); - - if (comment == '') { - show_event_dialog(event_id, $('#hidden-group_rep').val(), 'comments', 'comment_error'); - return false; - } - - var params = []; - params.push("page=include/ajax/events"); - params.push("add_comment=1"); - params.push("event_id=" + event_id); - params.push("comment=" + comment); - params.push("meta=" + meta); - params.push("history=" + history); - - $('#button-comment_button').attr('disabled','disabled'); - $('#response_loading').show(); - - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: action=ajax_file, - async: true, - timeout: 10000, - dataType: 'html', - success: function (data) { - $('#button-comment_button').removeAttr('disabled'); - $('#response_loading').show(); - - show_event_dialog(event_id, $('#hidden-group_rep').val(), 'comments', data); - } - }); - - return false; + var ajax_file = $("#hidden-ajax_file").val(); + + var event_id = $("#hidden-id_event").val(); + var comment = $("#textarea_comment").val(); + var meta = $("#hidden-meta").val(); + var history = $("#hidden-history").val(); + + if (comment == "") { + show_event_dialog( + event_id, + $("#hidden-group_rep").val(), + "comments", + "comment_error" + ); + return false; + } + + var params = []; + params.push("page=include/ajax/events"); + params.push("add_comment=1"); + params.push("event_id=" + event_id); + params.push("comment=" + comment); + params.push("meta=" + meta); + params.push("history=" + history); + + $("#button-comment_button").attr("disabled", "disabled"); + $("#response_loading").show(); + + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: (action = ajax_file), + async: true, + timeout: 10000, + dataType: "html", + success: function(data) { + $("#button-comment_button").removeAttr("disabled"); + $("#response_loading").show(); + + show_event_dialog( + event_id, + $("#hidden-group_rep").val(), + "comments", + data + ); + } + }); + + return false; } //Show event list when fielter repetead is Group agents -function show_events_group_agent (id_insert, id_agent, server_id) { - - var ajax_file = $('#hidden-ajax_file').val(); - parameter = []; - parameter.push ({name: "id_agent", - value: id_agent}); - parameter.push ({name: "server_id", - value: server_id}); - parameter.push ({name: "event_type", - value: $("#event_type").val()}); - parameter.push ({name: "severity", - value: $("#severity").val()}); - parameter.push ({name: "status", - value: $("#status").val()}); - parameter.push ({name: "search", - value: $("#text-search").val()}); - parameter.push ({name: "id_agent_module", - value: $('input:hidden[name=module_search_hidden]').val()}); - parameter.push ({name: "event_view_hr", - value: $("#text-event_view_hr").val()}); - parameter.push ({name: "id_user_ack", - value: $("#id_user_ack").val()}); - parameter.push ({name: "tag_with", - value: Base64.decode($("#hidden-tag_with").val())}); - parameter.push ({name: "tag_without", - value: Base64.decode($("#hidden-tag_without").val())}); - parameter.push ({name: "filter_only_alert", - value: $("#filter_only_alert").val()}); - parameter.push ({name: "date_from", - value: $("#text-date_from").val()}); - parameter.push ({name: "date_to", - value: $("#text-date_to").val()}); - parameter.push ({name: "server_id_search", - value: $("#server_id").val()}); - parameter.push ({ - name: "page", - value: "include/ajax/events"}); - parameter.push ({ - name: "get_list_events_agents", - value: 1}); - - jQuery.ajax ({ - type: 'POST', - url: action=ajax_file, - data: parameter, - dataType: 'html', - success: function (data) { - $("#"+id_insert).html(data); - $("#"+id_insert).toggle(); - } - }); - -} \ No newline at end of file +function show_events_group_agent(id_insert, id_agent, server_id) { + var ajax_file = $("#hidden-ajax_file").val(); + parameter = []; + parameter.push({ name: "id_agent", value: id_agent }); + parameter.push({ name: "server_id", value: server_id }); + parameter.push({ name: "event_type", value: $("#event_type").val() }); + parameter.push({ name: "severity", value: $("#severity").val() }); + parameter.push({ name: "status", value: $("#status").val() }); + parameter.push({ name: "search", value: $("#text-search").val() }); + parameter.push({ + name: "id_agent_module", + value: $("input:hidden[name=module_search_hidden]").val() + }); + parameter.push({ + name: "event_view_hr", + value: $("#text-event_view_hr").val() + }); + parameter.push({ name: "id_user_ack", value: $("#id_user_ack").val() }); + parameter.push({ + name: "tag_with", + value: Base64.decode($("#hidden-tag_with").val()) + }); + parameter.push({ + name: "tag_without", + value: Base64.decode($("#hidden-tag_without").val()) + }); + parameter.push({ + name: "filter_only_alert", + value: $("#filter_only_alert").val() + }); + parameter.push({ name: "date_from", value: $("#text-date_from").val() }); + parameter.push({ name: "date_to", value: $("#text-date_to").val() }); + parameter.push({ name: "server_id_search", value: $("#server_id").val() }); + parameter.push({ + name: "page", + value: "include/ajax/events" + }); + parameter.push({ + name: "get_list_events_agents", + value: 1 + }); + + jQuery.ajax({ + type: "POST", + url: (action = ajax_file), + data: parameter, + dataType: "html", + success: function(data) { + $("#" + id_insert).html(data); + $("#" + id_insert).toggle(); + } + }); +} diff --git a/pandora_console/include/javascript/pandora_modules.js b/pandora_console/include/javascript/pandora_modules.js index bb75e28667..135c8811de 100644 --- a/pandora_console/include/javascript/pandora_modules.js +++ b/pandora_console/include/javascript/pandora_modules.js @@ -1,937 +1,1123 @@ /* Modules ids to check types */ -var id_modules_icmp = Array (6, 7); -var id_modules_tcp = Array (8, 9, 10, 11); -var id_modules_snmp = Array (15, 16, 17, 18); +var id_modules_icmp = Array(6, 7); +var id_modules_tcp = Array(8, 9, 10, 11); +var id_modules_snmp = Array(15, 16, 17, 18); -function configure_modules_form () { - $("#id_module_type").change (function () { - if (id_modules_icmp.in_array (this.value)) { - $("tr#simple-snmp_1, tr#simple-snmp_2, tr#simple-tcp_send, tr#simple-tcp_receive").hide (); - $("#text-tcp_port").attr ("disabled", "1"); - } - else if (id_modules_snmp.in_array (this.value)) { - $("tr#simple-snmp_1, tr#simple-snmp_2").show (); - $("tr#simple-tcp_send, tr#simple-tcp_receive").hide (); - $("#text-tcp_port").removeAttr ("disabled"); - } - else if (id_modules_tcp.in_array (this.value)) { - $("tr#simple-snmp_1, tr#simple-snmp_2").hide (); - $("tr#simple-tcp_send, tr#simple-tcp_receive").show (); - $("#text-tcp_port").removeAttr ("disabled"); - } - }); - - $("#id_module_type").trigger("change"); - - $("#local_component_group").change (function () { - - var $select = $("#local_component").hide (); - $("#component").hide (); - if (this.value == 0) { - reset_data_module_form(); - return; - } - $("#component_loading").show (); - $(".error, #no_component").hide (); - $("option[value!=0]", $select).remove (); - jQuery.post ("ajax.php", - {"page" : "godmode/agentes/module_manager_editor", - "get_module_local_components" : 1, - "id_module_component_group" : this.value, - "id_module_component_type" : $("#hidden-id_module_component_type").attr ("value") - }, - function (data, status) { - if (data == false) { - $("#component_loading").hide (); - $("#no_component").show (); - return; - } - jQuery.each (data, function (i, val) { - option = $("") - .attr ("value", val['id']) - .append (val['name']); - $select.append (option); - }); - $("#component_loading").hide (); - $select.show (); - $("#component").show (); - }, - "json" - ); - } - ); - - function reset_data_module_form() { - // Delete macro fields - $('.macro_field').remove(); - - // Hide show/hide configuration data switch - $('#simple-show_configuration_data').hide(); - $('#simple-hide_configuration_data').hide(); - $('#configuration_data_legend').hide(); - - $("#textarea_configuration_data").val(''); - $('#simple-configuration_data').show(); - - $("#text-name").val(''); - $("#textarea_description").val(''); - $("#checkbox-history_data").check (); - $("#text-max").attr ("value", ""); - $("#text-min").attr ("value", ""); - $("#dynamic_interval_select").attr ("value", 0); - $("#text-dynamic_min").attr ("value", 0); - $("#text-dynamic_max").attr ("value", 0); - $("#checkbox-dynamic_two_tailed").attr ("value", 0); - $("#text-min_warning").attr ("value", 0); - $("#text-max_warning").attr ("value", 0); - $("#text-str_warning").attr ("value", ''); - $("#text-min_critical").attr ("value", 0); - $("#text-max_critical").attr ("value", 0); - $("#text-str_critical").attr ("value", ''); - $("#text-ff_event").attr ("value", 0); - $("#text-post_process").attr("value", 0); - $("#text-unit").attr("value", ''); - $("#checkbox-critical_inverse").attr ("value", 0); - $("#checkbox-warning_inverse").attr ("value", 0); - $("#textarea_critical_instructions").attr ("value", ''); - $("#textarea_warning_instructions").attr ("value", ''); - $("#textarea_unknown_instructions").attr ("value", ''); - - } - - $("#local_component").change (function () { - if (this.value == 0) { - reset_data_module_form(); - return; - } - $("#component_loading").show (); - $(".error").hide (); - jQuery.post ("ajax.php", { - "page" : "godmode/agentes/module_manager_editor", - "get_module_local_component" : 1, - "id_module_component" : this.value - }, - function (data, status) { - configuration_data = js_html_entity_decode (data['data']); - $("#text-name").attr ("value", - js_html_entity_decode (data["name"])); - $("#textarea_description").attr ("value", - js_html_entity_decode (data["description"])); - $("#textarea_description").html(js_html_entity_decode (data["description"])); - $("#textarea_configuration_data").val(configuration_data); - $("#component_loading").hide (); - $("#id_module_type").val(data["type"]); - $("#text-max").attr ("value", data["max"]); - $("#text-min").attr ("value", data["min"]); - // Workaround to update the advanced select control from html and ajax - if (typeof 'period_select_module_interval_update' == 'function') { - period_select_module_interval_update(data["module_interval"]); - } - else { - period_select_update('module_interval', - data["module_interval"]); - } - - $("#id_module_group").val (data["id_module_group"]); - - if (data["history_data"]) - $("#checkbox-history_data").check (); - else - $("#checkbox-history_data").uncheck (); +function configure_modules_form() { + $("#id_module_type").change(function() { + if (id_modules_icmp.in_array(this.value)) { + $( + "tr#simple-snmp_1, tr#simple-snmp_2, tr#simple-tcp_send, tr#simple-tcp_receive" + ).hide(); + $("#text-tcp_port").attr("disabled", "1"); + } else if (id_modules_snmp.in_array(this.value)) { + $("tr#simple-snmp_1, tr#simple-snmp_2").show(); + $("tr#simple-tcp_send, tr#simple-tcp_receive").hide(); + $("#text-tcp_port").removeAttr("disabled"); + } else if (id_modules_tcp.in_array(this.value)) { + $("tr#simple-snmp_1, tr#simple-snmp_2").hide(); + $("tr#simple-tcp_send, tr#simple-tcp_receive").show(); + $("#text-tcp_port").removeAttr("disabled"); + } + }); - $("#dynamic_interval_select").val (data["dynamic_interval"]); - $("#text-dynamic_max").attr ("value", (data["dynamic_max"] == 0) ? 0 : data["dynamic_max"]); - $("#text-dynamic_min").attr ("value", (data["dynamic_min"] == 0) ? 0 : data["dynamic_min"]); - - if (data["dynamic_two_tailed"]) - $("#checkbox-dynamic_two_tailed").check (); - else - $("#checkbox-dynamic_two_tailed").uncheck (); + $("#id_module_type").trigger("change"); - $("#text-min_warning").attr ("value", (data["min_warning"] == 0) ? 0 : data["min_warning"]); - $("#text-max_warning").attr ("value", (data["max_warning"] == 0) ? 0 : data["max_warning"]); - $("#text-str_warning").attr ("value", data["str_warning"]); - $("#text-min_critical").attr ("value", (data["min_critical"] == 0) ? 0 : data["min_critical"]); - $("#text-max_critical").attr ("value", (data["max_critical"] == 0) ? 0 : data["max_critical"]); - $("#text-str_critical").attr ("value", data["str_critical"]); - $("#text-ff_event").attr ("value", (data["min_ff_event"] == 0) ? 0 : data["min_ff_event"]); - $("#text-post_process").attr("value", (data["post_process"] == 0) ? 0 : data["post_process"]); - $("#text-unit").attr("value", (data["unit"] == '') ? '' : data["unit"]) - $("#checkbox-critical_inverse").prop ("checked", data["critical_inverse"]); - $("#checkbox-warning_inverse").prop ("checked", data["warning_inverse"]); - $("#component_loading").hide (); - $("#id_module_type").change (); - if ($("#id_category").is("select")) { - $("#id_category").val (data["id_category"]); - } - else { - $("#hidden-id_category").val(data["id_category"]); - } - - var tags = data["tags"]; - - // Reset the selection of tags (put all of them into available box) - $("#id_tag_selected option").each(function(){ - if ($(this).attr('value') != '') { - $("#id_tag_selected").find("option[value='" + $(this).attr('value') + "']").remove(); - $("select[name='id_tag_available[]']").append($("").val($(this).attr('value')).html($(this).text())); - } - }); - if ($("#id_tag_available option").length > 1) { - $("#id_tag_available").find("option[value='']").remove(); - } - if ($("#id_tag_selected option").length == 0) { - $("select[name='id_tag_selected[]']").append($("").val('').html('None')); - } - - if (tags != '') { - tags = tags.split(','); - - // Fill the selected tags box with select ones - for (i = 0; i < tags.length; i++){ - $("#id_tag_available option").each(function(){ - if (tags[i] == $(this).text()) { - $("#id_tag_available").find("option[value='" + $(this).attr('value') + "']").remove(); - $("select[name='id_tag_selected[]']").append($("").val($(this).attr('value')).html($(this).text())); - $("#id_tag_selected").find("option[value='']").remove(); - } - }); - - if ($("#id_tag_available option").length == 0) { - $("select[name='id_tag_available[]']").append($("").val('').html('None')); - } - } - } - - if (data["throw_unknown_events"]) - $("input[name='throw_unknown_events']").check(); - else - $("input[name='throw_unknown_events']").uncheck(); - - // Delete macro fields - $('.macro_field').remove(); - - $('#hidden-macros').val(''); - - var legend = ''; - // If exist macros, load the fields - if (data["macros"] != '' && data["macros"] != null) { - $('#hidden-macros').val(Base64.encode(data["macros"])); - - var obj = jQuery.parseJSON(data["macros"]); - $.each(obj, function(k,macro) { - add_macro_field(macro, 'simple-macro'); - legend += macro['macro']+" = "+ macro['desc']+"
              "; - }); - $('#configuration_data_legend').html(legend); - - $('#simple-show_configuration_data').show(); - $('#simple-hide_configuration_data').hide(); - $('#configuration_data_legend').show(); - $('#simple-configuration_data').hide(); - } - else { - $('#simple-show_configuration_data').hide(); - $('#simple-hide_configuration_data').hide(); - $('#configuration_data_legend').hide(); - $('#simple-configuration_data').show(); - } - }, - "json" - ); - }); - - network_component_group_change_event(); - - flag_load_plugin_component = false; - $("#network_component").change (function () { - if (this.value == 0) - return; - $("#component_loading").show (); - $(".error").hide (); - - jQuery.post ("ajax.php", - { - "page" : "godmode/agentes/module_manager_editor", - "get_module_component" : 1, - "id_module_component" : this.value - }, - function (data, status) { - flag_load_plugin_component = true; - - $("#text-name").attr ("value", js_html_entity_decode (data["name"])); - $("#textarea_description").html (js_html_entity_decode (data["description"])); - $("#id_module_type").val(data["type"]); - $("#text-max").attr ("value", data["max"]); - $("#text-min").attr ("value", data["min"]); - // Workaround to update the advanced select control from html and ajax - if (typeof 'period_select_module_interval_update' == 'function') { - period_select_module_interval_update(data["module_interval"]); - } - else { - period_select_update('module_interval', data["module_interval"]); - } - $("#text-tcp_port").attr ("value", data["tcp_port"]); - $("#textarea_tcp_send") - .attr ("value", js_html_entity_decode (data["tcp_send"])); - $("#textarea_tcp_rcv") - .attr ("value", js_html_entity_decode (data["tcp_rcv"])); - $("#textarea_tcp_send") - .html (js_html_entity_decode (data["tcp_send"])); - $("#textarea_tcp_rcv") - .html (js_html_entity_decode (data["tcp_rcv"])); - $("#text-snmp_community") - .attr ("value", js_html_entity_decode (data["snmp_community"])); - $("#text-snmp_oid") - .val( js_html_entity_decode (data["snmp_oid"])); - $("#oid, img#edit_oid").hide (); - $("#id_module_group").val (data["id_module_group"]); - $("#max_timeout").attr ("value", data["max_timeout"]); - $("#max_retries").attr ("value", data["max_retries"]); - if (data["id_plugin"] != undefined) { - $("#id_plugin").val(data["id_plugin"]); - } - //$("#id_plugin").trigger('change'); - $("#text-plugin_user").attr ("value", js_html_entity_decode (data["plugin_user"])); - $("#password-plugin_pass").attr ("value", js_html_entity_decode (data["plugin_pass"])); - $("#text-plugin_parameter").attr ("value", js_html_entity_decode (data["plugin_parameter"])); - if (data["history_data"]) - $("#checkbox-history_data").check (); - else - $("#checkbox-history_data").uncheck (); + $("#local_component_group").change(function() { + var $select = $("#local_component").hide(); + $("#component").hide(); + if (this.value == 0) { + reset_data_module_form(); + return; + } + $("#component_loading").show(); + $(".error, #no_component").hide(); + $("option[value!=0]", $select).remove(); + jQuery.post( + "ajax.php", + { + page: "godmode/agentes/module_manager_editor", + get_module_local_components: 1, + id_module_component_group: this.value, + id_module_component_type: $("#hidden-id_module_component_type").attr( + "value" + ) + }, + function(data, status) { + if (data == false) { + $("#component_loading").hide(); + $("#no_component").show(); + return; + } + jQuery.each(data, function(i, val) { + option = $("") + .attr("value", val["id"]) + .append(val["name"]); + $select.append(option); + }); + $("#component_loading").hide(); + $select.show(); + $("#component").show(); + }, + "json" + ); + }); - $("#dynamic_interval_select").val (data["dynamic_interval"]); - $("#text-dynamic_max").attr ("value", (data["dynamic_max"] == 0) ? 0 : data["dynamic_max"]); - $("#text-dynamic_min").attr ("value", (data["dynamic_min"] == 0) ? 0 : data["dynamic_min"]); - - if (data["dynamic_two_tailed"]) - $("#checkbox-dynamic_two_tailed").check (); - else - $("#checkbox-dynamic_two_tailed").uncheck (); - - $("#text-min_warning").attr ("value", (data["min_warning"] == 0) ? 0 : data["min_warning"]); - $("#text-max_warning").attr ("value", (data["max_warning"] == 0) ? 0 : data["max_warning"]); - $("#text-str_warning").attr ("value", data["str_warning"]); - $("#text-min_critical").attr ("value", (data["min_critical"] == 0) ? 0 : data["min_critical"]); - $("#text-max_critical").attr ("value", (data["max_critical"] == 0) ? 0 : data["max_critical"]); - $("#text-str_critical").attr ("value", data["str_critical"]); - $("#text-ff_event").attr ("value", (data["min_ff_event"] == 0) ? 0 : data["min_ff_event"]); - $("input[name=each_ff][value=" + data["each_ff"] + "]").prop('checked', true); - $("#text-ff_event_normal").attr ("value", (data["min_ff_event_normal"] == 0) ? 0 : data["min_ff_event_normal"]); - $("#text-ff_event_warning").attr ("value", (data["min_ff_event_warning"] == 0) ? 0 : data["min_ff_event_warning"]); - $("#text-ff_event_critical").attr ("value", (data["min_ff_event_critical"] == 0) ? 0 : data["min_ff_event_critical"]); - $("#text-post_process").attr("value", (data["post_process"] == 0) ? 0 : data["post_process"]); - $("#text-unit").attr("value", (data["unit"] == '') ? '' : data["unit"]); - $("#checkbox-critical_inverse").prop ("checked", data["critical_inverse"]); - $("#checkbox-warning_inverse").prop ("checked", data["warning_inverse"]); - $("#component_loading").hide (); - $("#id_module_type").change (); - if ($("#id_category").is("select")) { - $("#id_category").val (data["id_category"]); - } - else { - $("#hidden-id_category").val(data["id_category"]); - } - - var tags = data["tags"]; - - // Reset the selection of tags (put all of them into available box) - $("#id_tag_selected option").each(function() { - if ($(this).attr('value') != '') { - $("#id_tag_selected").find("option[value='" + $(this).attr('value') + "']").remove(); - $("select[name='id_tag_available[]']").append($("").val($(this).attr('value')).html($(this).text())); - } - }); - if ($("#id_tag_available option").length > 1) { - $("#id_tag_available").find("option[value='']").remove(); - } - if ($("#id_tag_selected option").length == 0) { - $("select[name='id_tag_selected[]']").append($("").val('').html('None')); - } - - if (tags != '') { - tags = tags.split(','); - - // Fill the selected tags box with select ones - for (i = 0; i < tags.length; i++){ - $("#id_tag_available option").each(function(){ - if (tags[i] == $(this).text()) { - $("#id_tag_available").find("option[value='" + $(this).attr('value') + "']").remove(); - $("select[name='id_tag_selected[]']").append($("").val($(this).attr('value')).html($(this).text())); - $("#id_tag_selected").find("option[value='']").remove(); - } - }); - - if ($("#id_tag_available option").length == 0) { - $("select[name='id_tag_available[]']").append($("").val('').html('None')); - } - } - } - - // Delete macro fields - $('.macro_field').remove(); - $('#hidden-macros').val(''); - - - // If exist macros, load the fields - if (data["macros"] != '' && data["macros"] != null) { - $('#hidden-macros').val(Base64.encode(data["macros"])); - - var obj = jQuery.parseJSON(data["macros"]); - $.each(obj, function(k,macro) { - add_macro_field(macro, 'simple-macro'); - }); - } - - if (data["type"] >= 15 && data["type"] <= 18) { - $("#snmp_version").val(data["tcp_send"]); - $("#text-snmp3_auth_user").val(data["plugin_user"]); - $("#password-snmp3_auth_pass").val(data["plugin_pass"]); - $("#snmp3_auth_method").val(data["plugin_parameter"]); - $("#snmp3_privacy_method").val(data["custom_string_1"]); - $("#password-snmp3_privacy_pass").val(data["custom_string_2"]); - $("#snmp3_security_level").val(data["custom_string_3"]); - - if (data["tcp_send"] == "3") { - $("#simple-field_snmpv3_row1").attr("style", ""); - $("#simple-field_snmpv3_row2").attr("style", ""); - $("#simple-field_snmpv3_row3").attr("style", ""); - $("input[name=active_snmp_v3]").val(1); - } - } - - if (data["throw_unknown_events"]) - $("input[name='throw_unknown_events']").check(); - else - $("input[name='throw_unknown_events']").uncheck(); - - if (data["id_plugin"] != undefined) { - $("#id_plugin").trigger("change"); - } - }, - "json" - ); - }); - - $("img#edit_oid").click (function () { - $("#oid").hide (); - $("#text-snmp_oid").show () - .attr ("value", $("#select_snmp_oid").fieldValue ()); - $(this).hide (); - }); - - $("form#module_form").submit (function () { - if ($("#text-name").val () == "") { - $("#text-name").focus (); - $("#message").showMessage (no_name_lang); - return false; - } - - if ($("#id_plugin").attr ("value") == 0) { - $("#id_plugin").focus (); - $("#message").showMessage (no_plugin_lang); - return false; - } - - moduletype = $("#hidden-moduletype").val (); - if (moduletype == 5) { - if ($("#prediction_module").val () == null) { - $("#prediction_module").focus (); - $("#message").showMessage (no_prediction_module_lang); - return false; - } - } + function reset_data_module_form() { + // Delete macro fields + $(".macro_field").remove(); - moduletype = $("#hidden-id_module_type").val (); - if (moduletype == 25) { - if ($("#custom_integer_1").val () == 0) { - $("#custom_integer_1").focus (); - $("#message").showMessage (no_execute_test_from); - return false; - } - } - module = $("#id_module_type").attr ("value"); - - if (id_modules_icmp.in_array (module) || id_modules_tcp.in_array (module) || id_modules_snmp.in_array (module)) { - /* Network module */ - if ($("#text-ip_target").val () == "") { - $("#text-ip_target").focus (); - $("#message").showMessage (no_target_lang); - return false; - } - } - - if (id_modules_snmp.in_array (module)) { - if ($("#text-snmp_oid").attr ("value") == "") { - if ($("#select_snmp_oid").attr ("value") == "") { - $("#message").showMessage (no_oid_lang); - return false; - } - } - } - - $("#message").hide (); - return true; - }); - - if (typeof $("#prediction_id_group").pandoraSelectGroupAgent == 'function') { - $("#prediction_id_group").pandoraSelectGroupAgent ({ - agentSelect: "select#prediction_id_agent", - callbackBefore: function () { - $("#module_loading").show (); - $("#prediction_module option").remove (); - return true; - }, - callbackAfter: function (e) { - if ($("#prediction_id_agent").children ().length == 0) { - $("#module_loading").hide (); - return; - } - $("#prediction_id_agent").change (); - } - }); - } - - if (typeof $("#prediction_id_agent").pandoraSelectAgentModule == 'function') { - $("#prediction_id_agent").pandoraSelectAgentModule ({ - moduleSelect: "select#prediction_module" - }); - } + // Hide show/hide configuration data switch + $("#simple-show_configuration_data").hide(); + $("#simple-hide_configuration_data").hide(); + $("#configuration_data_legend").hide(); + + $("#textarea_configuration_data").val(""); + $("#simple-configuration_data").show(); + + $("#text-name").val(""); + $("#textarea_description").val(""); + $("#checkbox-history_data").check(); + $("#text-max").attr("value", ""); + $("#text-min").attr("value", ""); + $("#dynamic_interval_select").attr("value", 0); + $("#text-dynamic_min").attr("value", 0); + $("#text-dynamic_max").attr("value", 0); + $("#checkbox-dynamic_two_tailed").attr("value", 0); + $("#text-min_warning").attr("value", 0); + $("#text-max_warning").attr("value", 0); + $("#text-str_warning").attr("value", ""); + $("#text-min_critical").attr("value", 0); + $("#text-max_critical").attr("value", 0); + $("#text-str_critical").attr("value", ""); + $("#text-ff_event").attr("value", 0); + $("#text-post_process").attr("value", 0); + $("#text-unit").attr("value", ""); + $("#checkbox-critical_inverse").attr("value", 0); + $("#checkbox-warning_inverse").attr("value", 0); + $("#textarea_critical_instructions").attr("value", ""); + $("#textarea_warning_instructions").attr("value", ""); + $("#textarea_unknown_instructions").attr("value", ""); + } + + $("#local_component").change(function() { + if (this.value == 0) { + reset_data_module_form(); + return; + } + $("#component_loading").show(); + $(".error").hide(); + jQuery.post( + "ajax.php", + { + page: "godmode/agentes/module_manager_editor", + get_module_local_component: 1, + id_module_component: this.value + }, + function(data, status) { + configuration_data = js_html_entity_decode(data["data"]); + $("#text-name").attr("value", js_html_entity_decode(data["name"])); + $("#textarea_description").attr( + "value", + js_html_entity_decode(data["description"]) + ); + $("#textarea_description").html( + js_html_entity_decode(data["description"]) + ); + $("#textarea_configuration_data").val(configuration_data); + $("#component_loading").hide(); + $("#id_module_type").val(data["type"]); + $("#text-max").attr("value", data["max"]); + $("#text-min").attr("value", data["min"]); + // Workaround to update the advanced select control from html and ajax + if (typeof "period_select_module_interval_update" == "function") { + period_select_module_interval_update(data["module_interval"]); + } else { + period_select_update("module_interval", data["module_interval"]); + } + + $("#id_module_group").val(data["id_module_group"]); + + if (data["history_data"]) $("#checkbox-history_data").check(); + else $("#checkbox-history_data").uncheck(); + + $("#dynamic_interval_select").val(data["dynamic_interval"]); + $("#text-dynamic_max").attr( + "value", + data["dynamic_max"] == 0 ? 0 : data["dynamic_max"] + ); + $("#text-dynamic_min").attr( + "value", + data["dynamic_min"] == 0 ? 0 : data["dynamic_min"] + ); + + if (data["dynamic_two_tailed"]) + $("#checkbox-dynamic_two_tailed").check(); + else $("#checkbox-dynamic_two_tailed").uncheck(); + + $("#text-min_warning").attr( + "value", + data["min_warning"] == 0 ? 0 : data["min_warning"] + ); + $("#text-max_warning").attr( + "value", + data["max_warning"] == 0 ? 0 : data["max_warning"] + ); + $("#text-str_warning").attr("value", data["str_warning"]); + $("#text-min_critical").attr( + "value", + data["min_critical"] == 0 ? 0 : data["min_critical"] + ); + $("#text-max_critical").attr( + "value", + data["max_critical"] == 0 ? 0 : data["max_critical"] + ); + $("#text-str_critical").attr("value", data["str_critical"]); + $("#text-ff_event").attr( + "value", + data["min_ff_event"] == 0 ? 0 : data["min_ff_event"] + ); + $("#text-post_process").attr( + "value", + data["post_process"] == 0 ? 0 : data["post_process"] + ); + $("#text-unit").attr("value", data["unit"] == "" ? "" : data["unit"]); + $("#checkbox-critical_inverse").prop( + "checked", + data["critical_inverse"] + ); + $("#checkbox-warning_inverse").prop("checked", data["warning_inverse"]); + $("#component_loading").hide(); + $("#id_module_type").change(); + if ($("#id_category").is("select")) { + $("#id_category").val(data["id_category"]); + } else { + $("#hidden-id_category").val(data["id_category"]); + } + + var tags = data["tags"]; + + // Reset the selection of tags (put all of them into available box) + $("#id_tag_selected option").each(function() { + if ($(this).attr("value") != "") { + $("#id_tag_selected") + .find("option[value='" + $(this).attr("value") + "']") + .remove(); + $("select[name='id_tag_available[]']").append( + $("") + .val($(this).attr("value")) + .html($(this).text()) + ); + } + }); + if ($("#id_tag_available option").length > 1) { + $("#id_tag_available") + .find("option[value='']") + .remove(); + } + if ($("#id_tag_selected option").length == 0) { + $("select[name='id_tag_selected[]']").append( + $("") + .val("") + .html("None") + ); + } + + if (tags != "") { + tags = tags.split(","); + + // Fill the selected tags box with select ones + for (i = 0; i < tags.length; i++) { + $("#id_tag_available option").each(function() { + if (tags[i] == $(this).text()) { + $("#id_tag_available") + .find("option[value='" + $(this).attr("value") + "']") + .remove(); + $("select[name='id_tag_selected[]']").append( + $("") + .val($(this).attr("value")) + .html($(this).text()) + ); + $("#id_tag_selected") + .find("option[value='']") + .remove(); + } + }); + + if ($("#id_tag_available option").length == 0) { + $("select[name='id_tag_available[]']").append( + $("") + .val("") + .html("None") + ); + } + } + } + + if (data["throw_unknown_events"]) + $("input[name='throw_unknown_events']").check(); + else $("input[name='throw_unknown_events']").uncheck(); + + // Delete macro fields + $(".macro_field").remove(); + + $("#hidden-macros").val(""); + + var legend = ""; + // If exist macros, load the fields + if (data["macros"] != "" && data["macros"] != null) { + $("#hidden-macros").val(Base64.encode(data["macros"])); + + var obj = jQuery.parseJSON(data["macros"]); + $.each(obj, function(k, macro) { + add_macro_field(macro, "simple-macro"); + legend += macro["macro"] + " = " + macro["desc"] + "
              "; + }); + $("#configuration_data_legend").html(legend); + + $("#simple-show_configuration_data").show(); + $("#simple-hide_configuration_data").hide(); + $("#configuration_data_legend").show(); + $("#simple-configuration_data").hide(); + } else { + $("#simple-show_configuration_data").hide(); + $("#simple-hide_configuration_data").hide(); + $("#configuration_data_legend").hide(); + $("#simple-configuration_data").show(); + } + }, + "json" + ); + }); + + network_component_group_change_event(); + + flag_load_plugin_component = false; + $("#network_component").change(function() { + if (this.value == 0) return; + $("#component_loading").show(); + $(".error").hide(); + + jQuery.post( + "ajax.php", + { + page: "godmode/agentes/module_manager_editor", + get_module_component: 1, + id_module_component: this.value + }, + function(data, status) { + flag_load_plugin_component = true; + + $("#text-name").attr("value", js_html_entity_decode(data["name"])); + $("#textarea_description").html( + js_html_entity_decode(data["description"]) + ); + $("#id_module_type").val(data["type"]); + $("#text-max").attr("value", data["max"]); + $("#text-min").attr("value", data["min"]); + // Workaround to update the advanced select control from html and ajax + if (typeof "period_select_module_interval_update" == "function") { + period_select_module_interval_update(data["module_interval"]); + } else { + period_select_update("module_interval", data["module_interval"]); + } + $("#text-tcp_port").attr("value", data["tcp_port"]); + $("#textarea_tcp_send").attr( + "value", + js_html_entity_decode(data["tcp_send"]) + ); + $("#textarea_tcp_rcv").attr( + "value", + js_html_entity_decode(data["tcp_rcv"]) + ); + $("#textarea_tcp_send").html(js_html_entity_decode(data["tcp_send"])); + $("#textarea_tcp_rcv").html(js_html_entity_decode(data["tcp_rcv"])); + $("#text-snmp_community").attr( + "value", + js_html_entity_decode(data["snmp_community"]) + ); + $("#text-snmp_oid").val(js_html_entity_decode(data["snmp_oid"])); + $("#oid, img#edit_oid").hide(); + $("#id_module_group").val(data["id_module_group"]); + $("#max_timeout").attr("value", data["max_timeout"]); + $("#max_retries").attr("value", data["max_retries"]); + if (data["id_plugin"] != undefined) { + $("#id_plugin").val(data["id_plugin"]); + } + //$("#id_plugin").trigger('change'); + $("#text-plugin_user").attr( + "value", + js_html_entity_decode(data["plugin_user"]) + ); + $("#password-plugin_pass").attr( + "value", + js_html_entity_decode(data["plugin_pass"]) + ); + $("#text-plugin_parameter").attr( + "value", + js_html_entity_decode(data["plugin_parameter"]) + ); + if (data["history_data"]) $("#checkbox-history_data").check(); + else $("#checkbox-history_data").uncheck(); + + $("#dynamic_interval_select").val(data["dynamic_interval"]); + $("#text-dynamic_max").attr( + "value", + data["dynamic_max"] == 0 ? 0 : data["dynamic_max"] + ); + $("#text-dynamic_min").attr( + "value", + data["dynamic_min"] == 0 ? 0 : data["dynamic_min"] + ); + + if (data["dynamic_two_tailed"]) + $("#checkbox-dynamic_two_tailed").check(); + else $("#checkbox-dynamic_two_tailed").uncheck(); + + $("#text-min_warning").attr( + "value", + data["min_warning"] == 0 ? 0 : data["min_warning"] + ); + $("#text-max_warning").attr( + "value", + data["max_warning"] == 0 ? 0 : data["max_warning"] + ); + $("#text-str_warning").attr("value", data["str_warning"]); + $("#text-min_critical").attr( + "value", + data["min_critical"] == 0 ? 0 : data["min_critical"] + ); + $("#text-max_critical").attr( + "value", + data["max_critical"] == 0 ? 0 : data["max_critical"] + ); + $("#text-str_critical").attr("value", data["str_critical"]); + $("#text-ff_event").attr( + "value", + data["min_ff_event"] == 0 ? 0 : data["min_ff_event"] + ); + $("input[name=each_ff][value=" + data["each_ff"] + "]").prop( + "checked", + true + ); + $("#text-ff_event_normal").attr( + "value", + data["min_ff_event_normal"] == 0 ? 0 : data["min_ff_event_normal"] + ); + $("#text-ff_event_warning").attr( + "value", + data["min_ff_event_warning"] == 0 ? 0 : data["min_ff_event_warning"] + ); + $("#text-ff_event_critical").attr( + "value", + data["min_ff_event_critical"] == 0 ? 0 : data["min_ff_event_critical"] + ); + + // Shows manual input if post_process field is setted + if (data["post_process"] != 0) { + $("#post_process_manual").show(); + $("#post_process_default").hide(); + } + + $("#text-post_process_text").attr( + "value", + data["post_process"] == 0 ? 0 : data["post_process"] + ); + + // Shows manual input if unit field is setted + if (data["unit"] != "") { + $("#unit_manual").show(); + $("#unit_default").hide(); + } + + $("#text-unit_text").attr( + "value", + data["unit"] == "" ? "" : data["unit"] + ); + + $("#checkbox-critical_inverse").prop( + "checked", + data["critical_inverse"] + ); + $("#checkbox-warning_inverse").prop("checked", data["warning_inverse"]); + $("#component_loading").hide(); + $("#id_module_type").change(); + if ($("#id_category").is("select")) { + $("#id_category").val(data["id_category"]); + } else { + $("#hidden-id_category").val(data["id_category"]); + } + + var tags = data["tags"]; + + // Reset the selection of tags (put all of them into available box) + $("#id_tag_selected option").each(function() { + if ($(this).attr("value") != "") { + $("#id_tag_selected") + .find("option[value='" + $(this).attr("value") + "']") + .remove(); + $("select[name='id_tag_available[]']").append( + $("") + .val($(this).attr("value")) + .html($(this).text()) + ); + } + }); + if ($("#id_tag_available option").length > 1) { + $("#id_tag_available") + .find("option[value='']") + .remove(); + } + if ($("#id_tag_selected option").length == 0) { + $("select[name='id_tag_selected[]']").append( + $("") + .val("") + .html("None") + ); + } + + if (tags != "") { + tags = tags.split(","); + + // Fill the selected tags box with select ones + for (i = 0; i < tags.length; i++) { + $("#id_tag_available option").each(function() { + if (tags[i] == $(this).text()) { + $("#id_tag_available") + .find("option[value='" + $(this).attr("value") + "']") + .remove(); + $("select[name='id_tag_selected[]']").append( + $("") + .val($(this).attr("value")) + .html($(this).text()) + ); + $("#id_tag_selected") + .find("option[value='']") + .remove(); + } + }); + + if ($("#id_tag_available option").length == 0) { + $("select[name='id_tag_available[]']").append( + $("") + .val("") + .html("None") + ); + } + } + } + + // Delete macro fields + $(".macro_field").remove(); + $("#hidden-macros").val(""); + + // If exist macros, load the fields + if (data["macros"] != "" && data["macros"] != null) { + $("#hidden-macros").val(Base64.encode(data["macros"])); + + var obj = jQuery.parseJSON(data["macros"]); + $.each(obj, function(k, macro) { + add_macro_field(macro, "simple-macro"); + }); + } + + if (data["type"] >= 15 && data["type"] <= 18) { + $("#snmp_version").val(data["tcp_send"]); + $("#text-snmp3_auth_user").val(data["plugin_user"]); + $("#password-snmp3_auth_pass").val(data["plugin_pass"]); + $("#snmp3_auth_method").val(data["plugin_parameter"]); + $("#snmp3_privacy_method").val(data["custom_string_1"]); + $("#password-snmp3_privacy_pass").val(data["custom_string_2"]); + $("#snmp3_security_level").val(data["custom_string_3"]); + + if (data["tcp_send"] == "3") { + $("#simple-field_snmpv3_row1").attr("style", ""); + $("#simple-field_snmpv3_row2").attr("style", ""); + $("#simple-field_snmpv3_row3").attr("style", ""); + $("input[name=active_snmp_v3]").val(1); + } + } + + if (data["throw_unknown_events"]) + $("input[name='throw_unknown_events']").check(); + else $("input[name='throw_unknown_events']").uncheck(); + + if (data["id_plugin"] != undefined) { + $("#id_plugin").trigger("change"); + } + }, + "json" + ); + }); + + $("img#edit_oid").click(function() { + $("#oid").hide(); + $("#text-snmp_oid") + .show() + .attr("value", $("#select_snmp_oid").fieldValue()); + $(this).hide(); + }); + + $("form#module_form").submit(function() { + if ($("#text-name").val() == "") { + $("#text-name").focus(); + $("#message").showMessage(no_name_lang); + return false; + } + + if ($("#id_plugin").attr("value") == 0) { + $("#id_plugin").focus(); + $("#message").showMessage(no_plugin_lang); + return false; + } + + moduletype = $("#hidden-moduletype").val(); + if (moduletype == 5) { + if ($("#prediction_module").val() == null) { + $("#prediction_module").focus(); + $("#message").showMessage(no_prediction_module_lang); + return false; + } + } + + moduletype = $("#hidden-id_module_type").val(); + if (moduletype == 25) { + if ($("#custom_integer_1").val() == 0) { + $("#custom_integer_1").focus(); + $("#message").showMessage(no_execute_test_from); + return false; + } + } + module = $("#id_module_type").attr("value"); + + if ( + id_modules_icmp.in_array(module) || + id_modules_tcp.in_array(module) || + id_modules_snmp.in_array(module) + ) { + /* Network module */ + if ($("#text-ip_target").val() == "") { + $("#text-ip_target").focus(); + $("#message").showMessage(no_target_lang); + return false; + } + } + + if (id_modules_snmp.in_array(module)) { + if ($("#text-snmp_oid").attr("value") == "") { + if ($("#select_snmp_oid").attr("value") == "") { + $("#message").showMessage(no_oid_lang); + return false; + } + } + } + + $("#message").hide(); + return true; + }); + + if (typeof $("#prediction_id_group").pandoraSelectGroupAgent == "function") { + $("#prediction_id_group").pandoraSelectGroupAgent({ + agentSelect: "select#prediction_id_agent", + callbackBefore: function() { + $("#module_loading").show(); + $("#prediction_module option").remove(); + return true; + }, + callbackAfter: function(e) { + if ($("#prediction_id_agent").children().length == 0) { + $("#module_loading").hide(); + return; + } + $("#prediction_id_agent").change(); + } + }); + } + + if (typeof $("#prediction_id_agent").pandoraSelectAgentModule == "function") { + $("#prediction_id_agent").pandoraSelectAgentModule({ + moduleSelect: "select#prediction_module" + }); + } } - // Functions to add and remove dynamic fields for macros function delete_macro_form(prefix) { - var next_number = parseInt($('#next_macro').html()); - // Is not possible delete first macro - if (next_number == 3) { - $('#delete_macro_button').hide(); - } - var next_row = parseInt($('#next_row').html()); - $('#next_macro').html(next_number-1); - $('#next_row').html(next_row-3); - - var nrow1 = next_row - 3; - var nrow2 = next_row - 2; - var nrow3 = next_row - 1; - - var $row1 = $('#'+prefix+nrow1).remove(); - var $row2 = $('#'+prefix+nrow2).remove(); - var $row3 = $('#'+prefix+nrow3).remove(); + var next_number = parseInt($("#next_macro").html()); + // Is not possible delete first macro + if (next_number == 3) { + $("#delete_macro_button").hide(); + } + var next_row = parseInt($("#next_row").html()); + $("#next_macro").html(next_number - 1); + $("#next_row").html(next_row - 3); + + var nrow1 = next_row - 3; + var nrow2 = next_row - 2; + var nrow3 = next_row - 1; + + var $row1 = $("#" + prefix + nrow1).remove(); + var $row2 = $("#" + prefix + nrow2).remove(); + var $row3 = $("#" + prefix + nrow3).remove(); } // The callback parameter is for a callback function // that will receive the 3 rows (function(row1, row2, row3)) // to edit them before the new_macro function ends. function new_macro(prefix, callback) { - $('#delete_macro_button').show(); - - var next_row = parseInt($('#next_row').html()); - - $('#next_row').html(next_row + 3); - var nrow1 = next_row - 3; - var nrow2 = next_row - 2; - var nrow3 = next_row - 1; - var nrow4 = next_row; - var nrow5 = next_row + 1; - var nrow6 = next_row + 2; - - var next_number = parseInt($('#next_macro').html()); - $('#next_macro').html(next_number + 1); - var current_number = next_number - 1; - - // Clone two last rows - var $row1 = $('#' + prefix + nrow1).clone(true); - var $row2 = $('#' + prefix + nrow2).clone(true); - var $row3 = $('#' + prefix + nrow3).clone(true); - - // Change the tr ID - $row1.attr('id',prefix + (nrow4)); - $row2.attr('id',prefix + (nrow5)); - $row3.attr('id',prefix + (nrow6)); - // Change the td ID - $row1.find('td').attr('id', changeTdId); - $row2.find('td').attr('id', changeTdId); - $row3.find('td').attr('id', changeTdId); - - // Insert after last field - $row3.insertAfter('#' + prefix + nrow3); - $row2.insertAfter('#' + prefix + nrow3); - $row1.insertAfter('#' + prefix + nrow3); - - // Change labels - for(i = 0; i <= 3; i++) { - var label1 = $("#" + prefix + nrow4 + "-" + i).html(); - var exp_reg = new RegExp('field' + current_number, 'g'); - label1 = label1.replace(exp_reg,'field' + next_number); - $("#" + prefix + nrow4 + "-" + i).html(label1); - } - - for(i = 0; i <= 1; i++) { - var label2 = $("#" + prefix + nrow5 + "-" + i).html(); - var exp_reg = new RegExp('field' + current_number, 'g'); - label2 = label2.replace(exp_reg,'field' + next_number); - $("#" + prefix + nrow5 + "-" + i).html(label2); - } - - for(i = 0; i <= 1; i++) { - var label3 = $("#" + prefix + nrow6 + "-" + i).html(); - var exp_reg = new RegExp('field' + current_number, 'g'); - label3 = label3.replace(exp_reg,'field' + next_number); - $("#" + prefix + nrow6 + "-" + i).html(label3); - } - - // Empty the text inputs - $('#text-field' + next_number + '_desc').val(''); - $('#text-field' + next_number + '_help').val(''); - $('#text-field' + next_number + '_value').val(''); - $('#radio-field' + next_number + '_hide').val(0); - - if (typeof callback === 'function') - callback($row1, $row2, $row3); - - function changeTdId() { - switch(this.id) { - case prefix + (nrow1) + '-0': - return prefix + (nrow4) + '-0'; - break; - case prefix + (nrow1) + '-1': - return prefix + (nrow4) + '-1'; - break; - case prefix + (nrow1) + '-2': - return prefix + (nrow4) + '-2'; - break; - case prefix + (nrow1) + '-3': - return prefix + (nrow4) + '-3'; - break; - case prefix + (nrow2) + '-0': - return prefix + (nrow5) + '-0'; - break; - case prefix + (nrow2) + '-1': - return prefix + (nrow5) + '-1'; - break; - case prefix + (nrow2) + '-2': - return prefix + (nrow5) + '-2'; - break; - case prefix + (nrow2) + '-3': - return prefix + (nrow5) + '-3'; - break; - case prefix + (nrow3) + '-0': - return prefix + (nrow6) + '-0'; - break; - case prefix + (nrow3) + '-1': - return prefix + (nrow6) + '-1'; - break; - case prefix + (nrow3) + '-2': - return prefix + (nrow6) + '-2'; - break; - case prefix + (nrow3) + '-3': - return prefix + (nrow6) + '-3'; - break; - } - } + $("#delete_macro_button").show(); + + var next_row = parseInt($("#next_row").html()); + + $("#next_row").html(next_row + 3); + var nrow1 = next_row - 3; + var nrow2 = next_row - 2; + var nrow3 = next_row - 1; + var nrow4 = next_row; + var nrow5 = next_row + 1; + var nrow6 = next_row + 2; + + var next_number = parseInt($("#next_macro").html()); + $("#next_macro").html(next_number + 1); + var current_number = next_number - 1; + + // Clone two last rows + var $row1 = $("#" + prefix + nrow1).clone(true); + var $row2 = $("#" + prefix + nrow2).clone(true); + var $row3 = $("#" + prefix + nrow3).clone(true); + + // Change the tr ID + $row1.attr("id", prefix + nrow4); + $row2.attr("id", prefix + nrow5); + $row3.attr("id", prefix + nrow6); + // Change the td ID + $row1.find("td").attr("id", changeTdId); + $row2.find("td").attr("id", changeTdId); + $row3.find("td").attr("id", changeTdId); + + // Insert after last field + $row3.insertAfter("#" + prefix + nrow3); + $row2.insertAfter("#" + prefix + nrow3); + $row1.insertAfter("#" + prefix + nrow3); + + // Change labels + for (i = 0; i <= 3; i++) { + var label1 = $("#" + prefix + nrow4 + "-" + i).html(); + var exp_reg = new RegExp("field" + current_number, "g"); + label1 = label1.replace(exp_reg, "field" + next_number); + $("#" + prefix + nrow4 + "-" + i).html(label1); + } + + for (i = 0; i <= 1; i++) { + var label2 = $("#" + prefix + nrow5 + "-" + i).html(); + var exp_reg = new RegExp("field" + current_number, "g"); + label2 = label2.replace(exp_reg, "field" + next_number); + $("#" + prefix + nrow5 + "-" + i).html(label2); + } + + for (i = 0; i <= 1; i++) { + var label3 = $("#" + prefix + nrow6 + "-" + i).html(); + var exp_reg = new RegExp("field" + current_number, "g"); + label3 = label3.replace(exp_reg, "field" + next_number); + $("#" + prefix + nrow6 + "-" + i).html(label3); + } + + // Empty the text inputs + $("#text-field" + next_number + "_desc").val(""); + $("#text-field" + next_number + "_help").val(""); + $("#text-field" + next_number + "_value").val(""); + $("#radio-field" + next_number + "_hide").val(0); + + if (typeof callback === "function") callback($row1, $row2, $row3); + + function changeTdId() { + switch (this.id) { + case prefix + nrow1 + "-0": + return prefix + nrow4 + "-0"; + break; + case prefix + nrow1 + "-1": + return prefix + nrow4 + "-1"; + break; + case prefix + nrow1 + "-2": + return prefix + nrow4 + "-2"; + break; + case prefix + nrow1 + "-3": + return prefix + nrow4 + "-3"; + break; + case prefix + nrow2 + "-0": + return prefix + nrow5 + "-0"; + break; + case prefix + nrow2 + "-1": + return prefix + nrow5 + "-1"; + break; + case prefix + nrow2 + "-2": + return prefix + nrow5 + "-2"; + break; + case prefix + nrow2 + "-3": + return prefix + nrow5 + "-3"; + break; + case prefix + nrow3 + "-0": + return prefix + nrow6 + "-0"; + break; + case prefix + nrow3 + "-1": + return prefix + nrow6 + "-1"; + break; + case prefix + nrow3 + "-2": + return prefix + nrow6 + "-2"; + break; + case prefix + nrow3 + "-3": + return prefix + nrow6 + "-3"; + break; + } + } } function add_macro_field(macro, row_model_id) { - var macro_desc = macro['desc']; - // Change the carriage returns by html returns
              in help - var macro_help = macro['help'].replace(/ /g, "
              "); - var macro_macro = macro['macro']; - var macro_value = $('
              ').html(macro['value']).text(); - var macro_hide = macro['hide']; - - macro_value.type = 'password'; - - var row_id = row_model_id + macro_macro; - - var $macro_field = $('#'+ row_model_id +'_field').clone(true); - - // Change attributes to be unique and with identificable class - $macro_field.attr('id', row_id); - $macro_field.attr('class', 'macro_field'); - - // Get the number of fields already printed - var fields = $('.macro_field').length; - - // If is the first, we insert it after model row - if (fields == 0) { - $macro_field.insertAfter('#'+ row_model_id +'_field'); - } - // If there are more fields, we insert it after the last one - else { - $macro_field.insertAfter('#'+ $('.macro_field').eq(fields-1).attr('id')); - } - - // Change the label - if (macro_help == '') { - $('#'+row_id).children().eq(0).html(macro_desc); - } - else { - var field_desc = $('#'+row_id).children().eq(0).html(); - - field_desc = field_desc.replace('macro_desc',macro_desc); - field_desc = field_desc.replace('macro_help',macro_help); - - $('#'+row_id).children().eq(0).html(field_desc); - } - - // Change the text box id and value - $('#'+row_id).children().eq(1).children().attr('id','text-'+macro_macro); - $('#'+row_id).children().eq(1).children().attr('name',macro_macro); - - macro_field_hide = false; - if (typeof(macro['hide']) == "string") { - if (macro['hide'].length == 0) { - macro_field_hide = false; - } - else { - if (parseInt(macro['hide'])) { - macro_field_hide = true; - } - else { - macro_field_hide = false; - } - } - } - - if (macro_field_hide) { - $('#'+row_id).children().eq(1).children().attr('type','password'); - } - $('#'+row_id).children().eq(1).children().val(macro_value); - - - $('#'+row_id).show(); + var macro_desc = macro["desc"]; + // Change the carriage returns by html returns
              in help + var macro_help = macro["help"].replace(/ /g, "
              "); + var macro_macro = macro["macro"]; + var macro_value = $("
              ") + .html(macro["value"]) + .text(); + var macro_hide = macro["hide"]; + + macro_value.type = "password"; + + var row_id = row_model_id + macro_macro; + + var $macro_field = $("#" + row_model_id + "_field").clone(true); + + // Change attributes to be unique and with identificable class + $macro_field.attr("id", row_id); + $macro_field.attr("class", "macro_field"); + + // Get the number of fields already printed + var fields = $(".macro_field").length; + + // If is the first, we insert it after model row + if (fields == 0) { + $macro_field.insertAfter("#" + row_model_id + "_field"); + } + // If there are more fields, we insert it after the last one + else { + $macro_field.insertAfter( + "#" + + $(".macro_field") + .eq(fields - 1) + .attr("id") + ); + } + + // Change the label + if (macro_help == "") { + $("#" + row_id) + .children() + .eq(0) + .html(macro_desc); + } else { + var field_desc = $("#" + row_id) + .children() + .eq(0) + .html(); + + field_desc = field_desc.replace("macro_desc", macro_desc); + field_desc = field_desc.replace("macro_help", macro_help); + + $("#" + row_id) + .children() + .eq(0) + .html(field_desc); + } + + // Change the text box id and value + $("#" + row_id) + .children() + .eq(1) + .children() + .attr("id", "text-" + macro_macro); + $("#" + row_id) + .children() + .eq(1) + .children() + .attr("name", macro_macro); + + macro_field_hide = false; + if (typeof macro["hide"] == "string") { + if (macro["hide"].length == 0) { + macro_field_hide = false; + } else { + if (parseInt(macro["hide"])) { + macro_field_hide = true; + } else { + macro_field_hide = false; + } + } + } + + if (macro_field_hide) { + $("#" + row_id) + .children() + .eq(1) + .children() + .attr("type", "password"); + } + $("#" + row_id) + .children() + .eq(1) + .children() + .val(macro_value); + + $("#" + row_id).show(); } function load_plugin_macros_fields(row_model_id) { - // Get plugin macros when selected and load macros fields - var id_plugin = $('#id_plugin').val(); - - var params = []; - params.push("page=include/ajax/module"); - params.push("get_plugin_macros=1"); - params.push("id_plugin=" + id_plugin); - - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: action = get_php_value('absolute_homeurl') + "ajax.php", - dataType: 'json', - success: function (data) { - // Delete all the macro fields - $('.macro_field').remove(); - - if (data['array'] != null) { - $('#hidden-macros').val(data['base64']); - jQuery.each (data['array'], function (i, macro) { - if (macro['desc'] != '') { - add_macro_field(macro, row_model_id); - } - }); - //Plugin text can be larger - $(".macro_field").find(":input").attr("maxlength", 1023); - // Add again the hover event to the 'force_callback' elements - forced_title_callback(); - } - } - }); + // Get plugin macros when selected and load macros fields + var id_plugin = $("#id_plugin").val(); + + var params = []; + params.push("page=include/ajax/module"); + params.push("get_plugin_macros=1"); + params.push("id_plugin=" + id_plugin); + + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: (action = get_php_value("absolute_homeurl") + "ajax.php"), + dataType: "json", + success: function(data) { + // Delete all the macro fields + $(".macro_field").remove(); + + if (data["array"] != null) { + $("#hidden-macros").val(data["base64"]); + jQuery.each(data["array"], function(i, macro) { + if (macro["desc"] != "") { + add_macro_field(macro, row_model_id); + } + }); + //Plugin text can be larger + $(".macro_field") + .find(":input") + .attr("maxlength", 1023); + // Add again the hover event to the 'force_callback' elements + forced_title_callback(); + } + } + }); } function load_plugin_description(id_plugin) { - jQuery.post ("ajax.php", - { - "page" : "godmode/servers/plugin", - "get_plugin_description" : 1, - "id_plugin" : id_plugin - }, - function (data, status) { - $("#plugin_description").html(data); - } - ); + jQuery.post( + "ajax.php", + { + page: "godmode/servers/plugin", + get_plugin_description: 1, + id_plugin: id_plugin + }, + function(data, status) { + $("#plugin_description").html(data); + } + ); } // Show the modal window of a module function show_module_detail_dialog(module_id, id_agente) { - - $.ajax({ - type: "POST", - url: "", - data: "page=include/ajax/module&get_module_detail=1&id_agente="+id_agente+"&id_module=" + module_id, - dataType: "json", - success: function(data){ - $("#module_details_window").hide () - .empty () - .append (data) - .dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: "black" - }, - width: 620, - height: 500 - }) - .show (); - } - }); + $.ajax({ + type: "POST", + url: "", + data: + "page=include/ajax/module&get_module_detail=1&id_agente=" + + id_agente + + "&id_module=" + + module_id, + dataType: "json", + success: function(data) { + $("#module_details_window") + .hide() + .empty() + .append(data) + .dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 620, + height: 500 + }) + .show(); + } + }); } function network_component_group_change_event() { - $("#network_component_group").change (function () { - var $select = $("#network_component").hide (); - $("#component").hide (); - if (this.value == 0) - return; - $("#component_loading").show (); - $(".error, #no_component").hide (); - $("option[value!=0]", $select).remove (); - jQuery.post ("ajax.php", - {"page" : "godmode/agentes/module_manager_editor", - "get_module_components" : 1, - "id_module_component_group" : this.value, - "id_module_component_type" : $("#hidden-id_module_component_type").attr ("value") - }, - function (data, status) { - if (data == false) { - $("#component_loading").hide (); - $("#no_component").show (); - return; - } - jQuery.each (data, function (i, val) { - option = $("") - .attr ("value", val['id_nc']) - .append (val['name']); - $select.append (option); - }); - $("#component_loading").hide (); - $select.show (); - $("#component").show (); - }, - "json" - ); - }); + $("#network_component_group").change(function() { + var $select = $("#network_component").hide(); + $("#component").hide(); + if (this.value == 0) return; + $("#component_loading").show(); + $(".error, #no_component").hide(); + $("option[value!=0]", $select).remove(); + jQuery.post( + "ajax.php", + { + page: "godmode/agentes/module_manager_editor", + get_module_components: 1, + id_module_component_group: this.value, + id_module_component_type: $("#hidden-id_module_component_type").attr( + "value" + ) + }, + function(data, status) { + if (data == false) { + $("#component_loading").hide(); + $("#no_component").show(); + return; + } + jQuery.each(data, function(i, val) { + option = $("") + .attr("value", val["id_nc"]) + .append(val["name"]); + $select.append(option); + }); + $("#component_loading").hide(); + $select.show(); + $("#component").show(); + }, + "json" + ); + }); } function new_macro_local_component(prefix) { - $('#delete_macro_button').show(); - - var next_row = parseInt($('#next_row').html()); - - $('#next_row').html(next_row + 2); - var nrow1 = next_row - 2; - var nrow2 = next_row - 1; - var nrow3 = next_row; - var nrow4 = next_row + 1; - - var next_number = parseInt($('#next_macro').html()); - $('#next_macro').html(next_number + 1); - var current_number = next_number - 1; - - // Clone two last rows - var $row1 = $('#' + prefix + nrow1).clone(true); - var $row2 = $('#' + prefix + nrow2).clone(true); - - // Change the tr ID - $row1.attr('id',prefix + (nrow3)); - $row2.attr('id',prefix + (nrow4)); - // Change the td ID - $row1.find('td').attr('id', changeTdId); - $row2.find('td').attr('id', changeTdId); - - // Insert after last field - $row2.insertAfter('#' + prefix + nrow2); - $row1.insertAfter('#' + prefix + nrow2); - - // Change labels - for(i = 0; i <= 3; i++) { - var label1 = $("#" + prefix + nrow3 + "-" + i).html(); - var exp_reg = new RegExp('field' + current_number, 'g'); - label1 = label1.replace(exp_reg,'field' + next_number); - $("#" + prefix + nrow3 + "-" + i).html(label1); - } - - for(i = 0; i <= 1; i++) { - var label2 = $("#" + prefix + nrow4 + "-" + i).html(); - var exp_reg = new RegExp('field' + current_number, 'g'); - label2 = label2.replace(exp_reg,'field' + next_number); - $("#" + prefix + nrow4 + "-" + i).html(label2); - } - - // Empty the text inputs - $('#text-field' + next_number + '_desc').val(''); - $('#text-field' + next_number + '_help').val(''); - $('#text-field' + next_number + '_value').val(''); - - function changeTdId() { - switch(this.id) { - case prefix + (nrow1) + '-0': - return prefix + (nrow3) + '-0'; - break; - case prefix + (nrow1) + '-1': - return prefix + (nrow3) + '-1'; - break; - case prefix + (nrow1) + '-2': - return prefix + (nrow3) + '-2'; - break; - case prefix + (nrow1) + '-3': - return prefix + (nrow3) + '-3'; - break; - case prefix + (nrow2) + '-0': - return prefix + (nrow4) + '-0'; - break; - case prefix + (nrow2) + '-1': - return prefix + (nrow4) + '-1'; - break; - case prefix + (nrow2) + '-2': - return prefix + (nrow4) + '-2'; - break; - case prefix + (nrow2) + '-3': - return prefix + (nrow4) + '-3'; - break; - } - } + $("#delete_macro_button").show(); + + var next_row = parseInt($("#next_row").html()); + + $("#next_row").html(next_row + 2); + var nrow1 = next_row - 2; + var nrow2 = next_row - 1; + var nrow3 = next_row; + var nrow4 = next_row + 1; + + var next_number = parseInt($("#next_macro").html()); + $("#next_macro").html(next_number + 1); + var current_number = next_number - 1; + + // Clone two last rows + var $row1 = $("#" + prefix + nrow1).clone(true); + var $row2 = $("#" + prefix + nrow2).clone(true); + + // Change the tr ID + $row1.attr("id", prefix + nrow3); + $row2.attr("id", prefix + nrow4); + // Change the td ID + $row1.find("td").attr("id", changeTdId); + $row2.find("td").attr("id", changeTdId); + + // Insert after last field + $row2.insertAfter("#" + prefix + nrow2); + $row1.insertAfter("#" + prefix + nrow2); + + // Change labels + for (i = 0; i <= 3; i++) { + var label1 = $("#" + prefix + nrow3 + "-" + i).html(); + var exp_reg = new RegExp("field" + current_number, "g"); + label1 = label1.replace(exp_reg, "field" + next_number); + $("#" + prefix + nrow3 + "-" + i).html(label1); + } + + for (i = 0; i <= 1; i++) { + var label2 = $("#" + prefix + nrow4 + "-" + i).html(); + var exp_reg = new RegExp("field" + current_number, "g"); + label2 = label2.replace(exp_reg, "field" + next_number); + $("#" + prefix + nrow4 + "-" + i).html(label2); + } + + // Empty the text inputs + $("#text-field" + next_number + "_desc").val(""); + $("#text-field" + next_number + "_help").val(""); + $("#text-field" + next_number + "_value").val(""); + + function changeTdId() { + switch (this.id) { + case prefix + nrow1 + "-0": + return prefix + nrow3 + "-0"; + break; + case prefix + nrow1 + "-1": + return prefix + nrow3 + "-1"; + break; + case prefix + nrow1 + "-2": + return prefix + nrow3 + "-2"; + break; + case prefix + nrow1 + "-3": + return prefix + nrow3 + "-3"; + break; + case prefix + nrow2 + "-0": + return prefix + nrow4 + "-0"; + break; + case prefix + nrow2 + "-1": + return prefix + nrow4 + "-1"; + break; + case prefix + nrow2 + "-2": + return prefix + nrow4 + "-2"; + break; + case prefix + nrow2 + "-3": + return prefix + nrow4 + "-3"; + break; + } + } } function delete_macro_local_component(prefix) { - var next_number = parseInt($('#next_macro').html()); - // Is not possible delete first macro - if (next_number == 3) { - $('#delete_macro_button').hide(); - } - var next_row = parseInt($('#next_row').html()); - $('#next_macro').html(next_number-1); - $('#next_row').html(next_row-2); - - var nrow1 = next_row - 2; - var nrow2 = next_row - 1; - - var $row1 = $('#'+prefix+nrow1).remove(); - var $row2 = $('#'+prefix+nrow2).remove(); + var next_number = parseInt($("#next_macro").html()); + // Is not possible delete first macro + if (next_number == 3) { + $("#delete_macro_button").hide(); + } + var next_row = parseInt($("#next_row").html()); + $("#next_macro").html(next_number - 1); + $("#next_row").html(next_row - 2); + + var nrow1 = next_row - 2; + var nrow2 = next_row - 1; + + var $row1 = $("#" + prefix + nrow1).remove(); + var $row2 = $("#" + prefix + nrow2).remove(); } //Add a new module macro -function add_macro () { - var macro_count = parseInt($("#hidden-module_macro_count").val()); - var delete_icon = ''; - - // Add inputs for the new macro - $("#module_macros").append('
              \ +function add_macro() { + var macro_count = parseInt($("#hidden-module_macro_count").val()); + var delete_icon = ''; + + // Add inputs for the new macro + $("#module_macros").append( + ' \ \ \ \ - '); - - // Update the macro count - $("#hidden-module_macro_count").val(macro_count + 1); + " + ); + + // Update the macro count + $("#hidden-module_macro_count").val(macro_count + 1); } // Delete an existing module macro -function delete_macro (num) { - if ($("#module_macros-" + num).length) { - $("#module_macros-" + num).remove(); - } - - // Do not decrease the macro counter or new macros may overlap existing ones! -} \ No newline at end of file +function delete_macro(num) { + if ($("#module_macros-" + num).length) { + $("#module_macros-" + num).remove(); + } + + // Do not decrease the macro counter or new macros may overlap existing ones! +} diff --git a/pandora_console/include/javascript/pandora_snmp_browser.js b/pandora_console/include/javascript/pandora_snmp_browser.js index 60f914c9e9..eb4cc80f2e 100644 --- a/pandora_console/include/javascript/pandora_snmp_browser.js +++ b/pandora_console/include/javascript/pandora_snmp_browser.js @@ -1,386 +1,417 @@ // Load the SNMP tree via AJAX -function snmpBrowse () { - - // Empty the SNMP tree - $("#snmp_browser").html(''); - - // Hide the data div - hideOIDData(); - - // Reset previous searches - $("#search_results").css('display', 'none'); - $("#hidden-search_count").val(-1); - - // Show the spinner - $("#spinner").css('display', ''); - - // Read the target IP and community - var target_ip = $('#text-target_ip').val(); - var community = $('#text-community').val(); - var starting_oid = $('#text-starting_oid').val(); - var snmp_version = $('#snmp_browser_version').val(); - var server_to_exec = $('#server_to_exec').val(); - var snmp3_auth_user = $('#text-snmp3_browser_auth_user').val(); - var snmp3_security_level = $('#snmp3_browser_security_level').val(); - var snmp3_auth_method = $('#snmp3_browser_auth_method').val(); - var snmp3_auth_pass = $('#password-snmp3_browser_auth_pass').val(); - var snmp3_privacy_method = $('#snmp3_browser_privacy_method').val(); - var snmp3_privacy_pass = $('#password-snmp3_browser_privacy_pass').val(); - var ajax_url = $('#hidden-ajax_url').val(); - - // Prepare the AJAX call - - var params = {}; - params["target_ip"] = target_ip; - params["community"] = community; - params["starting_oid"] = starting_oid; - params["snmp_browser_version"] = snmp_version; - params["server_to_exec"] = server_to_exec; - params["snmp3_browser_auth_user"] = snmp3_auth_user; - params["snmp3_browser_security_level"] = snmp3_security_level; - params["snmp3_browser_auth_method"] = snmp3_auth_method; - params["snmp3_browser_auth_pass"] = snmp3_auth_pass; - params["snmp3_browser_privacy_method"] = snmp3_privacy_method; - params["snmp3_browser_privacy_pass"] = snmp3_privacy_pass; - params["action"] = "snmptree"; - params["page"] = "operation/snmpconsole/snmp_browser"; - - // Browse! - jQuery.ajax ({ - data: params, - type: 'POST', - url: action= ajax_url, - async: true, - timeout: 120000, - success: function (data) { - - // Hide the spinner - $("#spinner").css('display', 'none'); - - // Load the SNMP tree - $("#snmp_browser").html(data); - } - }); +function snmpBrowse() { + // Empty the SNMP tree + $("#snmp_browser").html(""); + + // Hide the data div + hideOIDData(); + + // Reset previous searches + $("#search_results").css("display", "none"); + $("#hidden-search_count").val(-1); + + // Show the spinner + $("#spinner").css("display", ""); + + // Read the target IP and community + var target_ip = $("#text-target_ip").val(); + var community = $("#text-community").val(); + var starting_oid = $("#text-starting_oid").val(); + var snmp_version = $("#snmp_browser_version").val(); + var server_to_exec = $("#server_to_exec").val(); + var snmp3_auth_user = $("#text-snmp3_browser_auth_user").val(); + var snmp3_security_level = $("#snmp3_browser_security_level").val(); + var snmp3_auth_method = $("#snmp3_browser_auth_method").val(); + var snmp3_auth_pass = $("#password-snmp3_browser_auth_pass").val(); + var snmp3_privacy_method = $("#snmp3_browser_privacy_method").val(); + var snmp3_privacy_pass = $("#password-snmp3_browser_privacy_pass").val(); + var ajax_url = $("#hidden-ajax_url").val(); + + // Prepare the AJAX call + + var params = {}; + params["target_ip"] = target_ip; + params["community"] = community; + params["starting_oid"] = starting_oid; + params["snmp_browser_version"] = snmp_version; + params["server_to_exec"] = server_to_exec; + params["snmp3_browser_auth_user"] = snmp3_auth_user; + params["snmp3_browser_security_level"] = snmp3_security_level; + params["snmp3_browser_auth_method"] = snmp3_auth_method; + params["snmp3_browser_auth_pass"] = snmp3_auth_pass; + params["snmp3_browser_privacy_method"] = snmp3_privacy_method; + params["snmp3_browser_privacy_pass"] = snmp3_privacy_pass; + params["action"] = "snmptree"; + params["page"] = "operation/snmpconsole/snmp_browser"; + + // Browse! + jQuery.ajax({ + data: params, + type: "POST", + url: (action = ajax_url), + async: true, + timeout: 120000, + success: function(data) { + // Hide the spinner + $("#spinner").css("display", "none"); + + // Load the SNMP tree + $("#snmp_browser").html(data); + } + }); } // Expand or collapse an SNMP tree node function toggleTreeNode(node) { - - var display = $("#ul_" + node).css('display'); - var src = $("#anchor_" + node).children("img").attr('src'); - - // Show the expanded or collapsed square - if (display == "none") { - src = src.replace("closed", "expanded"); - } else { - src = src.replace("expanded", "closed"); - } - $("#anchor_" + node).children("img").attr('src', src); - - // Hide or show leaves - $("#ul_" + node).toggle(); + var display = $("#ul_" + node).css("display"); + var src = $("#anchor_" + node) + .children("img") + .attr("src"); + + // Show the expanded or collapsed square + if (display == "none") { + src = src.replace("closed", "expanded"); + } else { + src = src.replace("expanded", "closed"); + } + $("#anchor_" + node) + .children("img") + .attr("src", src); + + // Hide or show leaves + $("#ul_" + node).toggle(); } // Expand an SNMP tree node function expandTreeNode(node) { - - if (node == 0) { - return; - } - - // Show the expanded square - var src = $("#anchor_" + node).children("img").attr('src'); - src = src.replace("closed", "expanded"); - $("#anchor_" + node).children("img").attr('src', src); - - // Show leaves - $("#ul_" + node).css('display', ''); + if (node == 0) { + return; + } + + // Show the expanded square + var src = $("#anchor_" + node) + .children("img") + .attr("src"); + src = src.replace("closed", "expanded"); + $("#anchor_" + node) + .children("img") + .attr("src", src); + + // Show leaves + $("#ul_" + node).css("display", ""); } // Expand an SNMP tree node function collapseTreeNode(node) { - - if (node == 0) { - return; - } - - // Show the collapsed square - var src = $("#anchor_" + node).children("img").attr('src'); - src = src.replace("expanded", "closed"); - $("#anchor_" + node).children("img").attr('src', src); - - // Hide leaves - $("#ul_" + node).css('display', 'none'); + if (node == 0) { + return; + } + + // Show the collapsed square + var src = $("#anchor_" + node) + .children("img") + .attr("src"); + src = src.replace("expanded", "closed"); + $("#anchor_" + node) + .children("img") + .attr("src", src); + + // Hide leaves + $("#ul_" + node).css("display", "none"); } // Expand all tree nodes function expandAll(node) { - - $('#snmp_browser').find('ul').each ( function () { - var id = $(this).attr('id').substr(3); - expandTreeNode (id); - }); + $("#snmp_browser") + .find("ul") + .each(function() { + var id = $(this) + .attr("id") + .substr(3); + expandTreeNode(id); + }); } // Collapse all tree nodes function collapseAll(node) { + // Reset previous searches + $("#search_results").css("display", "none"); + $("#hidden-search_count").val(-1); - // Reset previous searches - $("#search_results").css('display', 'none'); - $("#hidden-search_count").val(-1); - - $('#snmp_browser').find('ul').each ( function () { - var id = $(this).attr('id').substr(3); - collapseTreeNode (id); - }); + $("#snmp_browser") + .find("ul") + .each(function() { + var id = $(this) + .attr("id") + .substr(3); + collapseTreeNode(id); + }); } // Perform an SNMP get request via AJAX -function snmpGet (oid) { +function snmpGet(oid) { + // Empty previous OID data + $("#snmp_data").empty(); - // Empty previous OID data - $("#snmp_data").empty(); + // Read the target IP and community + var target_ip = $("#text-target_ip").val(); + var community = $("#text-community").val(); + var snmp_version = $("#snmp_browser_version").val(); + var snmp3_auth_user = $("#text-snmp3_browser_auth_user").val(); + var snmp3_security_level = $("#snmp3_browser_security_level").val(); + var snmp3_auth_method = $("#snmp3_browser_auth_method").val(); + var snmp3_auth_pass = $("#password-snmp3_browser_auth_pass").val(); + var snmp3_privacy_method = $("#snmp3_browser_privacy_method").val(); + var snmp3_privacy_pass = $("#password-snmp3_browser_privacy_pass").val(); + var ajax_url = $("#hidden-ajax_url").val(); - // Read the target IP and community - var target_ip = $('#text-target_ip').val(); - var community = $('#text-community').val(); - var snmp_version = $('#snmp_browser_version').val(); - var snmp3_auth_user = $('#text-snmp3_browser_auth_user').val(); - var snmp3_security_level = $('#snmp3_browser_security_level').val(); - var snmp3_auth_method = $('#snmp3_browser_auth_method').val(); - var snmp3_auth_pass = $('#password-snmp3_browser_auth_pass').val(); - var snmp3_privacy_method = $('#snmp3_browser_privacy_method').val(); - var snmp3_privacy_pass = $('#password-snmp3_browser_privacy_pass').val(); - var ajax_url = $('#hidden-ajax_url').val(); - - // Check for a custom action - var custom_action = $('#hidden-custom_action').val(); - if (custom_action == undefined) { - custom_action = ''; - } - - // Prepare the AJAX call - var params = [ - "target_ip=" + target_ip, - "community=" + community, - "oid=" + oid, - "snmp_browser_version=" + snmp_version, - "snmp3_browser_auth_user=" + snmp3_auth_user, - "snmp3_browser_security_level=" + snmp3_security_level, - "snmp3_browser_auth_method=" + snmp3_auth_method, - "snmp3_browser_auth_pass=" + snmp3_auth_pass, - "snmp3_browser_privacy_method=" + snmp3_privacy_method, - "snmp3_browser_privacy_pass=" + snmp3_privacy_pass, - "action=" + "snmpget", - "custom_action=" + custom_action, - "page=operation/snmpconsole/snmp_browser" - ]; + // Check for a custom action + var custom_action = $("#hidden-custom_action").val(); + if (custom_action == undefined) { + custom_action = ""; + } - // SNMP get! - jQuery.ajax ({ - data: params.join ("&"), - type: 'POST', - url: action=ajax_url, - async: true, - timeout: 60000, - success: function (data) { - $("#snmp_data").html(data); - forced_title_callback(); - } - }); - - // Show the data div - showOIDData(); + // Prepare the AJAX call + var params = [ + "target_ip=" + target_ip, + "community=" + community, + "oid=" + oid, + "snmp_browser_version=" + snmp_version, + "snmp3_browser_auth_user=" + snmp3_auth_user, + "snmp3_browser_security_level=" + snmp3_security_level, + "snmp3_browser_auth_method=" + snmp3_auth_method, + "snmp3_browser_auth_pass=" + snmp3_auth_pass, + "snmp3_browser_privacy_method=" + snmp3_privacy_method, + "snmp3_browser_privacy_pass=" + snmp3_privacy_pass, + "action=" + "snmpget", + "custom_action=" + custom_action, + "page=operation/snmpconsole/snmp_browser" + ]; + + // SNMP get! + jQuery.ajax({ + data: params.join("&"), + type: "POST", + url: (action = ajax_url), + async: true, + timeout: 60000, + success: function(data) { + $("#snmp_data").html(data); + forced_title_callback(); + } + }); + + // Show the data div + showOIDData(); } // Show the div that displays OID data function showOIDData() { - $("#snmp_data").css('display', ''); + $("#snmp_data").css("display", ""); } // Hide the div that displays OID data function hideOIDData() { + // Empty previous OID data + $("#snmp_data").empty(); - // Empty previous OID data - $("#snmp_data").empty(); - - $("#snmp_data").css('display', 'none'); - $(".forced_title_layer").css('display', 'none'); + $("#snmp_data").css("display", "none"); + $(".forced_title_layer").css("display", "none"); } // Search the SNMP tree for a matching string function searchText() { + var text = $("#text-search_text").val(); + var regexp = new RegExp(text); + var search_matches_translation = $( + "#hidden-search_matches_translation" + ).val(); - var text = $('#text-search_text').val(); - var regexp = new RegExp(text); - var search_matches_translation = $('#hidden-search_matches_translation').val(); + // Hide previous search result count + $("#search_results").css("display", ""); - // Hide previous search result count - $("#search_results").css('display', ''); + // Show the spinner + $("#spinner").css("display", ""); - // Show the spinner - $("#spinner").css('display', ''); + // Collapse previously searched nodes + $(".expanded").each(function() { + $(this).removeClass("expanded"); - // Collapse previously searched nodes - $('.expanded').each( function () { - $(this).removeClass('expanded'); - - // Remove the leading ul_ - var node_id = $(this).attr('id').substr(3); - - collapseTreeNode(node_id); - }); - - // Un-highlight previously searched nodes - $('match').removeClass('match'); - $('span').removeClass('group_view_warn'); + // Remove the leading ul_ + var node_id = $(this) + .attr("id") + .substr(3); - // Hide values - $('span.value').css('display', 'none'); + collapseTreeNode(node_id); + }); - // Disable empty searches - var count = 0; - if (text != '') { - count = searchTreeNode($('#snmp_browser'), regexp); - } - - // Hide the spinner - $("#spinner").css('display', 'none'); + // Un-highlight previously searched nodes + $("match").removeClass("match"); + $("span").removeClass("group_view_warn"); - // Show and save the search result count - $("#hidden-search_count").val(count); - $("#search_results").text(search_matches_translation + ': ' + count); - $("#search_results").css('display', ''); + // Hide values + $("span.value").css("display", "none"); - // Reset the search index - $("#hidden-search_index").val(-1); + // Disable empty searches + var count = 0; + if (text != "") { + count = searchTreeNode($("#snmp_browser"), regexp); + } - // Focus the first match - searchNextMatch (); + // Hide the spinner + $("#spinner").css("display", "none"); + + // Show and save the search result count + $("#hidden-search_count").val(count); + $("#search_results").text(search_matches_translation + ": " + count); + $("#search_results").css("display", ""); + + // Reset the search index + $("#hidden-search_index").val(-1); + + // Focus the first match + searchNextMatch(); } // Recursively search an SNMP tree node trying to match the given regexp function searchTreeNode(obj, regexp) { - - // For each node tree - var count = 0; - $(obj).children("ul").each( function () { - var ul_node = this; - - // Expand if regexp matches one of its children - $(ul_node).addClass('expand') - - // Search children for matches - $(ul_node).children("li").each( function () { - var li_node = this; - var text = $(li_node).text(); + // For each node tree + var count = 0; + $(obj) + .children("ul") + .each(function() { + var ul_node = this; - // Match! - if (regexp.test(text) == true) { - - count++; - - // Highlight in yellow - $(li_node).children('span').addClass('group_view_warn'); - $(li_node).addClass('match'); - - // Show the value - $(li_node).children('span.value').css('display', ''); - - // Expand all nodes that lead to this one - $('.expand').each( function () { - $(this).addClass('expanded'); - - // Remove the leading ul_ - var node_id = $(this).attr('id').substr(3); - - expandTreeNode(node_id); - }); - } - }); - - // Search sub nodes - count += searchTreeNode(ul_node, regexp); - - // Do not expand this node if it has not been expanded already - $(ul_node).removeClass('expand'); - }); - - return count; + // Expand if regexp matches one of its children + $(ul_node).addClass("expand"); + + // Search children for matches + $(ul_node) + .children("li") + .each(function() { + var li_node = this; + var text = $(li_node).text(); + + // Match! + if (regexp.test(text) == true) { + count++; + + // Highlight in yellow + $(li_node) + .children("span") + .addClass("group_view_warn"); + $(li_node).addClass("match"); + + // Show the value + $(li_node) + .children("span.value") + .css("display", ""); + + // Expand all nodes that lead to this one + $(".expand").each(function() { + $(this).addClass("expanded"); + + // Remove the leading ul_ + var node_id = $(this) + .attr("id") + .substr(3); + + expandTreeNode(node_id); + }); + } + }); + + // Search sub nodes + count += searchTreeNode(ul_node, regexp); + + // Do not expand this node if it has not been expanded already + $(ul_node).removeClass("expand"); + }); + + return count; } // Focus the next search match -function searchNextMatch () { - var search_index = $("#hidden-search_index").val(); - var search_count = $("#hidden-search_count").val(); +function searchNextMatch() { + var search_index = $("#hidden-search_index").val(); + var search_count = $("#hidden-search_count").val(); - // Update the search index - search_index++; - if (search_index >= search_count) { - search_index = 0; - } + // Update the search index + search_index++; + if (search_index >= search_count) { + search_index = 0; + } - // Get the id of the next element - var id = $('.match:eq(' + search_index + ')').attr('id'); - - // Scroll - $('#snmp_browser').animate({ - scrollTop: $('#snmp_browser').scrollTop() + $('#' + id).offset().top - $('#snmp_browser').offset().top - }, 1000); + // Get the id of the next element + var id = $(".match:eq(" + search_index + ")").attr("id"); - // Save the search index - $("#hidden-search_index").val(search_index); + // Scroll + $("#snmp_browser").animate( + { + scrollTop: + $("#snmp_browser").scrollTop() + + $("#" + id).offset().top - + $("#snmp_browser").offset().top + }, + 1000 + ); + + // Save the search index + $("#hidden-search_index").val(search_index); } // Focus the previous search match -function searchPrevMatch () { - var search_index = $("#hidden-search_index").val(); - var search_count = $("#hidden-search_count").val(); +function searchPrevMatch() { + var search_index = $("#hidden-search_index").val(); + var search_count = $("#hidden-search_count").val(); - // Update the search index - search_index--; - if (search_index < 0) { - search_index = search_count - 1; - } + // Update the search index + search_index--; + if (search_index < 0) { + search_index = search_count - 1; + } - // Get the id of the next element - var id = $('.match:eq(' + search_index + ')').attr('id'); - - // Scroll - $('#snmp_browser').animate({ - scrollTop: $('#snmp_browser').scrollTop() + $('#' + id).offset().top - $('#snmp_browser').offset().top - }, 1000); + // Get the id of the next element + var id = $(".match:eq(" + search_index + ")").attr("id"); - // Save the search index - $("#hidden-search_index").val(search_index); + // Scroll + $("#snmp_browser").animate( + { + scrollTop: + $("#snmp_browser").scrollTop() + + $("#" + id).offset().top - + $("#snmp_browser").offset().top + }, + 1000 + ); + + // Save the search index + $("#hidden-search_index").val(search_index); } // Focus the first search match -function searchFirstMatch () { +function searchFirstMatch() { + // Reset the search index + $("#hidden-search_index").val(-1); - // Reset the search index - $("#hidden-search_index").val(-1); - - // Focus the first match - searchNextMatch(); + // Focus the first match + searchNextMatch(); } // Focus the last search match -function searchLastMatch () { +function searchLastMatch() { + // Reset the search index + $("#hidden-search_index").val(-1); - // Reset the search index - $("#hidden-search_index").val(-1); - - // Focus the last match - searchPrevMatch(); + // Focus the last match + searchPrevMatch(); } // Hide or show SNMP v3 options -function checkSNMPVersion () { - if ($("#snmp_browser_version").val() == "3") { - $("#snmp3_browser_options").css("display", ""); - } - else { - $("#snmp3_browser_options").css("display", "none"); - } +function checkSNMPVersion() { + if ($("#snmp_browser_version").val() == "3") { + $("#snmp3_browser_options").css("display", ""); + } else { + $("#snmp3_browser_options").css("display", "none"); + } } diff --git a/pandora_console/include/javascript/pandora_visual_console.js b/pandora_console/include/javascript/pandora_visual_console.js index 6fa70ad4c9..06209e092f 100755 --- a/pandora_console/include/javascript/pandora_visual_console.js +++ b/pandora_console/include/javascript/pandora_visual_console.js @@ -16,124 +16,143 @@ * @param id_div Div to draw the lines in * @param editor Boolean variable to set other css selector in editor (when true). */ -function draw_line (line, id_div) { - selector = ''; - - //Check if the global var resize_map is defined - if (typeof(resize_map) == 'undefined') { - resize_map = 0; - } - - var lineThickness = 2; - if (line['thickness']) - lineThickness = line['thickness']; - - div = document.getElementById (id_div); - - brush = new jsGraphics (div); - brush.setStroke (lineThickness); - brush.setColor (line['color']); - - have_node_begin_img = $('#' + line['node_begin'] + " img").length; - have_node_end_img = $('#' + line['node_end'] + " img").length; - - if (have_node_begin_img) { - var img_pos_begin = $('#' + line['node_begin'] + " img").position(); - var img_margin_left_begin = $('#' + line['node_begin'] + " img").css("margin-left"); - var img_margin_left_begin_aux = img_margin_left_begin.split("px"); - img_margin_left_begin = parseFloat(img_margin_left_begin_aux[0]); +function draw_line(line, id_div) { + selector = ""; - var img_margin_top_begin = $('#' + line['node_begin'] + " img").css("margin-top"); - var img_margin_top_begin_aux = img_margin_top_begin.split("px"); - img_margin_top_begin = parseFloat(img_margin_top_begin_aux[0]); - } - if (have_node_end_img) { - var img_pos_end = $('#' + line['node_end'] + " img").position(); - var img_margin_left_end = $('#' + line['node_end'] + " img").css("margin-left"); - var img_margin_left_end_aux = img_margin_left_end.split("px"); - img_margin_left_end = parseFloat(img_margin_left_end_aux[0]); + //Check if the global var resize_map is defined + if (typeof resize_map == "undefined") { + resize_map = 0; + } - var img_margin_top_end = $('#' + line['node_end'] + " img").css("margin-top"); - var img_margin_top_end_aux = img_margin_top_end.split("px"); - img_margin_top_end = parseFloat(img_margin_top_end_aux[0]); - } + var lineThickness = 2; + if (line["thickness"]) lineThickness = line["thickness"]; - if (line['x1']) { - x1 = line['x']; - } - else { - if (have_node_begin_img) { - width = $('#' + line['node_begin'] + " img").width(); - x1 = parseInt($('#' + line['node_begin']).css (selector + 'left')) + (width / 2) + img_pos_begin.left + img_margin_left_begin; - } - else { - width = $('#' + line['node_begin']).width(); - x1 = parseInt($('#' + line['node_begin']).css (selector + 'left')) + (width / 2); - } - - } - - if (line['y1']) { - y1 = line['y1']; - } - else { - if (have_node_begin_img) { - height = parseInt($('#' + line['node_begin'] + " img").css('height')); - y1 = parseInt($('#' + line['node_begin']).css (selector + 'top')) + (height / 2) + img_pos_begin.top + img_margin_top_begin; - } - else { - height = $('#' + line['node_begin']).height(); - y1 = parseInt($('#' + line['node_begin']).css (selector + 'top')) + (height / 2); - } - } - - if (line['x2']) { - x2 = line['x2']; - } - else { - if (have_node_end_img) { - width = $('#' + line['node_end'] + " img").width(); - x2 = parseInt($('#' + line['node_end']).css (selector + 'left')) + (width / 2) + img_pos_end.left + img_margin_left_end; - } - else { - width = $('#' + line['node_end']).width(); - x2 = parseInt($('#' + line['node_end']).css (selector + 'left')) + (width / 2); - } - } - - if (line['y2']) { - y2 = line['y2']; - } - else { - if (have_node_end_img) { - height = parseInt($('#' + line['node_end'] + " img").css('height')); - y2 = parseInt($('#' + line['node_end']).css (selector + 'top')) + (height / 2) + img_pos_end.top + img_margin_top_end; - } - else { - height = $('#' + line['node_end']).height(); - y2 = parseInt($('#' + line['node_end']).css (selector + 'top')) + (height / 2); - } - } - - - brush.drawLine (x1, y1, x2, y2); - brush.paint (); + div = document.getElementById(id_div); + + brush = new jsGraphics(div); + brush.setStroke(lineThickness); + brush.setColor(line["color"]); + + have_node_begin_img = $("#" + line["node_begin"] + " img").length; + have_node_end_img = $("#" + line["node_end"] + " img").length; + + if (have_node_begin_img) { + var img_pos_begin = $("#" + line["node_begin"] + " img").position(); + var img_margin_left_begin = $("#" + line["node_begin"] + " img").css( + "margin-left" + ); + var img_margin_left_begin_aux = img_margin_left_begin.split("px"); + img_margin_left_begin = parseFloat(img_margin_left_begin_aux[0]); + + var img_margin_top_begin = $("#" + line["node_begin"] + " img").css( + "margin-top" + ); + var img_margin_top_begin_aux = img_margin_top_begin.split("px"); + img_margin_top_begin = parseFloat(img_margin_top_begin_aux[0]); + } + if (have_node_end_img) { + var img_pos_end = $("#" + line["node_end"] + " img").position(); + var img_margin_left_end = $("#" + line["node_end"] + " img").css( + "margin-left" + ); + var img_margin_left_end_aux = img_margin_left_end.split("px"); + img_margin_left_end = parseFloat(img_margin_left_end_aux[0]); + + var img_margin_top_end = $("#" + line["node_end"] + " img").css( + "margin-top" + ); + var img_margin_top_end_aux = img_margin_top_end.split("px"); + img_margin_top_end = parseFloat(img_margin_top_end_aux[0]); + } + + if (line["x1"]) { + x1 = line["x"]; + } else { + if (have_node_begin_img) { + width = $("#" + line["node_begin"] + " img").width(); + x1 = + parseInt($("#" + line["node_begin"]).css(selector + "left")) + + width / 2 + + img_pos_begin.left + + img_margin_left_begin; + } else { + width = $("#" + line["node_begin"]).width(); + x1 = + parseInt($("#" + line["node_begin"]).css(selector + "left")) + + width / 2; + } + } + + if (line["y1"]) { + y1 = line["y1"]; + } else { + if (have_node_begin_img) { + height = parseInt($("#" + line["node_begin"] + " img").css("height")); + y1 = + parseInt($("#" + line["node_begin"]).css(selector + "top")) + + height / 2 + + img_pos_begin.top + + img_margin_top_begin; + } else { + height = $("#" + line["node_begin"]).height(); + y1 = + parseInt($("#" + line["node_begin"]).css(selector + "top")) + + height / 2; + } + } + + if (line["x2"]) { + x2 = line["x2"]; + } else { + if (have_node_end_img) { + width = $("#" + line["node_end"] + " img").width(); + x2 = + parseInt($("#" + line["node_end"]).css(selector + "left")) + + width / 2 + + img_pos_end.left + + img_margin_left_end; + } else { + width = $("#" + line["node_end"]).width(); + x2 = + parseInt($("#" + line["node_end"]).css(selector + "left")) + width / 2; + } + } + + if (line["y2"]) { + y2 = line["y2"]; + } else { + if (have_node_end_img) { + height = parseInt($("#" + line["node_end"] + " img").css("height")); + y2 = + parseInt($("#" + line["node_end"]).css(selector + "top")) + + height / 2 + + img_pos_end.top + + img_margin_top_end; + } else { + height = $("#" + line["node_end"]).height(); + y2 = + parseInt($("#" + line["node_end"]).css(selector + "top")) + height / 2; + } + } + + brush.drawLine(x1, y1, x2, y2); + brush.paint(); } -/** +/** * Draw all the lines in an array on a div - * + * * @param lines Array with lines objects (see draw_line) * @param id_div Div to draw the lines in * @param editor Boolean variable to set other css selector in editor (when true). */ -function draw_lines (lines, id_div, editor) { - jQuery.each (lines, function (i, line) { - draw_line (line, id_div, editor); - }); +function draw_lines(lines, id_div, editor) { + jQuery.each(lines, function(i, line) { + draw_line(line, id_div, editor); + }); } -/** +/** * Delete all the lines on a div * * The lines has the class 'map-line', so all the elements with this @@ -141,58 +160,60 @@ function draw_lines (lines, id_div, editor) { * * @param id_div Div to delete the lines in */ -function delete_lines (id_div) { - $('#' + id_div + ' .map-line').remove (); +function delete_lines(id_div) { + $("#" + id_div + " .map-line").remove(); } - -/** +/** * Re-draw all the lines in an array on a div * * It deletes all the lines and create then again. - * + * * @param lines Array with lines objects (see draw_line) * @param id_div Div to draw the lines in * @param editor Boolean variable to set other css selector in editor (when true). */ -function refresh_lines (lines, id_div, editor) { - delete_lines (id_div); - draw_lines (lines, id_div, editor); +function refresh_lines(lines, id_div, editor) { + delete_lines(id_div); + draw_lines(lines, id_div, editor); } - function draw_user_lines_read(divId) { - divId = divId || 'background'; - var obj_js_user_lines = new jsGraphics(divId); - - obj_js_user_lines.clear(); - - // Draw the previous lines - for (iterator = 0; iterator < user_lines.length; iterator++) { - obj_js_user_lines.setStroke(parseInt(user_lines[iterator]['line_width'])); - obj_js_user_lines.setColor(user_lines[iterator]['line_color']); - obj_js_user_lines.drawLine( - parseInt(user_lines[iterator]['start_x']), - parseInt(user_lines[iterator]['start_y']), - parseInt(user_lines[iterator]['end_x']), - parseInt(user_lines[iterator]['end_y'])); - - } - - obj_js_user_lines.paint(); + divId = divId || "background"; + var obj_js_user_lines = new jsGraphics(divId); + + obj_js_user_lines.clear(); + + // Draw the previous lines + for (iterator = 0; iterator < user_lines.length; iterator++) { + obj_js_user_lines.setStroke(parseInt(user_lines[iterator]["line_width"])); + obj_js_user_lines.setColor(user_lines[iterator]["line_color"]); + obj_js_user_lines.drawLine( + parseInt(user_lines[iterator]["start_x"]), + parseInt(user_lines[iterator]["start_y"]), + parseInt(user_lines[iterator]["end_x"]), + parseInt(user_lines[iterator]["end_y"]) + ); + } + + obj_js_user_lines.paint(); } function center_labels() { - jQuery.each($(".item"), function(i, item) { + jQuery.each($(".item"), function(i, item) { + if ( + $(item).width() > $("img", item).width() && + $("img", item).width() != null + ) { + dif_width = $(item).width() - $("img", item).width(); - if ($(item).width() > $("img", item).width() && ($("img", item).width() != null)) { - dif_width = $(item).width() - $("img", item).width(); - - x = parseInt($(item).css("left")); + x = parseInt($(item).css("left")); - x = x - (dif_width / 2); + x = x - dif_width / 2; - $(item).css("left", x + "px").css("text-align", "center"); - } - }); -} \ No newline at end of file + $(item) + .css("left", x + "px") + .css("text-align", "center"); + } + }); +} diff --git a/pandora_console/include/javascript/tree/TreeController.js b/pandora_console/include/javascript/tree/TreeController.js index 13a0b31cd4..e3f7260de4 100644 --- a/pandora_console/include/javascript/tree/TreeController.js +++ b/pandora_console/include/javascript/tree/TreeController.js @@ -13,781 +13,895 @@ // GNU General Public License for more details. var TreeController = { - controllers: [], - getController: function () { - var controller = { - index: -1, - recipient: '', - tree: [], - emptyMessage: "No data found.", - foundMessage: "Found groups", - errorMessage: "Error", - baseURL: "", - ajaxURL: "ajax.php", - ajaxPage: "include/ajax/tree.ajax", - detailRecipient: '', - filter: {}, - counterTitles: {}, - shouldHaveCounters: true, - reload: function () { - // Bad recipient - if (typeof this.recipient == 'undefined' || this.recipient.length == 0) { - return; - } - - // Load branch - function _processGroup (container, elements, rootGroup) { - - var $group = $("
                "); - - // First group - if (typeof rootGroup != 'undefinded' && rootGroup == true) { - $group - .addClass("tree-root") - .hide() - .prepend(''); - } - // Normal group - else { - $group - .addClass("tree-group") - .hide(); - } - - container.append($group); - - _.each(elements, function(element) { - element.jqObject = _processNode($group, element); - }); - - return $group; - } - - // Load leaf counters - function _processNodeCounters (container, counters, type) { - var hasCounters = false; - - if (typeof counters != 'undefined') { - - function _processNodeCounterTitle (container, elementType, counterType) { - var defaultCounterTitles = { - total: { - agents: "Total agents", - modules: "Total modules", - none: "Total" - }, - alerts: { - agents: "Alerts fired", - modules: "Alerts fired", - none: "Alerts fired" - }, - critical: { - agents: "Critical agents", - modules: "Critical modules", - none: "Critical" - }, - warning: { - agents: "Warning agents", - modules: "Warning modules", - none: "Warning" - }, - unknown: { - agents: "Unknown agents", - modules: "Unknown modules", - none: "Unknown" - }, - not_init: { - agents: "Not init agents", - modules: "Not init modules", - none: "Not init" - }, - ok: { - agents: "Normal agents", - modules: "Normal modules", - none: "Normal" - } - } - - try { - var title = ''; - switch (elementType) { - case "group": - if (typeof controller.counterTitles != 'undefined' - && typeof controller.counterTitles[counterType] != 'undefined' - && typeof controller.counterTitles[counterType].agents != 'undefined') { - title = controller.counterTitles[counterType].agents; - } - else { - title = defaultCounterTitles[counterType].agents; - } - break; - case "agent": - if (typeof controller.counterTitles != 'undefined' - && typeof controller.counterTitles[counterType] != 'undefined' - && typeof controller.counterTitles[counterType].modules != 'undefined') { - title = controller.counterTitles[counterType].modules; - } - else { - title = defaultCounterTitles[counterType].modules; - } - break; - default: - if (typeof controller.counterTitles != 'undefined' - && typeof controller.counterTitles[counterType] != 'undefined' - && typeof controller.counterTitles[counterType].none != 'undefined') { - title = controller.counterTitles[counterType].none; - } - else { - title = defaultCounterTitles[counterType].none; - } - break; - } - if (title.length > 0) { - container - .data("title", title) - .addClass("forced_title") - .data("use_title_for_force_title", 1); // Trick to make easier the 'force title' output - } - } - catch (error) { - // console.log(error); - } - } - - var $counters = $("
                "); - $counters.addClass('tree-node-counters'); - - if (typeof counters.total != 'undefined' - && counters.total >= 0) { - - var $totalCounter = $("
                "); - $totalCounter - .addClass('tree-node-counter') - .addClass('total') - .html(counters.total); - - _processNodeCounterTitle($totalCounter, type, "total"); - - // Open the parentheses - $counters.append(" ("); - - $counters.append($totalCounter); - - if (typeof counters.alerts != 'undefined' - && counters.alerts > 0) { - var $firedCounter = $("
                "); - $firedCounter - .addClass('tree-node-counter') - .addClass('alerts') - .addClass('orange') - .html(counters.alerts); - - _processNodeCounterTitle($firedCounter, type, "alerts"); - - $counters - .append(" : ") - .append($firedCounter); - } - if (typeof counters.critical != 'undefined' - && counters.critical > 0) { - var $criticalCounter = $("
                "); - $criticalCounter - .addClass('tree-node-counter') - .addClass('critical') - .addClass('red') - .html(counters.critical); - - _processNodeCounterTitle($criticalCounter, type, "critical"); - - $counters - .append(" : ") - .append($criticalCounter); - } - if (typeof counters.warning != 'undefined' - && counters.warning > 0) { - var $warningCounter = $("
                "); - $warningCounter - .addClass('tree-node-counter') - .addClass('warning') - .addClass('yellow') - .html(counters.warning); - - _processNodeCounterTitle($warningCounter, type, "warning"); - - $counters - .append(" : ") - .append($warningCounter); - } - if (typeof counters.unknown != 'undefined' - && counters.unknown > 0) { - var $unknownCounter = $("
                "); - $unknownCounter - .addClass('tree-node-counter') - .addClass('unknown') - .addClass('grey') - .html(counters.unknown); - - _processNodeCounterTitle($unknownCounter, type, "unknown"); - - $counters - .append(" : ") - .append($unknownCounter); - } - if (typeof counters.not_init != 'undefined' - && counters.not_init > 0) { - var $notInitCounter = $("
                "); - $notInitCounter - .addClass('tree-node-counter') - .addClass('not_init') - .addClass('blue') - .html(counters.not_init); - - _processNodeCounterTitle($notInitCounter, type, "not_init"); - - $counters - .append(" : ") - .append($notInitCounter); - } - if (typeof counters.ok != 'undefined' - && counters.ok > 0) { - var $okCounter = $("
                "); - $okCounter - .addClass('tree-node-counter') - .addClass('ok') - .addClass('green') - .html(counters.ok); - - _processNodeCounterTitle($okCounter, type, "ok"); - - $counters - .append(" : ") - .append($okCounter); - } - - // Close the parentheses - $counters.append(")"); - - hasCounters = true; - } - - // Add the counters html to the container - container.append($counters); - } - - return hasCounters; - } - - // Load leaf - function _processNode (container, element) { - // type, [id], [serverID], callback - function _getTreeDetailData (type, id, serverID, callback) { - var lastParam = arguments[arguments.length - 1]; - var callback; - if (typeof lastParam === 'function') - callback = lastParam; - - var serverID; - if (arguments.length >= 4) - serverID = arguments[2]; - var id; - if (arguments.length >= 3) - id = arguments[1]; - var type; - if (arguments.length >= 2) - type = arguments[0]; - - if (typeof type === 'undefined') - throw new TypeError('Type required'); - if (typeof callback === 'undefined') - throw new TypeError('Callback required'); - - var postData = { - page: controller.ajaxPage, - getDetail: 1, - type: type - } - - if (typeof id !== 'undefined') - postData.id = id; - if (typeof serverID !== 'undefined') - postData.serverID = serverID; - - $.ajax({ - url: controller.ajaxURL, - type: 'POST', - dataType: 'html', - data: postData, - success: function(data, textStatus, xhr) { - callback(null, data); - }, - error: function(xhr, textStatus, errorThrown) { - callback(errorThrown); - } - }); - } - - var $node = $("
              • "); - var $leafIcon = $("
                "); - var $content = $("
                "); - - // Leaf icon - $leafIcon.addClass("leaf-icon"); - - // Content - $content.addClass("node-content"); - switch (element.type) { - case 'group': - if (typeof element.icon != 'undefined' && element.icon.length > 0) { - $content.append(' '); - } - else if (typeof element.iconHTML != 'undefined' && element.iconHTML.length > 0) { - $content.append(element.iconHTML + " "); - } - $content.append(element.name); - - if(typeof element.edit != 'undefined'){ - var url_edit = controller.baseURL + "index.php?sec=gagente&sec2=godmode/groups/configure_group&tab=tree&id_group=" + element.id; - var $updateicon = $('') - var $updatebtn = $('') - .append($updateicon); - $content.append($updatebtn); - } - - if(typeof element.delete != 'undefined'){ - var url_delete = controller.baseURL + "index.php?sec=gagente&sec2=godmode/groups/group_list&tab=tree&delete_group=1&id_group=" + element.id; - var $deleteBtn = $(''); - $deleteBtn.click(function (event){ - var ok_function = function(){ - window.location.replace(url_delete); - }; - display_confirm_dialog( - element.delete.messages.messg, - element.delete.messages.confirm, - element.delete.messages.cancel, - ok_function - ) - }); - $content.append($deleteBtn); - } - - if(typeof element.alerts != 'undefined'){ - $content.append(element.alerts); - } - - break; - case 'agent': - // Is quiet - if (typeof element.quietImageHTML != 'undefined' - && element.quietImageHTML.length > 0) { - var $quietImage = $(element.quietImageHTML); - $quietImage.addClass("agent-quiet"); - - $content.append($quietImage); - } - // Status image - if (typeof element.statusImageHTML != 'undefined' - && element.statusImageHTML.length > 0) { - var $statusImage = $(element.statusImageHTML); - $statusImage.addClass("agent-status"); - - $content.append($statusImage); - } - // Alerts fired image - if (typeof element.alertImageHTML != 'undefined' - && element.alertImageHTML.length > 0) { - var $alertImage = $(element.alertImageHTML); - $alertImage.addClass("agent-alerts-fired"); - - $content.append($alertImage); - } - $content.append(element.alias); - break; - case 'module': - // Status image - if (typeof element.statusImageHTML != 'undefined' - && element.statusImageHTML.length > 0) { - var $statusImage = $(element.statusImageHTML); - $statusImage.addClass("module-status"); - - $content.append($statusImage); - } - // Server type - if (typeof element.serverTypeHTML != 'undefined' - && element.serverTypeHTML.length > 0 - && element.serverTypeHTML != '--') { - var $serverTypeImage = $(element.serverTypeHTML); - $serverTypeImage.addClass("module-server-type"); - - $content.append($serverTypeImage); - } - - if (typeof element.showGraphs != 'undefined' && element.showGraphs != 0) { - // Graph pop-up - if (typeof element.moduleGraph != 'undefined') { - - if(element.statusImageHTML.indexOf('data:image')!=-1){ - var $graphImage = $(' '); - } - else{ - - var $graphImage = $(' '); - } - - $graphImage - .addClass('module-graph') - .click(function (e) { - e.preventDefault(); - if(element.statusImageHTML.indexOf('data:image')!=-1){ - try { - winopeng_var( - decodeURI(element.snapshot[0]), - element.snapshot[1], - element.snapshot[2], - element.snapshot[3] - ); - } - catch (error) { - // console.log(error); - } - } - else{ - try { - winopeng(element.moduleGraph.url, element.moduleGraph.handle); - } - catch (error) { - // console.log(error); - } - } - }); - - $content.append($graphImage); - } - - // Data pop-up - if (typeof element.id != 'undefined' && !isNaN(element.id)) { - - var $dataImage = $(' '); - $dataImage - .addClass('module-data') - .click(function (e) { - e.preventDefault(); - - try { - var serverName = element.serverName.length > 0 ? element.serverName : ''; - if ($("#module_details_window").length > 0) - show_module_detail_dialog(element.id, '', serverName, 0, 86400, element.name.replace(/ /g , " ") ); - } - catch (error) { - // console.log(error); - } - }); - - $content.append($dataImage); - } - } - - // Alerts - if (typeof element.alertsImageHTML != 'undefined' - && element.alertsImageHTML.length > 0) { - - var $alertsImage = $(element.alertsImageHTML); - - $alertsImage - .addClass("module-alerts") - .click(function (e) { - _getTreeDetailData('alert', element.id, element.serverID, function (error, data) { - if (error) { - // console.error(error); - } - else { - controller.detailRecipient.render(element.name, data).open(); - } - }); - - // Avoid the execution of the module detail event - e.stopPropagation(); - }) - .css('cursor', 'pointer'); - - $content.append($alertsImage); - } - - $content.append(element.name); - break; - case 'os': - if (typeof element.icon != 'undefined' && element.icon.length > 0) { - $content.append(' '); - } - $content.append(element.name); - break; - case 'tag': - if (typeof element.icon != 'undefined' && element.icon.length > 0) { - $content.append(' '); - } - else { - $content.append(' '); - } - $content.append(element.name); - break; - default: - $content.append(element.name); - break; - } - - // Load the status counters - var hasCounters = _processNodeCounters($content, element.counters, element.type); - //Don't show empty groups - if (element.type == 'agent') { - if (!hasCounters) { - return; - } - } - // If exist the detail container, show the data - if (typeof controller.detailRecipient !== 'undefined') { - if (element.type == 'agent' || element.type == 'module') { - $content.click(function (e) { - _getTreeDetailData(element.type, element.id, element.serverID, function (error, data) { - if (error) { - // console.error(error); - } - else { - controller.detailRecipient.render(element.name, data).open(); - } - }); - }) - .css('cursor', 'pointer'); - } - } - - $node - .addClass("tree-node") - .append($leafIcon) - .append($content); - - container.append($node); - - $node.addClass("leaf-empty"); - - if (typeof element.children != 'undefined' && element.children.length > 0) { - $node - .removeClass("leaf-empty") - .addClass("leaf-closed"); - - // Add children - var $children = _processGroup($node, element.children); - $node.data('children', $children); - - if (typeof element.searchChildren == 'undefined' || !element.searchChildren) { - $leafIcon.click(function (e) { - e.preventDefault(); - - if ($node.hasClass("leaf-open")) { - $node - .removeClass("leaf-open") - .addClass("leaf-closed") - .data('children') - .slideUp(); - } - else { - $node - .removeClass("leaf-closed") - .addClass("leaf-open") - .data('children') - .slideDown(); - } - }); - } - } - // Get hash and user. - var public_hash = $("#hidden-publi_dash_tree_view_hash" ).val(); - if (typeof(public_hash) === 'undefined') public_hash = 0; - var public_user = $("#hidden-publi_dash_tree_view_id_user" ).val(); - if (typeof(public_user) === 'undefined') public_user = 0; - - if (typeof element.searchChildren != 'undefined' && element.searchChildren) { - if(element.rootType == "group_edition" - && typeof element.children == 'undefined'){ - $node.addClass("leaf-empty"); - } - else{ - $node - .removeClass("leaf-empty") - .addClass("leaf-closed"); - $leafIcon.click(function (e) { - e.preventDefault(); - - if (!$node.hasClass("leaf-loading") && !$node.hasClass("children-loaded") && !$node.hasClass("leaf-empty")) { - $node - .removeClass("leaf-closed") - .removeClass("leaf-error") - .addClass("leaf-loading"); - - $.ajax({ - url: controller.ajaxURL, - type: 'POST', - dataType: 'json', - data: { - page: controller.ajaxPage, - getChildren: 1, - id: element.id, - type: element.type, - rootID: element.rootID, - serverID: element.serverID, - rootType: element.rootType, - filter: controller.filter, - hash: public_hash, - id_user: public_user - }, - complete: function(xhr, textStatus) { - $node.removeClass("leaf-loading"); - $node.addClass("children-loaded"); - }, - success: function(data, textStatus, xhr) { - if (data.success) { - var $group = $node.children("ul.tree-group"); - if ((typeof data.tree != 'undefined' && data.tree.length > 0) || $group.length > 0) { - $node.addClass("leaf-open"); - - if ($group.length <= 0) { - $group = $("
                  "); - $group - .addClass("tree-group") - .hide(); - $node.append($group); - } - - _.each(data.tree, function(element) { - element.jqObject = _processNode($group, element); - }); - - $group.slideDown(); - - $node.data('children', $group); - - // Add again the hover event to the 'force_callback' elements - forced_title_callback(); - } - else { - $node.addClass("leaf-empty"); - } - } - else { - $node.addClass("leaf-error"); - } - }, - error: function(xhr, textStatus, errorThrown) { - $node.addClass("leaf-error"); - } - }); - } - else if (! $node.hasClass("leaf-empty")) { - if ($node.hasClass("leaf-open")) { - $node - .removeClass("leaf-open") - .addClass("leaf-closed") - .data('children') - .slideUp(); - } - else { - $node - .removeClass("leaf-closed") - .addClass("leaf-open") - .data('children') - .slideDown(); - } - } - }); - } - } - - return $node; - } - - if (controller.recipient.length == 0) { - return; - } - else if (controller.tree.length == 0) { - controller.recipient.empty(); - controller.recipient.html("
                  " + controller.emptyMessage + "
                  "); - return; - } - - controller.recipient.empty(); - controller.recipient.html( - "
                  " + - controller.foundMessage + ": " + controller.tree.length + - "
                  " + - "
                  " - ); - - var $children = _processGroup(this.recipient, this.tree, true); - $children.show(); - - controller.recipient.data('children', $children); - - // Add again the hover event to the 'force_callback' elements - forced_title_callback(); - }, - load: function () { - this.reload(); - }, - changeTree: function (tree) { - this.tree = tree; - this.reload(); - }, - init: function (data) { - if (typeof data.recipient !== 'undefined' && data.recipient.length > 0) { - this.recipient = data.recipient; - } - if (typeof data.detailRecipient !== 'undefined') { - this.detailRecipient = data.detailRecipient; - } - if (typeof data.tree !== 'undefined') { - this.tree = data.tree; - } - if (typeof data.emptyMessage !== 'undefined' && data.emptyMessage.length > 0) { - this.emptyMessage = data.emptyMessage; - } - if (typeof data.foundMessage !== 'undefined' && data.foundMessage.length > 0) { - this.foundMessage = data.foundMessage; - } - if (typeof data.errorMessage !== 'undefined' && data.errorMessage.length > 0) { - this.errorMessage = data.errorMessage; - } - if (typeof data.baseURL !== 'undefined' && data.baseURL.length > 0) { - this.baseURL = data.baseURL; - } - if (typeof data.ajaxURL !== 'undefined' && data.ajaxURL.length > 0) { - this.ajaxURL = data.ajaxURL; - } - if (typeof data.ajaxPage !== 'undefined' && data.ajaxPage.length > 0) { - this.ajaxPage = data.ajaxPage; - } - if (typeof data.filter !== 'undefined') { - this.filter = data.filter; - } - - this.load(); - }, - remove: function () { - if (typeof this.recipient != 'undefined' && this.recipient.length > 0) { - this.recipient.empty(); - } - - if (this.index > -1) { - TreeController.controllers.splice(this.index, 1); - } - } - } - controller.index = TreeController.controllers.push(controller) - 1; - - return controller; - } -} + controllers: [], + getController: function() { + var controller = { + index: -1, + recipient: "", + tree: [], + emptyMessage: "No data found.", + foundMessage: "Found groups", + errorMessage: "Error", + baseURL: "", + ajaxURL: "ajax.php", + ajaxPage: "include/ajax/tree.ajax", + detailRecipient: "", + filter: {}, + counterTitles: {}, + shouldHaveCounters: true, + reload: function() { + // Bad recipient + if ( + typeof this.recipient == "undefined" || + this.recipient.length == 0 + ) { + return; + } + + // Load branch + function _processGroup(container, elements, rootGroup) { + var $group = $("
                    "); + + // First group + if (typeof rootGroup != "undefinded" && rootGroup == true) { + $group + .addClass("tree-root") + .hide() + .prepend( + '' + ); + } + // Normal group + else { + $group.addClass("tree-group").hide(); + } + + container.append($group); + + _.each(elements, function(element) { + element.jqObject = _processNode($group, element); + }); + + return $group; + } + + // Load leaf counters + function _processNodeCounters(container, counters, type) { + var hasCounters = false; + + if (typeof counters != "undefined") { + function _processNodeCounterTitle( + container, + elementType, + counterType + ) { + var defaultCounterTitles = { + total: { + agents: "Total agents", + modules: "Total modules", + none: "Total" + }, + alerts: { + agents: "Alerts fired", + modules: "Alerts fired", + none: "Alerts fired" + }, + critical: { + agents: "Critical agents", + modules: "Critical modules", + none: "Critical" + }, + warning: { + agents: "Warning agents", + modules: "Warning modules", + none: "Warning" + }, + unknown: { + agents: "Unknown agents", + modules: "Unknown modules", + none: "Unknown" + }, + not_init: { + agents: "Not init agents", + modules: "Not init modules", + none: "Not init" + }, + ok: { + agents: "Normal agents", + modules: "Normal modules", + none: "Normal" + } + }; + + try { + var title = ""; + switch (elementType) { + case "group": + if ( + typeof controller.counterTitles != "undefined" && + typeof controller.counterTitles[counterType] != + "undefined" && + typeof controller.counterTitles[counterType].agents != + "undefined" + ) { + title = controller.counterTitles[counterType].agents; + } else { + title = defaultCounterTitles[counterType].agents; + } + break; + case "agent": + if ( + typeof controller.counterTitles != "undefined" && + typeof controller.counterTitles[counterType] != + "undefined" && + typeof controller.counterTitles[counterType].modules != + "undefined" + ) { + title = controller.counterTitles[counterType].modules; + } else { + title = defaultCounterTitles[counterType].modules; + } + break; + default: + if ( + typeof controller.counterTitles != "undefined" && + typeof controller.counterTitles[counterType] != + "undefined" && + typeof controller.counterTitles[counterType].none != + "undefined" + ) { + title = controller.counterTitles[counterType].none; + } else { + title = defaultCounterTitles[counterType].none; + } + break; + } + if (title.length > 0) { + container + .data("title", title) + .addClass("forced_title") + .data("use_title_for_force_title", 1); // Trick to make easier the 'force title' output + } + } catch (error) { + // console.log(error); + } + } + + var $counters = $("
                    "); + $counters.addClass("tree-node-counters"); + + if (typeof counters.total != "undefined" && counters.total >= 0) { + var $totalCounter = $("
                    "); + $totalCounter + .addClass("tree-node-counter") + .addClass("total") + .html(counters.total); + + _processNodeCounterTitle($totalCounter, type, "total"); + + // Open the parentheses + $counters.append(" ("); + + $counters.append($totalCounter); + + if ( + typeof counters.alerts != "undefined" && + counters.alerts > 0 + ) { + var $firedCounter = $("
                    "); + $firedCounter + .addClass("tree-node-counter") + .addClass("alerts") + .addClass("orange") + .html(counters.alerts); + + _processNodeCounterTitle($firedCounter, type, "alerts"); + + $counters.append(" : ").append($firedCounter); + } + if ( + typeof counters.critical != "undefined" && + counters.critical > 0 + ) { + var $criticalCounter = $("
                    "); + $criticalCounter + .addClass("tree-node-counter") + .addClass("critical") + .addClass("red") + .html(counters.critical); + + _processNodeCounterTitle($criticalCounter, type, "critical"); + + $counters.append(" : ").append($criticalCounter); + } + if ( + typeof counters.warning != "undefined" && + counters.warning > 0 + ) { + var $warningCounter = $("
                    "); + $warningCounter + .addClass("tree-node-counter") + .addClass("warning") + .addClass("yellow") + .html(counters.warning); + + _processNodeCounterTitle($warningCounter, type, "warning"); + + $counters.append(" : ").append($warningCounter); + } + if ( + typeof counters.unknown != "undefined" && + counters.unknown > 0 + ) { + var $unknownCounter = $("
                    "); + $unknownCounter + .addClass("tree-node-counter") + .addClass("unknown") + .addClass("grey") + .html(counters.unknown); + + _processNodeCounterTitle($unknownCounter, type, "unknown"); + + $counters.append(" : ").append($unknownCounter); + } + if ( + typeof counters.not_init != "undefined" && + counters.not_init > 0 + ) { + var $notInitCounter = $("
                    "); + $notInitCounter + .addClass("tree-node-counter") + .addClass("not_init") + .addClass("blue") + .html(counters.not_init); + + _processNodeCounterTitle($notInitCounter, type, "not_init"); + + $counters.append(" : ").append($notInitCounter); + } + if (typeof counters.ok != "undefined" && counters.ok > 0) { + var $okCounter = $("
                    "); + $okCounter + .addClass("tree-node-counter") + .addClass("ok") + .addClass("green") + .html(counters.ok); + + _processNodeCounterTitle($okCounter, type, "ok"); + + $counters.append(" : ").append($okCounter); + } + + // Close the parentheses + $counters.append(")"); + + hasCounters = true; + } + + // Add the counters html to the container + container.append($counters); + } + + return hasCounters; + } + + // Load leaf + function _processNode(container, element) { + // type, [id], [serverID], callback + function _getTreeDetailData(type, id, serverID, callback) { + var lastParam = arguments[arguments.length - 1]; + var callback; + if (typeof lastParam === "function") callback = lastParam; + + var serverID; + if (arguments.length >= 4) serverID = arguments[2]; + var id; + if (arguments.length >= 3) id = arguments[1]; + var type; + if (arguments.length >= 2) type = arguments[0]; + + if (typeof type === "undefined") + throw new TypeError("Type required"); + if (typeof callback === "undefined") + throw new TypeError("Callback required"); + + var postData = { + page: controller.ajaxPage, + getDetail: 1, + type: type + }; + + if (typeof id !== "undefined") postData.id = id; + if (typeof serverID !== "undefined") postData.serverID = serverID; + + $.ajax({ + url: controller.ajaxURL, + type: "POST", + dataType: "html", + data: postData, + success: function(data, textStatus, xhr) { + callback(null, data); + }, + error: function(xhr, textStatus, errorThrown) { + callback(errorThrown); + } + }); + } + + var $node = $("
                  • "); + var $leafIcon = $("
                    "); + var $content = $("
                    "); + + // Leaf icon + $leafIcon.addClass("leaf-icon"); + + // Content + $content.addClass("node-content"); + switch (element.type) { + case "group": + if ( + typeof element.icon != "undefined" && + element.icon.length > 0 + ) { + $content.append( + ' ' + ); + } else if ( + typeof element.iconHTML != "undefined" && + element.iconHTML.length > 0 + ) { + $content.append(element.iconHTML + " "); + } + $content.append(element.name); + + if (typeof element.edit != "undefined") { + var url_edit = + controller.baseURL + + "index.php?sec=gagente&sec2=godmode/groups/configure_group&tab=tree&id_group=" + + element.id; + var $updateicon = $( + '' + ); + var $updatebtn = $('').append( + $updateicon + ); + $content.append($updatebtn); + } + + if (typeof element.delete != "undefined") { + var url_delete = + controller.baseURL + + "index.php?sec=gagente&sec2=godmode/groups/group_list&tab=tree&delete_group=1&id_group=" + + element.id; + var $deleteBtn = $( + '' + ); + $deleteBtn.click(function(event) { + var ok_function = function() { + window.location.replace(url_delete); + }; + display_confirm_dialog( + element.delete.messages.messg, + element.delete.messages.confirm, + element.delete.messages.cancel, + ok_function + ); + }); + $content.append($deleteBtn); + } + + if (typeof element.alerts != "undefined") { + $content.append(element.alerts); + } + + break; + case "agent": + // Is quiet + if ( + typeof element.quietImageHTML != "undefined" && + element.quietImageHTML.length > 0 + ) { + var $quietImage = $(element.quietImageHTML); + $quietImage.addClass("agent-quiet"); + + $content.append($quietImage); + } + // Status image + if ( + typeof element.statusImageHTML != "undefined" && + element.statusImageHTML.length > 0 + ) { + var $statusImage = $(element.statusImageHTML); + $statusImage.addClass("agent-status"); + + $content.append($statusImage); + } + // Alerts fired image + if ( + typeof element.alertImageHTML != "undefined" && + element.alertImageHTML.length > 0 + ) { + var $alertImage = $(element.alertImageHTML); + $alertImage.addClass("agent-alerts-fired"); + + $content.append($alertImage); + } + $content.append(element.alias); + break; + case "module": + // Status image + if ( + typeof element.statusImageHTML != "undefined" && + element.statusImageHTML.length > 0 + ) { + var $statusImage = $(element.statusImageHTML); + $statusImage.addClass("module-status"); + + $content.append($statusImage); + } + // Server type + if ( + typeof element.serverTypeHTML != "undefined" && + element.serverTypeHTML.length > 0 && + element.serverTypeHTML != "--" + ) { + var $serverTypeImage = $(element.serverTypeHTML); + $serverTypeImage.addClass("module-server-type"); + + $content.append($serverTypeImage); + } + + if ( + typeof element.showGraphs != "undefined" && + element.showGraphs != 0 + ) { + // Graph pop-up + if (typeof element.moduleGraph != "undefined") { + if (element.statusImageHTML.indexOf("data:image") != -1) { + var $graphImage = $( + ' ' + ); + } else { + var $graphImage = $( + ' ' + ); + } + + $graphImage.addClass("module-graph").click(function(e) { + e.preventDefault(); + if (element.statusImageHTML.indexOf("data:image") != -1) { + try { + winopeng_var( + decodeURI(element.snapshot[0]), + element.snapshot[1], + element.snapshot[2], + element.snapshot[3] + ); + } catch (error) { + // console.log(error); + } + } else { + try { + winopeng( + element.moduleGraph.url, + element.moduleGraph.handle + ); + } catch (error) { + // console.log(error); + } + } + }); + + $content.append($graphImage); + } + + // Data pop-up + if (typeof element.id != "undefined" && !isNaN(element.id)) { + var $dataImage = $( + ' ' + ); + $dataImage.addClass("module-data").click(function(e) { + e.preventDefault(); + + try { + var serverName = + element.serverName.length > 0 ? element.serverName : ""; + if ($("#module_details_window").length > 0) + show_module_detail_dialog( + element.id, + "", + serverName, + 0, + 86400, + element.name.replace(/ /g, " ") + ); + } catch (error) { + // console.log(error); + } + }); + + $content.append($dataImage); + } + } + + // Alerts + if ( + typeof element.alertsImageHTML != "undefined" && + element.alertsImageHTML.length > 0 + ) { + var $alertsImage = $(element.alertsImageHTML); + + $alertsImage + .addClass("module-alerts") + .click(function(e) { + _getTreeDetailData( + "alert", + element.id, + element.serverID, + function(error, data) { + if (error) { + // console.error(error); + } else { + controller.detailRecipient + .render(element.name, data) + .open(); + } + } + ); + + // Avoid the execution of the module detail event + e.stopPropagation(); + }) + .css("cursor", "pointer"); + + $content.append($alertsImage); + } + + $content.append(element.name); + break; + case "os": + if ( + typeof element.icon != "undefined" && + element.icon.length > 0 + ) { + $content.append( + ' ' + ); + } + $content.append(element.name); + break; + case "tag": + if ( + typeof element.icon != "undefined" && + element.icon.length > 0 + ) { + $content.append( + ' ' + ); + } else { + $content.append( + ' ' + ); + } + $content.append(element.name); + break; + default: + $content.append(element.name); + break; + } + + // Load the status counters + var hasCounters = _processNodeCounters( + $content, + element.counters, + element.type + ); + //Don't show empty groups + if (element.type == "agent") { + if (!hasCounters) { + return; + } + } + // If exist the detail container, show the data + if (typeof controller.detailRecipient !== "undefined") { + if (element.type == "agent" || element.type == "module") { + $content + .click(function(e) { + _getTreeDetailData( + element.type, + element.id, + element.serverID, + function(error, data) { + if (error) { + // console.error(error); + } else { + controller.detailRecipient + .render(element.name, data) + .open(); + } + } + ); + }) + .css("cursor", "pointer"); + } + } + + $node + .addClass("tree-node") + .append($leafIcon) + .append($content); + + container.append($node); + + $node.addClass("leaf-empty"); + + if ( + typeof element.children != "undefined" && + element.children.length > 0 + ) { + $node.removeClass("leaf-empty").addClass("leaf-closed"); + + // Add children + var $children = _processGroup($node, element.children); + $node.data("children", $children); + + if ( + typeof element.searchChildren == "undefined" || + !element.searchChildren + ) { + $leafIcon.click(function(e) { + e.preventDefault(); + + if ($node.hasClass("leaf-open")) { + $node + .removeClass("leaf-open") + .addClass("leaf-closed") + .data("children") + .slideUp(); + } else { + $node + .removeClass("leaf-closed") + .addClass("leaf-open") + .data("children") + .slideDown(); + } + }); + } + } + // Get hash and user. + var public_hash = $("#hidden-publi_dash_tree_view_hash").val(); + if (typeof public_hash === "undefined") public_hash = 0; + var public_user = $("#hidden-publi_dash_tree_view_id_user").val(); + if (typeof public_user === "undefined") public_user = 0; + + if ( + typeof element.searchChildren != "undefined" && + element.searchChildren + ) { + if ( + element.rootType == "group_edition" && + typeof element.children == "undefined" + ) { + $node.addClass("leaf-empty"); + } else { + $node.removeClass("leaf-empty").addClass("leaf-closed"); + $leafIcon.click(function(e) { + e.preventDefault(); + + if ( + !$node.hasClass("leaf-loading") && + !$node.hasClass("children-loaded") && + !$node.hasClass("leaf-empty") + ) { + $node + .removeClass("leaf-closed") + .removeClass("leaf-error") + .addClass("leaf-loading"); + + $.ajax({ + url: controller.ajaxURL, + type: "POST", + dataType: "json", + data: { + page: controller.ajaxPage, + getChildren: 1, + id: element.id, + type: element.type, + rootID: element.rootID, + serverID: element.serverID, + rootType: element.rootType, + filter: controller.filter, + hash: public_hash, + id_user: public_user + }, + complete: function(xhr, textStatus) { + $node.removeClass("leaf-loading"); + $node.addClass("children-loaded"); + }, + success: function(data, textStatus, xhr) { + if (data.success) { + var $group = $node.children("ul.tree-group"); + if ( + (typeof data.tree != "undefined" && + data.tree.length > 0) || + $group.length > 0 + ) { + $node.addClass("leaf-open"); + + if ($group.length <= 0) { + $group = $("
                      "); + $group.addClass("tree-group").hide(); + $node.append($group); + } + + _.each(data.tree, function(element) { + element.jqObject = _processNode($group, element); + }); + + $group.slideDown(); + + $node.data("children", $group); + + // Add again the hover event to the 'force_callback' elements + forced_title_callback(); + } else { + $node.addClass("leaf-empty"); + } + } else { + $node.addClass("leaf-error"); + } + }, + error: function(xhr, textStatus, errorThrown) { + $node.addClass("leaf-error"); + } + }); + } else if (!$node.hasClass("leaf-empty")) { + if ($node.hasClass("leaf-open")) { + $node + .removeClass("leaf-open") + .addClass("leaf-closed") + .data("children") + .slideUp(); + } else { + $node + .removeClass("leaf-closed") + .addClass("leaf-open") + .data("children") + .slideDown(); + } + } + }); + } + } + + return $node; + } + + if (controller.recipient.length == 0) { + return; + } else if (controller.tree.length == 0) { + controller.recipient.empty(); + controller.recipient.html( + "
                      " + controller.emptyMessage + "
                      " + ); + return; + } + + controller.recipient.empty(); + controller.recipient.html( + "
                      " + + controller.foundMessage + + ": " + + controller.tree.length + + "
                      " + + "
                      " + ); + + var $children = _processGroup(this.recipient, this.tree, true); + $children.show(); + + controller.recipient.data("children", $children); + + // Add again the hover event to the 'force_callback' elements + forced_title_callback(); + }, + load: function() { + this.reload(); + }, + changeTree: function(tree) { + this.tree = tree; + this.reload(); + }, + init: function(data) { + if ( + typeof data.recipient !== "undefined" && + data.recipient.length > 0 + ) { + this.recipient = data.recipient; + } + if (typeof data.detailRecipient !== "undefined") { + this.detailRecipient = data.detailRecipient; + } + if (typeof data.tree !== "undefined") { + this.tree = data.tree; + } + if ( + typeof data.emptyMessage !== "undefined" && + data.emptyMessage.length > 0 + ) { + this.emptyMessage = data.emptyMessage; + } + if ( + typeof data.foundMessage !== "undefined" && + data.foundMessage.length > 0 + ) { + this.foundMessage = data.foundMessage; + } + if ( + typeof data.errorMessage !== "undefined" && + data.errorMessage.length > 0 + ) { + this.errorMessage = data.errorMessage; + } + if (typeof data.baseURL !== "undefined" && data.baseURL.length > 0) { + this.baseURL = data.baseURL; + } + if (typeof data.ajaxURL !== "undefined" && data.ajaxURL.length > 0) { + this.ajaxURL = data.ajaxURL; + } + if (typeof data.ajaxPage !== "undefined" && data.ajaxPage.length > 0) { + this.ajaxPage = data.ajaxPage; + } + if (typeof data.filter !== "undefined") { + this.filter = data.filter; + } + + this.load(); + }, + remove: function() { + if (typeof this.recipient != "undefined" && this.recipient.length > 0) { + this.recipient.empty(); + } + + if (this.index > -1) { + TreeController.controllers.splice(this.index, 1); + } + } + }; + controller.index = TreeController.controllers.push(controller) - 1; + + return controller; + } +}; diff --git a/pandora_console/include/javascript/update_manager.js b/pandora_console/include/javascript/update_manager.js index 89852e1030..a091b9c504 100644 --- a/pandora_console/include/javascript/update_manager.js +++ b/pandora_console/include/javascript/update_manager.js @@ -1,1611 +1,2292 @@ var correct_install_progress = true; -function form_upload (homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - - //Thanks to: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/ - var ul = $('#form-offline_update ul'); - - $('#form-offline_update div') - .prop("id", "drop_file"); - $('#drop_file') - .html(drop_the_package_here_or + - '   ' + browse_it +'' + - ''); - $('#drop_file a').click(function() { - // Simulate a click on the file input button to show the file browser dialog - $(this).parent().find('input').click(); - }); - - // Initialize the jQuery File Upload plugin - $('#form-offline_update').fileupload({ - - url: home_url + 'ajax.php?page=include/ajax/update_manager.ajax&upload_file=true', - - // This element will accept file drag/drop uploading - dropZone: $('#drop_file'), - - // This function is called when a file is added to the queue; - // either via the browse button, or via drag/drop: - add: function (e, data) { - $('#drop_file').slideUp(); - - var tpl = $('
                    • ' + - '' + - '

                      ' + - '
                    • '); - - // Append the file name and file size - tpl.find('p').text(data.files[0].name) - .append('' + formatFileSize(data.files[0].size) + ''); - - // Add the HTML to the UL element - ul.html(""); - data.context = tpl.appendTo(ul); - - // Initialize the knob plugin - tpl.find('input').val(0); - tpl.find('input').knob({ - 'draw' : function () { - $(this.i).val(this.cv + '%') - } - }); - - // Listen for clicks on the cancel icon - tpl.find('span').click(function() { - - if (tpl.hasClass('working') && typeof jqXHR != 'undefined') { - jqXHR.abort(); - } - - tpl.fadeOut(function() { - tpl.remove(); - $('#drop_file').slideDown(); - }); - - }); - - // Automatically upload the file once it is added to the queue - data.context.addClass('working'); - var jqXHR = data.submit(); - }, - - progress: function(e, data) { - - // Calculate the completion percentage of the upload - var progress = parseInt(data.loaded / data.total * 100, 10); - - // Update the hidden input field and trigger a change - // so that the jQuery knob plugin knows to update the dial - data.context.find('input').val(progress).change(); - - if (progress == 100) { - data.context.removeClass('working'); - // Class loading while the zip is extracted - data.context.addClass('loading'); - } - }, - - fail: function(e, data) { - // Something has gone wrong! - data.context.removeClass('working'); - data.context.removeClass('loading'); - data.context.addClass('error'); - }, - - done: function (e, data) { - - var res = JSON.parse(data.result); - - if (res.status == "success") { - data.context.removeClass('loading'); - data.context.addClass('suc'); - - ul.find('li').find('span').unbind("click"); - - // Transform the file input zone to show messages - $('#drop_file').prop('id', 'log_zone'); - - // Success messages - $('#log_zone').html("
                      " + the_package_has_been_uploaded_successfully + "
                      "); - $('#log_zone').append("
                      " + remember_that_this_package_will + "
                      "); - $('#log_zone').append("
                      " + click_on_the_file_below_to_begin + "
                      "); - - // Show messages - $('#log_zone').slideDown(400, function() { - $('#log_zone').height(75); - $('#log_zone').css("overflow", "auto"); - }); - - // Bind the the begin of the installation to the package li - ul.find('li').css("cursor", "pointer"); - ul.find('li').click(function () { - - ul.find('li').unbind("click"); - ul.find('li').css("cursor", "default"); - - // Change the log zone to show the copied files - $('#log_zone').html(""); - $('#log_zone').slideUp(200, function() { - $('#log_zone').slideDown(200, function() { - $('#log_zone').height(200); - $('#log_zone').css("overflow", "auto"); - }); - }); - - // Changed the data that shows the file li - data.context.find('p').text(updating + "..."); - data.context.find('input').val(0).change(); - - // Begin the installation - install_package(res.package, homeurl); - }); - } - else { - // Something has gone wrong! - data.context.removeClass('loading'); - data.context.addClass('error'); - ul.find('li').find('span').click( - function() { window.location.reload(); }); - - // Transform the file input zone to show messages - $('#drop_file').prop('id', 'log_zone'); - - // Error messages - $('#log_zone').html("
                      "+res.message+"
                      "); - - // Show error messages - $('#log_zone').slideDown(400, function() { - $('#log_zone').height(75); - $('#log_zone').css("overflow", "auto"); - }); - } - } - - }); - - // Prevent the default action when a file is dropped on the window - $(document).on('drop_file dragover', function (e) { - e.preventDefault(); - }); +function form_upload(homeurl) { + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; + + //Thanks to: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/ + var ul = $("#form-offline_update ul"); + + $("#form-offline_update div").prop("id", "drop_file"); + $("#drop_file").html( + drop_the_package_here_or + + "   " + + browse_it + + "" + + '' + ); + $("#drop_file a").click(function() { + // Simulate a click on the file input button to show the file browser dialog + $(this) + .parent() + .find("input") + .click(); + }); + + // Initialize the jQuery File Upload plugin + $("#form-offline_update").fileupload({ + url: + home_url + + "ajax.php?page=include/ajax/update_manager.ajax&upload_file=true", + + // This element will accept file drag/drop uploading + dropZone: $("#drop_file"), + + // This function is called when a file is added to the queue; + // either via the browse button, or via drag/drop: + add: function(e, data) { + $("#drop_file").slideUp(); + + var tpl = $( + "
                    • " + + '' + + "

                      " + + "
                    • " + ); + + // Append the file name and file size + tpl + .find("p") + .text(data.files[0].name) + .append("" + formatFileSize(data.files[0].size) + ""); + + // Add the HTML to the UL element + ul.html(""); + data.context = tpl.appendTo(ul); + + // Initialize the knob plugin + tpl.find("input").val(0); + tpl.find("input").knob({ + draw: function() { + $(this.i).val(this.cv + "%"); + } + }); + + // Listen for clicks on the cancel icon + tpl.find("span").click(function() { + if (tpl.hasClass("working") && typeof jqXHR != "undefined") { + jqXHR.abort(); + } + + tpl.fadeOut(function() { + tpl.remove(); + $("#drop_file").slideDown(); + }); + }); + + // Automatically upload the file once it is added to the queue + data.context.addClass("working"); + var jqXHR = data.submit(); + }, + + progress: function(e, data) { + // Calculate the completion percentage of the upload + var progress = parseInt((data.loaded / data.total) * 100, 10); + + // Update the hidden input field and trigger a change + // so that the jQuery knob plugin knows to update the dial + data.context + .find("input") + .val(progress) + .change(); + + if (progress == 100) { + data.context.removeClass("working"); + // Class loading while the zip is extracted + data.context.addClass("loading"); + } + }, + + fail: function(e, data) { + // Something has gone wrong! + data.context.removeClass("working"); + data.context.removeClass("loading"); + data.context.addClass("error"); + }, + + done: function(e, data) { + var res = JSON.parse(data.result); + + if (res.status == "success") { + data.context.removeClass("loading"); + data.context.addClass("suc"); + + ul.find("li") + .find("span") + .unbind("click"); + + // Transform the file input zone to show messages + $("#drop_file").prop("id", "log_zone"); + + // Success messages + $("#log_zone").html( + "
                      " + the_package_has_been_uploaded_successfully + "
                      " + ); + $("#log_zone").append( + "
                      " + remember_that_this_package_will + "
                      " + ); + $("#log_zone").append( + "
                      " + click_on_the_file_below_to_begin + "
                      " + ); + + // Show messages + $("#log_zone").slideDown(400, function() { + $("#log_zone").height(75); + $("#log_zone").css("overflow", "auto"); + }); + + // Bind the the begin of the installation to the package li + ul.find("li").css("cursor", "pointer"); + ul.find("li").click(function() { + ul.find("li").unbind("click"); + ul.find("li").css("cursor", "default"); + + // Change the log zone to show the copied files + $("#log_zone").html(""); + $("#log_zone").slideUp(200, function() { + $("#log_zone").slideDown(200, function() { + $("#log_zone").height(200); + $("#log_zone").css("overflow", "auto"); + }); + }); + + // Changed the data that shows the file li + data.context.find("p").text(updating + "..."); + data.context + .find("input") + .val(0) + .change(); + + // Begin the installation + install_package(res.package, homeurl); + }); + } else { + // Something has gone wrong! + data.context.removeClass("loading"); + data.context.addClass("error"); + ul.find("li") + .find("span") + .click(function() { + window.location.reload(); + }); + + // Transform the file input zone to show messages + $("#drop_file").prop("id", "log_zone"); + + // Error messages + $("#log_zone").html("
                      " + res.message + "
                      "); + + // Show error messages + $("#log_zone").slideDown(400, function() { + $("#log_zone").height(75); + $("#log_zone").css("overflow", "auto"); + }); + } + } + }); + + // Prevent the default action when a file is dropped on the window + $(document).on("drop_file dragover", function(e) { + e.preventDefault(); + }); } // Helper function that formats the file sizes function formatFileSize(bytes) { - if (typeof bytes !== 'number') { - return ''; - } - - if (bytes >= 1000000000) { - return (bytes / 1000000000).toFixed(2) + ' GB'; - } - - if (bytes >= 1000000) { - return (bytes / 1000000).toFixed(2) + ' MB'; - } - - return (bytes / 1000).toFixed(2) + ' KB'; + if (typeof bytes !== "number") { + return ""; + } + + if (bytes >= 1000000000) { + return (bytes / 1000000000).toFixed(2) + " GB"; + } + + if (bytes >= 1000000) { + return (bytes / 1000000).toFixed(2) + " MB"; + } + + return (bytes / 1000).toFixed(2) + " KB"; } -function install_package (package, homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); +function install_package(package, homeurl) { + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['search_minor'] = 1; - parameters['package'] = package; - parameters['ent'] = 1; - parameters['offline'] = 1; - - $.ajax({ - type: 'POST', - url: home_url + 'ajax.php', - data: parameters, - dataType: "json", - success: function (data) { - if (data['have_minor']) { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 270, - buttons: [{ - text:apply_mr_button, - click: function () { - var err = []; - err = apply_minor_release(data['mr'], package, 1, 1, home_url); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); - if (!err['error']) { - if (err['message'] == 'bad_mr_filename') { - $("#mr_dialog2").dialog("close"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 270, - buttons: [{ - text:apply_button, - click: function() { - $(this).dialog("close"); + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["search_minor"] = 1; + parameters["package"] = package; + parameters["ent"] = 1; + parameters["offline"] = 1; - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $.ajax({ + type: "POST", + url: home_url + "ajax.php", + data: parameters, + dataType: "json", + success: function(data) { + if (data["have_minor"]) { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 270, + buttons: [ + { + text: apply_mr_button, + click: function() { + var err = []; + err = apply_minor_release( + data["mr"], + package, + 1, + 1, + home_url + ); - var dialog_accept_package_mr_fail_text = "
                      "; - dialog_accept_package_mr_fail_text = dialog_accept_package_mr_fail_text + "
                      "; - dialog_accept_package_mr_fail_text = dialog_accept_package_mr_fail_text + "

                      INFO

                      "; - dialog_accept_package_mr_fail_text = dialog_accept_package_mr_fail_text + "

                      " + mr_not_accepted_code_yes + "

                      "; - dialog_accept_package_mr_fail_text = dialog_accept_package_mr_fail_text + "
                      "; - - $('#accept_package_mr_fail').html(dialog_accept_package_mr_fail_text); - $('#accept_package_mr_fail').dialog('open'); + if (!err["error"]) { + if (err["message"] == "bad_mr_filename") { + $("#mr_dialog2").dialog("close"); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 270, + buttons: [ + { + text: apply_button, + click: function() { + $(this).dialog("close"); - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['install_package'] = 1; - parameters['package'] = package; - parameters['accept'] = 1; - - $('#form-offline_update ul').find('li').removeClass('suc'); - $('#form-offline_update ul').find('li').addClass('loading'); - - $.ajax({ - type: 'POST', - url: home_url + 'ajax.php', - data: parameters, - dataType: "json", - success: function (data) { - $('#form-offline_update ul').find('li').removeClass('loading'); - if (data.status == "success") { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var dialog_success_pkg_text = "
                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "

                      SUCCESS

                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "

                      " + package_success + "

                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - - $('#success_pkg').html(dialog_success_pkg_text); - $('#success_pkg').dialog('open'); + var dialog_accept_package_mr_fail_text = + "
                      "; + dialog_accept_package_mr_fail_text = + dialog_accept_package_mr_fail_text + + "
                      "; + dialog_accept_package_mr_fail_text = + dialog_accept_package_mr_fail_text + + "

                      INFO

                      "; + dialog_accept_package_mr_fail_text = + dialog_accept_package_mr_fail_text + + "

                      " + + mr_not_accepted_code_yes + + "

                      "; + dialog_accept_package_mr_fail_text = + dialog_accept_package_mr_fail_text + + "
                      "; - $('#form-offline_update ul').find('li').addClass('suc'); - $('#form-offline_update ul').find('li').find('p').html(package_updated_successfully) - .append("" + if_there_are_any_database_change + ""); - } - else { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#accept_package_mr_fail").html( + dialog_accept_package_mr_fail_text + ); + $("#accept_package_mr_fail").dialog("open"); - var dialog_error_pkg_text = "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      ERROR

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      " + package_error + "

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - - $('#error_pkg').html(dialog_error_pkg_text); - $('#error_pkg').dialog('open'); + var parameters = {}; + parameters["page"] = + "include/ajax/update_manager.ajax"; + parameters["install_package"] = 1; + parameters["package"] = package; + parameters["accept"] = 1; - $('#form-offline_update ul').find('li').addClass('error'); - $('#form-offline_update ul').find('li').find('p').html(package_not_updated) - .append(""+data.message+""); - } - $('#form-offline_update ul').find('li').css("cursor", "pointer"); - $('#form-offline_update ul').find('li').click(function() { - window.location.reload(); - }); - } - }); - - // Check the status of the update - check_install_package(package, homeurl); - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); + $("#form-offline_update ul") + .find("li") + .removeClass("suc"); + $("#form-offline_update ul") + .find("li") + .addClass("loading"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 220, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $.ajax({ + type: "POST", + url: home_url + "ajax.php", + data: parameters, + dataType: "json", + success: function(data) { + $("#form-offline_update ul") + .find("li") + .removeClass("loading"); + if (data.status == "success") { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var dialog_cancel_pkg_text = "
                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "

                      INFO

                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "

                      " + package_cancel + "

                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; - - $('#cancel_pkg').html(dialog_cancel_pkg_text); - $('#cancel_pkg').dialog('open'); + var dialog_success_pkg_text = "
                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "
                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "

                      SUCCESS

                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "

                      " + + package_success + + "

                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + "
                      "; - $('#form-offline_update ul').find('li').removeClass('loading'); - $('#form-offline_update ul').find('li').addClass('error'); - $('#form-offline_update ul').find('li').find('p').html(mr_not_accepted) - .append(""+data.message+""); - } - }] - }); + $("#success_pkg").html( + dialog_success_pkg_text + ); + $("#success_pkg").dialog("open"); - var dialog_bad_message_text = "
                      "; - dialog_bad_message_text = dialog_bad_message_text + "
                      "; - dialog_bad_message_text = dialog_bad_message_text + "

                      ERROR

                      "; - dialog_bad_message_text = dialog_bad_message_text + "

                      " + bad_mr_file + "

                      "; - dialog_bad_message_text = dialog_bad_message_text + "
                      "; - - $('#bad_message').html(dialog_bad_message_text); - $('#bad_message').dialog('open'); - } - else { - $("#mr_dialog2").dialog("close"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#form-offline_update ul") + .find("li") + .addClass("suc"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_updated_successfully) + .append( + "" + + if_there_are_any_database_change + + "" + ); + } else { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var dialog_success_mr_text = "
                      "; - dialog_success_mr_text = dialog_success_mr_text + "
                      "; - dialog_success_mr_text = dialog_success_mr_text + "

                      SUCCESS

                      "; - dialog_success_mr_text = dialog_success_mr_text + "

                      " + mr_success + "

                      "; - dialog_success_mr_text = dialog_success_mr_text + "
                      "; - - $('#success_mr').html(dialog_success_mr_text); - $('#success_mr').dialog('open'); + var dialog_error_pkg_text = "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      ERROR

                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      " + + package_error + + "

                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + "
                      "; - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['install_package'] = 1; - parameters['package'] = package; - parameters['accept'] = 1; - - $('#form-offline_update ul').find('li').removeClass('suc'); - $('#form-offline_update ul').find('li').addClass('loading'); - - $.ajax({ - type: 'POST', - url: home_url + 'ajax.php', - data: parameters, - dataType: "json", - success: function (data) { - $('#form-offline_update ul').find('li').removeClass('loading'); - if (data.status == "success") { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#error_pkg").html( + dialog_error_pkg_text + ); + $("#error_pkg").dialog("open"); - var dialog_success_pkg_text = "
                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "

                      SUCCESS

                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "

                      " + package_success + "

                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - - $('#success_pkg').html(dialog_success_pkg_text); - $('#success_pkg').dialog('open'); + $("#form-offline_update ul") + .find("li") + .addClass("error"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_not_updated) + .append( + "" + data.message + "" + ); + } + $("#form-offline_update ul") + .find("li") + .css("cursor", "pointer"); + $("#form-offline_update ul") + .find("li") + .click(function() { + window.location.reload(); + }); + } + }); - $('#form-offline_update ul').find('li').addClass('suc'); - $('#form-offline_update ul').find('li').find('p').html(package_updated_successfully) - .append("" + if_there_are_any_database_change + ""); - } - else { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + // Check the status of the update + check_install_package(package, homeurl); + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); - var dialog_error_pkg_text = "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      ERROR

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      " + package_error + "

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - - $('#error_pkg').html(dialog_error_pkg_text); - $('#error_pkg').dialog('open'); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 220, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - $('#form-offline_update ul').find('li').addClass('error'); - $('#form-offline_update ul').find('li').find('p').html(package_not_updated) - .append(""+data.message+""); - } - $('#form-offline_update ul').find('li').css("cursor", "pointer"); - $('#form-offline_update ul').find('li').click(function() { - window.location.reload(); - }); - } - }); - - // Check the status of the update - check_install_package(package, homeurl); + var dialog_cancel_pkg_text = "
                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "
                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "

                      INFO

                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "

                      " + + package_cancel + + "

                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + "
                      "; - remove_rr_file(data['mr'], home_url); - } - } - else { - $("#mr_dialog2").dialog("close"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#cancel_pkg").html( + dialog_cancel_pkg_text + ); + $("#cancel_pkg").dialog("open"); - var dialog_error_mr_text = "
                      "; - dialog_error_mr_text = dialog_error_mr_text + "
                      "; - dialog_error_mr_text = dialog_error_mr_text + "

                      ERROR

                      "; - dialog_error_mr_text = dialog_error_mr_text + "

                      " + mr_error + "

                      "; - dialog_error_mr_text = dialog_error_mr_text + "
                      "; - - $('#error_mr').html(dialog_error_mr_text); - $('#error_mr').dialog('open'); + $("#form-offline_update ul") + .find("li") + .removeClass("loading"); + $("#form-offline_update ul") + .find("li") + .addClass("error"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(mr_not_accepted) + .append("" + data.message + ""); + } + } + ] + }); - $('#form-offline_update ul').find('li').addClass('error'); - $('#form-offline_update ul').find('li').find('p').html(error_in_mr) - .append(""+data.message+""); - } - } - }, - { - text:cancel_button, - click: function () { - $("#mr_dialog2").dialog("close"); + var dialog_bad_message_text = "
                      "; + dialog_bad_message_text = + dialog_bad_message_text + + "
                      "; + dialog_bad_message_text = + dialog_bad_message_text + + "

                      ERROR

                      "; + dialog_bad_message_text = + dialog_bad_message_text + + "

                      " + + bad_mr_file + + "

                      "; + dialog_bad_message_text = + dialog_bad_message_text + "
                      "; - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 220, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#bad_message").html(dialog_bad_message_text); + $("#bad_message").dialog("open"); + } else { + $("#mr_dialog2").dialog("close"); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var dialog_cancel_mr_text = "
                      "; - dialog_cancel_mr_text = dialog_cancel_mr_text + "
                      "; - dialog_cancel_mr_text = dialog_cancel_mr_text + "

                      INFO

                      "; - dialog_cancel_mr_text = dialog_cancel_mr_text + "

                      " + mr_cancel + "

                      "; - dialog_cancel_mr_text = dialog_cancel_mr_text + "
                      "; - - $('#cancel_mr').html(dialog_cancel_mr_text); - $('#cancel_mr').dialog('open'); + var dialog_success_mr_text = "
                      "; + dialog_success_mr_text = + dialog_success_mr_text + + "
                      "; + dialog_success_mr_text = + dialog_success_mr_text + + "

                      SUCCESS

                      "; + dialog_success_mr_text = + dialog_success_mr_text + + "

                      " + + mr_success + + "

                      "; + dialog_success_mr_text = + dialog_success_mr_text + "
                      "; - $('#form-offline_update ul').find('li').removeClass('loading'); - $('#form-offline_update ul').find('li').addClass('error'); - $('#form-offline_update ul').find('li').find('p').html(mr_not_accepted) - .append(""+data.message+""); - } - }] - }); + $("#success_mr").html(dialog_success_mr_text); + $("#success_mr").dialog("open"); - $('button:contains(Apply MR)').attr("id","apply_rr_button"); - $('button:contains(Cancel)').attr("id","cancel_rr_button"); - - var dialog_have_mr_text = "
                      "; - dialog_have_mr_text = dialog_have_mr_text + "
                      "; - dialog_have_mr_text = dialog_have_mr_text + "

                      " + mr_available_header + "

                      "; - dialog_have_mr_text = dialog_have_mr_text + "

                      " + text1_mr_file + "

                      "; - dialog_have_mr_text = dialog_have_mr_text + "

                      " + text2_mr_file + "" + text3_mr_file + "" + text4_mr_file + "

                      "; - dialog_have_mr_text = dialog_have_mr_text + "
                      "; - - $('#mr_dialog2').html(dialog_have_mr_text); - $('#mr_dialog2').dialog('open'); - } - else { - $("#pkg_apply_dialog").dialog("close"); + var parameters = {}; + parameters["page"] = + "include/ajax/update_manager.ajax"; + parameters["install_package"] = 1; + parameters["package"] = package; + parameters["accept"] = 1; - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['install_package'] = 1; - parameters['package'] = package; - parameters['accept'] = 1; - - $('#form-offline_update ul').find('li').removeClass('suc'); - $('#form-offline_update ul').find('li').addClass('loading'); - - $.ajax({ - type: 'POST', - url: home_url + 'ajax.php', - data: parameters, - dataType: "json", - success: function (data) { - $('#form-offline_update ul').find('li').removeClass('loading'); - if (data.status == "success") { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#form-offline_update ul") + .find("li") + .removeClass("suc"); + $("#form-offline_update ul") + .find("li") + .addClass("loading"); - var dialog_success_pkg_text = "
                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "

                      SUCCESS

                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "

                      " + package_success + "

                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - - $('#success_pkg').html(dialog_success_pkg_text); - $('#success_pkg').dialog('open'); + $.ajax({ + type: "POST", + url: home_url + "ajax.php", + data: parameters, + dataType: "json", + success: function(data) { + $("#form-offline_update ul") + .find("li") + .removeClass("loading"); + if (data.status == "success") { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - $('#form-offline_update ul').find('li').addClass('suc'); - $('#form-offline_update ul').find('li').find('p').html(package_updated_successfully) - .append("" + if_there_are_any_database_change + ""); - } - else { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + var dialog_success_pkg_text = "
                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "
                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "

                      SUCCESS

                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "

                      " + + package_success + + "

                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + "
                      "; - var dialog_error_pkg_text = "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      ERROR

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      " + package_error + "

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - - $('#error_pkg').html(dialog_error_pkg_text); - $('#error_pkg').dialog('open'); + $("#success_pkg").html( + dialog_success_pkg_text + ); + $("#success_pkg").dialog("open"); - $('#form-offline_update ul').find('li').addClass('error'); - $('#form-offline_update ul').find('li').find('p').html(package_not_updated) - .append(""+data.message+""); - } - $('#form-offline_update ul').find('li').css("cursor", "pointer"); - $('#form-offline_update ul').find('li').click(function() { - window.location.reload(); - }); - } - }); - - // Check the status of the update - check_install_package(package, homeurl); + $("#form-offline_update ul") + .find("li") + .addClass("suc"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_updated_successfully) + .append( + "" + + if_there_are_any_database_change + + "" + ); + } else { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - remove_rr_file_to_extras(home_url); - } - } - }); - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); + var dialog_error_pkg_text = "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      ERROR

                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      " + + package_error + + "

                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + "
                      "; - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 220, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#error_pkg").html(dialog_error_pkg_text); + $("#error_pkg").dialog("open"); - var dialog_cancel_pkg_text = "
                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "

                      INFO

                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "

                      " + package_cancel + "

                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; + $("#form-offline_update ul") + .find("li") + .addClass("error"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_not_updated) + .append("" + data.message + ""); + } + $("#form-offline_update ul") + .find("li") + .css("cursor", "pointer"); + $("#form-offline_update ul") + .find("li") + .click(function() { + window.location.reload(); + }); + } + }); - $('#cancel_pkg').html(dialog_cancel_pkg_text); - $('#cancel_pkg').dialog('open'); + // Check the status of the update + check_install_package(package, homeurl); - $('#form-offline_update ul').find('li').removeClass('loading'); - $('#form-offline_update ul').find('li').addClass('error'); - $('#form-offline_update ul').find('li').find('p').html(package_not_accepted) - .append(""+data.message+""); + remove_rr_file(data["mr"], home_url); + } + } else { + $("#mr_dialog2").dialog("close"); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['install_package'] = 1; - parameters['package'] = package; - parameters['accept'] = 0; - - $('#form-offline_update ul').find('li').removeClass('suc'); - $('#form-offline_update ul').find('li').addClass('loading'); - - $.ajax({ - type: 'POST', - url: home_url + 'ajax.php', - data: parameters, - dataType: "json", - success: function (data) { - $('#form-offline_update ul').find('li').removeClass('loading'); - if (data.status == "success") { - $('#form-offline_update ul').find('li').addClass('suc'); - $('#form-offline_update ul').find('li').find('p').html(package_updated_successfully) - .append("" + if_there_are_any_database_change + ""); - } - else { - $('#form-offline_update ul').find('li').addClass('error'); - $('#form-offline_update ul').find('li').find('p').html(package_not_updated) - .append(""+data.message+""); - } - $('#form-offline_update ul').find('li').css("cursor", "pointer"); - $('#form-offline_update ul').find('li').click(function() { - window.location.reload(); - }); - } - }); - - // Check the status of the update - check_install_package(package, homeurl); - } - }] - }); + var dialog_error_mr_text = "
                      "; + dialog_error_mr_text = + dialog_error_mr_text + + "
                      "; + dialog_error_mr_text = + dialog_error_mr_text + + "

                      ERROR

                      "; + dialog_error_mr_text = + dialog_error_mr_text + + "

                      " + + mr_error + + "

                      "; + dialog_error_mr_text = + dialog_error_mr_text + "
                      "; - var dialog_text = "
                      "; - dialog_text = dialog_text + "
                      "; - dialog_text = dialog_text + "

                      " + text1_package_file + "

                      "; - dialog_text = dialog_text + "

                      " + text2_package_file + "

                      "; - dialog_text = dialog_text + "
                      "; - - $('#pkg_apply_dialog').html(dialog_text); - $('#pkg_apply_dialog').dialog('open'); + $("#error_mr").html(dialog_error_mr_text); + $("#error_mr").dialog("open"); + + $("#form-offline_update ul") + .find("li") + .addClass("error"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(error_in_mr) + .append("" + data.message + ""); + } + } + }, + { + text: cancel_button, + click: function() { + $("#mr_dialog2").dialog("close"); + + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 220, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_cancel_mr_text = "
                      "; + dialog_cancel_mr_text = + dialog_cancel_mr_text + + "
                      "; + dialog_cancel_mr_text = + dialog_cancel_mr_text + + "

                      INFO

                      "; + dialog_cancel_mr_text = + dialog_cancel_mr_text + + "

                      " + + mr_cancel + + "

                      "; + dialog_cancel_mr_text = + dialog_cancel_mr_text + "
                      "; + + $("#cancel_mr").html(dialog_cancel_mr_text); + $("#cancel_mr").dialog("open"); + + $("#form-offline_update ul") + .find("li") + .removeClass("loading"); + $("#form-offline_update ul") + .find("li") + .addClass("error"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(mr_not_accepted) + .append("" + data.message + ""); + } + } + ] + }); + + $("button:contains(Apply MR)").attr("id", "apply_rr_button"); + $("button:contains(Cancel)").attr("id", "cancel_rr_button"); + + var dialog_have_mr_text = "
                      "; + dialog_have_mr_text = + dialog_have_mr_text + + "
                      "; + dialog_have_mr_text = + dialog_have_mr_text + + "

                      " + + mr_available_header + + "

                      "; + dialog_have_mr_text = + dialog_have_mr_text + + "

                      " + + text1_mr_file + + "

                      "; + dialog_have_mr_text = + dialog_have_mr_text + + "

                      " + + text2_mr_file + + "" + + text3_mr_file + + "" + + text4_mr_file + + "

                      "; + dialog_have_mr_text = dialog_have_mr_text + "
                      "; + + $("#mr_dialog2").html(dialog_have_mr_text); + $("#mr_dialog2").dialog("open"); + } else { + $("#pkg_apply_dialog").dialog("close"); + + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["install_package"] = 1; + parameters["package"] = package; + parameters["accept"] = 1; + + $("#form-offline_update ul") + .find("li") + .removeClass("suc"); + $("#form-offline_update ul") + .find("li") + .addClass("loading"); + + $.ajax({ + type: "POST", + url: home_url + "ajax.php", + data: parameters, + dataType: "json", + success: function(data) { + $("#form-offline_update ul") + .find("li") + .removeClass("loading"); + if (data.status == "success") { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_success_pkg_text = "
                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "
                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "

                      SUCCESS

                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "

                      " + + package_success + + "

                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + "
                      "; + + $("#success_pkg").html(dialog_success_pkg_text); + $("#success_pkg").dialog("open"); + + $("#form-offline_update ul") + .find("li") + .addClass("suc"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_updated_successfully) + .append( + "" + if_there_are_any_database_change + "" + ); + } else { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_error_pkg_text = "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      ERROR

                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      " + + package_error + + "

                      "; + dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; + + $("#error_pkg").html(dialog_error_pkg_text); + $("#error_pkg").dialog("open"); + + $("#form-offline_update ul") + .find("li") + .addClass("error"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_not_updated) + .append("" + data.message + ""); + } + $("#form-offline_update ul") + .find("li") + .css("cursor", "pointer"); + $("#form-offline_update ul") + .find("li") + .click(function() { + window.location.reload(); + }); + } + }); + + // Check the status of the update + check_install_package(package, homeurl); + + remove_rr_file_to_extras(home_url); + } + } + }); + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); + + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 220, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_cancel_pkg_text = "
                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "
                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "

                      INFO

                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "

                      " + + package_cancel + + "

                      "; + dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; + + $("#cancel_pkg").html(dialog_cancel_pkg_text); + $("#cancel_pkg").dialog("open"); + + $("#form-offline_update ul") + .find("li") + .removeClass("loading"); + $("#form-offline_update ul") + .find("li") + .addClass("error"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_not_accepted) + .append("" + data.message + ""); + + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["install_package"] = 1; + parameters["package"] = package; + parameters["accept"] = 0; + + $("#form-offline_update ul") + .find("li") + .removeClass("suc"); + $("#form-offline_update ul") + .find("li") + .addClass("loading"); + + $.ajax({ + type: "POST", + url: home_url + "ajax.php", + data: parameters, + dataType: "json", + success: function(data) { + $("#form-offline_update ul") + .find("li") + .removeClass("loading"); + if (data.status == "success") { + $("#form-offline_update ul") + .find("li") + .addClass("suc"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_updated_successfully) + .append("" + if_there_are_any_database_change + ""); + } else { + $("#form-offline_update ul") + .find("li") + .addClass("error"); + $("#form-offline_update ul") + .find("li") + .find("p") + .html(package_not_updated) + .append("" + data.message + ""); + } + $("#form-offline_update ul") + .find("li") + .css("cursor", "pointer"); + $("#form-offline_update ul") + .find("li") + .click(function() { + window.location.reload(); + }); + } + }); + + // Check the status of the update + check_install_package(package, homeurl); + } + } + ] + }); + + var dialog_text = "
                      "; + dialog_text = + dialog_text + + "
                      "; + dialog_text = + dialog_text + + "

                      " + + text1_package_file + + "

                      "; + dialog_text = + dialog_text + + "

                      " + + text2_package_file + + "

                      "; + dialog_text = dialog_text + "
                      "; + + $("#pkg_apply_dialog").html(dialog_text); + $("#pkg_apply_dialog").dialog("open"); } function check_install_package(package, homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl += '/' : ''; - - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['check_install_package'] = 1; - parameters['package'] = package; - - $.ajax({ - type: 'POST', - url: home_url + 'ajax.php', - data: parameters, - dataType: "json", - success: function(data) { - // Print the updated files and take the scroll to the bottom - $("#log_zone").html(data.info); - $("#log_zone").scrollTop($("#log_zone").prop("scrollHeight")); - - // Change the progress bar - if ($('#form-offline_update ul').find('li').hasClass('suc')) { - $('#form-offline_update').find('ul').find('li').find('input').val(100).trigger('change'); - } else { - $('#form-offline_update').find('ul').find('li').find('input').val(data['progress']).trigger('change'); - } - - // The class loading is present until the update ends - var isInstalling = $('#form-offline_update ul').find('li').hasClass('loading'); - if (data.progress < 100 && isInstalling) { - // Recursive call to check the update status - check_install_package(package, homeurl); - } - } - }) + var home_url = typeof homeurl !== "undefined" ? (homeurl += "/") : ""; + + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["check_install_package"] = 1; + parameters["package"] = package; + + $.ajax({ + type: "POST", + url: home_url + "ajax.php", + data: parameters, + dataType: "json", + success: function(data) { + // Print the updated files and take the scroll to the bottom + $("#log_zone").html(data.info); + $("#log_zone").scrollTop($("#log_zone").prop("scrollHeight")); + + // Change the progress bar + if ( + $("#form-offline_update ul") + .find("li") + .hasClass("suc") + ) { + $("#form-offline_update") + .find("ul") + .find("li") + .find("input") + .val(100) + .trigger("change"); + } else { + $("#form-offline_update") + .find("ul") + .find("li") + .find("input") + .val(data["progress"]) + .trigger("change"); + } + + // The class loading is present until the update ends + var isInstalling = $("#form-offline_update ul") + .find("li") + .hasClass("loading"); + if (data.progress < 100 && isInstalling) { + // Recursive call to check the update status + check_install_package(package, homeurl); + } + } + }); } function check_online_free_packages(homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - - $("#box_online .checking_package").show(); - - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['check_online_free_packages'] = 1; - - jQuery.post( - home_url + "ajax.php", - parameters, - function (data) { - $("#box_online .checking_package").hide(); - - $("#box_online .loading").hide(); - $("#box_online .content").html(data); - }, - "html" - ); + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; + + $("#box_online .checking_package").show(); + + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["check_online_free_packages"] = 1; + + jQuery.post( + home_url + "ajax.php", + parameters, + function(data) { + $("#box_online .checking_package").hide(); + + $("#box_online .loading").hide(); + $("#box_online .content").html(data); + }, + "html" + ); } function update_last_package(package, version, homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - - version_update = version; - - $("#box_online .content").html(""); - $("#box_online .loading").show(); - $("#box_online .download_package").show(); - - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['update_last_free_package'] = 1; - parameters['package'] = package; - parameters['version'] = version; - parameters['accept'] = 0; - - jQuery.post( - home_url + "ajax.php", - parameters, - function (data) { - if (data['in_progress']) { - $("#box_online .download_package").hide(); - - $("#box_online .content").html(data['message']); - - var parameters2 = {}; - parameters2['page'] = 'include/ajax/update_manager.ajax'; - parameters2['unzip_free_package'] = 1; - parameters2['package'] = package; - parameters2['version'] = version; - - jQuery.post( - home_url + "ajax.php", - parameters2, - function (data) { - if (data['correct']) { - $("#box_online .download_package").hide(); - - $("#box_online .content").html(data['message']); - - install_free_package_prev_step(package, version, home_url); - } - else { - $("#box_online .content").html(data['message']); - } - }, - "json" - ); - } - else { - $("#box_online .content").html(data['message']); - } - }, - "json" - ); + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; + + version_update = version; + + $("#box_online .content").html(""); + $("#box_online .loading").show(); + $("#box_online .downloading_package").show(); + + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["update_last_free_package"] = 1; + parameters["package"] = package; + parameters["version"] = version; + parameters["accept"] = 0; + + jQuery.post( + home_url + "ajax.php", + parameters, + function(data) { + if (data["in_progress"]) { + $("#box_online .downloading_package").hide(); + + $("#box_online .content").html(data["message"]); + + var parameters2 = {}; + parameters2["page"] = "include/ajax/update_manager.ajax"; + parameters2["unzip_free_package"] = 1; + parameters2["package"] = package; + parameters2["version"] = version; + + jQuery.post( + home_url + "ajax.php", + parameters2, + function(data) { + if (data["correct"]) { + $("#box_online .downloading_package").hide(); + + $("#box_online .content").html(data["message"]); + + install_free_package_prev_step(package, version, home_url); + } else { + $("#box_online .content").html(data["message"]); + } + }, + "json" + ); + } else { + $("#box_online .content").html(data["message"]); + } + }, + "json" + ); } function check_progress_update(homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - - if (stop_check_progress) { - return; - } - - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['check_update_free_package'] = 1; - - jQuery.post( - home_url + "ajax.php", - parameters, - function (data) { - if (stop_check_progress) { - return; - } - - if (data['correct']) { - if (data['end']) { - //$("#box_online .content").html(data['message']); - } - else { - $("#box_online .progressbar").show(); - - $("#box_online .progressbar .progressbar_img").attr('src', - data['progressbar']); - - setTimeout(function () { - check_progress_update(homeurl); - }, 1000); - } - } - else { - correct_install_progress = false; - $("#box_online .content").html(data['message']); - } - }, - "json" - ); + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; + + if (stop_check_progress) { + return; + } + + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["check_update_free_package"] = 1; + + jQuery.post( + home_url + "ajax.php", + parameters, + function(data) { + if (stop_check_progress) { + return; + } + + if (data["correct"]) { + if (data["end"]) { + //$("#box_online .content").html(data['message']); + } else { + $("#box_online .progressbar").show(); + + $("#box_online .progressbar .progressbar_img").attr( + "src", + data["progressbar"] + ); + + setTimeout(function() { + check_progress_update(homeurl); + }, 1000); + } + } else { + correct_install_progress = false; + $("#box_online .content").html(data["message"]); + } + }, + "json" + ); } function install_free_package_prev_step(package, version, homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['search_minor'] = 1; - parameters['ent'] = 0; - parameters['package'] = package; - parameters['offline'] = 0; - - jQuery.post( - home_url + "ajax.php", - parameters, - function (data) { - $("#box_online .downloading_package").hide(); - if (data['have_minor']) { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 270, - buttons: [{ - text:apply_mr_button, - click: function () { - var err = []; - err = apply_minor_release(data['mr'], package, 0, 0, home_url); - if (!err['error']) { - if (err['message'] == 'bad_mr_filename') { - $("#mr_dialog2").dialog("close"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 270, - buttons: [{ - text:apply_button, - click: function() { - $(this).dialog("close"); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["search_minor"] = 1; + parameters["ent"] = 0; + parameters["package"] = package; + parameters["offline"] = 0; - var dialog_accept_package_mr_fail_text = "
                      "; - dialog_accept_package_mr_fail_text = dialog_accept_package_mr_fail_text + "
                      "; - dialog_accept_package_mr_fail_text = dialog_accept_package_mr_fail_text + "

                      INFO

                      "; - dialog_accept_package_mr_fail_text = dialog_accept_package_mr_fail_text + "

                      " + mr_not_accepted_code_yes + "

                      "; - dialog_accept_package_mr_fail_text = dialog_accept_package_mr_fail_text + "
                      "; - - $('#accept_package_mr_fail').html(dialog_accept_package_mr_fail_text); - $('#accept_package_mr_fail').dialog('open'); + jQuery.post( + home_url + "ajax.php", + parameters, + function(data) { + $("#box_online .downloading_package").hide(); + if (data["have_minor"]) { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 270, + buttons: [ + { + text: apply_mr_button, + click: function() { + var err = []; + err = apply_minor_release( + data["mr"], + package, + 0, + 0, + home_url + ); + if (!err["error"]) { + if (err["message"] == "bad_mr_filename") { + $("#mr_dialog2").dialog("close"); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 270, + buttons: [ + { + text: apply_button, + click: function() { + $(this).dialog("close"); - var parameters2 = {}; - parameters2['page'] = 'include/ajax/update_manager.ajax'; - parameters2['update_last_free_package'] = 1; - parameters2['package'] = package; - parameters2['version'] = version; - - jQuery.post( - home_url + "ajax.php", - parameters2, - function (data) { - if (data['in_progress']) { - $("#box_online .download_package").hide(); - - $("#box_online .content").html(data['message']); - - install_free_package(package, version, homeurl); - setTimeout(function () { - check_progress_update(homeurl); - }, 1000); - } - else { - $("#box_online .content").html(data['message']); - } - }, - "json" - ); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - remove_rr_file_to_extras(home_url); - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); + var dialog_accept_package_mr_fail_text = + "
                      "; + dialog_accept_package_mr_fail_text = + dialog_accept_package_mr_fail_text + + "
                      "; + dialog_accept_package_mr_fail_text = + dialog_accept_package_mr_fail_text + + "

                      INFO

                      "; + dialog_accept_package_mr_fail_text = + dialog_accept_package_mr_fail_text + + "

                      " + + mr_not_accepted_code_yes + + "

                      "; + dialog_accept_package_mr_fail_text = + dialog_accept_package_mr_fail_text + + "
                      "; - $(this).dialog("close"); + $("#accept_package_mr_fail").html( + dialog_accept_package_mr_fail_text + ); + $("#accept_package_mr_fail").dialog("open"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 220, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + var parameters2 = {}; + parameters2["page"] = + "include/ajax/update_manager.ajax"; + parameters2["update_last_free_package"] = 1; + parameters2["package"] = package; + parameters2["version"] = version; - var dialog_cancel_pkg_text = "
                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "

                      INFO

                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "

                      " + package_cancel + "

                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; - - $('#cancel_pkg').html(dialog_cancel_pkg_text); - $('#cancel_pkg').dialog('open'); + jQuery.post( + home_url + "ajax.php", + parameters2, + function(data) { + if (data["in_progress"]) { + $( + "#box_online .download_package" + ).hide(); - $("#box_online .content").html(package_not_accepted); - } - }] - }); + $("#box_online .content").html( + data["message"] + ); - var dialog_bad_message_text = "
                      "; - dialog_bad_message_text = dialog_bad_message_text + "
                      "; - dialog_bad_message_text = dialog_bad_message_text + "

                      ERROR

                      "; - dialog_bad_message_text = dialog_bad_message_text + "

                      " + bad_mr_file + "

                      "; - dialog_bad_message_text = dialog_bad_message_text + "
                      "; - - $('#bad_message').html(dialog_bad_message_text); - $('#bad_message').dialog('open'); - } - else { - $("#mr_dialog2").dialog("close"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + install_free_package( + package, + version, + homeurl + ); + setTimeout(function() { + check_progress_update(homeurl); + }, 1000); + } else { + $("#box_online .content").html( + data["message"] + ); + } + }, + "json" + ); - var dialog_success_mr_text = "
                      "; - dialog_success_mr_text = dialog_success_mr_text + "
                      "; - dialog_success_mr_text = dialog_success_mr_text + "

                      SUCCESS

                      "; - dialog_success_mr_text = dialog_success_mr_text + "

                      " + mr_success + "

                      "; - dialog_success_mr_text = dialog_success_mr_text + "
                      "; - - $('#success_mr').html(dialog_success_mr_text); - $('#success_mr').dialog('open'); + remove_rr_file_to_extras(home_url); + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); - var parameters2 = {}; - parameters2['page'] = 'include/ajax/update_manager.ajax'; - parameters2['update_last_free_package'] = 1; - parameters2['package'] = package; - parameters2['version'] = version; - - jQuery.post( - home_url + "ajax.php", - parameters2, - function (data) { - if (data['in_progress']) { - $("#box_online .download_package").hide(); - - $("#box_online .content").html(data['message']); - - install_free_package(package, version, homeurl); - setTimeout(function () { - check_progress_update(homeurl); - }, 1000); - } - else { - $("#box_online .content").html(data['message']); - } - }, - "json" - ); + $(this).dialog("close"); - remove_rr_file_to_extras(home_url); - } - } - else { - $("#mr_dialog2").dialog("close"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 220, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var dialog_error_mr_text = "
                      "; - dialog_error_mr_text = dialog_error_mr_text + "
                      "; - dialog_error_mr_text = dialog_error_mr_text + "

                      ERROR

                      "; - dialog_error_mr_text = dialog_error_mr_text + "

                      " + mr_error + "

                      "; - dialog_error_mr_text = dialog_error_mr_text + "
                      "; - - $('#error_mr').html(dialog_error_mr_text); - $('#error_mr').dialog('open'); + var dialog_cancel_pkg_text = "
                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "
                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "

                      INFO

                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "

                      " + + package_cancel + + "

                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + "
                      "; - $("#box_online .content").html(mr_error); - } - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); + $("#cancel_pkg").html( + dialog_cancel_pkg_text + ); + $("#cancel_pkg").dialog("open"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 220, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#box_online .content").html( + package_not_accepted + ); + } + } + ] + }); - var dialog_cancel_mr_text = "
                      "; - dialog_cancel_mr_text = dialog_cancel_mr_text + "
                      "; - dialog_cancel_mr_text = dialog_cancel_mr_text + "

                      INFO

                      "; - dialog_cancel_mr_text = dialog_cancel_mr_text + "

                      " + mr_cancel + "

                      "; - dialog_cancel_mr_text = dialog_cancel_mr_text + "
                      "; - - $('#cancel_mr').html(dialog_cancel_mr_text); - $('#cancel_mr').dialog('open'); + var dialog_bad_message_text = "
                      "; + dialog_bad_message_text = + dialog_bad_message_text + + "
                      "; + dialog_bad_message_text = + dialog_bad_message_text + + "

                      ERROR

                      "; + dialog_bad_message_text = + dialog_bad_message_text + + "

                      " + + bad_mr_file + + "

                      "; + dialog_bad_message_text = + dialog_bad_message_text + "
                      "; - $("#box_online .loading").hide(); - $("#box_online .downloading_package").hide(); - $("#box_online .content").html("MR not accepted"); - } - }] - }); + $("#bad_message").html(dialog_bad_message_text); + $("#bad_message").dialog("open"); + } else { + $("#mr_dialog2").dialog("close"); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - $('button:contains(Apply MR)').attr("id","apply_rr_button"); - $('button:contains(Cancel)').attr("id","cancel_rr_button"); - - var dialog_have_mr_text = "
                      "; - dialog_have_mr_text = dialog_have_mr_text + "
                      "; - dialog_have_mr_text = dialog_have_mr_text + "

                      " + mr_available_header + "

                      "; - dialog_have_mr_text = dialog_have_mr_text + "

                      " + text1_mr_file + "

                      "; - dialog_have_mr_text = dialog_have_mr_text + "

                      " + text2_mr_file + "" + text3_mr_file + "" + text4_mr_file + "

                      "; - dialog_have_mr_text = dialog_have_mr_text + "
                      "; - - $('#mr_dialog2').html(dialog_have_mr_text); - $('#mr_dialog2').dialog('open'); - } - else { - var parameters2 = {}; - parameters2['page'] = 'include/ajax/update_manager.ajax'; - parameters2['update_last_free_package'] = 1; - parameters2['package'] = package; - parameters2['version'] = version; - - jQuery.post( - home_url + "ajax.php", - parameters2, - function (data) { - if (data['in_progress']) { - $("#box_online .download_package").hide(); - - $("#box_online .content").html(data['message']); - - install_free_package(package, version, homeurl); - setTimeout(function () { - check_progress_update(homeurl); - }, 1000); - } - else { - $("#box_online .content").html(data['message']); - } - }, - "json" - ); + var dialog_success_mr_text = "
                      "; + dialog_success_mr_text = + dialog_success_mr_text + + "
                      "; + dialog_success_mr_text = + dialog_success_mr_text + + "

                      SUCCESS

                      "; + dialog_success_mr_text = + dialog_success_mr_text + + "

                      " + + mr_success + + "

                      "; + dialog_success_mr_text = + dialog_success_mr_text + "
                      "; - remove_rr_file_to_extras(home_url); - } - }, - "json" - ); - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); + $("#success_mr").html(dialog_success_mr_text); + $("#success_mr").dialog("open"); - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 220, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + var parameters2 = {}; + parameters2["page"] = + "include/ajax/update_manager.ajax"; + parameters2["update_last_free_package"] = 1; + parameters2["package"] = package; + parameters2["version"] = version; - var dialog_cancel_pkg_text = "
                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "

                      INFO

                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "

                      " + package_cancel + "

                      "; - dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; - - $('#cancel_pkg').html(dialog_cancel_pkg_text); - $('#cancel_pkg').dialog('open'); + jQuery.post( + home_url + "ajax.php", + parameters2, + function(data) { + if (data["in_progress"]) { + $("#box_online .download_package").hide(); - $("#box_online .loading").hide(); - $("#box_online .progressbar").hide(); - $("#box_online .content").html(package_cancel); - } - }] - }); + $("#box_online .content").html( + data["message"] + ); - var dialog_text = "
                      "; - dialog_text = dialog_text + "
                      "; - dialog_text = dialog_text + "

                      " + text1_package_file + "

                      "; - dialog_text = dialog_text + "

                      " + text2_package_file + "

                      "; - dialog_text = dialog_text + "
                      "; - - $('#pkg_apply_dialog').html(dialog_text); - $('#pkg_apply_dialog').dialog('open'); + install_free_package( + package, + version, + homeurl + ); + setTimeout(function() { + check_progress_update(homeurl); + }, 1000); + } else { + $("#box_online .content").html( + data["message"] + ); + } + }, + "json" + ); + + remove_rr_file_to_extras(home_url); + } + } else { + $("#mr_dialog2").dialog("close"); + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_error_mr_text = "
                      "; + dialog_error_mr_text = + dialog_error_mr_text + + "
                      "; + dialog_error_mr_text = + dialog_error_mr_text + + "

                      ERROR

                      "; + dialog_error_mr_text = + dialog_error_mr_text + + "

                      " + + mr_error + + "

                      "; + dialog_error_mr_text = + dialog_error_mr_text + "
                      "; + + $("#error_mr").html(dialog_error_mr_text); + $("#error_mr").dialog("open"); + + $("#box_online .content").html(mr_error); + } + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); + + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 220, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_cancel_mr_text = "
                      "; + dialog_cancel_mr_text = + dialog_cancel_mr_text + + "
                      "; + dialog_cancel_mr_text = + dialog_cancel_mr_text + + "

                      INFO

                      "; + dialog_cancel_mr_text = + dialog_cancel_mr_text + + "

                      " + + mr_cancel + + "

                      "; + dialog_cancel_mr_text = + dialog_cancel_mr_text + "
                      "; + + $("#cancel_mr").html(dialog_cancel_mr_text); + $("#cancel_mr").dialog("open"); + + $("#box_online .loading").hide(); + $("#box_online .downloading_package").hide(); + $("#box_online .content").html("MR not accepted"); + } + } + ] + }); + + $("button:contains(Apply MR)").attr("id", "apply_rr_button"); + $("button:contains(Cancel)").attr("id", "cancel_rr_button"); + + var dialog_have_mr_text = "
                      "; + dialog_have_mr_text = + dialog_have_mr_text + + "
                      "; + dialog_have_mr_text = + dialog_have_mr_text + + "

                      " + + mr_available_header + + "

                      "; + dialog_have_mr_text = + dialog_have_mr_text + + "

                      " + + text1_mr_file + + "

                      "; + dialog_have_mr_text = + dialog_have_mr_text + + "

                      " + + text2_mr_file + + "" + + text3_mr_file + + "" + + text4_mr_file + + "

                      "; + dialog_have_mr_text = dialog_have_mr_text + "
                      "; + + $("#mr_dialog2").html(dialog_have_mr_text); + $("#mr_dialog2").dialog("open"); + } else { + var parameters2 = {}; + parameters2["page"] = "include/ajax/update_manager.ajax"; + parameters2["update_last_free_package"] = 1; + parameters2["package"] = package; + parameters2["version"] = version; + + jQuery.post( + home_url + "ajax.php", + parameters2, + function(data) { + if (data["in_progress"]) { + $("#box_online .download_package").hide(); + + $("#box_online .content").html(data["message"]); + + install_free_package(package, version, homeurl); + setTimeout(function() { + check_progress_update(homeurl); + }, 1000); + } else { + $("#box_online .content").html(data["message"]); + } + }, + "json" + ); + + remove_rr_file_to_extras(home_url); + } + }, + "json" + ); + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); + + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 220, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_cancel_pkg_text = "
                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "
                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "

                      INFO

                      "; + dialog_cancel_pkg_text = + dialog_cancel_pkg_text + + "

                      " + + package_cancel + + "

                      "; + dialog_cancel_pkg_text = dialog_cancel_pkg_text + "
                      "; + + $("#cancel_pkg").html(dialog_cancel_pkg_text); + $("#cancel_pkg").dialog("open"); + + $("#box_online .loading").hide(); + $("#box_online .progressbar").hide(); + $("#box_online .content").html(package_cancel); + } + } + ] + }); + + var dialog_text = "
                      "; + dialog_text = + dialog_text + + "
                      "; + dialog_text = + dialog_text + + "

                      " + + text1_package_file + + "

                      "; + dialog_text = + dialog_text + + "

                      " + + text2_package_file + + "

                      "; + dialog_text = dialog_text + "
                      "; + + $("#pkg_apply_dialog").html(dialog_text); + $("#pkg_apply_dialog").dialog("open"); } function install_free_package(package, version, homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - - var parameters = {}; - parameters['page'] = 'include/ajax/update_manager.ajax'; - parameters['install_free_package'] = 1; - parameters['package'] = package; - parameters['version'] = version; - - jQuery.ajax ({ - data: parameters, - type: 'POST', - url: home_url + "ajax.php", - timeout: 600000, - dataType: "json", - error: function(data) { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; - var dialog_error_pkg_text = "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      ERROR

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      " + data['message'] + "

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - - $('#error_pkg').html(dialog_error_pkg_text); - $('#error_pkg').dialog('open'); + var parameters = {}; + parameters["page"] = "include/ajax/update_manager.ajax"; + parameters["install_free_package"] = 1; + parameters["package"] = package; + parameters["version"] = version; - correct_install_progress = false; - stop_check_progress = 1; - - $("#box_online .loading").hide(); - $("#box_online .progressbar").hide(); - $("#box_online .content").html(unknown_error_update_manager); - }, - success: function (data) { - if (correct_install_progress) { - if (data["status"] == "success") { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + jQuery.ajax({ + data: parameters, + type: "POST", + url: home_url + "ajax.php", + timeout: 600000, + dataType: "json", + error: function(data) { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var dialog_success_pkg_text = "
                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "

                      SUCCESS

                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "

                      " + data['message'] + "

                      "; - dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - - $('#success_pkg').html(dialog_success_pkg_text); - $('#success_pkg').dialog('open'); + var dialog_error_pkg_text = "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      ERROR

                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      " + + data["message"] + + "

                      "; + dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - $("#pkg_version").text(version); + $("#error_pkg").html(dialog_error_pkg_text); + $("#error_pkg").dialog("open"); - $("#box_online .loading").hide(); - $("#box_online .progressbar").hide(); - $("#box_online .content").html(data['message']); - stop_check_progress = 1; - } - else { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + correct_install_progress = false; + stop_check_progress = 1; - var dialog_error_pkg_text = "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      ERROR

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      " + data['message'] + "

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - - $('#error_pkg').html(dialog_error_pkg_text); - $('#error_pkg').dialog('open'); + $("#box_online .loading").hide(); + $("#box_online .progressbar").hide(); + $("#box_online .content").html(unknown_error_update_manager); + }, + success: function(data) { + if (correct_install_progress) { + if (data["status"] == "success") { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - $("#box_online .loading").hide(); - $("#box_online .progressbar").hide(); - $("#box_online .content").html(data['message']); - stop_check_progress = 1; - } - } - else { - stop_check_progress = 1; + var dialog_success_pkg_text = "
                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "
                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "

                      SUCCESS

                      "; + dialog_success_pkg_text = + dialog_success_pkg_text + + "

                      " + + data["message"] + + "

                      "; + dialog_success_pkg_text = dialog_success_pkg_text + "
                      "; - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [{ - text:ok_button, - click: function () { - $(this).dialog("close"); - } - }] - }); + $("#success_pkg").html(dialog_success_pkg_text); + $("#success_pkg").dialog("open"); - var dialog_error_pkg_text = "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      ERROR

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "

                      " + data['message'] + "

                      "; - dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; - - $('#error_pkg').html(dialog_error_pkg_text); - $('#error_pkg').dialog('open'); - } - } - }); + $("#pkg_version").text(version); + + $("#box_online .loading").hide(); + $("#box_online .progressbar").hide(); + $("#box_online .content").html(data["message"]); + stop_check_progress = 1; + } else { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_error_pkg_text = "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      ERROR

                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      " + + data["message"] + + "

                      "; + dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; + + $("#error_pkg").html(dialog_error_pkg_text); + $("#error_pkg").dialog("open"); + + $("#box_online .loading").hide(); + $("#box_online .progressbar").hide(); + $("#box_online .content").html(data["message"]); + stop_check_progress = 1; + } + } else { + stop_check_progress = 1; + + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); + + var dialog_error_pkg_text = "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "
                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      ERROR

                      "; + dialog_error_pkg_text = + dialog_error_pkg_text + + "

                      " + + data["message"] + + "

                      "; + dialog_error_pkg_text = dialog_error_pkg_text + "
                      "; + + $("#error_pkg").html(dialog_error_pkg_text); + $("#error_pkg").dialog("open"); + } + } + }); } -function apply_minor_release (n_mr, pkg, ent, off, homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - var error = []; - error['error'] = false; - $('#mr_dialog2').empty(); - $.each(n_mr, function(i, mr) { - var params = {}; - params["updare_rr"] = 1; - params["number"] = mr; - params["ent"] = ent; - params["package"] = pkg; - params["offline"] = off; - params["page"] = "include/ajax/rolling_release.ajax"; +function apply_minor_release(n_mr, pkg, ent, off, homeurl) { + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; + var error = []; + error["error"] = false; + $("#mr_dialog2").empty(); + $.each(n_mr, function(i, mr) { + var params = {}; + params["updare_rr"] = 1; + params["number"] = mr; + params["ent"] = ent; + params["package"] = pkg; + params["offline"] = off; + params["page"] = "include/ajax/rolling_release.ajax"; - jQuery.ajax ({ - data: params, - async: false, - dataType: "html", - type: "POST", - url: home_url + "ajax.php", - success: function (data) { - $('#mr_dialog2').append(""); - if (data == 'bad_mr_filename') { - error['error'] = false; - error['message'] = "bad_mr_filename"; - } - else if (data != "") { - $('#mr_dialog2').empty(); - $('#mr_dialog2').html(data); - error['error'] = true; - } - else { - $('#mr_dialog2').append("

                      - " + applying_mr + " #" + mr + "

                      "); - } - } - }); - - if (error['error']) { - return false; - } - else if(error['message'] == "bad_mr_filename") { - return false; - } - }); - $('#mr_dialog2').append(""); - $(".ui-dialog-buttonset").empty(); + jQuery.ajax({ + data: params, + async: false, + dataType: "html", + type: "POST", + url: home_url + "ajax.php", + success: function(data) { + $("#mr_dialog2").append(""); + if (data == "bad_mr_filename") { + error["error"] = false; + error["message"] = "bad_mr_filename"; + } else if (data != "") { + $("#mr_dialog2").empty(); + $("#mr_dialog2").html(data); + error["error"] = true; + } else { + $("#mr_dialog2").append( + "

                      - " + + applying_mr + + " #" + + mr + + "

                      " + ); + } + } + }); - return error; + if (error["error"]) { + return false; + } else if (error["message"] == "bad_mr_filename") { + return false; + } + }); + $("#mr_dialog2").append(""); + $(".ui-dialog-buttonset").empty(); + + return error; } -function remove_rr_file (number, homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - var params = {}; - params["remove_rr"] = 1; - params["number"] = number; - params["page"] = "include/ajax/rolling_release.ajax"; +function remove_rr_file(number, homeurl) { + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; + var params = {}; + params["remove_rr"] = 1; + params["number"] = number; + params["page"] = "include/ajax/rolling_release.ajax"; - jQuery.ajax ({ - data: params, - dataType: "html", - type: "POST", - url: home_url + "ajax.php", - success: function (data) { - } - }); + jQuery.ajax({ + data: params, + dataType: "html", + type: "POST", + url: home_url + "ajax.php", + success: function(data) {} + }); } -function remove_rr_file_to_extras (homeurl) { - var home_url = (typeof homeurl !== 'undefined') ? homeurl + '/' : ''; - var params = {}; - params["remove_rr_extras"] = 1; - params["page"] = "include/ajax/rolling_release.ajax"; +function remove_rr_file_to_extras(homeurl) { + var home_url = typeof homeurl !== "undefined" ? homeurl + "/" : ""; + var params = {}; + params["remove_rr_extras"] = 1; + params["page"] = "include/ajax/rolling_release.ajax"; - jQuery.ajax ({ - data: params, - dataType: "html", - type: "POST", - url: home_url + "ajax.php", - success: function (data) { - } - }); -} \ No newline at end of file + jQuery.ajax({ + data: params, + dataType: "html", + type: "POST", + url: home_url + "ajax.php", + success: function(data) {} + }); +} diff --git a/pandora_console/include/javascript/webchat.js b/pandora_console/include/javascript/webchat.js index b45621cd1c..09c7ae81df 100644 --- a/pandora_console/include/javascript/webchat.js +++ b/pandora_console/include/javascript/webchat.js @@ -1,48 +1,47 @@ function check_new_chats_icon(id_icon) { - if (new_chat) { - $("#" + id_icon).pulsate (); - } + if (new_chat) { + $("#" + id_icon).pulsate(); + } } function check_new_chats_icon_ajax(id_icon) { - var exit = false; - - url_chunks = location.href.split('&'); - $.each(url_chunks, function(key, chunk) { - if (chunk == 'sec2=operation/users/webchat') - exit = true; - return; - }); - - if (exit) { - return; - } - - old = global_counter_chat; - get_last_global_counter(); - - if (old < global_counter_chat) { - $("#" + id_icon).pulsate (); - } - - setTimeout("check_new_chats_icon(\"" + id_icon + "\")", 5000); + var exit = false; + + url_chunks = location.href.split("&"); + $.each(url_chunks, function(key, chunk) { + if (chunk == "sec2=operation/users/webchat") exit = true; + return; + }); + + if (exit) { + return; + } + + old = global_counter_chat; + get_last_global_counter(); + + if (old < global_counter_chat) { + $("#" + id_icon).pulsate(); + } + + setTimeout('check_new_chats_icon("' + id_icon + '")', 5000); } function get_last_global_counter() { - var parameters = {}; - parameters['page'] = "operation/users/webchat"; - parameters['get_last_global_counter'] = 1; - - $.ajax({ - type: 'POST', - url: 'ajax.php', - data: parameters, - dataType: "json", - async: false, - success: function(data) { - if (data['correct'] == 1) { - global_counter_chat = data['global_counter']; - } - } - }); + var parameters = {}; + parameters["page"] = "operation/users/webchat"; + parameters["get_last_global_counter"] = 1; + + $.ajax({ + type: "POST", + url: "ajax.php", + data: parameters, + dataType: "json", + async: false, + success: function(data) { + if (data["correct"] == 1) { + global_counter_chat = data["global_counter"]; + } + } + }); } diff --git a/pandora_console/include/load_session.php b/pandora_console/include/load_session.php index b34c33b2bb..22a7226a8f 100644 --- a/pandora_console/include/load_session.php +++ b/pandora_console/include/load_session.php @@ -1,84 +1,92 @@ - $session_id)); - } + $session_exists = (bool) db_get_value('COUNT(id_session)', 'tsessions_php', 'id_session', $session_id); - return $retval_write !== false; + if (!$session_exists) { + $values['id_session'] = $session_id; + $retval_write = db_process_sql_insert('tsessions_php', $values); + } else { + $retval_write = db_process_sql_update('tsessions_php', $values, ['id_session' => $session_id]); + } + + return $retval_write !== false; } -function pandora_session_destroy ($session_id) { - $session_id = addslashes($session_id); - - $retval = (bool) db_process_sql_delete('tsessions_php', array('id_session' => $session_id)); - - return $retval; + +function pandora_session_destroy($session_id) +{ + $session_id = addslashes($session_id); + + $retval = (bool) db_process_sql_delete('tsessions_php', ['id_session' => $session_id]); + + return $retval; } -function pandora_session_gc ($max_lifetime = 300) { - global $config; - - if (isset($config['session_timeout'])) { - $max_lifetime = $config['session_timeout']; - } - - $time_limit = time() - $max_lifetime; - - $retval = (bool) db_process_sql_delete('tsessions_php', array('last_active' => "<" . $time_limit)); - - return $retval; + +function pandora_session_gc($max_lifetime=300) +{ + global $config; + + if (isset($config['session_timeout'])) { + $max_lifetime = $config['session_timeout']; + } + + $time_limit = (time() - $max_lifetime); + + $retval = (bool) db_process_sql_delete('tsessions_php', ['last_active' => '<'.$time_limit]); + + return $retval; } + // FIXME: 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', 'pandora_session_close', 'pandora_session_read', 'pandora_session_write', 'pandora_session_destroy', 'pandora_session_gc'); +if (db_get_value('value', 'tconfig', 'token', 'auth') != 'saml') { + $result_handler = session_set_save_handler('pandora_session_open', 'pandora_session_close', 'pandora_session_read', 'pandora_session_write', 'pandora_session_destroy', 'pandora_session_gc'); } -?> diff --git a/pandora_console/include/php_to_js_values.php b/pandora_console/include/php_to_js_values.php index a088189d44..73dddf0e6b 100644 --- a/pandora_console/include/php_to_js_values.php +++ b/pandora_console/include/php_to_js_values.php @@ -3,27 +3,24 @@ // ================================================== // Copyright (c) 2005-2012 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. /** - * @package Include + * @package Include * @subpackage php_to_js_values */ // Hidden div to forced title -html_print_div(array('id' => 'forced_title_layer', 'class' => 'forced_title_layer', 'hidden' => true)); +html_print_div(['id' => 'forced_title_layer', 'class' => 'forced_title_layer', 'hidden' => true]); -//======= Store values to be retrieved from javascript code ============ +// ======= Store values to be retrieved from javascript code ============ set_js_value('absolute_homeurl', ui_get_full_url(false, false, false, false)); -set_js_value('homeurl', $config["homeurl"]); -set_js_value('homedir', $config["homedir"] . '/'); -//====================================================================== -?> +set_js_value('homeurl', $config['homeurl']); +set_js_value('homedir', $config['homedir'].'/'); +// ====================================================================== diff --git a/pandora_console/include/styles/cluetip.css b/pandora_console/include/styles/cluetip.css deleted file mode 100644 index 5a33cd38ef..0000000000 --- a/pandora_console/include/styles/cluetip.css +++ /dev/null @@ -1,99 +0,0 @@ -/* global */ -#cluetip-close img { - border: 0; -} -#cluetip-title { - overflow: hidden; -} -#cluetip-title #cluetip-close { - float: right; - position: relative; -} -#cluetip-waitimage { - width: 43px; - height: 11px; - position: absolute; - background-image: url(../../images/wait.gif); -} -.cluetip-arrows { - display: none; - position: absolute; - top: 0; - left: -11px; - height: 22px; - width: 11px; - background-repeat: no-repeat; - background-position: 0 0; -} -#cluetip-extra { - display: none; -} -/*************************************** - =cluetipClass: 'default' --------------------------------------- */ - -.cluetip-default { - background-color: #FFF; - text-align: left; -} -.cluetip-default #cluetip-outer { - position: relative; - margin: 0; - background-color: #FFF; -} -.cluetip-default h3 { - margin: 0 0 5px; - padding: 8px 10px 4px; - font-size: 1.1em; - font-weight: bold; - background-color: #B1B1B1; - color: #fff; -} -.cluetip-default h3#cluetip-title { - display: none; - height: 0px; - margin: 0; - padding: 0; - color: #FFF; -} -.cluetip-default #cluetip-title a { - color: #FFF; - font-size: 0.95em; -} -.cluetip-default #cluetip-inner { - padding: 10px; -} -.cluetip-default div#cluetip-close { - text-align: right; - margin: 0 5px 5px; - color: #900; -} -.cluetip-default ul { - text-align: left; -} -/* default arrows */ - -.clue-right-default .cluetip-arrows { - background-image: url(../../images/darrowleft.png); -} -.clue-left-default .cluetip-arrows { - background-image: url(../../images/darrowright.png); - left: 100%; - margin-right: -11px; -} -.clue-top-default .cluetip-arrows { - background-image: url(../../images/darrowdown.png); - top: 100%; - left: 50%; - margin-left: -11px; - height: 11px; - width: 22px; -} -.clue-bottom-default .cluetip-arrows { - background-image: url(../../images/darrowup.png); - top: -11px; - left: 50%; - margin-left: -11px; - height: 11px; - width: 22px; -} diff --git a/pandora_console/include/styles/cluster_view.css b/pandora_console/include/styles/cluster_view.css new file mode 100644 index 0000000000..74e30f1a8c --- /dev/null +++ b/pandora_console/include/styles/cluster_view.css @@ -0,0 +1,144 @@ +/* + * --------------------------------------------------------------------- + * - CLUSTER VIEW - + * --------------------------------------------------------------------- + */ +#main_cluster { + max-width: 1770px; + margin: 0 auto; +} + +.sub_cluster_1 { + width: 400px; + float: left; + margin-left: 30px; + margin-bottom: 25px; + vertical-align: top; + border: 1px solid #e7e9ea; + height: 150px; +} + +.sub_cluster_2 { + width: 833px; + float: left; + margin-left: 30px; + margin-bottom: 25px; + vertical-align: top; + border: 1px solid #e7e9ea; + height: 150px; +} + +.sub_cluster_header { + width: 100%; + height: 30px; + background-color: #373737; + color: white; + text-align: center; + font-size: 9pt; + display: flex; + justify-content: center; + align-content: center; + flex-direction: column; +} + +.sub_cluster_body { + width: 100%; + height: 120px; + background-color: #f9faf9; + display: flex; + justify-content: center; + align-content: center; + flex-direction: column; +} + +.sub_cluster_body_3 { + width: 100%; + height: 120px; + background-color: #f9faf9; + overflow-y: scroll; +} + +#cluster_map { + border: 1px solid lightgray; + width: 900px; + height: 500px; + float: left; + margin-bottom: 30px; +} + +#cluster_status_content { + width: 90%; + height: 30px; + margin: 0px auto; +} + +#cluster_status_bar { + width: 85%; + height: 100%; + float: left; +} + +.status_animation { + width: 1%; + height: 100%; + left: 0%; + background-color: red; + position: relative; +} + +#cluster_status_button { + float: left; + width: 10%; + margin-left: 5%; +} + +#last_contact_content { + width: 90%; + height: 60px; + margin: 0px auto; +} + +#last_contact_clock { + width: 15%; + height: 100%; + float: left; +} + +#last_contact_date { + float: left; + height: 60px; + width: 80%; + margin-left: 5%; + text-align: center; + display: flex; + justify-content: center; + align-content: center; + flex-direction: column; +} + +#last_contact_date_text { + font-size: 14pt; +} + +.balanced_module_item { + float: left; + margin-top: 11.5px; + margin-left: 5%; + height: 25px; + width: 90%; +} + +.module_icon { + float: left; + width: 10%; +} + +.modal_module_list { + float: left; + width: 90%; + height: 100%; + display: flex; + justify-content: center; + align-content: center; + flex-direction: column; +} diff --git a/pandora_console/include/styles/color-picker.css b/pandora_console/include/styles/color-picker.css deleted file mode 100644 index 43383bb43f..0000000000 --- a/pandora_console/include/styles/color-picker.css +++ /dev/null @@ -1,24 +0,0 @@ -#ColorPickerDiv { - display: block; - display: none; - position: relative; - border: 1px solid #777; - background: #fff -} - -#ColorPickerDiv td.color { - cursor: pointer; - font-size: xx-small; - font-family: 'Arial' , 'Microsoft Sans Serif'; -} -#ColorPickerDiv td.color label { - cursor: pointer; -} - -.ColorPickerDivSample { - margin: 0px 0px 0px 4px; - border: solid 1px #000; - padding: 0px 10px; - position: relative; - cursor: pointer; -} diff --git a/pandora_console/include/styles/common.css b/pandora_console/include/styles/common.css index f9e44e571f..09c7abb566 100644 --- a/pandora_console/include/styles/common.css +++ b/pandora_console/include/styles/common.css @@ -1,53 +1,81 @@ -/* Common useful styles */ -.invisible { - display: none; -} -.left { clear: left; float: left;} -.right { clear: right; float: right;} -.clear { clear:both; } -.top { - vertical-align: top; - margin-top: 0; - padding-top: 0; -} -img.left { - margin-right:1em; - margin-bottom:1.8em; -} -img.right { - margin-left:1em; - margin-bottom:1.8em; -} -.text-right { - text-align:right; -} - /* Debug styles */ -pre.debug, div.backtrace { - font-family: monospace !important; - text-align: left; - padding: 10px; - margin: 5px; - border: 1px solid black; +pre.debug, +div.backtrace { + font-family: monospace !important; + text-align: left; + padding: 10px; + margin: 5px; + border: 1px solid black; } div.backtrace ol { - margin: 0; - padding-left: 20px; + margin: 0; + padding-left: 20px; } pre.debug { - background-color: #fff55f; + background-color: #fff55f; } -div.debug, div.database_debug_title, div.debug a, div.debug a:hover { - background-color: white; - color: black; - text-align: left; +div.debug, +div.database_debug_title, +div.debug a, +div.debug a:hover { + background-color: white; + color: black; + text-align: left; } -div.debug a, div.debug a:hover, div.parameters { - text-decoration: underline; +div.debug a, +div.debug a:hover, +div.parameters { + text-decoration: underline; } div.database_debug_title { - font-size: 15pt; - margin-top: 15px; - padding: 5px; - width: 95%; + font-size: 15pt; + margin-top: 15px; + padding: 5px; + width: 95%; +} + +/* Common useful styles */ +.invisible { + display: none; +} +.left { + clear: left; + float: left; +} +.right { + clear: right; + float: right; +} +.clear { + clear: both; +} +.top { + vertical-align: top; + margin-top: 0; + padding-top: 0; +} +img.left { + margin-right: 1em; + margin-bottom: 1.8em; +} +img.right { + margin-left: 1em; + margin-bottom: 1.8em; +} +.text-right { + text-align: right; +} +.noshadow { + -moz-box-shadow: 0px !important; + -webkit-box-shadow: 0px !important; + box-shadow: 0px !important; +} +.center_align { + text-align: center; +} +.left_align { + text-align: left; +} +.right_align { + text-align: right; } diff --git a/pandora_console/include/styles/countdown.css b/pandora_console/include/styles/countdown.css index 80db0a2cf2..d75bc8ced4 100644 --- a/pandora_console/include/styles/countdown.css +++ b/pandora_console/include/styles/countdown.css @@ -1,42 +1,42 @@ /* countdown styles */ #countdown { - border: 1px dotted #990000; - width: 200px; - margin-bottom: 5px; + border: 1px dotted #990000; + width: 200px; + margin-bottom: 5px; } .countdown_row { - clear: both; - width: 200px; - text-align: center; + clear: both; + width: 200px; + text-align: center; } .countdown_show1 div { - width: 100%; + width: 100%; } .countdown_show2 div { - width: 50%; + width: 50%; } .countdown_show3 div { - width: 33%; + width: 33%; } .countdown_show4 div { - width: 25%; + width: 25%; } .countdown_show5 div { - width: 20%; + width: 20%; } .countdown_show6 div { - width: 16%; + width: 16%; } .countdown_show7 div { - width: 14%; + width: 14%; } .countdown_section { - float: left; - font-size: 75% + float: left; + font-size: 75%; } .countdown_amount { - font-size: 200%; + font-size: 200%; } .countdown_descr { - width: 200px; + width: 200px; } diff --git a/pandora_console/include/styles/d3-context-menu.css b/pandora_console/include/styles/d3-context-menu.css index 757f6663b0..73e32a898e 100644 --- a/pandora_console/include/styles/d3-context-menu.css +++ b/pandora_console/include/styles/d3-context-menu.css @@ -1,29 +1,29 @@ .d3-context-menu { - position: absolute; - display: none; - background-color: #f2f2f2; - border-radius: 4px; + position: absolute; + display: none; + background-color: #f2f2f2; + border-radius: 4px; - font-family: Arial, sans-serif; - font-size: 14px; - min-width: 150px; - border: 1px solid #d4d4d4; + font-family: Arial, sans-serif; + font-size: 14px; + min-width: 150px; + border: 1px solid #d4d4d4; - z-index:1200; + z-index: 1200; } .d3-context-menu ul { - list-style-type: none; - margin: 4px 0px; - padding: 0px; - cursor: default; + list-style-type: none; + margin: 4px 0px; + padding: 0px; + cursor: default; } .d3-context-menu ul li { - padding: 4px 16px; + padding: 4px 16px; } .d3-context-menu ul li:hover { - background-color: #4677f8; - color: #fefefe; -} \ No newline at end of file + background-color: #4677f8; + color: #fefefe; +} diff --git a/pandora_console/include/styles/datepicker.css b/pandora_console/include/styles/datepicker.css index 0242eef335..4231036179 100644 --- a/pandora_console/include/styles/datepicker.css +++ b/pandora_console/include/styles/datepicker.css @@ -190,7 +190,7 @@ img.ui-datepicker-trigger { /* .ui-datepicker-cover { display: none; - display/**/: block; + display: block; position: absolute; z-index: -1; filter: mask(); @@ -203,4 +203,4 @@ img.ui-datepicker-trigger { .ui-datepicker-title * { color: white; } -*/ \ No newline at end of file +*/ diff --git a/pandora_console/include/styles/dialog.css b/pandora_console/include/styles/dialog.css index 220e1a4fb3..ecb4ab61f9 100644 --- a/pandora_console/include/styles/dialog.css +++ b/pandora_console/include/styles/dialog.css @@ -1,281 +1,203 @@ - /* This file skins dialog */ .ui-dialog { - background: none repeat scroll 0 0 #3f3f3f !important; - border: 1px solid #3f3f3f !important; - color: #333333 !important; - padding: 0.2em !important; - overflow: hidden !important; - - -moz-border-radius: 6px !important; - -webkit-border-radius: 6px !important; - border-radius: 6px !important; - - -moz-box-shadow: 0px 5px 5px #010E1B !important; - -webkit-box-shadow: 0px 5px 5px #010E1B !important; - box-shadow: 0px 5px 5px #010E1B !important; + background: none repeat scroll 0 0 #3f3f3f !important; + border: 1px solid #3f3f3f !important; + color: #333333 !important; + padding: 0.2em !important; + overflow: hidden !important; + + -moz-border-radius: 6px !important; + -webkit-border-radius: 6px !important; + border-radius: 6px !important; + + -moz-box-shadow: 0px 5px 5px #010e1b !important; + -webkit-box-shadow: 0px 5px 5px #010e1b !important; + box-shadow: 0px 5px 5px #010e1b !important; } .ui-widget-header { - background: #3f3f3f !important; + background: #3f3f3f !important; } .ui-dialog .ui-dialog-titlebar { - background-color: #ECECEC; - height: 24px !important; - padding: 0.3em 1em !important; - position:relative; - margin: 0px auto 0 auto !important; - font-weight: bold !important; - border-bottom: none !important; - border-top: none !important; - border-left: none !important; - border-right: none !important; - color: #FFFFFF !important; - #padding: 0.1em 1em !important; + background-color: #ececec; + height: 24px !important; + padding: 0.3em 1em !important; + position: relative; + margin: 0px auto 0 auto !important; + font-weight: bold !important; + border-bottom: none !important; + border-top: none !important; + border-left: none !important; + border-right: none !important; + color: #ffffff !important; + #padding: 0.1em 1em !important; - -moz-border-radius: 4px 4px 0 0; - -webkit-border-radius: 4px 4px 0 0; - border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + -webkit-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; } .ui-dialog .ui-dialog-title { - margin-left: 5px !important; - color: white !important; - font-weight: bold !important; - position: relative !important; - top: 3px; - font-size: 10pt; - left: 4px !important; - float: none !important; + margin-left: 5px !important; + color: white !important; + font-weight: bold !important; + position: relative !important; + top: 3px; + font-size: 10pt; + left: 4px !important; + float: none !important; } .ui-dialog.ui-draggable .ui-dialog-titlebar { - cursor: move !important; + cursor: move !important; } .ui-dialog .ui-dialog-titlebar-close { - width: 23px !important; - height: 23px !important; - background: url(images/dialog-titlebar-close.png) no-repeat !important; - position: absolute !important; - top: 6px; - right: 3px !important; - cursor: pointer !important; + width: 23px !important; + height: 23px !important; + background: url(images/dialog-titlebar-close.png) no-repeat !important; + position: absolute !important; + top: 6px; + right: 3px !important; + cursor: pointer !important; } - .ui-dialog .ui-dialog-titlebar-close span { - display: none !important; - } +.ui-dialog .ui-dialog-titlebar-close span { + display: none !important; +} - .ui-dialog .ui-dialog-titlebar-close-hover { - color: #000000 !important; - } +.ui-dialog .ui-dialog-titlebar-close-hover { + color: #000000 !important; +} - .ui-dialog .ui-dialog-titlebar-close:hover span { - display: none !important; - } +.ui-dialog .ui-dialog-titlebar-close:hover span { + display: none !important; +} - .ui-dialog .ui-dialog-titlebar-close:hover { - color: #000000 !important; - } - - +.ui-dialog .ui-dialog-titlebar-close:hover { + color: #000000 !important; +} .ui-dialog .ui-dialog-content { - margin: 12px !important; - #padding: 0.5em 1em !important; - overflow: auto !important; - - -moz-border-left: 1px solid #A9A9A9 !important; - -moz-border-right: 1px solid #A9A9A9 !important; - -moz-border-bottom: 1px solid #A9A9A9 !important; - -moz-border-radius: 8px 8px 8px 8px !important; - - -webkit-border-left: 1px solid #A9A9A9 !important; - -webkit-border-right: 1px solid #A9A9A9 !important; - -webkit-border-bottom: 1px solid #A9A9A9 !important; - -webkit-border-radius: 8px 8px 8px 8px !important; - - border-left: 1px solid #A9A9A9 !important; - border-right: 1px solid #A9A9A9 !important; - border-bottom: 1px solid #A9A9A9 !important; - border-radius: 8px 8px 8px 8px !important; - - background: #FFFFFF !important; - position: relative !important; + margin: 12px !important; + #padding: 0.5em 1em !important; + overflow: auto !important; + + -moz-border-left: 1px solid #a9a9a9 !important; + -moz-border-right: 1px solid #a9a9a9 !important; + -moz-border-bottom: 1px solid #a9a9a9 !important; + -moz-border-radius: 8px 8px 8px 8px !important; + + -webkit-border-left: 1px solid #a9a9a9 !important; + -webkit-border-right: 1px solid #a9a9a9 !important; + -webkit-border-bottom: 1px solid #a9a9a9 !important; + -webkit-border-radius: 8px 8px 8px 8px !important; + + border-left: 1px solid #a9a9a9 !important; + border-right: 1px solid #a9a9a9 !important; + border-bottom: 1px solid #a9a9a9 !important; + border-radius: 8px 8px 8px 8px !important; + + background: #ffffff !important; + position: relative !important; } .ui-tabs .ui-tabs-nav { - background-color: white !important; + background-color: white !important; } .ui-tabs-panel { - background: #ECECEC !important; - -moz-border-radius: 8px !important; - -webkit-border-radius: 8px !important; - border-radius: 8px !important; - -moz-border-top-left-radius: 0px !important; - -webkit-border-top-left-radius: 0px !important; - border-top-left-radius: 0px !important; - -moz-box-shadow: -1px 1px 6px #aaa; - -webkit-box-shadow: -1px 1px 6px #aaa; - box-shadow: 1px 1px 6px #aaa; + background: #ececec !important; + -moz-border-radius: 8px !important; + -webkit-border-radius: 8px !important; + border-radius: 8px !important; + -moz-border-top-left-radius: 0px !important; + -webkit-border-top-left-radius: 0px !important; + border-top-left-radius: 0px !important; + -moz-box-shadow: -1px 1px 6px #aaa; + -webkit-box-shadow: -1px 1px 6px #aaa; + box-shadow: 1px 1px 6px #aaa; } .ui-widget .ui-widget { - border: 0px !important; + border: 0px !important; } .ui-state-default:first-child { - margin-left: -3px !important; + margin-left: -3px !important; } .ui-state-default { - background: #fff !important; - border: 2px solid #ECECEC !important; - -moz-border-top-left-radius: 10px !important; - -webkit-top-left-border-radius: 10px !important; - border-top-left-radius: 10px !important; - -moz-border-top-right-radius: 10px !important; - -webkit-top-right-border-radius: 10px !important; - border-top-right-radius: 10px !important; - margin-left: 2px !important; + background: #fff !important; + border: 2px solid #ececec !important; + -moz-border-top-left-radius: 10px !important; + -webkit-top-left-border-radius: 10px !important; + border-top-left-radius: 10px !important; + -moz-border-top-right-radius: 10px !important; + -webkit-top-right-border-radius: 10px !important; + border-top-right-radius: 10px !important; + margin-left: 2px !important; } .ui-state-active { - background: #ECECEC !important; + background: #ececec !important; } .ui-dialog-content { - overflow: auto !important; - width: auto !important; - #height: auto !important; + overflow: auto !important; + width: auto !important; + #height: auto !important; } .ui-dialog .ui-dialog-buttonpane { - background-color: #2179B1; - position: absolute; - bottom: 8px; - right: 12px; - width: 100%; - text-align: right; - display: none; + background-color: #2179b1; + position: absolute; + bottom: 8px; + right: 12px; + width: 100%; + text-align: right; + display: none; } .ui-dialog .ui-dialog-buttonpane button { - margin-bottom: 6px; + margin-bottom: 6px; } .ui-dialog .ui-dialog-buttonpane button { - border-bottom-color: #708090; - border-right-color: #708090; - -moz-border-radius: 5%; - font-size: 0.85em; - font-weight: bold; - height: 22px; -} - -/* Dialog handle styles */ -/*Disabled*/ -/* -.ui-dialog .ui-resizable-n { - cursor: n-resize; - height: 6px; - width: 100%; - top: 0px; - left: 0px; - background: transparent url(images/dialog-n.gif) repeat scroll center top; -} - -.ui-dialog .ui-resizable-s { - cursor: s-resize; - height: 8px; - width: 100%; - bottom: 0px; - left: 0px; - background: transparent url(images/dialog-s.gif) repeat scroll center top; -} - -.ui-dialog .ui-resizable-e { - cursor: e-resize; - width: 7px; - right: 0px; - top: 0px; - height: 100%; - background: transparent url(images/dialog-e.gif) repeat scroll right center; -} - -.ui-dialog .ui-resizable-w { - cursor: w-resize; - width: 7px; - left: 0px; - top: 0px; - height: 100%; - background: transparent url(images/dialog-w.gif) repeat scroll right center; -} - -.ui-dialog .ui-resizable-se { - cursor: se-resize; - width: 9px; - height: 9px; - right: 0px; - bottom: 0px; - background: transparent url(images/dialog-se.gif); -} - -.ui-dialog .ui-resizable-sw { - cursor: sw-resize; - width: 9px; - height: 9px; - left: 0px; - bottom: 0px; - background: transparent url(images/dialog-sw.gif); -} - -.ui-dialog .ui-resizable-nw { - cursor: nw-resize; - width: 9px; - height: 29px; - left: 0px; - top: 0px; - background: transparent url(images/dialog-nw.gif); -} - -.ui-dialog .ui-resizable-ne { - cursor: ne-resize; - width: 9px; - height: 29px; - right: 0px; - top: 0px; - background: transparent url(images/dialog-ne.gif); -} -*/ - -.ui-dialog .ui-button-dialog { - cursor: pointer; - margin: 0.5em 0.4em 0.5em 0; + border-bottom-color: #708090; + border-right-color: #708090; + -moz-border-radius: 5%; + font-size: 0.85em; + font-weight: bold; + height: 22px; } .ui-dialog .ui-button-dialog { - background: #F6F6F6; - border: 1px solid #CCCCCC; - color: #696969; - font-weight: bold; - outline: medium none; - cursor: pointer; - margin: 0.5em 0.4em 0.5em 0 !important; - border-radius: 4px 4px 4px 4px !important; + cursor: pointer; + margin: 0.5em 0.4em 0.5em 0; +} + +.ui-dialog .ui-button-dialog { + background: #f6f6f6; + border: 1px solid #cccccc; + color: #696969; + font-weight: bold; + outline: medium none; + cursor: pointer; + margin: 0.5em 0.4em 0.5em 0 !important; + border-radius: 4px 4px 4px 4px !important; } .ui-dialog .ui-button-dialog:hover { - background: #FDF5CE; - border: 1px solid #FBCB09; - color: #C77405; - font-weight: bold; - outline: medium none; + background: #fdf5ce; + border: 1px solid #fbcb09; + color: #c77405; + font-weight: bold; + outline: medium none; } .ui-dialog-overlay { - background: url("images/ui-bg_diagonals-thick_20_666666_40x40.png") repeat scroll 50% 50% #666666 !important; + background: url("images/ui-bg_diagonals-thick_20_666666_40x40.png") repeat + scroll 50% 50% #666666 !important; } diff --git a/pandora_console/include/styles/firts_task.css b/pandora_console/include/styles/firts_task.css index 63ed752579..32be0eb832 100755 --- a/pandora_console/include/styles/firts_task.css +++ b/pandora_console/include/styles/firts_task.css @@ -1,88 +1,79 @@ -.new_task -{ - margin-top: 30px; - left: 20px; - width: 60%; - height: 300px; - background-color: #ececec; - border-radius: 3px 3px 3px 3px; +.new_task { + margin-top: 30px; + left: 20px; + width: 60%; + height: 300px; + background-color: #ececec; + border-radius: 3px 3px 3px 3px; } -div.new_task_cluster -{ - margin-top: 30px; - left: 20px; - width: 60%; - border-radius: 3px 3px 3px 3px; +div.new_task_cluster { + margin-top: 30px; + left: 20px; + width: 60%; + border-radius: 3px 3px 3px 3px; } -div.new_task_cluster, div.new_task_cluster > div -{ - background-color: #ececec; +div.new_task_cluster, +div.new_task_cluster > div { + background-color: #ececec; } -.title_task -{ - background: url(../../images/icono_exclamacion.png) no-repeat scroll 280px 50% #82B92E; - padding: 10px 5px 6px 300px; - margin: 5px 5px 10px 5px; - font-weight: bold; - color: #FFF; - border-radius: 3px 3px 3px 3px; +.title_task { + background: url(../../images/icono_exclamacion.png) no-repeat scroll 280px 50% + #82b92e; + padding: 10px 5px 6px 300px; + margin: 5px 5px 10px 5px; + font-weight: bold; + color: #fff; + border-radius: 3px 3px 3px 3px; } -.image_task -{ - width:20%; - height:100%; - float:left; +.image_task { + width: 20%; + height: 100%; + float: left; } -.image_task_cluster -{ - width:20%; - height:100%; - float:left; - margin-left: 50px; - margin-top: 50px; +.image_task_cluster { + width: 20%; + height: 100%; + float: left; + margin-left: 50px; + margin-top: 50px; } -.image_task>img { - margin-top: 35%; - margin-left: 15%; +.image_task > img { + margin-top: 35%; + margin-left: 15%; } -.text_task -{ - width: 70%; - float: right; - height: 100%; - padding-right: 25px; +.text_task { + width: 70%; + float: right; + height: 100%; + padding-right: 25px; } -.text_task_cluster -{ - width: 70%; - height: 100%; - padding-right: 25px; - margin-left:270px; - padding-top:10px; +.text_task_cluster { + width: 70%; + height: 100%; + padding-right: 25px; + margin-left: 270px; + padding-top: 10px; } -.text_task>p -{ - margin-top: 4%; +.text_task > p { + margin-top: 4%; } -.button_task -{ - margin-top:10px; - background-color: #3F3F3F !important; - padding: 10px 10px 10px 10px; - font-weight: bold; - color: #82B92E; - border:none; +.button_task { + margin-top: 10px; + background-color: #3f3f3f !important; + padding: 10px 10px 10px 10px; + font-weight: bold; + color: #82b92e; + border: none; } -#description_task -{ - font-size: 12px; +#description_task { + font-size: 12px; } -#fuerte{ - font-size: 12px; +#fuerte { + font-size: 12px; } diff --git a/pandora_console/include/styles/fixed-bottom-box.css b/pandora_console/include/styles/fixed-bottom-box.css index 8a3e7de7aa..b278e16cec 100644 --- a/pandora_console/include/styles/fixed-bottom-box.css +++ b/pandora_console/include/styles/fixed-bottom-box.css @@ -1,98 +1,96 @@ div.fixed-bottom-box { - background: #E1E1E1; - - border-radius: 10px 10px 0 0; - -moz-border-radius: 10px 10px 0 0; - -webkit-border-radius: 10px 10px 0 0; - -o-border-radius: 10px 10px 0 0; - -ms-border-radius: 10px 10px 0 0; - -khtml-border-radius: 10px 10px 0 0; + background: #e1e1e1; + + border-radius: 10px 10px 0 0; + -moz-border-radius: 10px 10px 0 0; + -webkit-border-radius: 10px 10px 0 0; + -o-border-radius: 10px 10px 0 0; + -ms-border-radius: 10px 10px 0 0; + -khtml-border-radius: 10px 10px 0 0; } -div.fixed-bottom-box > -div.fixed-bottom-box-head { - height: 30px; - line-height: 30px; - vertical-align: middle; - background-color: #3F3F3F; - - border-radius: 10px 10px 0 0; - -moz-border-radius: 10px 10px 0 0; - -webkit-border-radius: 10px 10px 0 0; - -o-border-radius: 10px 10px 0 0; - -ms-border-radius: 10px 10px 0 0; - -khtml-border-radius: 10px 10px 0 0; +div.fixed-bottom-box > div.fixed-bottom-box-head { + height: 30px; + line-height: 30px; + vertical-align: middle; + background-color: #3f3f3f; + + border-radius: 10px 10px 0 0; + -moz-border-radius: 10px 10px 0 0; + -webkit-border-radius: 10px 10px 0 0; + -o-border-radius: 10px 10px 0 0; + -ms-border-radius: 10px 10px 0 0; + -khtml-border-radius: 10px 10px 0 0; } -div.fixed-bottom-box > -div.fixed-bottom-box-head > -div.fixed-bottom-box-head-body { - height: inherit; - line-height: inherit; - color: #FFFFFF; - font-weight: bold; - vertical-align: middle; - text-align: center; +div.fixed-bottom-box + > div.fixed-bottom-box-head + > div.fixed-bottom-box-head-body { + height: inherit; + line-height: inherit; + color: #ffffff; + font-weight: bold; + vertical-align: middle; + text-align: center; } -div.fixed-bottom-box > -div.fixed-bottom-box-head > -span.fixed-bottom-box-head-close { - height: 30px; - width: 30px; - background-image: url(../../images/input_cross.png); - background-repeat: no-repeat; - background-position: center; - float: right; +div.fixed-bottom-box + > div.fixed-bottom-box-head + > span.fixed-bottom-box-head-close { + height: 30px; + width: 30px; + background-image: url(../../images/input_cross.png); + background-repeat: no-repeat; + background-position: center; + float: right; } -div.fixed-bottom-box > -div.fixed-bottom-box-head > -div.fixed-bottom-box-head-body:hover { - cursor: pointer; - background-color: #747474; - - border-radius: inherit; - -moz-border-radius: inherit; - -webkit-border-radius: inherit; - -o-border-radius: inherit; - -ms-border-radius: inherit; - -khtml-border-radius: inherit; +div.fixed-bottom-box + > div.fixed-bottom-box-head + > div.fixed-bottom-box-head-body:hover { + cursor: pointer; + background-color: #747474; + + border-radius: inherit; + -moz-border-radius: inherit; + -webkit-border-radius: inherit; + -o-border-radius: inherit; + -ms-border-radius: inherit; + -khtml-border-radius: inherit; } -div.fixed-bottom-box > -div.fixed-bottom-box-head > -span.fixed-bottom-box-head-close:hover { - cursor: pointer; - background-color: #747474; - - border-radius: 0 10px 0 0; - -moz-border-radius: 0 10px 0 0; - -webkit-border-radius: 0 10px 0 0; - -o-border-radius: 0 10px 0 0; - -ms-border-radius: 0 10px 0 0; - -khtml-border-radius: 0 10px 0 0; +div.fixed-bottom-box + > div.fixed-bottom-box-head + > span.fixed-bottom-box-head-close:hover { + cursor: pointer; + background-color: #747474; + + border-radius: 0 10px 0 0; + -moz-border-radius: 0 10px 0 0; + -webkit-border-radius: 0 10px 0 0; + -o-border-radius: 0 10px 0 0; + -ms-border-radius: 0 10px 0 0; + -khtml-border-radius: 0 10px 0 0; } -div.fixed-bottom-box.fixed-bottom-box-hided > -div.fixed-bottom-box-head > -div.fixed-bottom-box-head-body { - /*background-image: url(../../images/.png); +div.fixed-bottom-box.fixed-bottom-box-hided + > div.fixed-bottom-box-head + > div.fixed-bottom-box-head-body { + /*background-image: url(../../images/.png); background-repeat: no-repeat; background-position: right;*/ } -div.fixed-bottom-box.fixed-bottom-box-opened > -div.fixed-bottom-box-head > -div.fixed-bottom-box-head-body { - /*background-image: url(../../images/.png); +div.fixed-bottom-box.fixed-bottom-box-opened + > div.fixed-bottom-box-head + > div.fixed-bottom-box-head-body { + /*background-image: url(../../images/.png); background-repeat: no-repeat; background-position: right;*/ } -div.fixed-bottom-box > -div.fixed-bottom-box-content { - vertical-align: top; - text-align: center; - overflow: auto; +div.fixed-bottom-box > div.fixed-bottom-box-content { + vertical-align: top; + text-align: center; + overflow: auto; } diff --git a/pandora_console/include/styles/help.css b/pandora_console/include/styles/help.css index 4edfeedbec..e6908771ff 100644 --- a/pandora_console/include/styles/help.css +++ b/pandora_console/include/styles/help.css @@ -1,54 +1,92 @@ /* -// Pandora FMS - the Flexible Monitoring System -// ============================================= -// Copyright (c) 2004-2009 Artica Soluciones Tecnológicas S.L - -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; version 2 - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// Pandora FMS - the Flexible Monitoring System +// ============================================= +// Copyright (c) 2004-2009 Artica Soluciones Tecnológicas S.L + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; version 2 + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ * { - font-family: verdana, sans-serif; - font-size: 8pt; + font-family: verdana, sans-serif; + font-size: 8pt; } -h1, h2, h3 { - font: bold 1em Arial, Sans-serif; - text-transform: uppercase; - color: #675; - padding-bottom: 5px; - padding-top: 7px; +h1, +h2, +h3 { + font: bold 1em Arial, Sans-serif; + text-transform: uppercase; + color: #675; + padding-bottom: 5px; + padding-top: 7px; } h1 { - font-size: 16px; + font-size: 16px; } h2 { - font-size: 15px; + font-size: 15px; } h3 { - font-size: 13px; + font-size: 13px; } a { - color: #486787; - text-decoration: none; + color: #486787; + text-decoration: none; +} +dd.help_t1 { + margin-left: 10px; + margin-top: 6px; + margin-bottom: 5px; + font-size: 13px; + font-weight: bold; +} +dd.help_t2 { + margin-left: 28px; + margin-top: 3px; +} +dd.help_t3 { + margin-left: 55px; + margin-top: 4px; +} +dd.help_t4 { + margin-left: 92px; + margin-top: 3px; + margin-bottom: 2px; +} +.ml15 { + margin-left: 15px; +} +.ml25 { + margin-left: 25px; +} +.ml35 { + margin-left: 35px; +} +.ml75 { + margin-left: 75px; +} +div.logo { + float: left; +} +div.toc { + padding-left: 200px; +} +div.rayah { + border-top: 1px solid #708090; + width: 100%; +} +div.rayah2 { + clear: both; + border-top: 1px solid #708090; + width: 100%; + padding-bottom: 35px; } -dd.help_t1 {margin-left: 10px; margin-top: 6px; margin-bottom: 5px; font-size: 13px; font-weight: bold} -dd.help_t2 {margin-left: 28px; margin-top: 3px;} -dd.help_t3 {margin-left: 55px; margin-top: 4px;} -dd.help_t4 {margin-left: 92px; margin-top: 3px; margin-bottom: 2px;} -.ml15 {margin-left: 15px;} -.ml25 {margin-left: 25px;} -.ml35 {margin-left: 35px;} -.ml75 {margin-left: 75px;} -div.logo {float:left;} -div.toc {padding-left: 200px;} -div.rayah {border-top: 1px solid #708090; width: 100%;} -div.rayah2 {clear:both; border-top: 1px solid #708090; width: 100%; padding-bottom: 35px;} diff --git a/pandora_console/include/styles/ie.css b/pandora_console/include/styles/ie.css index f76b98dd76..b8077309a8 100644 --- a/pandora_console/include/styles/ie.css +++ b/pandora_console/include/styles/ie.css @@ -17,69 +17,66 @@ */ .title .toggle { - background: none; + background: none; } .title .toggle { - background: transparent url(images/toggle.png) no-repeat scroll !important; + background: transparent url(images/toggle.png) no-repeat scroll !important; } .title a { - clear: none; - zoom: 100%; - padding: 1; + clear: none; + zoom: 100%; + padding: 1; } -* html .timeEntry_control { /* IE only */ - margin-top: -4px; +* html .timeEntry_control { + /* IE only */ + margin-top: -4px; } table#simple input#text-snmp_oid { - width: 70%; + width: 70%; } div.configuration { - margin-top: -20px; + margin-top: -20px; } form.delete_link { - display:inline; + display: inline; } ul.action_list { - list-style-position: outside; + list-style-position: outside; } ul.action_list li { - display: block; + display: block; } span.action_name { - vertical-align: top; - float: none; + vertical-align: top; + float: none; } div#foot { + background: #ccc; + width: auto; - background: #CCC; - width: auto; - - clear: both; - position: relative; - -moz-border-radius: 10px; - -webkit-border-radius: 10px; - border-radius: 10px; - -moz-box-shadow: 0px 0px 15px #000000; - -webkit-box-shadow: 0px 0px 15px #000000; - box-shadow: 0px 0px 15px #000000; + clear: both; + position: relative; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + border-radius: 10px; + -moz-box-shadow: 0px 0px 15px #000000; + -webkit-box-shadow: 0px 0px 15px #000000; + box-shadow: 0px 0px 15px #000000; } div#foot a { - color: #333!important; + color: #333 !important; } div#foot a.white:after { - - font-size: 10px; - color: #666666; - position: absolute; - bottom: 5px; - right: 10px; + font-size: 10px; + color: #666666; + position: absolute; + bottom: 5px; + right: 10px; } - - diff --git a/pandora_console/include/styles/install.css b/pandora_console/include/styles/install.css index 18ccab6663..51197b9da7 100644 --- a/pandora_console/include/styles/install.css +++ b/pandora_console/include/styles/install.css @@ -17,200 +17,203 @@ */ h1 { - font: bold 1em Arial, Sans-serif; - font-size: 18px; - color: #ffffff; - text-align: center; + font: bold 1em Arial, Sans-serif; + font-size: 18px; + color: #ffffff; + text-align: center; } h2 { - font: Verdana; - font-size: 16px; + font: Verdana; + font-size: 16px; } div#install_container { - margin: 0 auto; - margin-top: 45px; - width: 650px; + margin: 0 auto; + margin-top: 45px; + width: 650px; } div#logo_img { - text-align: center; - width: 100%; - color: #666; + text-align: center; + width: 100%; + color: #666; } div#wizard { - text-align: left; - margin-top: 1em; + text-align: left; + margin-top: 1em; - width: 650px; - padding-left: 0px; - padding-top: 0px; - padding-bottom: 20px; - background-color: #ffffff; - margin-top: 0px; - margin-left: 0px; - margin-right: 0px; - position: relative; + width: 650px; + padding-left: 0px; + padding-top: 0px; + padding-bottom: 20px; + background-color: #ffffff; + margin-top: 0px; + margin-left: 0px; + margin-right: 0px; + position: relative; } div#wizard a img { - padding-right: 30px; + padding-right: 30px; } -div#wizard>input { - padding-right: 30px; - float:right; - margin-top: 20px; +div#wizard > input { + padding-right: 30px; + float: right; + margin-top: 20px; } -div#install_box, div#install_img { - padding-right: 20px; - margin-top: 0px; - width: 80%; - margin: 0px auto; +div#install_box, +div#install_img { + padding-right: 20px; + margin-top: 0px; + width: 80%; + margin: 0px auto; } div#install_box { - background: F3F3F3; - border: 1px solid #ccc; - padding: 10px 25px; - margin-top: 40px; + background: F3F3F3; + border: 1px solid #ccc; + padding: 10px 25px; + margin-top: 40px; } div#install_box h2 { - color: #82B92E; - text-transform: uppercase; + color: #82b92e; + text-transform: uppercase; } div#install_img { - margin-bottom: 25px; - margin-left: 25px; + margin-bottom: 25px; + margin-left: 25px; } div#foot_install { - font-size: 7pt; - color: #fff; - margin-top: #000; - padding-top: 5px; - padding-bottom: 5px; - padding-left: 20px; - padding-right: 20px; - text-align: center; + font-size: 7pt; + color: #fff; + margin-top: #000; + padding-top: 5px; + padding-bottom: 5px; + padding-left: 20px; + padding-right: 20px; + text-align: center; } div#foot_install a { - color: #ccc; + color: #ccc; } -input#step4, input#step4:hover { - width: 70px; - height: 16px; - border: 0px; - background-color: #fafafa; +input#step4, +input#step4:hover { + width: 70px; + height: 16px; + border: 0px; + background-color: #fafafa; } div.warn { - min-height: 24px; - background: url(../../images/icono_warning_install.png) no-repeat 0% -2px; - color: #222; - margin-top: 14px; - padding: 2px 1px 6px 40px; + min-height: 24px; + background: url(../../images/icono_warning_install.png) no-repeat 0% -2px; + color: #222; + margin-top: 14px; + padding: 2px 1px 6px 40px; } div.info { - min-height: 24px; - background: url(../../images/icono_info_install.png) no-repeat 0% -2px; - color: #222; - margin-top: 14px; - padding: 2px 1px 6px 40px; + min-height: 24px; + background: url(../../images/icono_info_install.png) no-repeat 0% -2px; + color: #222; + margin-top: 14px; + padding: 2px 1px 6px 40px; } div.err { - min-height: 24px; - background: url(../../images/icono_critical_install.png) no-repeat 0% -2px; - color: #cc0000; - margin-top: 14px; - padding: 2px 1px 6px 40px; + min-height: 24px; + background: url(../../images/icono_critical_install.png) no-repeat 0% -2px; + color: #cc0000; + margin-top: 14px; + padding: 2px 1px 6px 40px; } span.arr { - background: url(../../images/arrow.png) no-repeat; - margin-top: 2px; - margin-left: 5px; - padding: 2px 1px 6px 15px; - display: block; - font-family: verdana,arial, sans; - font-size: 8.5pt; + background: url(../../images/arrow.png) no-repeat; + margin-top: 2px; + margin-left: 5px; + padding: 2px 1px 6px 15px; + display: block; + font-family: verdana, arial, sans; + font-size: 8.5pt; } -body, td { - font-family: Sans, Arial, sans; - font-size: 9pt; - line-height: 15px; +body, +td { + font-family: Sans, Arial, sans; + font-size: 9pt; + line-height: 15px; } -body{ - background-color: #555555; +body { + background-color: #555555; } div.installation_step { - position: static; - float: right; - top: 7px; - right: 10px; - color: #666; - margin-top: 14px; - margin-right: 12px; + position: static; + float: right; + top: 7px; + right: 10px; + color: #666; + margin-top: 14px; + margin-right: 12px; } .btn_install_next { - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - margin: 10px; - padding: 8px 20px 8px 20px; - background-color: transparent; - border: 1px solid #82B92E; - font: 1em Verdana; - font-size: 11pt; - color: #82B92E; - border-radius: 0%; -} -.btn_install_next:hover { - cursor: pointer; - transition-property: background-color, color; - transition-duration: 1s; + transition-property: background-color, color; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - background-color:#82b92e; + margin: 10px; + padding: 8px 20px 8px 20px; + background-color: transparent; + border: 1px solid #82b92e; + font: 1em Verdana; + font-size: 11pt; + color: #82b92e; + border-radius: 0%; +} +.btn_install_next:hover { + cursor: pointer; + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + background-color: #82b92e; } .btn_install_next_text { transition-property: background-color, color; - transition-duration: 1s; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - color:#82b92e; - font-family: Sans, Arial, sans; + color: #82b92e; + font-family: Sans, Arial, sans; } .btn_install_next:hover .btn_install_next_text { transition-property: background-color, color; - transition-duration: 1s; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - color:white; + color: white; } :focus { - outline: 0; + outline: 0; } /* POPUP */ -.popup-lightbox{ +.popup-lightbox { position: fixed; z-index: 8888; width: 100%; @@ -220,52 +223,52 @@ div.installation_step { visibility: hidden; } -.popup{ - max-height: 450px; +.popup { + max-height: 450px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); - -webkit-transform: translate(-50%, -50%); - background-color: #FFF; - z-index: 9999; - display: none; + -webkit-transform: translate(-50%, -50%); + background-color: #fff; + z-index: 9999; + display: none; } -.popup-title{ - background-color: #82b92e; - padding: 10px 20px; - color: #FFF; - font-size:12pt; +.popup-title { + background-color: #82b92e; + padding: 10px 20px; + color: #fff; + font-size: 12pt; text-align: center; - font-family:Sans, Arial, sans; + font-family: Sans, Arial, sans; } -.popup-inner{ - max-height: 350px; - background: #FFF; -/* overflow-y: scroll;*/ - padding: 25px 35px; +.popup-inner { + max-height: 350px; + background: #fff; + /* overflow-y: scroll;*/ + padding: 25px 35px; font-size: 11pt; } -.popup-button-green{ - background-color: #82B92E; - border: 1px solid transparent; - color: blue; +.popup-button-green { + background-color: #82b92e; + border: 1px solid transparent; + color: #fff; } -.popup-button-green span{ - color: #FFF !important; +.popup-button-green span { + color: #fff !important; } -.popup-button-green:hover{ - background-color: transparent !important; - border: 1px solid #82B92E; - color: red !important; +.popup-button-green:hover { + background-color: transparent !important; + border: 1px solid #82b92e; + color: #82b92e !important; } -.popup-button-green:hover span{ - color: #82B92E !important; +.popup-button-green:hover span { + color: #82b92e !important; } /* POPUP -END */ diff --git a/pandora_console/include/styles/js/calendar.css b/pandora_console/include/styles/js/calendar.css new file mode 100644 index 0000000000..73315cf0e3 --- /dev/null +++ b/pandora_console/include/styles/js/calendar.css @@ -0,0 +1,67 @@ +/* + * --------------------------------------------------------------------- + * - CALENDAR TOOLTIP - + * --------------------------------------------------------------------- + */ + +/* Calendar background */ +table.scw { + background-color: #82b92e; + border: 0 !important; + border-radius: 4px; +} + +/* Week number heading */ +td.scwWeekNumberHead { + color: #111; +} + +td.scwWeek { + color: #111 !important; +} + +/* Today selector */ +td.scwFootDisabled { + background-color: #000; + color: #ffffff; +} + +tfoot.scwFoot { + color: #111; +} + +.scwFoot :hover { + color: #3f3f3f !important; +} + +table.scwCells { + background-color: #fff !important; + color: #3c3c3c !important; +} + +table.scwCells:hover { + background-color: #fff !important; +} + +td.scwCellsExMonth { + background-color: #eee !important; + color: #3c3c3c !important; +} + +td.scwCellsWeekend { + background-color: #3c3c3c !important; + color: #fff !important; + border: 0 !important; +} + +td.scwInputDate { + background-color: #777 !important; + color: #ffffff !important; + border: 0 !important; +} + +td.scwFoot { + background-color: #fff !important; + color: #3c3c3c !important; + border: 0 !important; +} diff --git a/pandora_console/include/styles/js/cluetip.css b/pandora_console/include/styles/js/cluetip.css new file mode 100644 index 0000000000..dea766762b --- /dev/null +++ b/pandora_console/include/styles/js/cluetip.css @@ -0,0 +1,99 @@ +/* global */ +#cluetip-close img { + border: 0; +} +#cluetip-title { + overflow: hidden; +} +#cluetip-title #cluetip-close { + float: right; + position: relative; +} +#cluetip-waitimage { + width: 43px; + height: 11px; + position: absolute; + background-image: url(../../images/wait.gif); +} +.cluetip-arrows { + display: none; + position: absolute; + top: 0; + left: -11px; + height: 22px; + width: 11px; + background-repeat: no-repeat; + background-position: 0 0; +} +#cluetip-extra { + display: none; +} +/*************************************** + =cluetipClass: 'default' +-------------------------------------- */ + +.cluetip-default { + background-color: #fff; + text-align: left; +} +.cluetip-default #cluetip-outer { + position: relative; + margin: 0; + background-color: #fff; +} +.cluetip-default h3 { + margin: 0 0 5px; + padding: 8px 10px 4px; + font-size: 1.1em; + font-weight: bold; + background-color: #b1b1b1; + color: #fff; +} +.cluetip-default h3#cluetip-title { + display: none; + height: 0px; + margin: 0; + padding: 0; + color: #fff; +} +.cluetip-default #cluetip-title a { + color: #fff; + font-size: 0.95em; +} +.cluetip-default #cluetip-inner { + padding: 10px; +} +.cluetip-default div#cluetip-close { + text-align: right; + margin: 0 5px 5px; + color: #900; +} +.cluetip-default ul { + text-align: left; +} +/* default arrows */ + +.clue-right-default .cluetip-arrows { + background-image: url(../../images/darrowleft.png); +} +.clue-left-default .cluetip-arrows { + background-image: url(../../images/darrowright.png); + left: 100%; + margin-right: -11px; +} +.clue-top-default .cluetip-arrows { + background-image: url(../../images/darrowdown.png); + top: 100%; + left: 50%; + margin-left: -11px; + height: 11px; + width: 22px; +} +.clue-bottom-default .cluetip-arrows { + background-image: url(../../images/darrowup.png); + top: -11px; + left: 50%; + margin-left: -11px; + height: 11px; + width: 22px; +} diff --git a/pandora_console/include/styles/js/color-picker.css b/pandora_console/include/styles/js/color-picker.css new file mode 100644 index 0000000000..2360bd346b --- /dev/null +++ b/pandora_console/include/styles/js/color-picker.css @@ -0,0 +1,24 @@ +#ColorPickerDiv { + display: block; + display: none; + position: relative; + border: 1px solid #777; + background: #fff; +} + +#ColorPickerDiv td.color { + cursor: pointer; + font-size: xx-small; + font-family: "Arial", "Microsoft Sans Serif"; +} +#ColorPickerDiv td.color label { + cursor: pointer; +} + +.ColorPickerDivSample { + margin: 0px 0px 0px 4px; + border: solid 1px #000; + padding: 0px 10px; + position: relative; + cursor: pointer; +} diff --git a/pandora_console/include/styles/datatables.min.css b/pandora_console/include/styles/js/datatables.min.css similarity index 100% rename from pandora_console/include/styles/datatables.min.css rename to pandora_console/include/styles/js/datatables.min.css diff --git a/pandora_console/include/javascript/introjs.css b/pandora_console/include/styles/js/introjs.css similarity index 58% rename from pandora_console/include/javascript/introjs.css rename to pandora_console/include/styles/js/introjs.css index cab762e70c..03db182404 100644 --- a/pandora_console/include/javascript/introjs.css +++ b/pandora_console/include/styles/js/introjs.css @@ -3,25 +3,58 @@ z-index: 999999; background-color: #000; opacity: 0; - background: -moz-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); - background: -webkit-gradient(radial,center center,0px,center center,100%,color-stop(0%,rgba(0,0,0,0.4)),color-stop(100%,rgba(0,0,0,0.9))); - background: -webkit-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); - background: -o-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); - background: -ms-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); - background: radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: -moz-radial-gradient( + center, + ellipse cover, + rgba(0, 0, 0, 0.4) 0, + rgba(0, 0, 0, 0.9) 100% + ); + background: -webkit-gradient( + radial, + center center, + 0px, + center center, + 100%, + color-stop(0%, rgba(0, 0, 0, 0.4)), + color-stop(100%, rgba(0, 0, 0, 0.9)) + ); + background: -webkit-radial-gradient( + center, + ellipse cover, + rgba(0, 0, 0, 0.4) 0, + rgba(0, 0, 0, 0.9) 100% + ); + background: -o-radial-gradient( + center, + ellipse cover, + rgba(0, 0, 0, 0.4) 0, + rgba(0, 0, 0, 0.9) 100% + ); + background: -ms-radial-gradient( + center, + ellipse cover, + rgba(0, 0, 0, 0.4) 0, + rgba(0, 0, 0, 0.9) 100% + ); + background: radial-gradient( + center, + ellipse cover, + rgba(0, 0, 0, 0.4) 0, + rgba(0, 0, 0, 0.9) 100% + ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#66000000',endColorstr='#e6000000',GradientType=1); -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; filter: alpha(opacity=50); -webkit-transition: all 0.3s ease-out; - -moz-transition: all 0.3s ease-out; - -ms-transition: all 0.3s ease-out; - -o-transition: all 0.3s ease-out; - transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + -ms-transition: all 0.3s ease-out; + -o-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; } .introjs-fixParent { z-index: auto !important; - opacity: 1.0 !important; + opacity: 1 !important; } .introjs-showElement, @@ -39,17 +72,17 @@ tr.introjs-showElement > th { .introjs-helperLayer { position: absolute; z-index: 9999998; - background-color: #FFF; - background-color: rgba(255,255,255,.9); + background-color: #fff; + background-color: rgba(255, 255, 255, 0.9); border: 1px solid #777; - border: 1px solid rgba(0,0,0,.5); + border: 1px solid rgba(0, 0, 0, 0.5); border-radius: 4px; - box-shadow: 0 2px 15px rgba(0,0,0,.4); + box-shadow: 0 2px 15px rgba(0, 0, 0, 0.4); -webkit-transition: all 0.3s ease-out; - -moz-transition: all 0.3s ease-out; - -ms-transition: all 0.3s ease-out; - -o-transition: all 0.3s ease-out; - transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + -ms-transition: all 0.3s ease-out; + -o-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; } .introjs-helperNumberLayer { @@ -63,75 +96,89 @@ tr.introjs-showElement > th { font-weight: bold; color: white; text-align: center; - text-shadow: 1px 1px 1px rgba(0,0,0,.3); + text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3); background: #ff3019; /* Old browsers */ - background: -webkit-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* Chrome10+,Safari5.1+ */ - background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ff3019), color-stop(100%, #cf0404)); /* Chrome,Safari4+ */ - background: -moz-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* FF3.6+ */ - background: -ms-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* IE10+ */ - background: -o-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* Opera 11.10+ */ - background: linear-gradient(to bottom, #ff3019 0%, #cf0404 100%); /* W3C */ + background: -webkit-linear-gradient( + top, + #ff3019 0%, + #cf0404 100% + ); /* Chrome10+,Safari5.1+ */ + background: -webkit-gradient( + linear, + left top, + left bottom, + color-stop(0%, #ff3019), + color-stop(100%, #cf0404) + ); /* Chrome,Safari4+ */ + background: -moz-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* FF3.6+ */ + background: -ms-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* IE10+ */ + background: -o-linear-gradient( + top, + #ff3019 0%, + #cf0404 100% + ); /* Opera 11.10+ */ + background: linear-gradient(to bottom, #ff3019 0%, #cf0404 100%); /* W3C */ width: 20px; - height:20px; + height: 20px; line-height: 20px; border: 3px solid white; border-radius: 50%; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3019', endColorstr='#cf0404', GradientType=0); /* IE6-9 */ filter: progid:DXImageTransform.Microsoft.Shadow(direction=135, strength=2, color=ff0000); /* IE10 text shadows */ - box-shadow: 0 2px 5px rgba(0,0,0,.4); + box-shadow: 0 2px 5px rgba(0, 0, 0, 0.4); } .introjs-arrow { border: 5px solid white; - content:''; + content: ""; position: absolute; } .introjs-arrow.top { top: -10px; - border-top-color:transparent; - border-right-color:transparent; - border-bottom-color:white; - border-left-color:transparent; + border-top-color: transparent; + border-right-color: transparent; + border-bottom-color: white; + border-left-color: transparent; } .introjs-arrow.top-right { top: -10px; right: 10px; - border-top-color:transparent; - border-right-color:transparent; - border-bottom-color:white; - border-left-color:transparent; + border-top-color: transparent; + border-right-color: transparent; + border-bottom-color: white; + border-left-color: transparent; } .introjs-arrow.top-middle { top: -10px; left: 50%; margin-left: -5px; - border-top-color:transparent; - border-right-color:transparent; - border-bottom-color:white; - border-left-color:transparent; + border-top-color: transparent; + border-right-color: transparent; + border-bottom-color: white; + border-left-color: transparent; } .introjs-arrow.right { right: -10px; top: 10px; - border-top-color:transparent; - border-right-color:transparent; - border-bottom-color:transparent; - border-left-color:white; + border-top-color: transparent; + border-right-color: transparent; + border-bottom-color: transparent; + border-left-color: white; } .introjs-arrow.bottom { bottom: -10px; - border-top-color:white; - border-right-color:transparent; - border-bottom-color:transparent; - border-left-color:transparent; + border-top-color: white; + border-right-color: transparent; + border-bottom-color: transparent; + border-left-color: transparent; } .introjs-arrow.left { left: -10px; top: 10px; - border-top-color:transparent; - border-right-color:white; - border-bottom-color:transparent; - border-left-color:transparent; + border-top-color: transparent; + border-right-color: white; + border-bottom-color: transparent; + border-left-color: transparent; } .introjs-tooltip { @@ -141,12 +188,12 @@ tr.introjs-showElement > th { min-width: 220px; max-width: 260px; border-radius: 3px; - box-shadow: 0 1px 10px rgba(0,0,0,.4); + box-shadow: 0 1px 10px rgba(0, 0, 0, 0.4); -webkit-transition: opacity 0.1s ease-out; - -moz-transition: opacity 0.1s ease-out; - -ms-transition: opacity 0.1s ease-out; - -o-transition: opacity 0.1s ease-out; - transition: opacity 0.1s ease-out; + -moz-transition: opacity 0.1s ease-out; + -ms-transition: opacity 0.1s ease-out; + -o-transition: opacity 0.1s ease-out; + transition: opacity 0.1s ease-out; } .introjs-tooltipbuttons { @@ -166,13 +213,19 @@ tr.introjs-showElement > th { margin: 0; text-decoration: none; text-shadow: 1px 1px 0 #fff; - font: 11px/normal sans-serif; + font: 11px / normal sans-serif; color: #333; white-space: nowrap; cursor: pointer; outline: none; background-color: #ececec; - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f4f4f4), to(#ececec)); + background-image: -webkit-gradient( + linear, + 0 0, + 0 100%, + from(#f4f4f4), + to(#ececec) + ); background-image: -moz-linear-gradient(#f4f4f4, #ececec); background-image: -o-linear-gradient(#f4f4f4, #ececec); background-image: linear-gradient(#f4f4f4, #ececec); @@ -197,7 +250,13 @@ tr.introjs-showElement > th { .introjs-button:focus, .introjs-button:active { - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ececec), to(#f4f4f4)); + background-image: -webkit-gradient( + linear, + 0 0, + 0 100%, + from(#ececec), + to(#f4f4f4) + ); background-image: -moz-linear-gradient(#ececec, #f4f4f4); background-image: -o-linear-gradient(#ececec, #f4f4f4); background-image: linear-gradient(#ececec, #f4f4f4); @@ -227,7 +286,9 @@ tr.introjs-showElement > th { border-radius: 0 0.2em 0.2em 0; } -.introjs-disabled, .introjs-disabled:hover, .introjs-disabled:focus { +.introjs-disabled, +.introjs-disabled:hover, +.introjs-disabled:focus { color: #9a9a9a; border-color: #d4d4d4; box-shadow: none; diff --git a/pandora_console/include/styles/jquery-ui.min.css b/pandora_console/include/styles/js/jquery-ui.min.css similarity index 99% rename from pandora_console/include/styles/jquery-ui.min.css rename to pandora_console/include/styles/js/jquery-ui.min.css index 121f222ff1..86e93597f3 100644 --- a/pandora_console/include/styles/jquery-ui.min.css +++ b/pandora_console/include/styles/js/jquery-ui.min.css @@ -4,4 +4,6 @@ * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Arial%2CHelvetica%2Csans-serif&fsDefault=1em&fwDefault=normal&cornerRadius=3px&bgColorHeader=e9e9e9&bgTextureHeader=flat&borderColorHeader=dddddd&fcHeader=333333&iconColorHeader=444444&bgColorContent=ffffff&bgTextureContent=flat&borderColorContent=dddddd&fcContent=333333&iconColorContent=444444&bgColorDefault=f6f6f6&bgTextureDefault=flat&borderColorDefault=c5c5c5&fcDefault=454545&iconColorDefault=777777&bgColorHover=ededed&bgTextureHover=flat&borderColorHover=cccccc&fcHover=2b2b2b&iconColorHover=555555&bgColorActive=007fff&bgTextureActive=flat&borderColorActive=003eff&fcActive=ffffff&iconColorActive=ffffff&bgColorHighlight=fffa90&bgTextureHighlight=flat&borderColorHighlight=dad55e&fcHighlight=777620&iconColorHighlight=777620&bgColorError=fddfdf&bgTextureError=flat&borderColorError=f1a899&fcError=5f3f3f&iconColorError=cc0000&bgColorOverlay=aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=666666&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=5px&offsetTopShadow=0px&offsetLeftShadow=0px&cornerRadiusShadow=8px * Copyright jQuery Foundation and other contributors; Licensed MIT */ +@import url(jquery-ui_custom.css); + .ui-helper-hidden{display:none}.ui-helper-hidden-accessible{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table;border-collapse:collapse}.ui-helper-clearfix:after{clear:both}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0;filter:Alpha(Opacity=0)}.ui-front{z-index:100}.ui-state-disabled{cursor:default!important;pointer-events:none}.ui-icon{display:inline-block;vertical-align:middle;margin-top:-.25em;position:relative;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-icon-block{left:50%;margin-left:-8px;display:block}.ui-widget-overlay{position:fixed;top:0;left:0;width:100%;height:100%}.ui-accordion .ui-accordion-header{display:block;cursor:pointer;position:relative;margin:2px 0 0 0;padding:.5em .5em .5em .7em;font-size:100%}.ui-accordion .ui-accordion-content{padding:1em 2.2em;border-top:0;overflow:auto}.ui-autocomplete{position:absolute;top:0;left:0;cursor:default}.ui-menu{list-style:none;padding:0;margin:0;display:block;outline:0}.ui-menu .ui-menu{position:absolute}.ui-menu .ui-menu-item{margin:0;cursor:pointer;list-style-image:url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")}.ui-menu .ui-menu-item-wrapper{position:relative;padding:3px 1em 3px .4em}.ui-menu .ui-menu-divider{margin:5px 0;height:0;font-size:0;line-height:0;border-width:1px 0 0 0}.ui-menu .ui-state-focus,.ui-menu .ui-state-active{margin:-1px}.ui-menu-icons{position:relative}.ui-menu-icons .ui-menu-item-wrapper{padding-left:2em}.ui-menu .ui-icon{position:absolute;top:0;bottom:0;left:.2em;margin:auto 0}.ui-menu .ui-menu-icon{left:auto;right:0}.ui-button{padding:.4em 1em;display:inline-block;position:relative;line-height:normal;margin-right:.1em;cursor:pointer;vertical-align:middle;text-align:center;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:visible}.ui-button,.ui-button:link,.ui-button:visited,.ui-button:hover,.ui-button:active{text-decoration:none}.ui-button-icon-only{width:2em;box-sizing:border-box;text-indent:-9999px;white-space:nowrap}input.ui-button.ui-button-icon-only{text-indent:0}.ui-button-icon-only .ui-icon{position:absolute;top:50%;left:50%;margin-top:-8px;margin-left:-8px}.ui-button.ui-icon-notext .ui-icon{padding:0;width:2.1em;height:2.1em;text-indent:-9999px;white-space:nowrap}input.ui-button.ui-icon-notext .ui-icon{width:auto;height:auto;text-indent:0;white-space:normal;padding:.4em 1em}input.ui-button::-moz-focus-inner,button.ui-button::-moz-focus-inner{border:0;padding:0}.ui-controlgroup{vertical-align:middle;display:inline-block}.ui-controlgroup > .ui-controlgroup-item{float:left;margin-left:0;margin-right:0}.ui-controlgroup > .ui-controlgroup-item:focus,.ui-controlgroup > .ui-controlgroup-item.ui-visual-focus{z-index:9999}.ui-controlgroup-vertical > .ui-controlgroup-item{display:block;float:none;width:100%;margin-top:0;margin-bottom:0;text-align:left}.ui-controlgroup-vertical .ui-controlgroup-item{box-sizing:border-box}.ui-controlgroup .ui-controlgroup-label{padding:.4em 1em}.ui-controlgroup .ui-controlgroup-label span{font-size:80%}.ui-controlgroup-horizontal .ui-controlgroup-label + .ui-controlgroup-item{border-left:none}.ui-controlgroup-vertical .ui-controlgroup-label + .ui-controlgroup-item{border-top:none}.ui-controlgroup-horizontal .ui-controlgroup-label.ui-widget-content{border-right:none}.ui-controlgroup-vertical .ui-controlgroup-label.ui-widget-content{border-bottom:none}.ui-controlgroup-vertical .ui-spinner-input{width:75%;width:calc( 100% - 2.4em )}.ui-controlgroup-vertical .ui-spinner .ui-spinner-up{border-top-style:solid}.ui-checkboxradio-label .ui-icon-background{box-shadow:inset 1px 1px 1px #ccc;border-radius:.12em;border:none}.ui-checkboxradio-radio-label .ui-icon-background{width:16px;height:16px;border-radius:1em;overflow:visible;border:none}.ui-checkboxradio-radio-label.ui-checkboxradio-checked .ui-icon,.ui-checkboxradio-radio-label.ui-checkboxradio-checked:hover .ui-icon{background-image:none;width:8px;height:8px;border-width:4px;border-style:solid}.ui-checkboxradio-disabled{pointer-events:none}.ui-datepicker{width:17em;padding:.2em .2em 0;display:none}.ui-datepicker .ui-datepicker-header{position:relative;padding:.2em 0}.ui-datepicker .ui-datepicker-prev,.ui-datepicker .ui-datepicker-next{position:absolute;top:2px;width:1.8em;height:1.8em}.ui-datepicker .ui-datepicker-prev-hover,.ui-datepicker .ui-datepicker-next-hover{top:1px}.ui-datepicker .ui-datepicker-prev{left:2px}.ui-datepicker .ui-datepicker-next{right:2px}.ui-datepicker .ui-datepicker-prev-hover{left:1px}.ui-datepicker .ui-datepicker-next-hover{right:1px}.ui-datepicker .ui-datepicker-prev span,.ui-datepicker .ui-datepicker-next span{display:block;position:absolute;left:50%;margin-left:-8px;top:50%;margin-top:-8px}.ui-datepicker .ui-datepicker-title{margin:0 2.3em;line-height:1.8em;text-align:center}.ui-datepicker .ui-datepicker-title select{font-size:1em;margin:1px 0}.ui-datepicker select.ui-datepicker-month,.ui-datepicker select.ui-datepicker-year{width:45%}.ui-datepicker table{width:100%;font-size:.9em;border-collapse:collapse;margin:0 0 .4em}.ui-datepicker th{padding:.7em .3em;text-align:center;font-weight:bold;border:0}.ui-datepicker td{border:0;padding:1px}.ui-datepicker td span,.ui-datepicker td a{display:block;padding:.2em;text-align:right;text-decoration:none}.ui-datepicker .ui-datepicker-buttonpane{background-image:none;margin:.7em 0 0 0;padding:0 .2em;border-left:0;border-right:0;border-bottom:0}.ui-datepicker .ui-datepicker-buttonpane button{float:right;margin:.5em .2em .4em;cursor:pointer;padding:.2em .6em .3em .6em;width:auto;overflow:visible}.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current{float:left}.ui-datepicker.ui-datepicker-multi{width:auto}.ui-datepicker-multi .ui-datepicker-group{float:left}.ui-datepicker-multi .ui-datepicker-group table{width:95%;margin:0 auto .4em}.ui-datepicker-multi-2 .ui-datepicker-group{width:50%}.ui-datepicker-multi-3 .ui-datepicker-group{width:33.3%}.ui-datepicker-multi-4 .ui-datepicker-group{width:25%}.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header,.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-buttonpane{clear:left}.ui-datepicker-row-break{clear:both;width:100%;font-size:0}.ui-datepicker-rtl{direction:rtl}.ui-datepicker-rtl .ui-datepicker-prev{right:2px;left:auto}.ui-datepicker-rtl .ui-datepicker-next{left:2px;right:auto}.ui-datepicker-rtl .ui-datepicker-prev:hover{right:1px;left:auto}.ui-datepicker-rtl .ui-datepicker-next:hover{left:1px;right:auto}.ui-datepicker-rtl .ui-datepicker-buttonpane{clear:right}.ui-datepicker-rtl .ui-datepicker-buttonpane button{float:left}.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current,.ui-datepicker-rtl .ui-datepicker-group{float:right}.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header,.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker .ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat;left:.5em;top:.3em}.ui-dialog{position:absolute;top:0;left:0;padding:.2em;outline:0}.ui-dialog .ui-dialog-titlebar{padding:.4em 1em;position:relative}.ui-dialog .ui-dialog-title{float:left;margin:.1em 0;white-space:nowrap;width:90%;overflow:hidden;text-overflow:ellipsis}.ui-dialog .ui-dialog-titlebar-close{position:absolute;right:.3em;top:50%;width:20px;margin:-10px 0 0 0;padding:1px;height:20px}.ui-dialog .ui-dialog-content{position:relative;border:0;padding:.5em 1em;background:none;overflow:auto}.ui-dialog .ui-dialog-buttonpane{text-align:left;border-width:1px 0 0 0;background-image:none;margin-top:.5em;padding:.3em 1em .5em .4em}.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset{float:right}.ui-dialog .ui-dialog-buttonpane button{margin:.5em .4em .5em 0;cursor:pointer}.ui-dialog .ui-resizable-n{height:2px;top:0}.ui-dialog .ui-resizable-e{width:2px;right:0}.ui-dialog .ui-resizable-s{height:2px;bottom:0}.ui-dialog .ui-resizable-w{width:2px;left:0}.ui-dialog .ui-resizable-se,.ui-dialog .ui-resizable-sw,.ui-dialog .ui-resizable-ne,.ui-dialog .ui-resizable-nw{width:7px;height:7px}.ui-dialog .ui-resizable-se{right:0;bottom:0}.ui-dialog .ui-resizable-sw{left:0;bottom:0}.ui-dialog .ui-resizable-ne{right:0;top:0}.ui-dialog .ui-resizable-nw{left:0;top:0}.ui-draggable .ui-dialog-titlebar{cursor:move}.ui-draggable-handle{-ms-touch-action:none;touch-action:none}.ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:0.1px;display:block;-ms-touch-action:none;touch-action:none}.ui-resizable-disabled .ui-resizable-handle,.ui-resizable-autohide .ui-resizable-handle{display:none}.ui-resizable-n{cursor:n-resize;height:7px;width:100%;top:-5px;left:0}.ui-resizable-s{cursor:s-resize;height:7px;width:100%;bottom:-5px;left:0}.ui-resizable-e{cursor:e-resize;width:7px;right:-5px;top:0;height:100%}.ui-resizable-w{cursor:w-resize;width:7px;left:-5px;top:0;height:100%}.ui-resizable-se{cursor:se-resize;width:12px;height:12px;right:1px;bottom:1px}.ui-resizable-sw{cursor:sw-resize;width:9px;height:9px;left:-5px;bottom:-5px}.ui-resizable-nw{cursor:nw-resize;width:9px;height:9px;left:-5px;top:-5px}.ui-resizable-ne{cursor:ne-resize;width:9px;height:9px;right:-5px;top:-5px}.ui-progressbar{height:2em;text-align:left;overflow:hidden}.ui-progressbar .ui-progressbar-value{margin:-1px;height:100%}.ui-progressbar .ui-progressbar-overlay{background:url("data:image/gif;base64,R0lGODlhKAAoAIABAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJAQABACwAAAAAKAAoAAACkYwNqXrdC52DS06a7MFZI+4FHBCKoDeWKXqymPqGqxvJrXZbMx7Ttc+w9XgU2FB3lOyQRWET2IFGiU9m1frDVpxZZc6bfHwv4c1YXP6k1Vdy292Fb6UkuvFtXpvWSzA+HycXJHUXiGYIiMg2R6W459gnWGfHNdjIqDWVqemH2ekpObkpOlppWUqZiqr6edqqWQAAIfkECQEAAQAsAAAAACgAKAAAApSMgZnGfaqcg1E2uuzDmmHUBR8Qil95hiPKqWn3aqtLsS18y7G1SzNeowWBENtQd+T1JktP05nzPTdJZlR6vUxNWWjV+vUWhWNkWFwxl9VpZRedYcflIOLafaa28XdsH/ynlcc1uPVDZxQIR0K25+cICCmoqCe5mGhZOfeYSUh5yJcJyrkZWWpaR8doJ2o4NYq62lAAACH5BAkBAAEALAAAAAAoACgAAAKVDI4Yy22ZnINRNqosw0Bv7i1gyHUkFj7oSaWlu3ovC8GxNso5fluz3qLVhBVeT/Lz7ZTHyxL5dDalQWPVOsQWtRnuwXaFTj9jVVh8pma9JjZ4zYSj5ZOyma7uuolffh+IR5aW97cHuBUXKGKXlKjn+DiHWMcYJah4N0lYCMlJOXipGRr5qdgoSTrqWSq6WFl2ypoaUAAAIfkECQEAAQAsAAAAACgAKAAAApaEb6HLgd/iO7FNWtcFWe+ufODGjRfoiJ2akShbueb0wtI50zm02pbvwfWEMWBQ1zKGlLIhskiEPm9R6vRXxV4ZzWT2yHOGpWMyorblKlNp8HmHEb/lCXjcW7bmtXP8Xt229OVWR1fod2eWqNfHuMjXCPkIGNileOiImVmCOEmoSfn3yXlJWmoHGhqp6ilYuWYpmTqKUgAAIfkECQEAAQAsAAAAACgAKAAAApiEH6kb58biQ3FNWtMFWW3eNVcojuFGfqnZqSebuS06w5V80/X02pKe8zFwP6EFWOT1lDFk8rGERh1TTNOocQ61Hm4Xm2VexUHpzjymViHrFbiELsefVrn6XKfnt2Q9G/+Xdie499XHd2g4h7ioOGhXGJboGAnXSBnoBwKYyfioubZJ2Hn0RuRZaflZOil56Zp6iioKSXpUAAAh+QQJAQABACwAAAAAKAAoAAACkoQRqRvnxuI7kU1a1UU5bd5tnSeOZXhmn5lWK3qNTWvRdQxP8qvaC+/yaYQzXO7BMvaUEmJRd3TsiMAgswmNYrSgZdYrTX6tSHGZO73ezuAw2uxuQ+BbeZfMxsexY35+/Qe4J1inV0g4x3WHuMhIl2jXOKT2Q+VU5fgoSUI52VfZyfkJGkha6jmY+aaYdirq+lQAACH5BAkBAAEALAAAAAAoACgAAAKWBIKpYe0L3YNKToqswUlvznigd4wiR4KhZrKt9Upqip61i9E3vMvxRdHlbEFiEXfk9YARYxOZZD6VQ2pUunBmtRXo1Lf8hMVVcNl8JafV38aM2/Fu5V16Bn63r6xt97j09+MXSFi4BniGFae3hzbH9+hYBzkpuUh5aZmHuanZOZgIuvbGiNeomCnaxxap2upaCZsq+1kAACH5BAkBAAEALAAAAAAoACgAAAKXjI8By5zf4kOxTVrXNVlv1X0d8IGZGKLnNpYtm8Lr9cqVeuOSvfOW79D9aDHizNhDJidFZhNydEahOaDH6nomtJjp1tutKoNWkvA6JqfRVLHU/QUfau9l2x7G54d1fl995xcIGAdXqMfBNadoYrhH+Mg2KBlpVpbluCiXmMnZ2Sh4GBqJ+ckIOqqJ6LmKSllZmsoq6wpQAAAh+QQJAQABACwAAAAAKAAoAAAClYx/oLvoxuJDkU1a1YUZbJ59nSd2ZXhWqbRa2/gF8Gu2DY3iqs7yrq+xBYEkYvFSM8aSSObE+ZgRl1BHFZNr7pRCavZ5BW2142hY3AN/zWtsmf12p9XxxFl2lpLn1rseztfXZjdIWIf2s5dItwjYKBgo9yg5pHgzJXTEeGlZuenpyPmpGQoKOWkYmSpaSnqKileI2FAAACH5BAkBAAEALAAAAAAoACgAAAKVjB+gu+jG4kORTVrVhRlsnn2dJ3ZleFaptFrb+CXmO9OozeL5VfP99HvAWhpiUdcwkpBH3825AwYdU8xTqlLGhtCosArKMpvfa1mMRae9VvWZfeB2XfPkeLmm18lUcBj+p5dnN8jXZ3YIGEhYuOUn45aoCDkp16hl5IjYJvjWKcnoGQpqyPlpOhr3aElaqrq56Bq7VAAAOw==");height:100%;filter:alpha(opacity=25);opacity:0.25}.ui-progressbar-indeterminate .ui-progressbar-value{background-image:none}.ui-selectable{-ms-touch-action:none;touch-action:none}.ui-selectable-helper{position:absolute;z-index:100;border:1px dotted black}.ui-selectmenu-menu{padding:0;margin:0;position:absolute;top:0;left:0;display:none}.ui-selectmenu-menu .ui-menu{overflow:auto;overflow-x:hidden;padding-bottom:1px}.ui-selectmenu-menu .ui-menu .ui-selectmenu-optgroup{font-size:1em;font-weight:bold;line-height:1.5;padding:2px 0.4em;margin:0.5em 0 0 0;height:auto;border:0}.ui-selectmenu-open{display:block}.ui-selectmenu-text{display:block;margin-right:20px;overflow:hidden;text-overflow:ellipsis}.ui-selectmenu-button.ui-button{text-align:left;white-space:nowrap;width:14em}.ui-selectmenu-icon.ui-icon{float:right;margin-top:0}.ui-slider{position:relative;text-align:left}.ui-slider .ui-slider-handle{position:absolute;z-index:2;width:1.2em;height:1.2em;cursor:default;-ms-touch-action:none;touch-action:none}.ui-slider .ui-slider-range{position:absolute;z-index:1;font-size:.7em;display:block;border:0;background-position:0 0}.ui-slider.ui-state-disabled .ui-slider-handle,.ui-slider.ui-state-disabled .ui-slider-range{filter:inherit}.ui-slider-horizontal{height:.8em}.ui-slider-horizontal .ui-slider-handle{top:-.3em;margin-left:-.6em}.ui-slider-horizontal .ui-slider-range{top:0;height:100%}.ui-slider-horizontal .ui-slider-range-min{left:0}.ui-slider-horizontal .ui-slider-range-max{right:0}.ui-slider-vertical{width:.8em;height:100px}.ui-slider-vertical .ui-slider-handle{left:-.3em;margin-left:0;margin-bottom:-.6em}.ui-slider-vertical .ui-slider-range{left:0;width:100%}.ui-slider-vertical .ui-slider-range-min{bottom:0}.ui-slider-vertical .ui-slider-range-max{top:0}.ui-sortable-handle{-ms-touch-action:none;touch-action:none}.ui-spinner{position:relative;display:inline-block;overflow:hidden;padding:0;vertical-align:middle}.ui-spinner-input{border:none;background:none;color:inherit;padding:.222em 0;margin:.2em 0;vertical-align:middle;margin-left:.4em;margin-right:2em}.ui-spinner-button{width:1.6em;height:50%;font-size:.5em;padding:0;margin:0;text-align:center;position:absolute;cursor:default;display:block;overflow:hidden;right:0}.ui-spinner a.ui-spinner-button{border-top-style:none;border-bottom-style:none;border-right-style:none}.ui-spinner-up{top:0}.ui-spinner-down{bottom:0}.ui-tabs{position:relative;padding:.2em}.ui-tabs .ui-tabs-nav{margin:0;padding:.2em .2em 0}.ui-tabs .ui-tabs-nav li{list-style:none;float:left;position:relative;top:0;margin:1px .2em 0 0;border-bottom-width:0;padding:0;white-space:nowrap}.ui-tabs .ui-tabs-nav .ui-tabs-anchor{float:left;padding:.5em 1em;text-decoration:none}.ui-tabs .ui-tabs-nav li.ui-tabs-active{margin-bottom:-1px;padding-bottom:1px}.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor,.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor,.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor{cursor:text}.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor{cursor:pointer}.ui-tabs .ui-tabs-panel{display:block;border-width:0;padding:1em 1.4em;background:none}.ui-tooltip{padding:8px;position:absolute;z-index:9999;max-width:300px}body .ui-tooltip{border-width:2px}.ui-widget{font-family:Arial,Helvetica,sans-serif;font-size:1em}.ui-widget .ui-widget{font-size:1em}.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button{font-family:Arial,Helvetica,sans-serif;font-size:1em}.ui-widget.ui-widget-content{border:1px solid #c5c5c5}.ui-widget-content{border:1px solid #ddd;background:#fff;color:#333}.ui-widget-content a{color:#333}.ui-widget-header{border:1px solid #ddd;background:#e9e9e9;color:#333;font-weight:bold}.ui-widget-header a{color:#333}.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default,.ui-button,html .ui-button.ui-state-disabled:hover,html .ui-button.ui-state-disabled:active{border:1px solid #c5c5c5;background:#f6f6f6;font-weight:normal;color:#454545}.ui-state-default a,.ui-state-default a:link,.ui-state-default a:visited,a.ui-button,a:link.ui-button,a:visited.ui-button,.ui-button{color:#454545;text-decoration:none}.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus,.ui-button:hover,.ui-button:focus{border:1px solid #ccc;background:#ededed;font-weight:normal;color:#2b2b2b}.ui-state-hover a,.ui-state-hover a:hover,.ui-state-hover a:link,.ui-state-hover a:visited,.ui-state-focus a,.ui-state-focus a:hover,.ui-state-focus a:link,.ui-state-focus a:visited,a.ui-button:hover,a.ui-button:focus{color:#2b2b2b;text-decoration:none}.ui-visual-focus{box-shadow:0 0 3px 1px rgb(94,158,214)}.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active,a.ui-button:active,.ui-button:active,.ui-button.ui-state-active:hover{border:1px solid #003eff;background:#007fff;font-weight:normal;color:#fff}.ui-icon-background,.ui-state-active .ui-icon-background{border:#003eff;background-color:#fff}.ui-state-active a,.ui-state-active a:link,.ui-state-active a:visited{color:#fff;text-decoration:none}.ui-state-highlight,.ui-widget-content .ui-state-highlight,.ui-widget-header .ui-state-highlight{border:1px solid #dad55e;background:#fffa90;color:#777620}.ui-state-checked{border:1px solid #dad55e;background:#fffa90}.ui-state-highlight a,.ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a{color:#777620}.ui-state-error,.ui-widget-content .ui-state-error,.ui-widget-header .ui-state-error{border:1px solid #f1a899;background:#fddfdf;color:#5f3f3f}.ui-state-error a,.ui-widget-content .ui-state-error a,.ui-widget-header .ui-state-error a{color:#5f3f3f}.ui-state-error-text,.ui-widget-content .ui-state-error-text,.ui-widget-header .ui-state-error-text{color:#5f3f3f}.ui-priority-primary,.ui-widget-content .ui-priority-primary,.ui-widget-header .ui-priority-primary{font-weight:bold}.ui-priority-secondary,.ui-widget-content .ui-priority-secondary,.ui-widget-header .ui-priority-secondary{opacity:.7;filter:Alpha(Opacity=70);font-weight:normal}.ui-state-disabled,.ui-widget-content .ui-state-disabled,.ui-widget-header .ui-state-disabled{opacity:.35;filter:Alpha(Opacity=35);background-image:none}.ui-state-disabled .ui-icon{filter:Alpha(Opacity=35)}.ui-icon{width:16px;height:16px}.ui-icon,.ui-widget-content .ui-icon{background-image:url("images/ui-icons_444444_256x240.png")}.ui-widget-header .ui-icon{background-image:url("images/ui-icons_444444_256x240.png")}.ui-state-hover .ui-icon,.ui-state-focus .ui-icon,.ui-button:hover .ui-icon,.ui-button:focus .ui-icon{background-image:url("images/ui-icons_555555_256x240.png")}.ui-state-active .ui-icon,.ui-button:active .ui-icon{background-image:url("images/ui-icons_ffffff_256x240.png")}.ui-state-highlight .ui-icon,.ui-button .ui-state-highlight.ui-icon{background-image:url("images/ui-icons_777620_256x240.png")}.ui-state-error .ui-icon,.ui-state-error-text .ui-icon{background-image:url("images/ui-icons_cc0000_256x240.png")}.ui-button .ui-icon{background-image:url("images/ui-icons_777777_256x240.png")}.ui-icon-blank{background-position:16px 16px}.ui-icon-caret-1-n{background-position:0 0}.ui-icon-caret-1-ne{background-position:-16px 0}.ui-icon-caret-1-e{background-position:-32px 0}.ui-icon-caret-1-se{background-position:-48px 0}.ui-icon-caret-1-s{background-position:-65px 0}.ui-icon-caret-1-sw{background-position:-80px 0}.ui-icon-caret-1-w{background-position:-96px 0}.ui-icon-caret-1-nw{background-position:-112px 0}.ui-icon-caret-2-n-s{background-position:-128px 0}.ui-icon-caret-2-e-w{background-position:-144px 0}.ui-icon-triangle-1-n{background-position:0 -16px}.ui-icon-triangle-1-ne{background-position:-16px -16px}.ui-icon-triangle-1-e{background-position:-32px -16px}.ui-icon-triangle-1-se{background-position:-48px -16px}.ui-icon-triangle-1-s{background-position:-65px -16px}.ui-icon-triangle-1-sw{background-position:-80px -16px}.ui-icon-triangle-1-w{background-position:-96px -16px}.ui-icon-triangle-1-nw{background-position:-112px -16px}.ui-icon-triangle-2-n-s{background-position:-128px -16px}.ui-icon-triangle-2-e-w{background-position:-144px -16px}.ui-icon-arrow-1-n{background-position:0 -32px}.ui-icon-arrow-1-ne{background-position:-16px -32px}.ui-icon-arrow-1-e{background-position:-32px -32px}.ui-icon-arrow-1-se{background-position:-48px -32px}.ui-icon-arrow-1-s{background-position:-65px -32px}.ui-icon-arrow-1-sw{background-position:-80px -32px}.ui-icon-arrow-1-w{background-position:-96px -32px}.ui-icon-arrow-1-nw{background-position:-112px -32px}.ui-icon-arrow-2-n-s{background-position:-128px -32px}.ui-icon-arrow-2-ne-sw{background-position:-144px -32px}.ui-icon-arrow-2-e-w{background-position:-160px -32px}.ui-icon-arrow-2-se-nw{background-position:-176px -32px}.ui-icon-arrowstop-1-n{background-position:-192px -32px}.ui-icon-arrowstop-1-e{background-position:-208px -32px}.ui-icon-arrowstop-1-s{background-position:-224px -32px}.ui-icon-arrowstop-1-w{background-position:-240px -32px}.ui-icon-arrowthick-1-n{background-position:1px -48px}.ui-icon-arrowthick-1-ne{background-position:-16px -48px}.ui-icon-arrowthick-1-e{background-position:-32px -48px}.ui-icon-arrowthick-1-se{background-position:-48px -48px}.ui-icon-arrowthick-1-s{background-position:-64px -48px}.ui-icon-arrowthick-1-sw{background-position:-80px -48px}.ui-icon-arrowthick-1-w{background-position:-96px -48px}.ui-icon-arrowthick-1-nw{background-position:-112px -48px}.ui-icon-arrowthick-2-n-s{background-position:-128px -48px}.ui-icon-arrowthick-2-ne-sw{background-position:-144px -48px}.ui-icon-arrowthick-2-e-w{background-position:-160px -48px}.ui-icon-arrowthick-2-se-nw{background-position:-176px -48px}.ui-icon-arrowthickstop-1-n{background-position:-192px -48px}.ui-icon-arrowthickstop-1-e{background-position:-208px -48px}.ui-icon-arrowthickstop-1-s{background-position:-224px -48px}.ui-icon-arrowthickstop-1-w{background-position:-240px -48px}.ui-icon-arrowreturnthick-1-w{background-position:0 -64px}.ui-icon-arrowreturnthick-1-n{background-position:-16px -64px}.ui-icon-arrowreturnthick-1-e{background-position:-32px -64px}.ui-icon-arrowreturnthick-1-s{background-position:-48px -64px}.ui-icon-arrowreturn-1-w{background-position:-64px -64px}.ui-icon-arrowreturn-1-n{background-position:-80px -64px}.ui-icon-arrowreturn-1-e{background-position:-96px -64px}.ui-icon-arrowreturn-1-s{background-position:-112px -64px}.ui-icon-arrowrefresh-1-w{background-position:-128px -64px}.ui-icon-arrowrefresh-1-n{background-position:-144px -64px}.ui-icon-arrowrefresh-1-e{background-position:-160px -64px}.ui-icon-arrowrefresh-1-s{background-position:-176px -64px}.ui-icon-arrow-4{background-position:0 -80px}.ui-icon-arrow-4-diag{background-position:-16px -80px}.ui-icon-extlink{background-position:-32px -80px}.ui-icon-newwin{background-position:-48px -80px}.ui-icon-refresh{background-position:-64px -80px}.ui-icon-shuffle{background-position:-80px -80px}.ui-icon-transfer-e-w{background-position:-96px -80px}.ui-icon-transferthick-e-w{background-position:-112px -80px}.ui-icon-folder-collapsed{background-position:0 -96px}.ui-icon-folder-open{background-position:-16px -96px}.ui-icon-document{background-position:-32px -96px}.ui-icon-document-b{background-position:-48px -96px}.ui-icon-note{background-position:-64px -96px}.ui-icon-mail-closed{background-position:-80px -96px}.ui-icon-mail-open{background-position:-96px -96px}.ui-icon-suitcase{background-position:-112px -96px}.ui-icon-comment{background-position:-128px -96px}.ui-icon-person{background-position:-144px -96px}.ui-icon-print{background-position:-160px -96px}.ui-icon-trash{background-position:-176px -96px}.ui-icon-locked{background-position:-192px -96px}.ui-icon-unlocked{background-position:-208px -96px}.ui-icon-bookmark{background-position:-224px -96px}.ui-icon-tag{background-position:-240px -96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px -112px}.ui-icon-calendar{background-position:-32px -112px}.ui-icon-cart{background-position:-48px -112px}.ui-icon-pencil{background-position:-64px -112px}.ui-icon-clock{background-position:-80px -112px}.ui-icon-disk{background-position:-96px -112px}.ui-icon-calculator{background-position:-112px -112px}.ui-icon-zoomin{background-position:-128px -112px}.ui-icon-zoomout{background-position:-144px -112px}.ui-icon-search{background-position:-160px -112px}.ui-icon-wrench{background-position:-176px -112px}.ui-icon-gear{background-position:-192px -112px}.ui-icon-heart{background-position:-208px -112px}.ui-icon-star{background-position:-224px -112px}.ui-icon-link{background-position:-240px -112px}.ui-icon-cancel{background-position:0 -128px}.ui-icon-plus{background-position:-16px -128px}.ui-icon-plusthick{background-position:-32px -128px}.ui-icon-minus{background-position:-48px -128px}.ui-icon-minusthick{background-position:-64px -128px}.ui-icon-close{background-position:-80px -128px}.ui-icon-closethick{background-position:-96px -128px}.ui-icon-key{background-position:-112px -128px}.ui-icon-lightbulb{background-position:-128px -128px}.ui-icon-scissors{background-position:-144px -128px}.ui-icon-clipboard{background-position:-160px -128px}.ui-icon-copy{background-position:-176px -128px}.ui-icon-contact{background-position:-192px -128px}.ui-icon-image{background-position:-208px -128px}.ui-icon-video{background-position:-224px -128px}.ui-icon-script{background-position:-240px -128px}.ui-icon-alert{background-position:0 -144px}.ui-icon-info{background-position:-16px -144px}.ui-icon-notice{background-position:-32px -144px}.ui-icon-help{background-position:-48px -144px}.ui-icon-check{background-position:-64px -144px}.ui-icon-bullet{background-position:-80px -144px}.ui-icon-radio-on{background-position:-96px -144px}.ui-icon-radio-off{background-position:-112px -144px}.ui-icon-pin-w{background-position:-128px -144px}.ui-icon-pin-s{background-position:-144px -144px}.ui-icon-play{background-position:0 -160px}.ui-icon-pause{background-position:-16px -160px}.ui-icon-seek-next{background-position:-32px -160px}.ui-icon-seek-prev{background-position:-48px -160px}.ui-icon-seek-end{background-position:-64px -160px}.ui-icon-seek-start{background-position:-80px -160px}.ui-icon-seek-first{background-position:-80px -160px}.ui-icon-stop{background-position:-96px -160px}.ui-icon-eject{background-position:-112px -160px}.ui-icon-volume-off{background-position:-128px -160px}.ui-icon-volume-on{background-position:-144px -160px}.ui-icon-power{background-position:0 -176px}.ui-icon-signal-diag{background-position:-16px -176px}.ui-icon-signal{background-position:-32px -176px}.ui-icon-battery-0{background-position:-48px -176px}.ui-icon-battery-1{background-position:-64px -176px}.ui-icon-battery-2{background-position:-80px -176px}.ui-icon-battery-3{background-position:-96px -176px}.ui-icon-circle-plus{background-position:0 -192px}.ui-icon-circle-minus{background-position:-16px -192px}.ui-icon-circle-close{background-position:-32px -192px}.ui-icon-circle-triangle-e{background-position:-48px -192px}.ui-icon-circle-triangle-s{background-position:-64px -192px}.ui-icon-circle-triangle-w{background-position:-80px -192px}.ui-icon-circle-triangle-n{background-position:-96px -192px}.ui-icon-circle-arrow-e{background-position:-112px -192px}.ui-icon-circle-arrow-s{background-position:-128px -192px}.ui-icon-circle-arrow-w{background-position:-144px -192px}.ui-icon-circle-arrow-n{background-position:-160px -192px}.ui-icon-circle-zoomin{background-position:-176px -192px}.ui-icon-circle-zoomout{background-position:-192px -192px}.ui-icon-circle-check{background-position:-208px -192px}.ui-icon-circlesmall-plus{background-position:0 -208px}.ui-icon-circlesmall-minus{background-position:-16px -208px}.ui-icon-circlesmall-close{background-position:-32px -208px}.ui-icon-squaresmall-plus{background-position:-48px -208px}.ui-icon-squaresmall-minus{background-position:-64px -208px}.ui-icon-squaresmall-close{background-position:-80px -208px}.ui-icon-grip-dotted-vertical{background-position:0 -224px}.ui-icon-grip-dotted-horizontal{background-position:-16px -224px}.ui-icon-grip-solid-vertical{background-position:-32px -224px}.ui-icon-grip-solid-horizontal{background-position:-48px -224px}.ui-icon-gripsmall-diagonal-se{background-position:-64px -224px}.ui-icon-grip-diagonal-se{background-position:-80px -224px}.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{border-top-left-radius:3px}.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{border-top-right-radius:3px}.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{border-bottom-left-radius:3px}.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{border-bottom-right-radius:3px}.ui-widget-overlay{background:#aaa;opacity:.3;filter:Alpha(Opacity=30)}.ui-widget-shadow{-webkit-box-shadow:0 0 5px #666;box-shadow:0 0 5px #666} \ No newline at end of file diff --git a/pandora_console/include/styles/js/jquery-ui_custom.css b/pandora_console/include/styles/js/jquery-ui_custom.css new file mode 100644 index 0000000000..ca2cdb51e7 --- /dev/null +++ b/pandora_console/include/styles/js/jquery-ui_custom.css @@ -0,0 +1,263 @@ +@import url(calendar.css); + +/* --- JQUERY-UI --- */ +.ui-dialog .ui-dialog-titlebar { + background-color: #82b92e !important; +} + +/*center ui dialog center*/ +.ui-dialog-titlebar .ui-icon-closethick { + margin-top: -5px !important; +} +.ui-button-text-only .ui-button-text { + font-family: nunito; + font-size: 9pt; + color: #82b92e; +} +.ui-datepicker .ui-datepicker-title *, +.ui-datepicker th * { + color: white; +} +.ui-datepicker .ui-datepicker-title select, +.ui-datepicker .ui-datepicker-title option { + color: #111 !important; +} +.ui-dialog .ui-dialog-titlebar { + display: inherit; + text-align: center; + padding: 0.4em 1em; + height: 30px; + position: relative; +} +.ui-dialog .ui-dialog-title { + font-family: Nunito, sans-serif; + margin: 0.1em 0 !important; + white-space: nowrap !important; + width: 100% !important; + overflow: hidden !important; + text-overflow: ellipsis !important; + font-size: 11pt; + position: relative; + top: 5px; + float: none !important; +} +.ui-dialog .ui-dialog-titlebar-close { + position: absolute !important; + right: 1em !important; + width: 21px !important; + margin: 0px 0 0 0 !important; + padding: 1px !important; + height: 20px !important; + bottom: 30% !important; + top: 20% !important; +} +.ui-dialog .ui-dialog-content { + position: relative !important; + border: 0; + padding: 0.5em 1em !important; + background: none !important; + overflow: auto !important; + margin-bottom: 1em; +} +.ui-dialog .ui-dialog-buttonpane { + text-align: left; + border-width: 1px 0 0 0; + background-image: none; + margin-top: 0.5em; + padding: 0.3em 1em 0.5em 0.4em; +} +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { + float: right; +} +.ui-dialog .ui-dialog-buttonpane button { + margin: 0.5em 1em 0.5em 0 !important; + cursor: pointer !important; + background: white !important; + background-color: white !important; + border: 1px solid #82b92e !important; + height: 30px !important; + width: 90px !important; +} +.ui-widget-header .ui-icon { + background-image: url(../images/ui-icons_444444_256x240.png) !important; +} +.ui-icon, +.ui-widget-content .ui-icon { + background-image: url(../images/ui-icons_444444_256x240.png) !important; +} +.ui-widget-content { + background: #ffffff url(../images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% + repeat-x; +} +.ui-state-default, +.ui-widget-content .ui-state-default, +.ui-widget-header .ui-state-default { + margin-top: 3px; + border: 1px solid #d3d3d3 !important; + border-bottom: 0 !important; + background: #e6e6e6 url(../images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% + repeat-x !important; + font-weight: normal !important; + color: #555555 !important; +} +.ui-corner-all, +.ui-corner-top, +.ui-corner-left, +.ui-corner-tl { + border-top-left-radius: 0 !important; +} +.ui-corner-all, +.ui-corner-top, +.ui-corner-right, +.ui-corner-tr { + border-top-right-radius: 0 !important; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-left, +.ui-corner-bl { + border-bottom-left-radius: 0 !important; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-right, +.ui-corner-br { + border-bottom-right-radius: 0 !important; +} +#ui-datepicker-div { + border-color: #b1b1b1; + background: #ffffff; +} +.ui-widget-header { + background: #b1b1b1 !important; + color: #ffffff !important; +} +.ui-datepicker-calendar th { + background-color: #3f3f3f; +} +.ui-dialog .ui-widget-header { + background-color: #82b92e; +} +.ui_tpicker_hour, +.ui_tpicker_minute, +.ui_tpicker_second, +.ui-slider-handle { + border: 1px solid #aaaaaa !important; +} +.ui-timepicker-div dd { + margin: 0px 15px 0px 15px; +} +.ui-timepicker-div .ui-datepicker-title { + color: white; +} +.ui-datepicker-buttonpane button { + border-color: #b1b1b1 !important; +} +.ui-datepicker-buttonpane .ui-datepicker-current { + margin-left: 0.2em !important; +} +.ui-dialog .ui-widget-content { + border: 0px !important; +} +.ui-dialog { + box-shadow: 5px 5px 19px #4e4e4e; + border: 0px !important; + padding: 0 !important; +} +.ui-dialog-titlebar { + border: 0px !important; +} +.ui-dialog-titlebar .ui-icon-closethick, +.ui-dialog-titlebar .ui-state-default, +.ui-dialog-titlebar .ui-state-hover, +.ui-dialog-titlebar button { + background: transparent; + border: 0px; +} +.ui-dialog-titlebar .ui-icon-closethick { + background-image: url("../../../images/icono_cerrar.png") !important; +} +.ui-dialog-title { + color: #ffffff; + font-size: 9pt; +} +.ui-widget input, +.ui-widget select, +.ui-widget textarea, +.ui-widget button { + font-family: Verdana, Arial, sans-serif !important; +} + +a.ui-button:active, +.ui-button:active, +.ui-button.ui-state-active:hover, +.ui-state-focus .ui-widget-content, +.ui-state-focus .ui-widget-header, +.ui-state-focus .ui-button:hover, +.ui-button:focus { + background: transparent !important; + border: none !important; +} + +.ui-state-hover, +.ui-widget-content .ui-state-hover, +.ui-widget-header .ui-state-hover { + border: 1px solid #999999 !important; + border-bottom: 0 !important; + background: #dadada url(../images/ui-bg_glass_75_dadada_1x400.png) 50% 50% + repeat-x !important; +} + +.ui-state-active, +.ui-widget-content .ui-state-active, +.ui-widget-header .ui-state-active { + border: 1px solid #aaaaaa !important; + border-bottom: 0 !important; + background: #ffffff url(../images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% + repeat-x !important; + font-weight: normal !important; + color: #212121 !important; +} +.ui-state-active a, +.ui-state-active a:link, +.ui-state-active a:visited { + color: #212121 !important; +} + +ul.ui-front { + z-index: 1000000 !important; + padding-right: 0px !important; +} + +ul.ui-front li { + padding: 3px !important; +} + +ul.ui-front li:hover { + background-color: #e1e3e1 !important; +} + +ul.ui-front li a.ui-menu-item-wrapper { + background: transparent !important; + border: none !important; +} + +ul.ui-front li a.ui-menu-item-wrapper span { + padding-left: 5px !important; +} + +ul.ui-front li a.ui-menu-item-wrapper:hover { + text-decoration: none !important; +} + +input[type="submit"].ui-button-dialog { + margin: 0.5em 1em 0.5em 0 !important; + cursor: pointer !important; + background: white !important; + background-color: white !important; + color: #82b92e !important; + text-align: center !important; + border: 1px solid #82b92e !important; + height: 30px !important; + width: 90px !important; +} diff --git a/pandora_console/include/styles/js/jquery.contextMenu.css b/pandora_console/include/styles/js/jquery.contextMenu.css new file mode 100644 index 0000000000..64d86cf7bc --- /dev/null +++ b/pandora_console/include/styles/js/jquery.contextMenu.css @@ -0,0 +1,211 @@ +/*! + * jQuery contextMenu - Plugin for simple contextMenu handling + * + * Version: 1.6.5 + * + * Authors: Rodney Rehm, Addy Osmani (patches for FF) + * Web: http://medialize.github.com/jQuery-contextMenu/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * GPL v3 http://opensource.org/licenses/GPL-3.0 + * + */ + +.context-menu-list { + margin: 0; + padding: 0; + + min-width: 120px; + max-width: 250px; + display: inline-block; + position: absolute; + list-style-type: none; + border: 1px solid #ddd; + border-radius: 4px; + background: #eee; + + -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + -ms-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + -o-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); + + font-family: Verdana, Arial, Helvetica, sans-serif; + font-size: 11px; + text-align: left; +} + +.context-menu-item { + padding: 0px 2px 0px 24px; + background-color: #eee; + position: relative; + border-radius: 4px; + -webkit-user-select: none; + -moz-user-select: -moz-none; + -ms-user-select: none; + user-select: none; + padding-top: 8px; + padding-bottom: 8px; +} + +.context-menu-item span { + padding-top: 10px; + padding-bottom: 10px; + padding-right: 10px; + padding-left: 10px; +} + +.context-menu-separator { + padding-bottom: 0; + border-bottom: 1px solid #ddd; +} + +.context-menu-item > label > input, +.context-menu-item > label > textarea { + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; +} + +.context-menu-item.hover { + cursor: pointer; + background-color: #82b92e; + border-radius: 4px; + color: #fff; +} + +.context-menu-item.disabled { + color: #666 !important; +} + +.context-menu-input.hover, +.context-menu-item.disabled.hover { + cursor: default; + background-color: #eee; +} + +.context-menu-submenu:after { + content: ">"; + color: #666; + position: absolute; + top: 0; + right: 3px; + z-index: 1; +} + +/* icons + #protip: + In case you want to use sprites for icons (which I would suggest you do) have a look at + http://css-tricks.com/13224-pseudo-spriting/ to get an idea of how to implement + .context-menu-item.icon:before {} + */ +.context-menu-item.icon { + min-height: 18px; + background-repeat: no-repeat; + background-position: 4px 2px; +} +.context-menu-item.icon-edit { + background-image: url(../../images/page_white_edit.png); +} +.context-menu-item.icon-cut { + background-image: url(../../images/cut.png); +} +.context-menu-item.icon-copy { + background-image: url(../../images/page_white_copy.png); +} +.context-menu-item.icon-paste { + background-image: url(../../images/page_white_paste.png); +} +.context-menu-item.icon-delete { + background-image: url(../../images/delete.png); +} +.context-menu-item.icon-add { + background-image: url(../../images/page_white_add.png); +} +.context-menu-item.icon-quit { + background-image: url(../../images/door.png); +} +.context-menu-item.icon-refresh { + background-image: url(../../images/refresh.png); +} +.context-menu-item.icon-center { + background-image: url(../../images/set_center.png); +} +.context-menu-item.icon-details { + background-image: url(../../images/show_details.png); +} +.context-menu-item.icon-children { + background-image: url(../../images/children.png); +} +.context-menu-item.icon-cancel_set_parent { + background-image: url(../../images/link_delete.png); +} +.context-menu-item.icon-set_parent { + background-image: url(../../images/father.png); +} +.context-menu-item.icon-add_node { + background-image: url(../../images/add.png); +} +.context-menu-item.icon-refresh_holding_area { + background-image: url(../../images/refresh_holding_area.png); +} +.context-menu-item.icon-restart_map { + background-image: url(../../images/reset.png); +} +.context-menu-item.icon-interface_link_children { + background-image: url(../../images/icono_link_hijo.png); +} +.context-menu-item.icon-interface_link_parent { + background-image: url(../../images/icono_link_padre.png); +} +.context-menu-item.icon-interface_link_cancel { + background-image: url(../../images/link_abortar.png); +} + +/* vertically align inside labels */ +.context-menu-input > label > * { + vertical-align: top; +} + +/* position checkboxes and radios as icons */ +.context-menu-input > label > input[type="checkbox"], +.context-menu-input > label > input[type="radio"] { + margin-left: -17px; +} +.context-menu-input > label > span { + margin-left: 5px; +} + +.context-menu-input > label, +.context-menu-input > label > input[type="text"], +.context-menu-input > label > textarea, +.context-menu-input > label > select { + display: block; + width: 100%; + + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + -ms-box-sizing: border-box; + -o-box-sizing: border-box; + box-sizing: border-box; +} + +.context-menu-input > label > textarea { + height: 100px; +} +.context-menu-item > .context-menu-list { + display: none; + /* re-positioned by js */ + right: -5px; + top: 5px; +} + +.context-menu-item.hover > .context-menu-list { + display: block; +} + +.context-menu-accesskey { + text-decoration: underline; +} diff --git a/pandora_console/include/styles/login.css b/pandora_console/include/styles/login.css new file mode 100644 index 0000000000..f7066ba92c --- /dev/null +++ b/pandora_console/include/styles/login.css @@ -0,0 +1,411 @@ +/* + * --------------------------------------------------------------------- + * - LOGIN STYLES - + * --------------------------------------------------------------------- + */ +h1#log_title { + font-size: 18px; + margin-bottom: 0px; + color: #fff !important; + width: 300px; +} + +div#log_msg { + display: none; +} + +div#error_buttons { + margin-top: 20px; +} + +div#error_buttons a { + margin: 14px; +} + +#login_body { + /* Set rules to fill background */ + min-height: 100%; + min-width: 1200px; + width: 100%; + z-index: -9999; + position: absolute; + background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); + background-repeat: repeat; +} + +/*@media screen and (max-width: 1024px) { /* Specific to this particular image */ +/* #login_body { + left: 50%; + margin-left: -512px; /* 50% */ +/* } +} +@media screen and (max-width: 1100px) { /* Specific to this particular image */ +/* #login_body { + background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); + background-repeat: repeat; + } +} +@media screen and (max-width: 1400px) { /* Specific to this particular image */ +/* #login_body { + background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); + background-repeat: repeat; + } +} +@media screen and (max-width: 2000px) { /* Specific to this particular image */ +/* #login_body { + background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); + background-repeat: repeat; + } +} +@media screen and (min-width: 2000px) { /* Specific to this particular image */ +/* #login_body { + background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); + background-repeat: repeat; + } +}*/ + +p.log_in { + color: #fff !important; + padding: 0px 10px; + width: 300px; +} + +h1#log_f { + color: #c00; + border-bottom: 1px solid #c00; + padding-bottom: 3px; +} + +div#error_login { + text-align: center; + margin-top: 5px; + margin-left: 5px; + width: 75%; + float: right; + text-align: left; + top: 100px; +} + +div#error_login_icon { + margin-top: 10px; + margin-right: 7px; + text-align: center; + width: 20%; + float: right; +} + +div#login_f { + margin-top: 10px; + margin-bottom: 25px; +} + +#ver_num { + margin: 0px auto; + width: 100%; + position: absolute; + bottom: 10px; + color: #fff; + text-align: center; +} + +/* + * --------------------------------------------------------------------- + * - LOGIN PAGE - + * --------------------------------------------------------------------- + */ + +/* --- Login page - header --- */ +div#header_login { + width: 100%; + height: 65px; + background-color: rgba(255, 255, 255, 0.06); +} + +div#icon_custom_pandora { + float: left; + margin-top: 5px; + margin-left: 4%; +} + +div#list_icon_docs_support { + float: right; + margin-top: 8px; + margin-right: 4%; +} + +div#list_icon_docs_support ul { + margin-top: 5px; +} + +div#list_icon_docs_support ul li { + display: inline-block; + color: white; + vertical-align: middle; + margin-right: 5px; + font-size: 10pt; +} + +li#li_margin_left { + margin-left: 30px; +} + +/* --- Login page - form --- */ +div.container_login { + margin-top: 10%; + margin-left: 5%; + margin-right: 5%; +} + +div.login_page { + width: 35%; + min-height: 600px; + float: left; +} + +div.login_page form { + border-right: 1px solid #868686; + padding-top: 30px; + padding-bottom: 50px; + min-width: 400px; + max-height: 600px; +} + +div.login_logo_icon { + margin-bottom: 40px; + text-align: center; +} + +div.login_logo_icon img { + margin: 0 auto; + width: 150px; +} + +div.login_double_auth_code, +div.login_nick, +div.login_pass { + margin: 0 auto; + width: 70%; + height: 40px; + background-color: rgba(255, 255, 255, 0.2) !important; + margin-bottom: 25px; + min-width: 260px; +} + +div.login_nick img, +div.login_pass img { + vertical-align: middle; + margin: 3px; +} + +div.login_nick input, +div.login_pass input { + background-color: rgba(255, 255, 255, 0) !important; + border: 0px !important; + color: white !important; + border-radius: 0px; + width: 89%; + height: 40px; + font-size: 9pt; + padding: 0px !important; +} + +div.login_nick input:focus, +div.login_pass input:focus { + outline: none; +} + +div.login_nick input:-webkit-autofill, +div.login_nick input:-webkit-autofill:hover, +div.login_nick input:-webkit-autofill:focus, +div.login_nick input:-webkit-autofill:active, +div.login_pass input:-webkit-autofill, +div.login_pass input:-webkit-autofill:hover, +div.login_pass input:-webkit-autofill:focus, +div.login_pass input:-webkit-autofill:active { + transition: background-color 10000s ease-in-out 0s; + -webkit-box-shadow: 0 0 0px 0px transparent inset !important; + -webkit-text-fill-color: white !important; + border: 0px; + width: 89%; +} + +div.login_nick input::-webkit-input-placeholder, +div.login_pass input::-webkit-input-placeholder { + color: white; +} + +div.login_pass img, +div.login_nick img { + width: 30px; +} + +div.login_pass div, +div.login_nick div { + float: left; + width: 11%; +} + +div.login_button { + margin: 0 auto; + width: 70%; + height: 40px; + background-color: rgb(25, 25, 25); + border: 1px solid white; + min-width: 260px; +} + +div.login_button input { + width: 100%; + background-color: rgb(25, 25, 25) !important; + text-align: center; + border: 0px; + border-radius: 0px; + height: 40px; + padding: 0px; + font-size: 9pt; + color: white; +} + +div.login_data { + width: 65%; + min-height: 600px; + float: left; +} + +div.text_banner_login { + width: 100%; + margin-bottom: 60px; + color: white; + text-align: center; +} + +div.text_banner_login span { + width: 100%; +} + +span.span1 { + font-size: 3vw; + font-family: "lato-thin"; + color: white; +} + +span.span2 { + font-size: 3vw; + font-family: "lato-bolder"; + color: white; +} + +div.img_banner_login { + width: 100%; + text-align: center; +} + +div.img_banner_login img { + max-width: 70%; + min-width: 70%; + max-height: 50%; + min-height: 50%; +} + +@media all and (max-width: 1200px) { + span.span1 { + font-size: 30pt; + } + span.span2 { + font-size: 30pt; + } +} + +/* --- Login page - modal windows --- */ +div.content_alert { + width: 98%; + margin-top: 20px; +} + +div.icon_message_alert { + float: left; + width: 25%; + text-align: center; +} + +div.icon_message_alert img { + width: 85px; +} + +div.content_message_alert { + width: 75%; + float: right; +} + +div.text_message_alert { + width: 100%; + margin-top: 10px; +} + +div.text_message_alert h1 { + margin: 0px; +} + +div.text_message_alert p { + margin: 0px; + font-size: 10.3pt; + line-height: 14pt; +} + +div.button_message_alert { + width: 100%; +} + +div.button_message_alert input { + float: right; + width: 87px; + height: 33px; + color: #82b92e; + border: 1px solid #82b92e; + font-weight: bold; + margin-right: 20px; + margin-top: 20px; + font-size: 10pt; +} + +div.form_message_alert { + width: 90%; + clear: both; + padding-top: 20px; + padding-left: 40px; +} + +div.form_message_alert ul li { + display: inline-block; + padding: 10px; +} + +div.form_message_alert ul li input { + border: none; + background-color: #dadada !important; + border-radius: 0px; + height: 17px; + width: 145px; + padding-left: 5px; +} + +div.form_message_alert ul li label { + font-size: 10pt; + padding-right: 20px; +} + +div.form_message_alert h4 { + margin: 0px; + margin-bottom: 10px; +} + +div.button_message_alert_form input { + float: right; + width: 87px; + height: 33px; + color: #82b92e; + border: 1px solid #82b92e; + font-weight: bold; + font-size: 10pt; + margin-right: 25px; +} diff --git a/pandora_console/include/styles/menu.css b/pandora_console/include/styles/menu.css index 763604e51c..a30978b3a8 100644 --- a/pandora_console/include/styles/menu.css +++ b/pandora_console/include/styles/menu.css @@ -17,233 +17,376 @@ */ .menu { - border-width: 0px 0px 0px 0px; - border-style: none; - border-color: #777; + border-width: 0px 0px 0px 0px; + border-style: none; + border-color: #777; } .menu ul { - list-style-type: none; - padding: 0; - margin: 0; + list-style-type: none; + padding: 0; + margin: 0; } -.menu li.selected, .menu li.not_selected { - border: 0px none black; - border-bottom: 0px none #d4d4d4; - margin: 0; +.menu li.selected, +.menu li.not_selected { + border: 0px none black; + border-bottom: 0px none #d4d4d4; + margin: 0; } - .menu li a { - /*background-color: inherit;*/ - color: #FFFFFF; - /*font-weight: bold;*/ - /* This makes it so that the whole li is clickable */ - text-decoration:none; + color: #ffffff; + text-decoration: none; } -li:hover ul { display: block; } +li:hover ul { + display: block; +} .submenu_text { - padding: 10.5px; - margin-left: 0px; - width: 100%; + padding: 10.5px; + margin-left: 0px; + width: 100%; + color: #fff; } -.menu li.subselected a{ - background-color: grey !important; +.menu li.subselected a { + background-color: grey !important; } .menu a:hover { - text-decoration:none; - border:0px; + text-decoration: none; + border: 0px; } .submenu { - margin: 0px 0px 0px 0px; - position: absolute; - z-index: 999; - left: 44px; - min-height: 35px; - height: 35px; - width: 180px; + margin: 0px 0px 0px 0px; + position: absolute; + z-index: 999; + left: 44px; + min-height: 35px; + height: 35px; + width: 180px; } -.submenu2{ - position: absolute; - z-index: 999; - left: 180px; +.submenu2 { + position: absolute; + z-index: 999; + left: 180px; } -.sub_subMenu{ - min-height: 35px !important; - height: 35px; - width: 180px; - font-weight: normal !important; +.sub_subMenu { + min-height: 35px !important; + height: 35px; + width: 180px; + font-weight: normal !important; } -.sub_subMenu.selected{ - font-weight: bold !important; +.sub_subMenu.selected { + font-weight: bold !important; } .submenu2 li a { - margin-left: 0px; - padding-left: 0px; + margin-left: 0px; + padding-left: 0px; } .menu li img.toggle { - visibility: hidden; - float:right; - /* Positions it back where it should be */ - border-left: 1px; + visibility: hidden; + float: right; + /* Positions it back where it should be */ + border-left: 1px; } .menu li.has_submenu > a > div { - background: url(../../images/arrow.png) no-repeat 80% 50%; - z-index: 1; /* Positions it on top of the rest */ + background: url(../../images/arrow.png) no-repeat 80% 50%; + z-index: 1; /* Positions it on top of the rest */ } -.menu li.has_submenu>.SubNoLink{ - background: url(../../images/arrow.png) no-repeat 80% 50%; - z-index: 1; /* Positions it on top of the rest */ +.menu li.has_submenu > .SubNoLink { + background: url(../../images/arrow.png) no-repeat 80% 50%; + z-index: 1; /* Positions it on top of the rest */ } -.is_submenu2{ - background-color: #E4E4E4 !important; +.is_submenu2 { + background-color: #e4e4e4 !important; } -.menu li.submenu_not_selected a, .menu li.submenu2_not_selected a { - font-weight: normal !important; +.menu li.submenu_not_selected a, +.menu li.submenu2_not_selected a { + font-weight: normal !important; } .submenu_selected { - margin-bottom: 0px !important; - box-shadow: inset 4px 0 #80BA27 !important; + margin-bottom: 0px !important; + box-shadow: inset 4px 0 #80ba27 !important; } -.menu .menu_icon, .menu li.links { - background-position: 4px 4px; - background-repeat: no-repeat; - cursor: pointer; +.menu .menu_icon, +.menu li.links { + background-position: 4px 4px; + background-repeat: no-repeat; + cursor: pointer; } .menu li.links { - background-image: url(../../images/link.png); - background-position: 4px 8px; + background-image: url(../../images/link.png); + background-position: 4px 8px; } /* Icons specified here */ #icon_oper-networkconsole { - background: url(../../images/op_network.menu.png) no-repeat 50% 50%; + background: url(../../images/op_network.menu.png) no-repeat 50% 50%; } #icon_oper-agents { - border-top-right-radius: 5px; - border-right-style: solid; - border-right-width: 0px; - background: url(../../images/op_monitoring.menu.png) no-repeat 50% 50%; + border-top-right-radius: 5px; + border-right-style: solid; + border-right-width: 0px; + background: url(../../images/op_monitoring.menu.png) no-repeat 50% 50%; } #icon_oper-events { - background: url(../../images/op_events.menu.png) no-repeat 50% 50%; + background: url(../../images/op_events.menu.png) no-repeat 50% 50%; } /* users */ #icon_oper-users { - background: url(../../images/op_workspace.menu.png) no-repeat 50% 50%; + background: url(../../images/op_workspace.menu.png) no-repeat 50% 50%; } /* trap console */ -#icon_oper-snmpc, #icon_god-snmpc { - background: url(../../images/op_snmp.menu.png) no-repeat 50% 50%; +#icon_oper-snmpc, +#icon_god-snmpc { + background: url(../../images/op_snmp.menu.png) no-repeat 50% 50%; } #icon_oper-reporting { - background: url(../../images/op_reporting.menu.png) no-repeat 50% 50%; + background: url(../../images/op_reporting.menu.png) no-repeat 50% 50%; } #icon_oper-gismaps { - background: url(../../images/op_gis.menu.png) no-repeat 50% 50%; + background: url(../../images/op_gis.menu.png) no-repeat 50% 50%; } #icon_oper-netflow { - background: url(../../images/op_netflow.menu.png) no-repeat 50% 50%; + background: url(../../images/op_netflow.menu.png) no-repeat 50% 50%; } #icon_oper-extensions { - background: url(../../images/extensions.menu.png) no-repeat 50% 50%; + background: url(../../images/extensions.menu.png) no-repeat 50% 50%; } /* Godmode images */ #icon_god-resources { - background: url(../../images/gm_resources.menu.png) no-repeat 50% 50%; + background: url(../../images/gm_resources.menu.png) no-repeat 50% 50%; } #icon_god-configuration { - background: url(../../images/gm_configuration.menu.png) no-repeat 50% 50%; + background: url(../../images/gm_configuration.menu.png) no-repeat 50% 50%; } #icon_god-alerts { - background: url(../../images/gm_alerts.menu.png) no-repeat 50% 50%; + background: url(../../images/gm_alerts.menu.png) no-repeat 50% 50%; } #icon_god-users { - background: url(../../images/gm_users.menu.png) no-repeat 50% 50%; + background: url(../../images/gm_users.menu.png) no-repeat 50% 50%; } #icon_god-reporting { - background: url(../../images/reporting_edit.menu.png) no-repeat 50% 50%; + background: url(../../images/reporting_edit.menu.png) no-repeat 50% 50%; } #icon_god-servers { - background: url(../../images/gm_servers.menu.png) no-repeat 50% 50%; + background: url(../../images/gm_servers.menu.png) no-repeat 50% 50%; } #icon_god-setup { - background: url(../../images/gm_setup.menu.png) no-repeat 50% 50%; + background: url(../../images/gm_setup.menu.png) no-repeat 50% 50%; } #icon_god-events { - background: url(../../images/gm_events.menu.png) no-repeat 50% 50%; + background: url(../../images/gm_events.menu.png) no-repeat 50% 50%; } #icon_god-extensions { - background: url(../../images/builder.menu.png) no-repeat 50% 50%; + background: url(../../images/builder.menu.png) no-repeat 50% 50%; } #icon_god-links { - border-top: 4px solid #777!important; - border-color: #777; - background: url(../../images/links.menu.png) no-repeat 50% 50%; + border-top: 4px solid #777 !important; + border-color: #777; + background: url(../../images/links.menu.png) no-repeat 50% 50%; } #icon_god-um_messages { - border-color: #777; - background: url(../../images/um_messages.menu.png) no-repeat 50% 50%; + border-color: #777; + background: url(../../images/um_messages.menu.png) no-repeat 50% 50%; } #menu_container { - z-index: 3; - position: absolute; - left: -80px; - background-color: #AAA; + z-index: 3; + position: absolute; + left: -80px; + background-color: #aaa; } .notification_ball { - margin-top: 2px; - margin-left: 29px; - font-size: 6pt; - font-weight: 900; - background: red; - height: 12px; - width: 12px; - border-radius: 50px; - position: absolute; - text-align: center; - color: white; - padding-top: 1px; - font-family: sans-serif; + margin-top: 2px; + margin-left: 29px; + font-size: 6pt; + font-weight: 900; + background: red; + height: 12px; + width: 12px; + border-radius: 50px; + position: absolute; + text-align: center; + color: white; + padding-top: 1px; + font-family: sans-serif; } ul { - margin: 0; - padding: 0; - list-style: none; - } + margin: 0; + padding: 0; + list-style: none; +} ul li { - position: relative; - } - + position: relative; +} + .menu li ul { - position: absolute; - top: 0; - display: none; + position: absolute; + top: 0; + display: none; } /* Fix IE. Hide from IE Mac \*/ -* html ul li { float: left; height: 1%; } -* html ul li a { height: 1%; } +* html ul li { + float: left; + height: 1%; +} +* html ul li a { + height: 1%; +} /* End */ -ul li a:hover { color: #E2144A; } /* Hover Styles */ +ul li a:hover { + color: #e2144a; +} /* Hover Styles */ /*li ul li a { padding: 2px 5px; } Sub Menu Styles */ + +/* + * --------------------------------------------------------------------- + * - MAIN LEFT MENU and SUBMENU - + * --------------------------------------------------------------------- + */ +.menu li.selected { + font-weight: bold; +} + +.menu_icon { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + -o-transition-timing-function: ease-out; +} + +.menu_icon:hover { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + -o-transition-timing-function: ease-out; + background-color: #585858 !important; +} +.submenu_not_selected:hover { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + -o-transition-timing-function: ease-out; + background-color: #585858 !important; +} +.submenu_selected:hover { + background-color: #585858 !important; +} +.sub_subMenu { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; +} +.sub_subMenu:hover { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + background-color: #585858 !important; +} + +.menu li.selected { + box-shadow: inset 4px 0 #80ba27; +} +/* creo que no se usan +.is_submenu2 li { + background-color: #ff0000; +} + +.is_submenu2 { + background-color: #222222 !important; +} +*/ +.operation { + background-color: #333 !important; + border-top-right-radius: 5px; + border-right-style: solid; + border-right-width: 0px; +} + +.operation .selected { + background-color: #585858 !important; +} + +.menu li, +.menu .li.not_selected { + border-radius: 0px 0px 0px 0px; + display: block; + min-height: 35px; + border-bottom: 0px none #424242; + vertical-align: middle; +} + +.godmode, +.menu_icon ul li { + background-color: #222; +} +.operation .menu_icon ul li { + background-color: #333; +} + +.godmode { + border-top: 4px solid #777 !important; + padding-bottom: 4px !important; + border-bottom-right-radius: 5px; + border-right-style: solid; + border-right-width: 0px; +} diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index c3eff053c1..70a9c4920e 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -5,7 +5,7 @@ Description: The default Pandora FMS theme layout // Pandora FMS - http://pandorafms.com // ========================================================== -// Copyright (c) 2004-2011 Artica Soluciones Tecnológicas S.L +// Copyright (c) 2004-2019 Artica Soluciones Tecnológicas S.L // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License @@ -21,185 +21,474 @@ Description: The default Pandora FMS theme layout */ /* Tree view styles */ -@import url(tree.css); -@import url(fixed-bottom-box.css); +/*@import url(tree.css); +@import url(fixed-bottom-box.css);*/ +/* + * --------------------------------------------------------------------- + * - GENERAL STYLES - + * --------------------------------------------------------------------- + */ +@font-face { + font-family: "Nunito"; + font-style: normal; + font-weight: 400; + src: local("Nunito-Regular"), url(../../fonts/nunito.woff) format("woff"); +} +@font-face { + font-family: "lato-thin"; + src: url("../../fonts/Lato-Hairline.ttf"); +} +@font-face { + font-family: "lato-bolder"; + src: url("../../fonts/Lato-Light.ttf"); +} +@font-face { + font-family: "lato-boldest"; + src: url("../../fonts/Lato-Regular.ttf"); +} * { - font-family: verdana, sans-serif; - letter-spacing: 0.03pt; - font-size: 8pt; + font-family: verdana, sans-serif; + letter-spacing: 0.03pt; + font-size: 8pt; } svg * { - font-size: 11pt; - } + font-size: 11pt; +} body { - background-color: #FFF; - margin: 0 auto; + background-color: #fff; + margin: 0 auto; +} +input, +textarea { + border: 1px solid #ddd; +} +textarea { + padding: 5px; + min-height: 100px; + width: 99%; +} +input { + padding: 2px 3px 4px 3px; + vertical-align: middle; } +input[type="checkbox"] { + display: inline !important; +} +select { + padding: 2px 3px 3px 3px; + vertical-align: middle; + border: 1px solid #ddd; +} +input.button { + font-family: Arial, Sans-serif; + border: 4px solid #ccc; + background: #fff; + padding: 2px 3px; + margin: 10px 15px; +} + +input[type="submit"], +input[type="button"] { + cursor: pointer; +} + +h1, +h2, +h3, +h4 { + font-weight: bold; + font-size: 1em; + font-family: Arial, Sans-serif; + text-transform: uppercase; + color: #3f3f3f; + padding-bottom: 4px; + padding-top: 7px; +} +h1 { + font-size: 16px; +} +h2 { + font-size: 15px; +} +h3 { + font-size: 14px; +} +h4 { + margin-bottom: 10px; + font-size: 13px; + color: #3f3f3f; + text-transform: none; +} +a { + color: #3f3f3f; + text-decoration: none; +} +a:hover { + color: #373737; + text-decoration: underline; +} +a:focus, +input:focus, +button:focus { + outline-width: 0; + outline: 0; +} +th > label { + padding-top: 7px; +} +input:disabled { + background-color: #ddd !important; +} +textarea:disabled { + background-color: #ddd !important; +} +select:disabled { + background-color: #ddd !important; +} +ul { + list-style-type: none; + padding-left: 0; + margin-left: 0; +} +code, +pre { + font-family: courier, serif; +} +fieldset { + background-color: #f9faf9; + border: 1px solid #e2e2e2; + padding: 0.5em; + margin-bottom: 20px; + position: relative; +} +fieldset legend { + font-size: 1.1em; + font-weight: bold; + line-height: 20px; + color: #3f3f3f; +} +td input[type="checkbox"] { + padding: 10px; + margin-top: 2px; + display: table-cell; +} +input[type="image"] { + border: 0px; + background-color: transparent !important; +} +table, +img { + border: 0px; +} +table pre { + white-space: pre-wrap; +} +tr:first-child > th { + background-color: #373737; +} +th { + color: #fff; + background-color: #666; + font-size: 7.5pt; + letter-spacing: 0.3pt; +} + +/* --- Font ttf --- */ +@font-face { + font-family: "DejaVuSerif-BoldFont"; + src: url("../fonts/DejaVuSerif-Bold.ttf") format("truetype"); +} + +.DejaVuSerif-Bold { + font-family: DejaVuSerif-BoldFont; +} + +@font-face { + font-family: "DejaVuSerif-BoldItalicFont"; + src: url("../fonts/DejaVuSerif-BoldItalic.ttf") format("truetype"); +} + +.DejaVuSerif-BoldItalic { + font-family: DejaVuSerif-BoldItalicFont; +} + +@font-face { + font-family: "DejaVuSerif-ItalicFont"; + src: url("../fonts/DejaVuSerif-Italic.ttf") format("truetype"); +} + +.DejaVuSerif-Italic { + font-family: DejaVuSerif-ItalicFont; +} + +@font-face { + font-family: "DejaVuSerifFont"; + src: url("../fonts/DejaVuSerif.ttf") format("truetype"); +} + +.DejaVuSerif { + font-family: DejaVuSerifFont; +} + +@font-face { + font-family: "DejaVuSerifCondensed-BoldFont"; + src: url("../fonts/DejaVuSerifCondensed-Bold.ttf") format("truetype"); +} + +.DejaVuSerifCondensed-Bold { + font-family: DejaVuSerifCondensed-BoldFont; +} + +@font-face { + font-family: "DejaVuSerifCondensed-BoldItalicFont"; + src: url("../fonts/DejaVuSerifCondensed-BoldItalic.ttf") format("truetype"); +} + +.DejaVuSerifCondensed-BoldItalic { + font-family: DejaVuSerifCondensed-BoldItalicFont; +} + +@font-face { + font-family: "DejaVuSerifCondensed-ItalicFont"; + src: url("../fonts/DejaVuSerifCondensed-Italic.ttf") format("truetype"); +} + +.DejaVuSerifCondensed-Italic { + font-family: DejaVuSerifCondensed-ItalicFont; +} + +@font-face { + font-family: "DejaVuSerifCondensedFont"; + src: url("../fonts/DejaVuSerifCondensed.ttf") format("truetype"); +} + +.DejaVuSerifCondensed { + font-family: DejaVuSerifCondensedFont; +} + +@font-face { + font-family: "FreeSansFont"; + src: url("../fonts/FreeSans.ttf") format("truetype"); +} + +.FreeSans { + font-family: FreeSansFont; +} + +@font-face { + font-family: "FreeSansBoldFont"; + src: url("../fonts/FreeSansBold.ttf") format("truetype"); +} + +.FreeSansBold { + font-family: FreeSansBoldFont; +} + +@font-face { + font-family: "smallfontFont"; + src: url("../fonts/smallfont.ttf") format("truetype"); +} + +.smallfont { + font-family: smallfontFont; +} + +@font-face { + font-family: "unicodeFont"; + src: url("../fonts/unicode.ttf") format("truetype"); +} + +@font-face { + font-family: "roboto"; + src: url("../../fonts/roboto.woff2") format("woff2"); +} + +@font-face { + font-family: "opensans"; + src: url("../../fonts/opensans.woff2") format("woff2"); +} + +@font-face { + font-family: "lato"; + src: url("../../fonts/lato.woff2") format("woff2"); +} + +@font-face { + font-family: "leaguegothic"; + src: url("../../fonts/leaguegothic.woff") format("woff"); +} +.unicode { + font-family: unicodeFont; +} + +/* + * --------------------------------------------------------------------- + * - GLOBAL STYLES - + * --------------------------------------------------------------------- + */ div#page { - background: #FFF; - background-image: none; + background: #fff; + background-image: none; + clear: both; + width: auto; } body.pure { - background-color: #fff; -} -input, textarea { - border: 1px solid #ddd; -} -form { - margin-block-end: 0px + background-color: #fff; } -textarea { - padding: 5px; - min-height: 100px; - width: 99%; +div#container { + margin: 0 auto; + min-width: 960px; + text-align: left; + height: 100%; + background: #fff; + width: 100%; } + +div#main { + width: auto; + margin: 0px 0% 0px 0%; + float: left; + position: relative; + min-height: 850px; + margin-left: 60px; + max-width: 93%; + min-width: 93%; +} + textarea.conf_editor { - padding: 5px; - width: 650px; - height: 350px; + padding: 5px; + width: 650px; + height: 350px; } + textarea.conf_error { - background-image: url(../../images/err.png); - background-repeat: no-repeat; - background-position: top right; -} -input { - padding: 2px 3px 4px 3px; - vertical-align: middle; + background-image: url(../../images/err.png); + background-repeat: no-repeat; + background-position: top right; } -input[type='checkbox'] { - display: inline !important; -} - -select { - padding: 2px 3px 3px 3px; - vertical-align: middle; -} input.button { - font-family: Arial,Sans-serif; - border: 4px solid #ccc; - background: #fff; - padding: 2px 3px; - margin: 10px 15px; + font-family: Arial, Sans-serif; + border: 4px solid #ccc; + background: #fff; + padding: 2px 3px; + margin: 10px 15px; } -input[type=submit], input[type=button] { - cursor: pointer; -} - -select { - border: 1px solid #ddd; -} -checkbox { - padding: 4px; - border: 1px solid #eee; -} -h1, h2, h3, h4 { - font-weight: bold; - font-size: 1em; - font-family: Arial, Sans-serif; - text-transform: uppercase; - color: #3F3F3F; - padding-bottom: 4px; - padding-top: 7px; -} -h1 { - font-size: 16px; -} -h2 { - font-size: 15px; -} -h3 { - font-size: 14px; -} -h4 { - margin-bottom: 10px; - font-size: 13px; - color: #3F3F3F; - text-transform: none; -} -a { - color: #3F3F3F; - text-decoration: none; -} -a:hover { - color: #373737; - text-decoration: underline; -} a.white_bold { - color: #eee; - text-decoration: none; - font-weight: bold; -} -a.white { - color: #eee; - text-decoration: none; -} -p.center { - text-align: center; -} -h1#log_title { - font-size: 18px; - margin-bottom: 0px; - color: #FFF !important; - width:300px; -} -div#log_msg { - display: none; -} -div#error_buttons { - margin-top: 20px; -} -div#error_buttons a{ - margin: 14px; + color: #eee; + text-decoration: none; + font-weight: bold; } +a.white { + color: #eee; + text-decoration: none; +} + +p.center { + text-align: center; +} + +.img_help { + cursor: help; +} + +#loading { + position: fixed; + width: 200px; + margin-left: 30%; + text-align: center; + top: 50%; + background-color: #999999; + padding: 20px; +} + +.tactical_set legend { + text-align: left; + color: #3f3f3f; +} + +.tactical_set { + background: #fff; + border: 1px solid #e2e2e2; + margin-left: auto; + margin-right: auto; + width: auto; +} + +/* --- Botones --- */ +input.sub { + font-weight: normal; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; + border-radius: 2px; + font-size: 8pt; + background-color: #333 !important; + background-repeat: no-repeat !important; + background-position: 92% 3px !important; + color: white !important; + padding: 3px 3px 5px 12px; + border-color: #333; +} + +input.sub[disabled] { + color: #b4b4b4 !important; + background-color: #f3f3f3 !important; + border-color: #b6b6b6; + cursor: default; +} + +/* + * --------------------------------------------------------------------- + * - NO ACCESS PAGE - noaccess2.php - + * --------------------------------------------------------------------- + */ #noaccess { - position: relative; - margin-top:25px; - left: 15px; - padding-top: 5px; - background-color: #FFFFFF; - border-top-left-radius: 2px; - border-top-right-radius: 2px; - border-bottom-left-radius: 2px; - border-bottom-right-radius: 2px; + position: relative; + margin-top: 25px; + left: 15px; + padding-top: 5px; + background-color: #ffffff; + border-top-left-radius: 2px; + border-top-right-radius: 2px; + border-bottom-left-radius: 2px; + border-bottom-right-radius: 2px; } #noaccess-title { - color: #FFF; - font-weight: bold; - padding-top: 5px; - margin-left: 5px; - background: none repeat scroll 0% 0% #82B92E; - border-top-left-radius: 2px; - border-top-right-radius: 2px; - border-bottom-left-radius: 2px; - border-bottom-right-radius: 2px; - text-align: center; + color: #fff; + font-weight: bold; + padding-top: 5px; + margin-left: 5px; + background: none repeat scroll 0% 0% #82b92e; + border-top-left-radius: 2px; + border-top-right-radius: 2px; + border-bottom-left-radius: 2px; + border-bottom-right-radius: 2px; + text-align: center; } #noaccess-text { - font-size: 12px; - text-align: justify; - padding-top: 25px; - padding-right: 50px; - float:right; + font-size: 12px; + text-align: justify; + padding-top: 25px; + padding-right: 50px; + float: right; } #noaccess-image { - position: relative; - left: 10px; - top: 10px; - float:left; + position: relative; + left: 10px; + top: 10px; + float: left; } -div#activity{ +/*div#activity{ padding-top: 0px; padding-bottom: 18px; } @@ -221,373 +510,137 @@ div#db_f { div#db_ftxt { float: right; padding-top: 10px; -} -div#container { - margin: 0 auto; - min-width: 960px; - text-align: left; - #border-left: solid 2px #000; - #border-right: solid 2px #000; - #border-top: solid 2px #000; - #margin-top: 5px; - height: 100%; - background: #FFF; -} -div#page { - width: 960px; - clear: both; -} -div#main { - width: auto; - margin: 0px 0% 0px 0%; - float: left; - position: relative; - min-height: 850px; - margin-left:60px; -} +}*/ + +/* + * --------------------------------------------------------------------- + * - HELP DIALOG - login_help_dialog.php and pandora_help.php - + * --------------------------------------------------------------------- + */ div#main_help { - width: 100%; + width: 100%; } -div#main_help div.databox, .license_databox { - background: F3F3F3; - -moz-border-radius: 8px; - -webkit-border-radius: 8px; - border-radius: 8px; - border: 0px; - padding-left: 25px; - padding-right: 25px; - margin-top: 10px; - -moz-box-shadow: -1px 1px 6px #aaa; - -webkit-box-shadow: -1px 1px 6px #aaa; - box-shadow: -1px 1px 6px #aaa; - +div#main_help div.databox, +.license_databox { + background: F3F3F3; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + border-radius: 8px; + border: 0px; + padding-left: 25px; + padding-right: 25px; + margin-top: 10px; + -moz-box-shadow: -1px 1px 6px #aaa; + -webkit-box-shadow: -1px 1px 6px #aaa; + box-shadow: -1px 1px 6px #aaa; } -div#main_help div.databox h1{ - padding-bottom: 0px; - margin-bottom: 0px; - font-weight: bold; - font-family: sans-serif, verdana; +div#main_help div.databox h1 { + padding-bottom: 0px; + margin-bottom: 0px; + font-weight: bold; + font-family: sans-serif, verdana; } -div#main_help div.databox h3, div#main_help div.databox h2 { - color: #6EB432; - font-family: sans-serif, verdana; +div#main_help div.databox h3, +div#main_help div.databox h2 { + color: #6eb432; + font-family: sans-serif, verdana; } div#main_help div.databox h3 { - font-size: 12px; + font-size: 12px; } -div#main_help a.footer, div#main_help span { - color: #999; +div#main_help a.footer, +div#main_help span { + color: #999; } -a.footer, a.footer span{ - font-size: 9px; - color: white; +div#main_help div.databox hr { + width: 100%; + border: 0px; + height: 1px; + background-color: #222; + margin: 0px; } -div#main_help div.databox hr{ - width:100%; - border: 0px; - height: 1px; - background-color: #222; - margin: 0px; +div#main_help div.databox p { + line-height: 15px; + text-align: justify; } -div#main_help div.databox p{ - line-height: 15px; - text-align: justify; -} - -div#menu_container { - -moz-border-top-right-radius: 6px; - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - z-index: 1010; - width: 40px; - height: 100%; -} - -div#menu { - width: 45px; - float: left; - z-index: 2000; - position: absolute; -} - -div#head { - font-size: 8pt; - width: 100%; - height: 60px; - padding-top: 0px; - margin-bottom: 20px; - border-bottom-style: solid; - border-bottom-width: 3px; - border-color: #82B92E; - min-width: 882px; - background-color: #333; - color: white; -} - -.fixed_header { - z-index: 9999; - position: fixed; - left: 0; - top: 0; - width: 100%; +/* + * --------------------------------------------------------------------- + * - FOOTER - + * --------------------------------------------------------------------- + */ +a.footer, +a.footer span { + font-size: 9px; + color: white; } div#foot { - font-size: 6pt !important; - border-top: solid 2px #222; - padding-top: 8px; - padding-bottom: 5px; - text-align: center; - background: #333333; - height: 30px; - clear: both; - width: auto; -} -#ver { - margin-bottom: 25px; + font-size: 6pt !important; + border-top: solid 2px #222; + padding-top: 8px; + padding-bottom: 5px; + text-align: center; + background: #333333; + height: 30px; + clear: both; + width: auto; } -/****************/ -/* LOGIN STYLES */ -/****************/ - -@font-face { - font-family: 'Nunito'; - font-style: normal; - font-weight: 400; - src: local('Nunito-Regular'), url(../../fonts/nunito.woff) format('woff'); -} - -@font-face { - font-family: 'lato-thin'; - src: url('../../fonts/Lato-Hairline.ttf'); -} -@font-face { - font-family: 'lato-bolder'; - src: url('../../fonts/Lato-Light.ttf'); -} -@font-face { - font-family: 'lato-boldest'; - src: url('../../fonts/Lato-Regular.ttf'); -} - - -#login_body { - /* Set rules to fill background */ - min-height: 100%; - min-width: 1200px; - width: 100%; - z-index: -9999; - position: absolute; -} - -@media screen and (max-width: 1024px) { /* Specific to this particular image */ - #login_body { - left: 50%; - margin-left: -512px; /* 50% */ - } -} -@media screen and (max-width: 1100px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); - background-repeat: repeat; - } -} -@media screen and (max-width: 1400px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); - background-repeat: repeat; - } -} -@media screen and (max-width: 2000px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); - background-repeat: repeat; - } -} -@media screen and (min-width: 2000px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/background_pandora_console_keys.jpg"); - background-repeat: repeat; - } -} - -p.log_in { - color: #FFF !important; - padding: 0px 10px; - width:300px; -} - -h1#log_f { - color: #c00; - border-bottom: 1px solid #c00; - padding-bottom: 3px; -} - -div#error_login { - text-align: center; - margin-top: 5px; - margin-left: 5px; - width: 75%; - float: right; - text-align: left; - top: 100px; -} - -div#error_login_icon { - #margin: 0 auto; - margin-top: 10px; - margin-right: 7px; - text-align: center; - #margin-left: 20px; - width: 20%; - float: right; -} - -div#login_f { - margin-top: 10px; - margin-bottom: 25px; -} - -a:focus, input:focus, button:focus { - utline-width: 0; - outline: 0; -} /* -DIV.login_links { - margin: 10px 0px 0px; - color: #FFF; - text-align: center; + * --------------------------------------------------------------------- + * - HEADER AND LEFT MENU STYLES - + * --------------------------------------------------------------------- + */ +div#menu_container { + -moz-border-top-right-radius: 6px; + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + z-index: 1010; + width: 40px; + height: 100%; } -DIV.login_links>a { - color: #FFF; +div#menu { + width: 45px; + float: left; + z-index: 2000; + position: absolute; } -DIV.login_button{ - text-align:right; - width: 100%; - margin-top: 15px; +div#head { + font-size: 8pt; + width: 100%; + height: 60px; + padding-top: 0px; + margin-bottom: 20px; + border-bottom-style: solid; + border-bottom-width: 3px; + border-color: #82b92e; + min-width: 882px; + background-color: #333; + color: white; } -DIV.login_button>input{ - background-color: #373737 !important; - border: 0px none; - background-image: url("../../images/input_go.png") !important; - padding-right: 25px !important; +.fixed_header { + z-index: 9999; + position: fixed; + left: 0; + top: 0; + width: 100%; } -.login_page{ - height: 200px; - padding-top: 10%; - text-align: center; - width: 100%; - position: absolute; +#ver { + margin-bottom: 25px; } -input.next_login { - padding-right: 12px !important; - padding-left: 12px !important; - height: 23px; - text-align: center; - font-weight: 600 !important; - letter-spacing: 0.5pt; - font-size: 12px !important; - border-radius: 3px !important; -} - -DIV.login_nick, DIV.login_pass { - text-align:left; - padding-left: 15px; - margin-top: 10px; -} - -DIV.login_nick>input, DIV.login_pass>input { - height: 20px; - border-radius:0px; - margin-left: 10px; -} - -DIV.login_nick>input:focus,DIV.login_pass>input:focus { - outline-width: 0px; - border-color: #82B92E; - background-color: #82B92E; - font-size: 12px; - height: 20px; - box-shadow: 0px 0px 3px 3px #82B92E; -} - -DIV.login_nick>img, DIV.login_pass>img { - vertical-align: middle; -} - -DIV.login_links a { - letter-spacing: 0.8pt; -} - -DIV.login_links a:first-child { - margin-right: 5px; -} - -DIV.login_links a:last-child { - margin-left: 5px; -} - -DIV.login_nick_text { - text-align: left; - margin-bottom: 3px; - width: 191px; - margin: 5px 0px; - font-size: 12px; - letter-spacing: 0.4pt; -} - -DIV.login_pass_text { - text-align: left; - width: 191px; - margin: 13px 0px 5px 0px; - font-size: 12px; - letter-spacing: 0.4pt; -} - -DIV.login_pass { -} - -input.login { - border: 0px none; - margin: 0px 0px; - width: 135px; - height: 18px; - font-weight: 100 !important; - - letter-spacing: 0.3pt; -} - -input.login_user { - - color: #373737 !important; - padding-left: 8px; - width: 179px; - color: #222; - height: 18px; -} - -input.login_password { - - padding-left: 8px; - width: 179px; - color: #222; - height: 20px; -} -*/ -.databox_error { +/*.databox_error { width: 657px !important; height: 400px; border: none !important; @@ -595,327 +648,282 @@ input.login_password { background: url(../../images/splash_error.png) no-repeat; } -#ver_num { - margin: 0px auto; - width: 100%; - position: absolute; - bottom: 10px; - color: #FFF; - text-align: center; -} - -input:-webkit-autofill { - #-webkit-box-shadow: 0 0 0px 1000px #DDD inset; -} -/***********************/ -/* END OF LOGIN STYLES */ -/***********************/ - -th > label { - padding-top: 7px; -} input.chk { margin-right: 0px; border: 0px none; height: 14px; -} +}*/ input.datos { - background-color: #f5f5f5; + background-color: #f5f5f5; } -input.datos_readonly { +/*input.datos_readonly { background-color: #050505; +}*/ + +/* + * --------------------------------------------------------------------- + * - VISUAL MAPS - + * --------------------------------------------------------------------- + */ +input.vs_button_ghost { + background-color: transparent !important; + border: 1px solid #82b92e; + color: #82b92e !important; + text-align: center; + padding: 4px 12px; + font-weight: bold; } -input.sub { - font-weight: normal; - - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - border-radius: 2px; - - font-size: 8pt; - - background-color: #333 !important; - background-repeat: no-repeat !important; - background-position: 92% 3px !important; - - color: white !important; - padding: 3px 3px 5px 12px; - - border-color: #333; -} - -input.sub[disabled] { - color: #B4B4B4 !important; - background-color: #F3F3F3 !important; - border-color: #B6B6B6; - cursor: default; -} - -input.vs_button_ghost{ - background-color: transparent !important; - border: 1px solid #82b92e; - color: #82b92e !important; - text-align: center; - padding: 4px 12px; - font-weight: bold; -} - -input.next, input.upd, input.ok, input.wand, input.delete, input.cog, -input.target, input.search, input.copy, input.add, input.graph, -input.percentile, input.binary, input.camera, input.config, -input.cancel, input.default, input.filter, input.pdf,input.spinn { - padding-right: 30px; - height: 23px; - -} - -input:disabled { - background-color: #DDD !important; -} -textarea:disabled { - background-color: #DDD !important; -} -select:disabled { - background-color: #DDD !important; +input.next, +input.upd, +input.ok, +input.wand, +input.delete, +input.cog, +input.target, +input.search, +input.copy, +input.add, +input.graph, +input.percentile, +input.binary, +input.camera, +input.config, +input.cancel, +input.default, +input.filter, +input.pdf, +input.spinn { + padding-right: 30px; + height: 23px; } input.next { - background-image: url(../../images/input_go.png) !important; + background-image: url(../../images/input_go.png) !important; } input.upd { - background-image: url(../../images/input_update.png) !important; + background-image: url(../../images/input_update.png) !important; } input.wand { - background-image: url(../../images/input_wand.png) !important; + background-image: url(../../images/input_wand.png) !important; } input.wand:disabled { - background-image: url(../../images/input_wand.disabled.png) !important; + background-image: url(../../images/input_wand.disabled.png) !important; } input.search { - background-image: url(../../images/input_zoom.png) !important; + background-image: url(../../images/input_zoom.png) !important; } input.search:disabled { - background-image: url(../../images/input_zoom.disabled.png) !important; + background-image: url(../../images/input_zoom.disabled.png) !important; } input.ok { - background-image: url(../../images/input_tick.png) !important; + background-image: url(../../images/input_tick.png) !important; } input.ok:disabled { - background-image: url(../../images/input_tick.disabled.png) !important; + background-image: url(../../images/input_tick.disabled.png) !important; } input.add { - background-image: url(../../images/input_add.png) !important; + background-image: url(../../images/input_add.png) !important; } input.add:disabled { - background-image: url(../../images/input_add.disabled.png) !important; + background-image: url(../../images/input_add.disabled.png) !important; } input.cancel { - background-image: url(../../images/input_cross.png) !important; + background-image: url(../../images/input_cross.png) !important; } input.cancel:disabled { - background-image: url(../../images/input_cross.disabled.png) !important; + background-image: url(../../images/input_cross.disabled.png) !important; } input.delete { - background-image: url(../../images/input_delete.png) !important; + background-image: url(../../images/input_delete.png) !important; } input.delete:disabled { - background-image: url(../../images/input_delete.disabled.png) !important; + background-image: url(../../images/input_delete.disabled.png) !important; } input.cog { - background-image: url(../../images/input_cog.png) !important; + background-image: url(../../images/input_cog.png) !important; } input.cog:disabled { - background-image: url(../../images/input_cog.disabled.png) !important; + background-image: url(../../images/input_cog.disabled.png) !important; } input.config { - background-image: url(../../images/input_config.png) !important; + background-image: url(../../images/input_config.png) !important; } input.config:disabled { - background-image: url(../../images/input_config.disabled.png) !important; + background-image: url(../../images/input_config.disabled.png) !important; } input.filter { - background-image: url(../../images/input_filter.png) !important; + background-image: url(../../images/input_filter.png) !important; } input.filter:disabled { - background-image: url(../../images/input_filter.disabled.png) !important; + background-image: url(../../images/input_filter.disabled.png) !important; } input.pdf { - background-image: url(../../images/input_pdf.png) !important; + background-image: url(../../images/input_pdf.png) !important; } input.pdf:disabled { - background-image: url(../../images/input_pdf.disabled.png) !important; + background-image: url(../../images/input_pdf.disabled.png) !important; } input.camera { - background-image: url(../../images/input_camera.png) !important; + background-image: url(../../images/input_camera.png) !important; } input.spinn { - background-image: url(../../images/spinner_green.gif) !important; + background-image: url(../../images/spinner_green.gif) !important; } #toolbox #auto_save { - padding-top: 5px; + padding-top: 5px; } #toolbox { - margin-top: 13px; + margin-top: 13px; } input.visual_editor_button_toolbox { - padding-right: 15px; - padding-top: 10px; - margin-top:5px; + padding-right: 15px; + padding-top: 10px; + margin-top: 5px; } input.delete_min { - background: #fefefe url(../../images/cross.png) no-repeat center !important; + background: #fefefe url(../../images/cross.png) no-repeat center !important; } input.delete_min[disabled] { - background: #fefefe url(../../images/cross.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/cross.disabled.png) no-repeat center !important; } input.graph_min { - background: #fefefe url(../../images/chart_curve.png) no-repeat center !important; + background: #fefefe url(../../images/chart_curve.png) no-repeat center !important; } input.graph_min[disabled] { - background: #fefefe url(../../images/chart_curve.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/chart_curve.disabled.png) no-repeat + center !important; } input.bars_graph_min { - background: #fefefe url(../../images/icono-barras-arriba.png) no-repeat center !important; + background: #fefefe url(../../images/icono-barras-arriba.png) no-repeat center !important; } input.bars_graph_min[disabled] { - background: #fefefe url(../../images/icono-barras-arriba.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/icono-barras-arriba.disabled.png) + no-repeat center !important; } input.percentile_min { - background: #fefefe url(../../images/chart_bar.png) no-repeat center !important; + background: #fefefe url(../../images/chart_bar.png) no-repeat center !important; } input.percentile_min[disabled] { - background: #fefefe url(../../images/chart_bar.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/chart_bar.disabled.png) no-repeat center !important; } input.percentile_item_min { - background: #fefefe url(../../images/percentile_item.png) no-repeat center !important; + background: #fefefe url(../../images/percentile_item.png) no-repeat center !important; } input.percentile_item_min[disabled] { - background: #fefefe url(../../images/percentile_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/percentile_item.disabled.png) no-repeat + center !important; } input.auto_sla_graph_min { - background: #fefefe url(../../images/auto_sla_graph.png) no-repeat center !important; + background: #fefefe url(../../images/auto_sla_graph.png) no-repeat center !important; } input.auto_sla_graph_min[disabled] { - background: #fefefe url(../../images/auto_sla_graph.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/auto_sla_graph.disabled.png) no-repeat + center !important; } input.donut_graph_min { - background: #fefefe url(../../images/icono-quesito.png) no-repeat center !important; + background: #fefefe url(../../images/icono-quesito.png) no-repeat center !important; } input.donut_graph_min[disabled] { - background: #fefefe url(../../images/icono-quesito.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/icono-quesito.disabled.png) no-repeat + center !important; } input.binary_min { - background: #fefefe url(../../images/binary.png) no-repeat center !important; + background: #fefefe url(../../images/binary.png) no-repeat center !important; } input.binary_min[disabled] { - background: #fefefe url(../../images/binary.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/binary.disabled.png) no-repeat center !important; } input.camera_min { - background: #fefefe url(../../images/camera.png) no-repeat center !important; + background: #fefefe url(../../images/camera.png) no-repeat center !important; } input.camera_min[disabled] { - background: #fefefe url(../../images/camera.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/camera.disabled.png) no-repeat center !important; } input.config_min { - background: #fefefe url(../../images/config.png) no-repeat center !important; + background: #fefefe url(../../images/config.png) no-repeat center !important; } input.config_min[disabled] { - background: #fefefe url(../../images/config.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/config.disabled.png) no-repeat center !important; } input.label_min { - background: #fefefe url(../../images/tag_red.png) no-repeat center !important; + background: #fefefe url(../../images/tag_red.png) no-repeat center !important; } input.label_min[disabled] { - background: #fefefe url(../../images/tag_red.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/tag_red.disabled.png) no-repeat center !important; } input.icon_min { - background: #fefefe url(../../images/photo.png) no-repeat center !important; + background: #fefefe url(../../images/photo.png) no-repeat center !important; } input.icon_min[disabled] { - background: #fefefe url(../../images/photo.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/photo.disabled.png) no-repeat center !important; } input.clock_min { - background: #fefefe url(../../images/clock-tab.png) no-repeat center !important; + background: #fefefe url(../../images/clock-tab.png) no-repeat center !important; } input.clock_min[disabled] { - background: #fefefe url(../../images/clock-tab.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/clock-tab.disabled.png) no-repeat center !important; } input.box_item { - background: #fefefe url(../../images/box_item.png) no-repeat center !important; + background: #fefefe url(../../images/box_item.png) no-repeat center !important; } input.box_item[disabled] { - background: #fefefe url(../../images/box_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/box_item.disabled.png) no-repeat center !important; } input.line_item { - background: #fefefe url(../../images/line_item.png) no-repeat center !important; + background: #fefefe url(../../images/line_item.png) no-repeat center !important; } input.line_item[disabled] { - background: #fefefe url(../../images/line_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/line_item.disabled.png) no-repeat center !important; } input.copy_item { - background: #fefefe url(../../images/copy_visualmap.png) no-repeat center !important; + background: #fefefe url(../../images/copy_visualmap.png) no-repeat center !important; } input.copy_item[disabled] { - background: #fefefe url(../../images/copy_visualmap.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/copy_visualmap.disabled.png) no-repeat + center !important; } input.grid_min { - background: #fefefe url(../../images/grid.png) no-repeat center !important; + background: #fefefe url(../../images/grid.png) no-repeat center !important; } input.grid_min[disabled] { - background: #fefefe url(../../images/grid.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/grid.disabled.png) no-repeat center !important; } input.save_min { - background: #fefefe url(../../images/file.png) no-repeat center !important; + background: #fefefe url(../../images/file.png) no-repeat center !important; } input.save_min[disabled] { - background: #fefefe url(../../images/file.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/file.disabled.png) no-repeat center !important; } input.service_min { - background: #fefefe url(../../images/box.png) no-repeat center !important; + background: #fefefe url(../../images/box.png) no-repeat center !important; } input.service_min[disabled] { - background: #fefefe url(../../images/box.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/box.disabled.png) no-repeat center !important; } input.group_item_min { - background: #fefefe url(../../images/group_green.png) no-repeat center !important; + background: #fefefe url(../../images/group_green.png) no-repeat center !important; } input.group_item_min[disabled] { - background: #fefefe url(../../images/group_green.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/group_green.disabled.png) no-repeat + center !important; } div#cont { - position: fixed; - max-height: 320px; - overflow-y: auto; - overflow-x: hidden; + position: fixed; + max-height: 320px; + overflow-y: auto; + overflow-x: hidden; } -.termframe{ +/*.termframe{ background-color: #80BA27 !important; -} +}*/ -table, img { - border: 0px; -} -table pre{ - white-space: pre-wrap; -} - -tr:first-child>th { - background-color: #373737; -} - -th { - color: #fff; - background-color: #666; - font-size: 7.5pt; - letter-spacing: 0.3pt; -} -tr.datos, tr.datost, tr.datosb , tr.datos_id, +/*tr.datos, tr.datost, tr.datosb , tr.datos_id, tr.datosf9 { #background-color: #eaeaea; } @@ -929,418 +937,503 @@ tr.datos:hover, tr.datost:hover, tr.datosb:hover, tr.datos_id:hover, tr.datosf9:hover, tr.datos2:hover, tr.datos2t:hover, tr.datos2b:hover, tr.datos2_id:hover, tr.datos2f9:hover { #background-color: #efefef; +}*/ + +/* + * --------------------------------------------------------------------- + * - REPORTS - + * --------------------------------------------------------------------- + */ +.agent_reporting { + margin: 5px; + padding: 5px; } -/* Checkbox styles */ -td input[type=checkbox] -{ - /* Double-sized Checkboxes */ - /*-ms-transform: scale(1.3); /* IE */ - /*-moz-transform: scale(1.3); /* FF */ - /*-o-transform: scale(1.3); /* Opera */ - /*-webkit-transform: scale(1.3); /* Safari and Chrome */ - padding: 10px; - margin-top: 2px; - display: table-cell; +.report_table, +.agent_reporting { + border: #ccc outset 3px; } -td.datos3, td.datos3 * { - background-color: #666; - color: white !important; +td.datos3, +td.datos3 * { + background-color: #666; + color: white !important; } -td.datos4, td.datos4 * { - /*Add !important because in php the function html_print_table write style in cell and this is style head.*/ - text-align: center !important; - background-color: #666; - color: white !important; +td.datos4, +td.datos4 * { + /*Add !important because in php the function html_print_table write style in cell and this is style head.*/ + text-align: center !important; + background-color: #666; + color: white !important; } -td.datos_id { +/*td.datos_id { color: #1a313a; -} +}*/ +/* user list php */ tr.disabled_row_user * { - color: grey; + color: grey; } -.bg { /* op menu */ - background: #82b92e; -} - -.bg2 { /* main page */ - background-color: #0A160C; -} -.bg3 { /* godmode */ - background: #666666; -} -.bg4 { /* links */ - background-color: #989898; -} -.bg, .bg2, .bg3, .bg4 { - position: relative; - width: 100%; -} +/* global syles */ .bg { - height: 20px; + /* op menu */ + background: #82b92e; } -.bg2, .bg3, .bg4 { - height: 18px; + +.bg { + /* op menu */ + background: #82b92e; + height: 20px; } -.f10, #ip { - font-size: 7pt; - text-align: center; + +.bg2 { + /* main page */ + background-color: #0a160c; } -.f9, .f9i, .f9b, .datos_greyf9, .datos_bluef9, .datos_greenf9, -.datos_redf9, .datos_yellowf9, td.f9, td.f9i, td.datosf9, td.datos2f9 { - font-size: 6.5pt; +.bg3 { + /* godmode */ + background: #666666; } -.f9i, .redi { - font-style: italic; +.bg4 { + /* links */ + background-color: #989898; +} +.bg, +.bg2, +.bg3, +.bg4 { + position: relative; + width: 100%; +} +.bg2, +.bg3, +.bg4 { + height: 18px; +} +.f10, +#ip { + font-size: 7pt; + text-align: center; +} +.f9, +.f9i, +.f9b, +.datos_greyf9, +.datos_bluef9, +.datos_greenf9, +.datos_redf9, +.datos_yellowf9, +td.f9, +td.f9i, +td.datosf9, +td.datos2f9 { + font-size: 6.5pt; +} +.f9i, +.redi { + font-style: italic; } .tit { - padding: 6px 0px; - height: 14px; + padding: 6px 0px; + height: 14px; } -.tit, .titb { - font-weight: bold; - color: #fff; - text-align: center; +.tit, +.titb { + font-weight: bold; + color: #fff; + text-align: center; } .suc * { - color: #5a8629; + color: #5a8629; } -.info *{ - color: #006F9D; +.info * { + color: #006f9d; } -.error *{ - color: #f85858; +.error * { + color: #f85858; } -.warning *{ - color: #FAD403; +.warning * { + color: #fad403; } .help { - background: url(../../images/help.png) no-repeat; + background: url(../../images/help.png) no-repeat; } -.red, .redb, .redi, .error { - color: #c00; +.red, +.redb, +.redi, +.error { + color: #c00; } .sep { - margin-left: 30px; - border-bottom: 1px solid #708090; - width: 100%; + margin-left: 30px; + border-bottom: 1px solid #708090; + width: 100%; } .orange { - color: #fd7304; + color: #fd7304; } .green { - color: #5a8629; + color: #5a8629; } .yellow { - color: #F3C500; + color: #f3c500; } .greenb { - color: #00aa00; + color: #00aa00; } .grey { - color: #808080; - font-weight: bold; + color: #808080; + font-weight: bold; } .blue { - color: #5AB7E5; - font-weight: bold; + color: #5ab7e5; + font-weight: bold; } -.redb, .greenb, td.datos_id, td.datos2_id, f9b { - font-weight: bold; +.redb, +.greenb, +td.datos_id, +td.datos2_id { + font-weight: bold; } .p10 { - padding-top: 1px; - padding-bottom: 0px; + padding-top: 1px; + padding-bottom: 0px; } .p21 { - padding-top: 2px; - padding-bottom: 1px; + padding-top: 2px; + padding-bottom: 1px; } .w120 { - width: 120px; + width: 120px; } -.w130, #table-agent-configuration select { - width: 130px; +.w130, +#table-agent-configuration select { + width: 130px; } .w135 { - width: 135px; + width: 135px; } -.w155, #table_layout_data select { - width: 155px; +.w155, +#table_layout_data select { + width: 155px; } -.top, .top_red, .bgt, td.datost, td.datos2t { - vertical-align: top; +.top, +.top_red, +.bgt, +td.datost, +td.datos2t { + vertical-align: top; } .top_red { - background: #ff0000; + background: #ff0000; } -.bot, .titb, td.datosb { - vertical-align: bottom; +.bot, +.titb, +td.datosb { + vertical-align: bottom; } .msg { - margin-top: 15px; - text-align: justify; + margin-top: 15px; + text-align: justify; } ul.mn { - list-style: none; - padding: 0px 0px 0px 0px; - margin: 0px 0px 0px 0px; - line-height: 15px; + list-style: none; + padding: 0px 0px 0px 0px; + margin: 0px 0px 0px 0px; + line-height: 15px; } .gr { - font-size: 10pt; - font-weight: bold; + font-size: 10pt; + font-weight: bold; } -a.mn, .gr { - font-family: Arial, Verdana, sans-serif, Helvetica; +a.mn, +.gr { + font-family: Arial, Verdana, sans-serif, Helvetica; } div.nf { - background: url(../../images/info.png) no-repeat scroll 0 50% transparent; - margin-left: 7px; - padding: 8px 1px 6px 25px; + background: url(../../images/info.png) no-repeat scroll 0 50% transparent; + margin-left: 7px; + padding: 8px 1px 6px 25px; } div.title_line { - background-color: #4e682c; - height: 5px; - width: 762px; + background-color: #4e682c; + height: 5px; + width: 762px; } .alpha50 { - filter:alpha(opacity=50); - -moz-opacity: 0.5; - opacity: 0.5; - -khtml-opacity: 0.5; + filter: alpha(opacity=50); + -moz-opacity: 0.5; + opacity: 0.5; + -khtml-opacity: 0.5; } - -#menu_tab_frame, #menu_tab_frame_view { - display: block !important; - border-bottom: 1px solid #80BA27; -/* float:left; */ - margin-left: 0px !important; - max-height: 31px; - min-height: 31px; - padding-right: 28px; - width: 100%; +/* + * --------------------------------------------------------------------- + * - RIGHT MENU SECTION - + * --------------------------------------------------------------------- + */ +#menu_tab_frame, +#menu_tab_frame_view { + display: block !important; + border-bottom: 1px solid #80ba27; + max-height: 31px; + min-height: 31px; + width: 100%; + padding-right: 0px; + margin-left: 0px !important; + margin-bottom: 20px; + height: 31px; } #menu_tab { - margin: 0px 0px 0px 0px !important; + margin: 0px 0px 0px 0px !important; } -#menu_tab .mn, #menu_tab ul, #menu_tab .mn ul { - padding: 0px; - list-style: none; - margin: 0px 0px 0px 0px; +#menu_tab .mn, +#menu_tab ul, +#menu_tab .mn ul { + padding: 0px; + list-style: none; + margin: 0px 0px 0px 0px; } #menu_tab .mn li { - float: right; - position: relative; - margin: 0px 0px 0px 0px; + float: right; + position: relative; + margin: 0px 0px 0px 0px; } -/* -#menu_tab li a, #menu_tab a { - padding: 2px 0px; - font-weight: bold; - line-height: 18px; - margin-left: 3px; - margin-right: 0px; - - -moz-border-top-right-radius: 5px; - -webkit-border-top-right-radius: 5px; - border-top-right-radius: 5px; - - -moz-border-top-left-radius: 5px; - -webkit-border-top-left-radius: 5px; - border-top-left-radius: 5px; -} - -#menu_tab li>form { - padding-left: 7px; - padding-top: 4px; -} -*/ #menu_tab li.separator_view { - padding: 4px; + padding: 4px; } #menu_tab li.separator { - padding: 4px; + padding: 4px; } #menu_tab li.nomn_high a { - /*background: #82b92e;*/ - color: #fff; + color: #fff; } #menu_tab .mn li a { - display: block; - text-decoration: none; - padding: 0px; - margin: 0px; + display: block; + text-decoration: none; + padding: 0px; + margin: 0px; } -#menu_tab li.nomn:hover a, #menu_tab li:hover ul a:hover { - /*background: #82b92e;*/ - color: #fff; -} -#menu_tab li:hover a { - /*background: #b2b08a url("../../images/arrow.png") no-repeat right 3px;*/ +#menu_tab li.nomn:hover a, +#menu_tab li:hover ul a:hover { + color: #fff; } #menu_tab li.nomn { - min-width: 30px; - height: 28px; + min-width: 30px; + height: 28px; } #menu_tab li.nomn_high { - min-width: 30px; - height: 28px; -} -/* TAB TITLE */ -#menu_tab_left { - margin-left: 0px !important; + min-width: 30px; + height: 28px; } -#menu_tab_left .mn, #menu_tab_left ul, #menu_tab_left .mn ul { - background-color: #000; - color: #fff; - font-weight: bold; - padding: 0px 0px 0px 0px; - list-style: none; - margin: 0px 0px 0px 0px; +/* --- Submenu --- */ +ul.subsubmenu { + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; + -moz-border-bottom-right-radius: 5px; + -moz-border-bottom-left-radius: 5px; + -webkit-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; + + background: #ececec !important; +} + +ul.subsubmenu li { + background-color: #ececec; + font-weight: bold; + text-decoration: none; + font-size: 14px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; +} + +ul.subsubmenu li a { + padding: 0px 10px 5px; +} + +.subsubmenu { + position: absolute; + float: right; + z-index: 9999; + display: none; + margin-top: 5px !important ; + left: 0px !important; +} +.subsubmenu li { + margin-top: 0px !important ; +} + +div#agent_wizard_subtabs { + position: absolute; + margin-left: 0px; + display: none; + padding-bottom: 3px; + z-index: 1000; +} + +.agent_wizard_tab:hover { + cursor: default; +} + +/* + * --------------------------------------------------------------------- + * - SECTION TITLE LEFT (green background) - + * --------------------------------------------------------------------- + */ +/* TAB TITLE */ +#menu_tab_left { + margin-left: 0px !important; +} + +#menu_tab_left .mn, +#menu_tab_left ul, +#menu_tab_left .mn ul { + background-color: #000; + color: #fff; + font-weight: bold; + padding: 0px 0px 0px 0px; + list-style: none; + margin: 0px 0px 0px 0px; } #menu_tab_left .mn li { - float: left; - position: relative; - height: 26px; - max-height: 26px; + float: left; + position: relative; + height: 26px; + max-height: 26px; } #menu_tab_left .mn li a { - display: block; - text-decoration: none; + display: block; + text-decoration: none; } #menu_tab_left li.view a { - color: #fff; - font-weight: bold; - font-weight: 100; - line-height: 18px; - display: none; + color: #fff; + font-weight: bold; + font-weight: 100; + line-height: 18px; + display: none; } #menu_tab_left li.view { - background: #82b92e; - max-width: 60%; - min-width: 30%; - padding: 5px 5px 0px; - text-align: center; - -moz-border-top-right-radius: 3px; - -webkit-border-top-right-radius: 3px; - border-top-right-radius: 3px; + background: #82b92e; + max-width: 60%; + min-width: 30%; + padding: 5px 5px 0px; + text-align: center; + -moz-border-top-right-radius: 3px; + -webkit-border-top-right-radius: 3px; + border-top-right-radius: 3px; - -moz-border-top-left-radius: 3px; - -webkit-border-top-left-radius: 3px; - border-top-left-radius: 3px; - margin-left:0px !important; - overflow-y: hidden; + -moz-border-top-left-radius: 3px; + -webkit-border-top-left-radius: 3px; + border-top-left-radius: 3px; + margin-left: 0px !important; + overflow-y: hidden; } #menu_tab_left li.view img.bottom { - width: 24px; - height: 24px; + width: 24px; + height: 24px; } -#menu_tab_frame *, #menu_tab_frame_view *{ - #margin: 0px 0px 0px 0px !important; -} - - -#menu_tab_left li a, #menu_tab_left li span { - text-transform: uppercase; - color: #fff; - font-size: 100%; - line-height: 20px; - letter-spacing:0px; - font-family: verdana, sans-serif; - font-weight: bold; +#menu_tab_left li a, +#menu_tab_left li span { + text-transform: uppercase; + color: #fff; + font-size: 100%; + line-height: 20px; + letter-spacing: 0px; + font-family: verdana, sans-serif; + font-weight: bold; } +/* span.users { - background: url(../../images/group.png) no-repeat; + background: url(../../images/group.png) no-repeat; } span.agents { - background: url(../../images/bricks.png) no-repeat; + background: url(../../images/bricks.png) no-repeat; } span.data { - background: url(../../images/data.png) no-repeat; + background: url(../../images/data.png) no-repeat; } span.alerts { - background: url(../../images/bell.png) no-repeat; + background: url(../../images/bell.png) no-repeat; } span.time { - background: url(../../images/hourglass.png) no-repeat; + background: url(../../images/hourglass.png) no-repeat; } span.net { - background: url(../../images/network.png) no-repeat; + background: url(../../images/network.png) no-repeat; } span.master { - background: url(../../images/master.png) no-repeat; + background: url(../../images/master.png) no-repeat; } span.wmi { - background: url(../../images/wmi.png) no-repeat; + background: url(../../images/wmi.png) no-repeat; } span.prediction { - background: url(../../images/chart_bar.png) no-repeat; + background: url(../../images/chart_bar.png) no-repeat; } span.plugin { - background: url(../../images/plugin.png) no-repeat; + background: url(../../images/plugin.png) no-repeat; } span.export { - background: url(../../images/database_refresh.png) no-repeat; + background: url(../../images/database_refresh.png) no-repeat; } span.snmp { - background: url(../../images/snmp.png) no-repeat; + background: url(../../images/snmp.png) no-repeat; } span.binary { - background: url(../../images/binary.png) no-repeat; + background: url(../../images/binary.png) no-repeat; } span.recon { - background: url(../../images/recon.png) no-repeat; + background: url(../../images/recon.png) no-repeat; } span.rmess { - background: url(../../images/email_open.png) no-repeat; + background: url(../../images/email_open.png) no-repeat; } span.nrmess { - background: url(../../images/email.png) no-repeat; + background: url(../../images/email.png) no-repeat; } span.recon_server { - background: url(../../images/recon.png) no-repeat; + background: url(../../images/recon.png) no-repeat; } span.wmi_server { - background: url(../../images/wmi.png) no-repeat; + background: url(../../images/wmi.png) no-repeat; } span.export_server { - background: url(../../images/server_export.png) no-repeat; + background: url(../../images/server_export.png) no-repeat; } span.inventory_server { - background: url(../../images/page_white_text.png) no-repeat; + background: url(../../images/page_white_text.png) no-repeat; } span.web_server { - background: url(../../images/world.png) no-repeat; + background: url(../../images/world.png) no-repeat; } +*/ + /* This kind of span do not have any sense, should be replaced on PHP code by a real img in code. They are not useful because insert too much margin around (for example, not valid to use in the table of server view */ -span.users, span.agents, span.data, span.alerts, span.time, span.net, +/*span.users, span.agents, span.data, span.alerts, span.time, span.net, span.master, span.snmp, span.binary, span.recon, span.wmi, span.prediction, span.plugin, span.plugin, span.export, span.recon_server, span.wmi_server, span.export_server, span.inventory_server, span.web_server { @@ -1353,318 +1446,294 @@ span.rmess, span.nrmess { margin-left: 14px; padding: 1px 0px 10px 30px; display: block; -} -/* New styles for data box */ -.databox, .databox_color, .databox_frame { - margin-bottom: 5px; - margin-top: 0px; - margin-left: 0px; - border: 1px solid #e2e2e2; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; +}*/ +/* New styles for data box */ +/* + * --------------------------------------------------------------------- + * - TABLES - + * --------------------------------------------------------------------- + */ +.databox, +.databox_color, +.databox_frame { + margin-bottom: 5px; + margin-top: 0px; + margin-left: 0px; + border: 1px solid #e2e2e2; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + border-radius: 4px; } -.databox_color{ - padding-top: 5px; +.databox_color { + padding-top: 5px; + background-color: #fafafa; } table.databox { - background-color: #f9faf9; - border-spacing: 0px; - -moz-box-shadow: 0px 0px 0px #DDD !important; - -webkit-box-shadow: 0px 0px 0px #DDD !important; - box-shadow: 0px 0px 0px #DDD !important; + background-color: #f9faf9; + border-spacing: 0px; + -moz-box-shadow: 0px 0px 0px #ddd !important; + -webkit-box-shadow: 0px 0px 0px #ddd !important; + box-shadow: 0px 0px 0px #ddd !important; } -.databox>tbody>tr>td { - -moz-border-radius: 0px; - -webkit-border-radius: 0px; - border-radius: 0px; - border: 0px none #E2E2E2; +.databox > tbody > tr > td { + -moz-border-radius: 0px; + -webkit-border-radius: 0px; + border-radius: 0px; + border: 0px none #e2e2e2; + padding-left: 9px; + padding-right: 9px; + padding-top: 7px; + padding-bottom: 7px; } -.databox>thead>tr>th, .databox>tbody>tr>th, .databox>thead>tr>th a { - padding: 9px 7px; - font-weight: normal; - color: #fff; +.databox > thead > tr > th, +.databox > tbody > tr > th { + padding: 9px 7px; + font-weight: normal; + color: #fff; } -.databox>td { - #border-bottom: 1px solid #E2E2E2; +.databox > td { + #border-bottom: 1px solid #e2e2e2; } -.databox>th * { - color: #fff; +.databox > th * { + color: #fff; } -.databox>th>input, .databox>th>textarea, .databox>th>select, .databox>th>select>option { - color: #222 !important; +.databox > th > input, +.databox > th > textarea, +.databox > th > select, +.databox > th > select > option { + color: #222 !important; } -.databox.data>tbody>tr>td:first-child{ - border-left: 1px solid #e2e2e2; +.databox.data > tbody > tr > td:first-child { + border-left: 1px solid #e2e2e2; } -.databox.data>tbody>tr:last-child>td:first-child{ - border-bottom-left-radius: 4px; +.databox.data > tbody > tr:last-child > td:first-child { + border-bottom-left-radius: 4px; } -.databox.data>tbody>tr>td:last-child { - border-right: 1px solid #e2e2e2; +.databox.data > tbody > tr > td:last-child { + border-right: 1px solid #e2e2e2; } -.databox.data>tbody>tr:last-child >td:last-child { - border-bottom-right-radius: 4px; +.databox.data > tbody > tr:last-child > td:last-child { + border-bottom-right-radius: 4px; } -.databox.data>thead>tr:first-child>th:first-child { - border-left: 1px solid #e2e2e2; - border-top-left-radius: 4px; - border-color: #373737; +.databox.data > thead > tr:first-child > th:first-child { + border-left: 1px solid #e2e2e2; + border-top-left-radius: 4px; + border-color: #373737; } -.databox.data>thead>tr:first-child>th:last-child { - border-right: 1px solid #e2e2e2; - border-top-right-radius: 4px; - border-color: #373737; +.databox.data > thead > tr:first-child > th:last-child { + border-right: 1px solid #e2e2e2; + border-top-right-radius: 4px; + border-color: #373737; } -.databox.data{ - border: none; +.databox.data { + border: none; } .tabletitle { - color: #333; -} - -.tactical_set legend{ - text-align:left; - color: #3F3F3F; -} - -.tactical_set{ - background: #FFF; - border: 1px solid #E2E2E2; - margin-left: auto; - margin-right: auto; - width: auto; + color: #333; } /* For use in Netflow */ - +/* table.databox_grid { - margin: 25px; + margin: 25px; } -table.databox_grid>th { - font-size: 12px; +table.databox_grid > th { + font-size: 12px; } -table.databox_grid>td { - padding: 6px; - margin: 4px; - border-bottom: 1px solid #acacac; - border-right: 1px solid #acacac; +table.databox_grid > td { + padding: 6px; + margin: 4px; + border-bottom: 1px solid #acacac; + border-right: 1px solid #acacac; } +*/ - -table.alternate tr:nth-child(odd) td{ - background-color: #ffffff; +/* events */ +table.alternate tr:nth-child(odd) td { + background-color: #ffffff; } -table.alternate tr:nth-child(even) td{ - background-color: #e4e5e4; +table.alternate tr:nth-child(even) td { + background-color: #e4e5e4; } table.rounded_cells td { - padding: 4px 4px 4px 10px; - -moz-border-radius: 6px !important; - -webkit-border-radius: 6px !important; - border-radius: 6px !important; + padding: 4px 4px 4px 10px; + -moz-border-radius: 6px !important; + -webkit-border-radius: 6px !important; + border-radius: 6px !important; } -.databox_color { - background-color: #fafafa; -} -#head_l { +/*#head_l { float: left; margin: 0; padding: 0; } #head_r { - float: right; - text-align: right; - margin-right: 10px; - padding-top: 0px; + float: right; + text-align: right; + margin-right: 10px; + padding-top: 0px; } #head_m { position: absolute; padding-top: 6px; padding-left: 12em; -} -span#logo_text1 { +}*/ +/*span#logo_text1 { font: bolder 3em Arial, Sans-serif; letter-spacing: -2px; color: #eee; } span#logo_text2 { - font: 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #aaa; + font: 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #aaa; } div#logo_text3 { - text-align: right; - font: 2em Arial, Sans-serif; - letter-spacing: 6px; - color: #aaa; - font-weight: bold; - margin-top: 0px; - margin-left: 4px; - padding-top: 0px; + text-align: right; + font: 2em Arial, Sans-serif; + letter-spacing: 6px; + color: #aaa; + font-weight: bold; + margin-top: 0px; + margin-left: 4px; + padding-top: 0px; } .bb0 { - border-bottom: 0px; + border-bottom: 0px; } .bt0 { border-top: 0px; -} +}*/ .action-buttons { - text-align: right; + text-align: right; } -#table-add-item select, #table-add-sla select { +/*#table-add-item select, #table-add-sla select { width: 180px; -} +}*/ /* end of classes for event priorities */ div#main_pure { - background-color: #fefefe; - text-align: left; - margin-bottom: 25px; - margin-top: 30px; - margin-left: 10px; - margin-right: 10px; - height: 1000px; - width: 98%; - position: static; + background-color: #fefefe; + text-align: left; + margin-bottom: 25px; + margin-top: 30px; + margin-left: 10px; + margin-right: 10px; + height: 1000px; + width: 98%; + position: static; } -#table-agent-configuration radio { +/*#table-agent-configuration radio { margin-right: 40px; -} +}*/ .ui-draggable { - cursor:move; + cursor: move; } -#layout_trash_drop { +/*#layout_trash_drop { float: right; width: 300px; height: 180px; background: #fff url("../../images/trash.png") no-repeat bottom left; } #layout_trash_drop div { - display: block; + display: block; } #layout_editor_drop { float: left; width: 300px; -} -.agent_reporting { - margin: 5px; - padding: 5px; -} -.report_table, .agent_reporting { - border: #CCC outset 3px; -} -.img_help { - cursor: help; -} -#loading { - position:fixed; - width: 200px; - margin-left: 30%; - text-align:center; - top: 50%; - background-color: #999999; - padding: 20px; -} +}*/ + /* IE 7 Hack */ #editor { - *margin-top: 10px !important; + *margin-top: 10px !important; } /* big_data is used in tactical and logon_ok */ .big_data { - text-decoration: none; font: bold 2em Arial, Sans-serif; + text-decoration: none; + font: bold 2em Arial, Sans-serif; } .med_data { - text-decoration: none; font: bold 1.5em Arial, Sans-serif; + text-decoration: none; + font: bold 1.5em Arial, Sans-serif; } .notify { - background-color: #f7ffa5; - text-align: center; - font-weight: bold; - padding: 8px; - margin: 0px 0px 0px 0px !important; - z-index: -1; + background-color: #f7ffa5; + text-align: center; + font-weight: bold; + padding: 8px; + margin: 0px 0px 0px 0px !important; + z-index: -1; } .notify a { - color: #003a3a; - text-decoration: underline; + color: #003a3a; + text-decoration: underline; } .listing { - border-collapse: collapse; + border-collapse: collapse; } .listing td { - border-bottom: 1px solid #CCCCCC; - border-top: 1px solid #CCCCCC; -} -ul { - list-style-type: none; - padding-left: 0; - margin-left: 0; + border-bottom: 1px solid #cccccc; + border-top: 1px solid #cccccc; } span.actions { - margin-left: 30px; + margin-left: 30px; } .actions { - min-width: 200px! important; + min-width: 200px !important; } -code, pre { - font-family: courier, serif; +select#template, +select#action { + width: 250px; } -select#template, select#action { - width: 250px; -} -#label-checkbox-matches_value, +/*#label-checkbox-matches_value, #label-checkbox-copy_modules, #label-checkbox-copy_alerts { display: inline; font-weight: normal; -} -input[type=image] { - border:0px; - background-color: transparent !important; -} -table#simple{ - padding: 30px; +}*/ + +/* Modules */ +table#simple { + padding: 30px; } table#simple select#id_module_type, table#alert_search select#id_agent, table#alert_search select#id_group, table#network_component select#type { - width: 200px; + width: 200px; } table#simple select#select_snmp_oid, table#simple select#id_plugin, table#network_component select#id_plugin { - width: 270px; + width: 270px; } table#simple select#prediction_id_group, table#simple select#prediction_id_agent, table#simple select#prediction_module { - width: 50%; - display: block; + width: 50%; + display: block; } table#simple input#text-plugin_parameter, table#simple input#text-snmp_oid, @@ -1674,320 +1743,285 @@ table#target_table select, table#filter_compound_table select, table#filter_compound_table #text-search, table#delete_table select { - width: 100%; + width: 100%; } table#simple select#network_component_group, table#simple select#network_component { - width: 90%; + width: 90%; } table#simple span#component_group, table#simple span#component { - width: 45%; - font-style: italic; + width: 45%; + font-style: italic; } table#simple label { - display: inline; - font-weight: normal; - font-style: italic; + display: inline; + font-weight: normal; + font-style: italic; } .clickable { - cursor: pointer; + cursor: pointer; } -table#agent_list tr, table.alert_list tr { - vertical-align: top; +table#agent_list tr, +table.alert_list tr { + vertical-align: top; +} +.toggle { + border-collapse: collapse; +} +.toggle td { + border-left: 1px solid #d3d3d3; } -.toggle { border-collapse: collapse;} -.toggle td { border-left: 1px solid #D3D3D3;} ul.actions_list { - list-style-image: url(../../images/arrow.png); - list-style-position: inside; - margin-top: 0; + list-style-image: url(../../images/arrow.png); + list-style-position: inside; + margin-top: 0; } div.loading { - background-color: #FFF1A8; - margin-left: auto; - margin-right: auto; - padding: 5px; - text-align: center; - font-style: italic; - width: 95%; + background-color: #fff1a8; + margin-left: auto; + margin-right: auto; + padding: 5px; + text-align: center; + font-style: italic; + width: 95%; } div.loading img { - float: right; + float: right; } /* Tablesorter jQuery pager */ div.pager { - margin-left: 10px; - margin-top: 5px; + margin-left: 10px; + margin-top: 5px; } -div.pager img{ - position: relative; - top: 4px; - padding-left: 5px; +div.pager img { + position: relative; + top: 4px; + padding-left: 5px; } div.pager input { - padding-left: 5px; + padding-left: 5px; } .pagedisplay { - border: 0; - width: 35px; + border: 0; + width: 35px; } /* Steps style */ ol.steps { - margin-bottom: 15px; - padding: 0; - list-style-type: none; - list-style-position: outside; + margin-bottom: 70px; + padding: 0; + list-style-type: none; + list-style-position: outside; } ol.steps li { - float: left; - background-color: #efefef; - padding: 5px; - margin-left: 5px; - width: 150px; + float: left; + background-color: #efefef; + padding: 5px; + margin-left: 5px; + width: 150px; } ol.steps li a { - color: #111; + color: #111; } ol.steps li.visited a { - color: #999; + color: #999; } ol.steps li span { - font-weight: normal; - display: block; -} -ol.steps li span { - color: #777; + font-weight: normal; + display: block; + color: #777; } ol.steps li.visited span { - color: #999; + color: #999; } ol.steps li.current { - border-left: 5px solid #778866; - margin-left: 0; - font-weight: bold; - background-color: #E9F3D2; + border-left: 5px solid #778866; + margin-left: 0; + font-weight: bold; + background-color: #e9f3d2; } ol.steps li.visited { - color: #999 !important; -} - -fieldset { - background-color:#F9FAF9; - border: 1px solid #E2E2E2; - padding:0.5em; - margin-bottom:20px; - position:relative; -} -fieldset legend { - font-size:1.1em; - font-weight:bold; - #color:#3f4e2f; - line-height: 20px; - color: #3F3F3F; - #top:-2em; + color: #999 !important; } fieldset .databox { - border: 0px solid; + border: 0px solid; } fieldset.databox { - padding: 14px !important; + padding: 14px !important; } fieldset legend span, span#latest_value { - font-style:italic; + font-style: italic; } span#latest_value span#value { - font-style:normal; + font-style: normal; } form#filter_form { - margin-bottom: 15px; + margin-bottom: 15px; } ul.action_list { - margin: 0; - list-style: none inside circle; + margin: 0; + list-style: none inside circle; } ul.action_list li div { - margin-left: 15px; + margin-left: 15px; } span.action_name { - float: none; + float: none; } div.actions_container { - overflow:auto; - width: 100%; - max-height: 200px; + overflow: auto; + width: 100%; + max-height: 200px; } div.actions_container label { - display: inline; - font-weight: normal; - font-style: italic; + display: inline; + font-weight: normal; + font-style: italic; } a.add_action { - clear: both; - display: block; + clear: both; + display: block; } /* timeEntry styles */ .timeEntry_control { - vertical-align: middle; - margin-left: 2px; -} -div#steps_clean { - clear:both; + vertical-align: middle; + margin-left: 2px; } + div#event_control { - clear:right; + clear: right; } /* Autocomplete styles */ .ac_results { - padding: 0px; - border: 1px solid black; - background-color: white; - overflow: hidden; - z-index: 99999; + padding: 0px; + border: 1px solid black; + background-color: white; + overflow: hidden; + z-index: 99999; } .ac_results ul { - width: 100%; - list-style-position: outside; - list-style: none; - padding: 0; - margin: 0; - text-align: left; + width: 100%; + list-style-position: outside; + padding: 0; + margin: 0; + text-align: left; } .ac_results li { - margin: 0px; - padding: 2px 5px; - cursor: default; - display: block; - /* + margin: 0px; + padding: 2px 5px; + cursor: default; + display: block; + /* if width will be 100% horizontal scrollbar will apear when scroll mode will be used */ - /*width: 100%;*/ - font: menu; - font-size: 12px; - /* + /*width: 100%;*/ + font: menu; + font-size: 12px; + /* it is very important, if line-height not setted or setted in relative units scroll will be broken in firefox */ - line-height: 16px; + line-height: 16px; } .ac_loading { - background: white url('../images/loading.gif') right center no-repeat; + background: white url("../images/loading.gif") right center no-repeat; } .ac_over { - background-color: #efefef; + background-color: #efefef; } span.ac_extra_field, span.ac_extra_field strong { - font-style: italic; - font-size: 9px; + font-style: italic; + font-size: 9px; } - div#pandora_logo_header { -/* Put here your company logo (139x60 pixels) like this: */ -/* background: url(../../images/MiniLogoArtica.jpg); */ - background: url(../../images/pandora_logo_head.png); - background-position: 0% 0%; - width: 139px; - height: 60px; - float: left; + /* Put here your company logo (139x60 pixels) like this: */ + /* background: url(../../images/MiniLogoArtica.jpg); */ + background: url(../../images/pandora_logo_head.png); + background-position: 0% 0%; + width: 139px; + height: 60px; + float: left; } #header_table img { - margin-top: 0px; + margin-top: 0px; } .autorefresh_disabled { - cursor: not-allowed !important; + cursor: not-allowed !important; } a.autorefresh { - padding-right: 8px; + padding-right: 8px; } #refrcounter { - color: white; + color: white; } #combo_refr select { - margin-right: 8px; + margin-right: 8px; } .disabled_module { - color: #aaa; + color: #aaa; } div.warn { - background: url(../../images/info.png) no-repeat; - margin-top: 7px; - padding: 2px 1px 6px 25px; + background: url(../../images/info.png) no-repeat; + margin-top: 7px; + padding: 2px 1px 6px 25px; } .submenu_not_selected { - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - -o-transition-timing-function: ease-out; - font-weight: normal !important; + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + -o-transition-timing-function: ease-out; + font-weight: normal !important; } /* Submenus havent borders */ -.submenu_not_selected, .submenu_selected, .submenu2 { - border: 0px !important; - min-height: 35px !important; -} - -/* Pandora width style theme */ - -div#container { - width: 100%; -} -div#page { - width: auto; -} -div#main { - max-width: 93%; - min-width: 93%; +.submenu_not_selected, +.submenu_selected, +.submenu2 { + border: 0px !important; + min-height: 35px !important; } ol.steps { - margin-bottom: 70px; + margin-bottom: 70px; } div#steps_clean { - display:none; + display: none; } -#menu_tab_frame, #menu_tab_frame_view { - width: 100%; - padding-right: 0px; - margin-left: 0px !important; - margin-bottom: 20px; - height: 31px; -} div#events_list { - float: left; - width: 100%; + float: left; + width: 100%; } -span#logo_text1 { +/*span#logo_text1 { font: bolder 3em Arial, Sans-serif; letter-spacing: -2px; color: #eee; @@ -2006,1349 +2040,1322 @@ div#logo_text3 { margin-top: 0px; margin-left: 4px; padding-top: 0px; -} +}*/ .pagination { - margin-top: 15px; - margin-bottom: 5px; + margin-top: 15px; + margin-bottom: 5px; } .pagination * { - margin-left: 0px !important; - margin-right: 0px !important; - vertical-align: middle; + margin-left: 0px !important; + margin-right: 0px !important; + vertical-align: middle; } -/*CALENDAR TOOLTIP STYLE*/ - -/* Calendar background */ -table.scw { - background-color: #82b92e; - border: 0 !important; - border-radius: 4px; -} - -/* Week number heading */ -td.scwWeekNumberHead { - color: #111; -} - -td.scwWeek { - color: #111 !important; -} - - Today selector -td.scwFoot { - background-color: #daedae; - color: #111; -} - -td.scwFootDisabled { - background-color: #000; - color: #FFFFFF; -} - -tfoot.scwFoot { - color: #111; -} - -.scwFoot :hover{ - color: #3F3F3F !important; -} - -table.scwCells { - background-color: #fff !important; - color: #3c3c3c !important; -} - -table.scwCells:hover { - background-color: #fff !important; -} - -td.scwCellsExMonth { - background-color: #eee !important; - color: #3c3c3c !important; -} - -td.scwCellsWeekend { - background-color: #3c3c3c !important; - color: #fff !important; - border: 0 !important; -} - -td.scwInputDate { - background-color: #777 !important; - color: #ffffff !important; - border: 0 !important; -} - -td.scwFoot { - background-color: #fff !important; - color: #3c3c3c !important; - border: 0 !important; -} - - - +/* TABLAS */ /* Cells divs to set individual styles with the table objects */ div.cellBold { - width: 100%; - height: 100%; - font-weight: bold; + width: 100%; + height: 100%; + font-weight: bold; } div.cellRight { - width: 100%; - height: 100%; - text-align: right; + width: 100%; + height: 100%; + text-align: right; } div.cellCenter { - width:100%; - height:100%; - text-align:center; + width: 100%; + height: 100%; + text-align: center; } div.cellWhite { - width: 100%; - height: 100%; - background: #fff; - color: #111; + width: 100%; + height: 100%; + background: #fff; + color: #111; } div.cellNormal { - width: 100%; - height: 100%; - background: #6EB432; - color: #fff; + width: 100%; + height: 100%; + background: #6eb432; + color: #fff; } div.cellCritical { - width: 100%; - height: 100%; - background: #f85858; - color: #fff; + width: 100%; + height: 100%; + background: #f85858; + color: #fff; } div.cellWarning { - width: 100%; - height: 100%; - background: #ffea59; - color: #111; + width: 100%; + height: 100%; + background: #ffea59; + color: #111; } div.cellUnknown { - width: 100%; - height: 100%; - background: #AAAAAA; - color: #FFFFFF; + width: 100%; + height: 100%; + background: #aaaaaa; + color: #ffffff; } div.cellNotInit { - width: 100%; - height: 100%; - background: #3BA0FF; - color: #FFFFFF; + width: 100%; + height: 100%; + background: #3ba0ff; + color: #ffffff; } div.cellAlert { - width: 100%; - height: 100%; - background: #FF8800; - color: #111; + width: 100%; + height: 100%; + background: #ff8800; + color: #111; } div.cellBorder1 { - width: 100%; - height: 100%; - border: 1px solid #666; + width: 100%; + height: 100%; + border: 1px solid #666; } div.cellBig { - width: 100%; - height: 100%; - font-size: 18px; + width: 100%; + height: 100%; + font-size: 18px; } .info_box { - background: #F9FAF9; - margin-top: 10px !important; - margin-bottom: 10px !important; - padding: 0px 5px 5px 10px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; - width: 100% !important; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; + background: #f9faf9; + margin-top: 10px !important; + margin-bottom: 10px !important; + padding: 0px 5px 5px 10px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; + width: 100% !important; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + border-radius: 4px; } .info_box .title * { - font-size: 10pt !important; - font-weight: bolder; + font-size: 10pt !important; + font-weight: bolder; } .info_box .icon { - width: 30px !important; - text-align: center; + width: 30px !important; + text-align: center; } /* Standard styles for status colos (groups, events, backgrounds...) */ - .opacity_cell { - filter:alpha(opacity=80); - -moz-opacity: 0.8; - opacity: 0.8; - -khtml-opacity: 0.8; + filter: alpha(opacity=80); /* For IE8 and earlier */ + -moz-opacity: 0.8; + opacity: 0.8; + -khtml-opacity: 0.8; } - -tr.group_view_data, .group_view_data { - color: #3F3F3F; +tr.group_view_data, +.group_view_data { + color: #3f3f3f; } -tr.group_view_crit, .group_view_crit { - background-color: #FC4444; - color: #fff; +tr.group_view_crit, +.group_view_crit { + background-color: #fc4444; + color: #fff; } -tr.group_view_norm, .group_view_norm, tr.group_view_normal, .group_view_normal { - #background-color: #ffffff; -} -tr.group_view_ok, .group_view_ok { - background-color: #80BA27; - color: #fff; +tr.group_view_ok, +.group_view_ok { + background-color: #80ba27; + color: #fff; } -tr.group_view_not_init, .group_view_not_init, tr.group_view_not_init, .group_view_not_init { - background-color: #5BB6E5; - color: #fff !important; +tr.group_view_not_init, +.group_view_not_init { + background-color: #5bb6e5; + color: #fff !important; } -tr.group_view_warn, .group_view_warn, tr.group_view_warn.a, a.group_view_warn, tr.a.group_view_warn { - background-color: #FAD403; - color: #fff !important; +tr.group_view_warn, +.group_view_warn, +tr.group_view_warn.a, +a.group_view_warn, +tr.a.group_view_warn { + background-color: #fad403; + color: #fff !important; } a.group_view_warn { - color: #FAD403 !important; - color: #FFF !important; + color: #fad403 !important; + color: #fff !important; } -tr.group_view_alrm, .group_view_alrm { - background-color: #FFA631; - color: #FFF !important; +tr.group_view_alrm, +.group_view_alrm { + background-color: #ffa631; + color: #fff !important; } -tr.group_view_unk, .group_view_unk { - background-color: #B2B2B2 ; - color: #fff !important; +tr.group_view_unk, +.group_view_unk { + background-color: #b2b2b2; + color: #fff !important; } /* classes for event priorities. Sits now in functions.php */ -.datos_green, .datos_greenf9, .datos_green a, .datos_greenf9 a, .datos_green * { - background-color: #80BA27; - color: #fff; +.datos_green, +.datos_greenf9, +.datos_green a, +.datos_greenf9 a, +.datos_green * { + background-color: #80ba27; + color: #fff; } -.datos_red, .datos_redf9, .datos_red a, .datos_redf9 a, .datos_red *{ - background-color: #FC4444; - color: #fff !important; +.datos_red, +.datos_redf9, +.datos_red a, +.datos_redf9 a, +.datos_red * { + background-color: #fc4444; + color: #fff !important; } -.datos_yellow, .datos_yellowf9, .datos_yellow * { - background-color: #FAD403; - color: #111; +.datos_yellow, +.datos_yellowf9, +.datos_yellow * { + background-color: #fad403; + color: #111; } -a.datos_blue, .datos_bluef9, .datos_blue, .datos_blue * { - background-color: #4CA8E0; - color: #fff !important; +a.datos_blue, +.datos_bluef9, +.datos_blue, +.datos_blue * { + background-color: #4ca8e0; + color: #fff !important; } -.datos_grey, .datos_greyf9, .datos_grey * { - background-color: #999999; - color: #fff; +.datos_grey, +.datos_greyf9, +.datos_grey * { + background-color: #999999; + color: #fff; } -.datos_pink, .datos_pinkf9, .datos_pink * { - background-color: #fdc4ca; - color: #111; +.datos_pink, +.datos_pinkf9, +.datos_pink * { + background-color: #fdc4ca; + color: #111; } -.datos_brown, .datos_brownf9, .datos_brown * { - background-color: #A67C52; - color: #fff; +.datos_brown, +.datos_brownf9, +.datos_brown * { + background-color: #a67c52; + color: #fff; } -.datos_orange, .datos_orangef9, .datos_orange * { - background-color: #F7931E; - color: #111; +.datos_orange, +.datos_orangef9, +.datos_orange * { + background-color: #f7931e; + color: #111; } -td.datos_greyf9, td.datos_bluef9, td.datos_greenf9, td.datos_redf9, td.datos_yellowf9, td.datos_pinkf9, td.datos_brownf9 ,td.datos_orangef9 { - padding: 5px 5px 5px 5px; +td.datos_greyf9, +td.datos_bluef9, +td.datos_greenf9, +td.datos_redf9, +td.datos_yellowf9, +td.datos_pinkf9, +td.datos_brownf9, +td.datos_orangef9 { + padding: 5px 5px 5px 5px; } -.menu li.selected { - font-weight: bold; -} - -ul.operation li a:hover { - #font-weight: bold; -} - -.menu_icon{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - -o-transition-timing-function: ease-out; -} - -.menu_icon:hover{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - -o-transition-timing-function: ease-out; - background-color: #585858 !important; -} -.submenu_not_selected:hover{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - -o-transition-timing-function: ease-out; - background-color: #585858 !important; -} -.submenu_selected:hover{ - background-color: #585858 !important; -} -.sub_subMenu{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; -} -.sub_subMenu:hover{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - background-color: #585858 !important; -} - -.submenu_text { - color: #fff; -} - -.menu li.selected { - box-shadow: inset 4px 0 #80BA27; -} - -li.links a:hover { - #font-weight: bold; -} - -.is_submenu2 li { - background-color: #ff0000; -} - -.is_submenu2 { - background-color: #222222 !important; -} - -.operation { - background-color: #333 !important; -} - -.operation .selected { - background-color: #585858 !important; -} - -.menu li, .menu .li.not_selected { - border-radius: 0px 0px 0px 0px; - display: block; - min-height: 35px; - border-bottom: 0px none #424242; - vertical-align: middle; -} - -#menu_tab li.separator { - /* Empty */ -} - -.operation{ - border-top-right-radius: 5px; - border-right-style: solid; - border-right-width: 0px; - -} - -input#text-id_parent.ac_input, input, textarea, select { - background-color: #ffffff !important; - border: 1px solid #cbcbcb; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; +/* global */ +input#text-id_parent.ac_input, +input, +textarea, +select { + background-color: #ffffff !important; + border: 1px solid #cbcbcb; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; } +/* plugins */ span#plugin_description { - font-size: 9px; + font-size: 9px; } -/*FOR TINYMCE*/ +/* + * --------------------------------------------------------------------- + * - TINYMCE - + * --------------------------------------------------------------------- + */ #tinymce { - text-align: left; + text-align: left; + padding-top: 20px; } -.visual_font_size_4pt, .visual_font_size_4pt > em, .visual_font_size_4pt > strong, .visual_font_size_4pt > strong > span, .visual_font_size_4pt > span, .visual_font_size_4pt > strong > em, .visual_font_size_4pt > em > strong, .visual_font_size_4pt em span, .visual_font_size_4pt span em { - font-size: 4pt !important; - line-height: 4pt; +.visual_font_size_4pt, +.visual_font_size_4pt > em, +.visual_font_size_4pt > strong, +.visual_font_size_4pt > strong > span, +.visual_font_size_4pt > span, +.visual_font_size_4pt > strong > em, +.visual_font_size_4pt > em > strong, +.visual_font_size_4pt em span, +.visual_font_size_4pt span em { + font-size: 4pt !important; + line-height: 4pt; } -.visual_font_size_6pt, .visual_font_size_6pt > em, .visual_font_size_6pt > strong, .visual_font_size_6pt > strong > span, .visual_font_size_6pt > span, .visual_font_size_6pt > strong > em, .visual_font_size_6pt > em > strong, .visual_font_size_6pt em span, .visual_font_size_6pt span em { - font-size: 6pt !important; - line-height: 6pt; +.visual_font_size_6pt, +.visual_font_size_6pt > em, +.visual_font_size_6pt > strong, +.visual_font_size_6pt > strong > span, +.visual_font_size_6pt > span, +.visual_font_size_6pt > strong > em, +.visual_font_size_6pt > em > strong, +.visual_font_size_6pt em span, +.visual_font_size_6pt span em { + font-size: 6pt !important; + line-height: 6pt; } -.visual_font_size_8pt, .visual_font_size_8pt > em, .visual_font_size_8pt > strong, .visual_font_size_8pt > strong > span , .visual_font_size_8pt > span, .visual_font_size_8pt > strong > em, .visual_font_size_8pt > em > strong, .visual_font_size_8pt em span, .visual_font_size_8pt span em { - font-size: 8pt !important; - line-height: 8pt; +.visual_font_size_8pt, +.visual_font_size_8pt > em, +.visual_font_size_8pt > strong, +.visual_font_size_8pt > strong > span, +.visual_font_size_8pt > span, +.visual_font_size_8pt > strong > em, +.visual_font_size_8pt > em > strong, +.visual_font_size_8pt em span, +.visual_font_size_8pt span em { + font-size: 8pt !important; + line-height: 8pt; } -.visual_font_size_10pt, .visual_font_size_10pt > em, .visual_font_size_10pt > strong, .visual_font_size_10pt > strong > span , .visual_font_size_10pt > span, .visual_font_size_10pt > strong > em, .visual_font_size_10pt > em > strong, .visual_font_size_10pt em span, .visual_font_size_10pt span em { - font-size: 10pt !important; - line-height: 10pt; +.visual_font_size_10pt, +.visual_font_size_10pt > em, +.visual_font_size_10pt > strong, +.visual_font_size_10pt > strong > span, +.visual_font_size_10pt > span, +.visual_font_size_10pt > strong > em, +.visual_font_size_10pt > em > strong, +.visual_font_size_10pt em span, +.visual_font_size_10pt span em { + font-size: 10pt !important; + line-height: 10pt; } -.visual_font_size_12pt, .visual_font_size_12pt > em, .visual_font_size_12pt > strong, .visual_font_size_12pt > strong > span , .visual_font_size_12pt > span, .visual_font_size_12pt > strong > em, .visual_font_size_12pt > em > strong, .visual_font_size_12pt em span, .visual_font_size_12pt span em { - font-size: 12pt !important; - line-height: 12pt; +.visual_font_size_12pt, +.visual_font_size_12pt > em, +.visual_font_size_12pt > strong, +.visual_font_size_12pt > strong > span, +.visual_font_size_12pt > span, +.visual_font_size_12pt > strong > em, +.visual_font_size_12pt > em > strong, +.visual_font_size_12pt em span, +.visual_font_size_12pt span em { + font-size: 12pt !important; + line-height: 12pt; } -.visual_font_size_14pt, .visual_font_size_14pt > em , .visual_font_size_14pt > strong, .visual_font_size_14pt > strong > span, .visual_font_size_14pt > span, .visual_font_size_14pt > strong > em, .visual_font_size_14pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 14pt !important; - line-height: 14pt; +.visual_font_size_14pt, +.visual_font_size_14pt > em, +.visual_font_size_14pt > strong, +.visual_font_size_14pt > strong > span, +.visual_font_size_14pt > span, +.visual_font_size_14pt > strong > em, +.visual_font_size_14pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 14pt !important; + line-height: 14pt; } -.visual_font_size_18pt, .visual_font_size_18pt > em , .visual_font_size_18pt > strong, .visual_font_size_18pt > strong > span, .visual_font_size_18pt > span, .visual_font_size_18pt > strong > em, .visual_font_size_18pt > em > strong, .visual_font_size_18pt em span, .visual_font_size_18pt span em { - font-size: 18pt !important; - line-height: 18pt; +.visual_font_size_18pt, +.visual_font_size_18pt > em, +.visual_font_size_18pt > strong, +.visual_font_size_18pt > strong > span, +.visual_font_size_18pt > span, +.visual_font_size_18pt > strong > em, +.visual_font_size_18pt > em > strong, +.visual_font_size_18pt em span, +.visual_font_size_18pt span em { + font-size: 18pt !important; + line-height: 18pt; } -.visual_font_size_24pt, .visual_font_size_24pt > em, .visual_font_size_24pt > strong, .visual_font_size_24pt > strong > span , .visual_font_size_24pt > span, .visual_font_size_24pt > strong > em, .visual_font_size_24pt > em > strong, .visual_font_size_24pt em span, .visual_font_size_24pt span em { - font-size: 24pt !important; - line-height: 24pt; +.visual_font_size_24pt, +.visual_font_size_24pt > em, +.visual_font_size_24pt > strong, +.visual_font_size_24pt > strong > span, +.visual_font_size_24pt > span, +.visual_font_size_24pt > strong > em, +.visual_font_size_24pt > em > strong, +.visual_font_size_24pt em span, +.visual_font_size_24pt span em { + font-size: 24pt !important; + line-height: 24pt; } -.visual_font_size_28pt, .visual_font_size_28pt > em, .visual_font_size_28pt > strong, .visual_font_size_28pt > strong > span , .visual_font_size_28pt > span, .visual_font_size_28pt > strong > em, .visual_font_size_28pt > em > strong, .visual_font_size_28pt em span, .visual_font_size_28pt span em { - font-size: 28pt !important; - line-height: 28pt; +.visual_font_size_28pt, +.visual_font_size_28pt > em, +.visual_font_size_28pt > strong, +.visual_font_size_28pt > strong > span, +.visual_font_size_28pt > span, +.visual_font_size_28pt > strong > em, +.visual_font_size_28pt > em > strong, +.visual_font_size_28pt em span, +.visual_font_size_28pt span em { + font-size: 28pt !important; + line-height: 28pt; } -.visual_font_size_36pt, .visual_font_size_36pt > em, .visual_font_size_36pt > strong, .visual_font_size_36pt > strong > span, .visual_font_size_36pt > span, .visual_font_size_36pt > strong > em, .visual_font_size_36pt > em > strong, .visual_font_size_36pt em span, .visual_font_size_36pt span em { - font-size: 36pt !important; - line-height: 36pt; +.visual_font_size_36pt, +.visual_font_size_36pt > em, +.visual_font_size_36pt > strong, +.visual_font_size_36pt > strong > span, +.visual_font_size_36pt > span, +.visual_font_size_36pt > strong > em, +.visual_font_size_36pt > em > strong, +.visual_font_size_36pt em span, +.visual_font_size_36pt span em { + font-size: 36pt !important; + line-height: 36pt; } -.visual_font_size_48pt, .visual_font_size_48pt > em, .visual_font_size_48pt > strong, .visual_font_size_48pt > strong > span, .visual_font_size_48pt > span, .visual_font_size_48pt > strong > em, .visual_font_size_48pt > em > strong, .visual_font_size_48pt em span, .visual_font_size_48pt span em { - font-size: 48pt !important; - line-height: 48pt; +.visual_font_size_48pt, +.visual_font_size_48pt > em, +.visual_font_size_48pt > strong, +.visual_font_size_48pt > strong > span, +.visual_font_size_48pt > span, +.visual_font_size_48pt > strong > em, +.visual_font_size_48pt > em > strong, +.visual_font_size_48pt em span, +.visual_font_size_48pt span em { + font-size: 48pt !important; + line-height: 48pt; } -.visual_font_size_60pt, .visual_font_size_60pt > em, .visual_font_size_60pt > strong, .visual_font_size_60pt > strong > span, .visual_font_size_60pt > span, .visual_font_size_60pt > strong > em, .visual_font_size_60pt > em > strong, .visual_font_size_60pt em span, .visual_font_size_60pt span em { - font-size: 60pt !important; - line-height: 60pt; +.visual_font_size_60pt, +.visual_font_size_60pt > em, +.visual_font_size_60pt > strong, +.visual_font_size_60pt > strong > span, +.visual_font_size_60pt > span, +.visual_font_size_60pt > strong > em, +.visual_font_size_60pt > em > strong, +.visual_font_size_60pt em span, +.visual_font_size_60pt span em { + font-size: 60pt !important; + line-height: 60pt; } -.visual_font_size_72pt, .visual_font_size_72pt > em, .visual_font_size_72pt > strong, .visual_font_size_72pt > strong > span, .visual_font_size_72pt > span, .visual_font_size_72pt > strong > em, .visual_font_size_72pt > em > strong, .visual_font_size_72pt em span, .visual_font_size_72pt span em { - font-size: 72pt !important; - line-height: 72pt; +.visual_font_size_72pt, +.visual_font_size_72pt > em, +.visual_font_size_72pt > strong, +.visual_font_size_72pt > strong > span, +.visual_font_size_72pt > span, +.visual_font_size_72pt > strong > em, +.visual_font_size_72pt > em > strong, +.visual_font_size_72pt em span, +.visual_font_size_72pt span em { + font-size: 72pt !important; + line-height: 72pt; } -.visual_font_size_84pt, .visual_font_size_84pt > em, .visual_font_size_84pt > strong, .visual_font_size_84pt > strong > span, .visual_font_size_84pt > span, .visual_font_size_84pt > strong > em, .visual_font_size_84pt > em > strong, .visual_font_size_84pt em span, .visual_font_size_84pt span em { - font-size: 84pt !important; - line-height: 84pt; +.visual_font_size_84pt, +.visual_font_size_84pt > em, +.visual_font_size_84pt > strong, +.visual_font_size_84pt > strong > span, +.visual_font_size_84pt > span, +.visual_font_size_84pt > strong > em, +.visual_font_size_84pt > em > strong, +.visual_font_size_84pt em span, +.visual_font_size_84pt span em { + font-size: 84pt !important; + line-height: 84pt; } -.visual_font_size_96pt, .visual_font_size_96pt > em, .visual_font_size_96pt > strong, .visual_font_size_96pt > strong > span, .visual_font_size_96pt > span, .visual_font_size_96pt > strong > em, .visual_font_size_96pt > em > strong, .visual_font_size_96pt em span, .visual_font_size_96pt span em { - font-size: 96pt !important; - line-height: 96pt; +.visual_font_size_96pt, +.visual_font_size_96pt > em, +.visual_font_size_96pt > strong, +.visual_font_size_96pt > strong > span, +.visual_font_size_96pt > span, +.visual_font_size_96pt > strong > em, +.visual_font_size_96pt > em > strong, +.visual_font_size_96pt em span, +.visual_font_size_96pt span em { + font-size: 96pt !important; + line-height: 96pt; } -.visual_font_size_116pt, .visual_font_size_116pt > em, .visual_font_size_116pt > strong, .visual_font_size_116pt > strong > span, .visual_font_size_116pt > span, .visual_font_size_116pt > strong > em, .visual_font_size_116pt > em > strong, .visual_font_size_116pt em span, .visual_font_size_116pt span em { - font-size: 116pt !important; - line-height: 116pt; +.visual_font_size_116pt, +.visual_font_size_116pt > em, +.visual_font_size_116pt > strong, +.visual_font_size_116pt > strong > span, +.visual_font_size_116pt > span, +.visual_font_size_116pt > strong > em, +.visual_font_size_116pt > em > strong, +.visual_font_size_116pt em span, +.visual_font_size_116pt span em { + font-size: 116pt !important; + line-height: 116pt; } -.visual_font_size_128pt, .visual_font_size_128pt > em, .visual_font_size_128pt > strong, .visual_font_size_128pt > strong > span, .visual_font_size_128pt > span, .visual_font_size_128pt > strong > em, .visual_font_size_128pt > em > strong, .visual_font_size_128pt em span, .visual_font_size_128pt span em { - font-size: 128pt !important; - line-height: 128pt; +.visual_font_size_128pt, +.visual_font_size_128pt > em, +.visual_font_size_128pt > strong, +.visual_font_size_128pt > strong > span, +.visual_font_size_128pt > span, +.visual_font_size_128pt > strong > em, +.visual_font_size_128pt > em > strong, +.visual_font_size_128pt em span, +.visual_font_size_128pt span em { + font-size: 128pt !important; + line-height: 128pt; } -.visual_font_size_140pt, .visual_font_size_140pt > em, .visual_font_size_140pt > strong, .visual_font_size_140pt > strong > span, .visual_font_size_140pt > span, .visual_font_size_140pt > strong > em, .visual_font_size_140pt > em > strong, .visual_font_size_140pt em span, .visual_font_size_140pt span em { - font-size: 140pt !important; - line-height: 140pt; +.visual_font_size_140pt, +.visual_font_size_140pt > em, +.visual_font_size_140pt > strong, +.visual_font_size_140pt > strong > span, +.visual_font_size_140pt > span, +.visual_font_size_140pt > strong > em, +.visual_font_size_140pt > em > strong, +.visual_font_size_140pt em span, +.visual_font_size_140pt span em { + font-size: 140pt !important; + line-height: 140pt; } -.visual_font_size_154pt, .visual_font_size_154pt > em, .visual_font_size_154pt > strong, .visual_font_size_154pt > strong > span, .visual_font_size_154pt > span, .visual_font_size_154pt > strong > em, .visual_font_size_154pt > em > strong, .visual_font_size_154pt em span, .visual_font_size_154pt span em { - font-size: 154pt !important; - line-height: 154pt; +.visual_font_size_154pt, +.visual_font_size_154pt > em, +.visual_font_size_154pt > strong, +.visual_font_size_154pt > strong > span, +.visual_font_size_154pt > span, +.visual_font_size_154pt > strong > em, +.visual_font_size_154pt > em > strong, +.visual_font_size_154pt em span, +.visual_font_size_154pt span em { + font-size: 154pt !important; + line-height: 154pt; } -.visual_font_size_196pt, .visual_font_size_196pt > em, .visual_font_size_196pt > strong, .visual_font_size_196pt > strong > span, .visual_font_size_196pt > span, .visual_font_size_196pt > strong > em, .visual_font_size_196pt > em > strong, .visual_font_size_196pt em span, .visual_font_size_196pt span em { - font-size: 196pt !important; - line-height: 196pt; +.visual_font_size_196pt, +.visual_font_size_196pt > em, +.visual_font_size_196pt > strong, +.visual_font_size_196pt > strong > span, +.visual_font_size_196pt > span, +.visual_font_size_196pt > strong > em, +.visual_font_size_196pt > em > strong, +.visual_font_size_196pt em span, +.visual_font_size_196pt span em { + font-size: 196pt !important; + line-height: 196pt; } - - -.resize_visual_font_size_8pt, .resize_visual_font_size_8pt > em, .resize_visual_font_size_8pt > strong, .resize_visual_font_size_8pt > strong > span, .resize_visual_font_size_8pt > span, .resize_visual_font_size_8pt > strong > em, .resize_visual_font_size_8pt > em > strong, .visual_font_size_8pt em span, .visual_font_size_8pt span em { - font-size: 4pt !important; - line-height: 4pt; +.resize_visual_font_size_8pt, +.resize_visual_font_size_8pt > em, +.resize_visual_font_size_8pt > strong, +.resize_visual_font_size_8pt > strong > span, +.resize_visual_font_size_8pt > span, +.resize_visual_font_size_8pt > strong > em, +.resize_visual_font_size_8pt > em > strong, +.visual_font_size_8pt em span, +.visual_font_size_8pt span em { + font-size: 4pt !important; + line-height: 4pt; } -.resize_visual_font_size_14pt, .resize_visual_font_size_14pt > em , .resize_visual_font_size_14pt > strong, .resize_visual_font_size_14pt > strong > span, .resize_visual_font_size_14pt > span, .resize_visual_font_size_14pt > strong > em, .resize_visual_font_size_14pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 7pt !important; - line-height: 7pt; +.resize_visual_font_size_14pt, +.resize_visual_font_size_14pt > em, +.resize_visual_font_size_14pt > strong, +.resize_visual_font_size_14pt > strong > span, +.resize_visual_font_size_14pt > span, +.resize_visual_font_size_14pt > strong > em, +.resize_visual_font_size_14pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 7pt !important; + line-height: 7pt; } -.resize_visual_font_size_24pt, .resize_visual_font_size_24pt > em, .resize_visual_font_size_24pt > strong, .resize_visual_font_size_24pt > strong > span, .resize_visual_font_size_24pt > span, .resize_visual_font_size_24pt > strong > em, .resize_visual_font_size_24pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 12pt !important; - line-height: 12pt; - +.resize_visual_font_size_24pt, +.resize_visual_font_size_24pt > em, +.resize_visual_font_size_24pt > strong, +.resize_visual_font_size_24pt > strong > span, +.resize_visual_font_size_24pt > span, +.resize_visual_font_size_24pt > strong > em, +.resize_visual_font_size_24pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 12pt !important; + line-height: 12pt; } -.resize_visual_font_size_36pt, .resize_visual_font_size_36pt > em, .resize_visual_font_size_36pt > strong, .resize_visual_font_size_36pt > strong > span, .resize_visual_font_size_36pt > span, .resize_visual_font_size_36pt > strong > em, .resize_visual_font_size_36pt > em > strong, .visual_font_size_36pt em span, .visual_font_size_36pt span em { - font-size: 18pt !important; - line-height: 18pt; +.resize_visual_font_size_36pt, +.resize_visual_font_size_36pt > em, +.resize_visual_font_size_36pt > strong, +.resize_visual_font_size_36pt > strong > span, +.resize_visual_font_size_36pt > span, +.resize_visual_font_size_36pt > strong > em, +.resize_visual_font_size_36pt > em > strong, +.visual_font_size_36pt em span, +.visual_font_size_36pt span em { + font-size: 18pt !important; + line-height: 18pt; } -.resize_visual_font_size_72pt, .resize_visual_font_size_72pt > em, .resize_visual_font_size_72pt > strong, .resize_visual_font_size_72pt > strong > span, .resize_visual_font_size_72pt > span, .resize_visual_font_size_72pt > strong > em, .resize_visual_font_size_72pt > em > strong, .visual_font_size_72pt em span, .visual_font_size_72pt span em { - font-size: 36pt !important; - line-height: 36pt; +.resize_visual_font_size_72pt, +.resize_visual_font_size_72pt > em, +.resize_visual_font_size_72pt > strong, +.resize_visual_font_size_72pt > strong > span, +.resize_visual_font_size_72pt > span, +.resize_visual_font_size_72pt > strong > em, +.resize_visual_font_size_72pt > em > strong, +.visual_font_size_72pt em span, +.visual_font_size_72pt span em { + font-size: 36pt !important; + line-height: 36pt; } -/*SIDEBAR*/ +/* + * --------------------------------------------------------------------- + * - LEFT SIDEBAR IN GRAPHS POPUP - stat_win.php - + * --------------------------------------------------------------------- + */ .menu_sidebar { - color:#111; - background: #3f3f3f; + color: #111; + background: #3f3f3f; + margin: 0px; + margin-left: 10px; + padding-left: 0px; + padding-right: 0px; + padding-top: 10px; + text-align: left; + font-family: arial, sans-serif, verdana; + font-size: 10px; + border: 1px solid #000; + position: absolute; + width: 400px; + height: 260px; - margin-left: 10px; - padding-left: 0px; - padding-right: 0px; - padding-top: 10px; - text-align: left; - font-family:arial,sans-serif,verdana; - font-size:10px; - border:1px solid #000; - position:absolute; - margin:0; - width:400px; - height:260px; + -moz-box-shadow: 0px 4px 4px #010e1b !important; + -webkit-box-shadow: 0px 4px 4px #010e1b !important; + box-shadow: 0px 4px 4px #010e1b !important; - -moz-box-shadow: 0px 4px 4px #010E1B !important; - -webkit-box-shadow: 0px 4px 4px #010E1B !important; - box-shadow: 0px 4px 4px #010E1B !important; - - filter:alpha(opacity=97); - -moz-opacity: 0.97; - opacity: 0.97; + filter: alpha(opacity=97); + -moz-opacity: 0.97; + opacity: 0.97; } .menu_sidebar_radius_left { - -moz-border-top-left-radius: 8px; - -webkit-border-top-left-radius: 8px; - border-top-left-radius: 8px; + -moz-border-top-left-radius: 8px; + -webkit-border-top-left-radius: 8px; + border-top-left-radius: 8px; - -moz-border-bottom-left-radius: 8px; - -webkit-border-bottom-left-radius: 8px; - border-bottom-left-radius: 8px; + -moz-border-bottom-left-radius: 8px; + -webkit-border-bottom-left-radius: 8px; + border-bottom-left-radius: 8px; - border-right:0px solid #000; + border-right: 0px solid #000; } .menu_sidebar_radius_right { - -moz-border-top-right-radius: 8px; - -webkit-border-top-right-radius: 8px; - border-top-right-radius: 8px; - -moz-border-bottom-right-radius: 8px; - -webkit-border-bottom-right-radius: 8px; - border-bottom-right-radius: 8px; + -moz-border-top-right-radius: 8px; + -webkit-border-top-right-radius: 8px; + border-top-right-radius: 8px; + -moz-border-bottom-right-radius: 8px; + -webkit-border-bottom-right-radius: 8px; + border-bottom-right-radius: 8px; } .menu_sidebar_outer { - margin-left: 3px; - background: #ECECEC; - width: 100%; - text-align: center; - -moz-border-radius: 6px; - -webkit-border-radius: 6px; - border-radius: 6px; - padding: 8px; + margin-left: 3px; + background: #ececec; + width: 100%; + text-align: center; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: 8px; } /*Groupsview*/ - +/* .groupsview { - border-spacing: 0px 4px; + border-spacing: 0px 4px; } .groupsview tr { - background-color: #666; + background-color: #666; } .groupsview th { - font-size: 12px; - padding: 5px; + font-size: 12px; + padding: 5px; } -.groupsview td.first, .groupsview th.first { - -moz-border-top-left-radius: 10px; - -webkit-border-top-left-radius: 10px; - border-top-left-radius: 10px; +.groupsview td.first, +.groupsview th.first { + -moz-border-top-left-radius: 10px; + -webkit-border-top-left-radius: 10px; + border-top-left-radius: 10px; - -moz-border-bottom-left-radius: 10px; - -webkit-border-bottom-left-radius: 10px; - border-bottom-left-radius: 10px; + -moz-border-bottom-left-radius: 10px; + -webkit-border-bottom-left-radius: 10px; + border-bottom-left-radius: 10px; } -.groupsview td.last, .groupsview th.last { - -moz-border-top-right-radius: 10px; - -webkit-border-top-right-radius: 10px; - border-top-right-radius: 10px; - -moz-border-bottom-right-radius: 10px; - -webkit-border-bottom-right-radius: 10px; - border-bottom-right-radius: 10px; +.groupsview td.last, +.groupsview th.last { + -moz-border-top-right-radius: 10px; + -webkit-border-top-right-radius: 10px; + border-top-right-radius: 10px; + -moz-border-bottom-right-radius: 10px; + -webkit-border-bottom-right-radius: 10px; + border-bottom-right-radius: 10px; } +*/ +/* + * --------------------------------------------------------------------- + * - TIP (to show help) - + * --------------------------------------------------------------------- + */ a.tip { - display: inline !important; - cursor: help; + display: inline !important; + cursor: help; } -a.tip>img { - margin-left: 2px; - margin-right: 2px; +a.tip > img { + margin-left: 2px; + margin-right: 2px; } +/* + * --------------------------------------------------------------------- + * - SEARCH BOX in header - + * --------------------------------------------------------------------- + */ input.search_input { - background: white url('../../images/input_zoom.png') no-repeat right; - padding: 0px; - padding-left:5px; - margin: 0; - width: 80%; - height: 19px; - margin-bottom: 5px; - margin-left: 2px; - padding-right: 25px; - color: #999; + background: white url("../../images/input_zoom.png") no-repeat right; + padding: 0px; + padding-left: 5px; + margin: 0; + width: 80%; + height: 19px; + margin-bottom: 5px; + margin-left: 2px; + padding-right: 25px; + color: #999; } -.vertical_fields td input, .vertical_fields td select { +/*.vertical_fields td input, .vertical_fields td select { margin-top: 8px !important; -} +}*/ -a[id^='tgl_ctrl_']>img, a[id^='tgl_ctrl_']>b>img{ - vertical-align:middle; -} - -.noshadow { - -moz-box-shadow: 0px !important; - -webkit-box-shadow: 0px !important; - box-shadow: 0px !important; +a[id^="tgl_ctrl_"] > img, +a[id^="tgl_ctrl_"] > b > img { + vertical-align: middle; } /* Images forced title */ -DIV.forced_title_layer { - display: block; - text-decoration: none; - position: absolute; - z-index: 100000; - border: 1px solid #708090; - background-color: #666; - color: #FFF; - padding: 4px 5px; - font-weight: bold; - font-size: small; - font-size: 11px; - /* IE 8 */ - -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=9)"; - /* Netscape */ - -moz-opacity: 0.9; - opacity: 0.9; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; +div.forced_title_layer { + display: block; + text-decoration: none; + position: absolute; + z-index: 100000; + border: 1px solid #708090; + background-color: #666; + color: #fff; + padding: 4px 5px; + font-weight: bold; + font-size: small; + font-size: 11px; + /* IE 8 */ + -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=9)"; + /* Netscape */ + -moz-opacity: 0.9; + opacity: 0.9; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; } /* Graphs styles */ -div.legend>div { - pointer-events: none; /* Allow to click the graphs below */ - opacity: 0.65 !important; +div.legend > div { + pointer-events: none; /* Allow to click the graphs below */ + opacity: 0.65 !important; } /* Recover the padding of the legend elements under a databox parent */ -table.databox div.legend>td { - padding: 1px; +table.databox div.legend > td { + padding: 1px; } div.nodata_text { - padding: 5px 12px 0px 68px; - font-weight: bold; - color: #C1C1C1; - text-transform: uppercase; - display: table-cell; - vertical-align: middle; - text-align: left; + padding: 5px 12px 0px 68px; + font-weight: bold; + color: #c1c1c1; + text-transform: uppercase; + display: table-cell; + vertical-align: middle; + text-align: left; } div.nodata_container { - width:150px; - height:100px; - background-repeat:no-repeat; - background-position: center; - margin: auto auto; - display: table; + width: 150px; + height: 100px; + background-repeat: no-repeat; + background-position: center; + margin: auto auto; + display: table; } #snmp_data { - width: 40%; - position: absolute; - top:0; - right:20px; - - #background-color: #fff; - #padding: 10px; + width: 40%; + position: absolute; + top: 0; + right: 20px; } #rmf_data { - width: 40%; - height: 80%; - position: absolute; - top:0; - right:20px; - overflow: auto; - - #background-color: #fff; - #padding: 10px; -} - -/* Subtab styles */ - -ul.subsubmenu { - border-bottom-right-radius: 5px; - border-bottom-left-radius: 5px; - -moz-border-bottom-right-radius: 5px; - -moz-border-bottom-left-radius: 5px; - -webkit-border-bottom-right-radius: 5px; - -webkit-border-bottom-left-radius: 5px; - - background: #ECECEC !important; -} - -ul.subsubmenu li{ - background-color: #ECECEC; - font-weight: bold; - text-decoration: none; - font-size: 14px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; -} - -ul.subsubmenu li a{ - padding: 0px 10px 5px; -} - -div#agent_wizard_subtabs { - position: absolute; - margin-left: 0px; - display: none; - padding-bottom: 3px; - z-index: 1000; -} - -.agent_wizard_tab:hover { - cursor: default; + width: 40%; + height: 80%; + position: absolute; + top: 0; + right: 20px; + overflow: auto; } +/* service map */ #container_servicemap_legend { - position: absolute; - width: 200px; - background: #FFF; - margin-top: 10px; - right: 2px; - border: 1px solid #E2E2E2; - border-radius: 5px; - padding: 10px; - opacity: .90; + position: absolute; + width: 200px; + background: #fff; + margin-top: 10px; + right: 2px; + border: 1px solid #e2e2e2; + border-radius: 5px; + padding: 10px; + opacity: 0.9; } #container_servicemap_legend table { - text-align: left; + text-align: left; } .legend_servicemap_item { - display: none; + display: none; } +/* agent modules*/ .legend_square { - width: 20px; - padding-left: 20px; - padding-right: 10px; + width: 20px; + padding-left: 20px; + padding-right: 10px; } .legend_square_simple { - padding-left:0px; - padding-right: 10px; - padding-bottom: 3px; + padding-left: 0px; + padding-right: 10px; + padding-bottom: 3px; } -.legend_square div, .legend_square_simple div { - width: 20px; - height: 20px; - border-radius: 3px; +.legend_square div, +.legend_square_simple div { + width: 20px; + height: 20px; + border-radius: 3px; } .legend_basic { - background: #F4F4F4; - margin-top: 10px; - border-radius: 5px; - padding: 10px; + background: #f4f4f4; + margin-top: 10px; + border-radius: 5px; + padding: 10px; } .agents_modules_table th { - background: #3F3F3F; + background: #3f3f3f; + border: 1px solid #e2e2e2; } .agents_modules_table th * { - color: #FFFFFF; + color: #ffffff; } /* * LOAD_ENTERPRISE.PHP */ #code_license_dialog { - padding: 50px; - padding-top: 10px; + padding: 50px; + padding-top: 10px; } #code_license_dialog #logo { - margin-bottom: 20px; - text-align: center; + margin-bottom: 20px; + text-align: center; } -#code_license_dialog, #code_license_dialog * { - font-size: 14px; +#code_license_dialog, +#code_license_dialog * { + font-size: 14px; } #code_license_dialog ul { - padding-left: 30px; - list-style-image: url("../../images/input_tick.png"); + padding-left: 30px; + list-style-image: url("../../images/input_tick.png"); } #code_license_dialog li { - margin-bottom: 12px; + margin-bottom: 12px; } #code_license_dialog #code { - font-weight: bolder; - font-size: 20px; - border: 1px solid #dddddd; - padding: 5px; - text-align: center; - -moz-border-radius: 8px; - -webkit-border-radius: 8px; - border-radius: 8px; + font-weight: bolder; + font-size: 20px; + border: 1px solid #dddddd; + padding: 5px; + text-align: center; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + border-radius: 8px; } #code_license_dialog a { - text-decoration: underline; + text-decoration: underline; } /* GRAPHS CSS */ .parent_graph { - position: relative; - margin: 0 auto; + position: relative; + margin: 0 auto; } -.menu_graph, .timestamp_graph { - position: absolute !important; +.menu_graph, +.timestamp_graph { + position: absolute !important; } .menu_graph { - -moz-border-top-right-radius: 6px; - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - -moz-border-top-left-radius: 6px; - -webkit-border-top-left-radius: 6px; - border-top-left-radius: 6px; + -moz-border-top-right-radius: 6px; + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + -moz-border-top-left-radius: 6px; + -webkit-border-top-left-radius: 6px; + border-top-left-radius: 6px; } .legend_graph { - margin: 0px; - padding: 0px; - text-align: left; + margin: 0px; + padding: 0px; + text-align: left; } .legendColorBox * { - font-size: 0px; - padding: 0px 4px; - overflow: visible !important; + font-size: 0px; + padding: 0px 4px; + overflow: visible !important; } /* GIS CSS */ .olLayerDiv { - z-index: 102 !important; + z-index: 102 !important; } /* Alert view */ -table.alert_days th, table.alert_time th{ - height: 30px; - vertical-align: middle; +table.alert_days th, +table.alert_time th { + height: 30px; + vertical-align: middle; } table.alert_escalation th img { - width: 18px; + width: 18px; } - td.used_field { - #border: solid #6EB432; - background: #6EB432 !important; - color: #FFFFFF; - font-weight: bold; + background: #6eb432 !important; + color: #ffffff; + font-weight: bold; } td.overrided_field { - color: #666; + color: #666; } td.unused_field { - color: #888; + color: #888; } td.empty_field { - background: url('../../images/long_arrow.png') no-repeat 100% center; + background: url("../../images/long_arrow.png") no-repeat 100% center; } #table_macros textarea { - width: 96%; + width: 96%; } /* Policies styles */ table#policy_modules td * { - display: inline; + display: inline; } .context_help_title { - font-weight: bolder; - text-align: left; + font-weight: bolder; + text-align: left; } .context_help_body { - text-align: left; + text-align: left; } #left_column_logon_ok { - width: 750px; - float:left; + width: 750px; + float: left; } #news_board { - min-width: 530px; + min-width: 530px; } #right_column_logon_ok { - width: 350px; - float: right; - margin-right: 20px; + width: 350px; + float: right; + margin-right: 20px; } #clippy_head_title { - font-weight: bold; - background: #82b92e; - color: #ffffff; - margin-top: -15px; - margin-left: -15px; - margin-right: -15px; - padding: 5px; - margin-bottom: 10px; - border-top-left-radius: 2px; - border-top-right-radius: 2px; + font-weight: bold; + background: #82b92e; + color: #ffffff; + margin-top: -15px; + margin-left: -15px; + margin-right: -15px; + padding: 5px; + margin-bottom: 10px; + border-top-left-radius: 2px; + border-top-right-radius: 2px; } #dialog-double_auth-container { - width: 100%; - text-align: center; - vertical-align: middle; + width: 100%; + text-align: center; + vertical-align: middle; } -.center_align { - text-align: center; -} - -.left_align { - text-align: left; -} - -.right_align { - text-align: right; -} - -.saml_button { +/*.saml_button { float: left; position: fixed; vertical-align: middle; -} +}*/ -.status_tactical{ - width: 100%; - margin-left: auto; - margin-right: auto; - background-color: #FFF !important; - padding: 10px; - border: 1px solid #E2E2E2; - margin-top: 5%; - text-align: left; +/* + * --------------------------------------------------------------------- + * - TACTICAL VIEW y TABLAS - + * --------------------------------------------------------------------- + */ +.status_tactical { + width: 100%; + margin-left: auto; + margin-right: auto; + background-color: #fff !important; + padding: 10px; + border: 1px solid #e2e2e2; + margin-top: 5%; + text-align: left; } .status_tactical img { - border: 3px solid #000; - border-radius: 100px; + border: 3px solid #000; + border-radius: 100px; } -#sumary{ - color: #FFF; - margin: 2px; - padding: 10px 30px; - font-size: 15px; - font-weight: bold; - border-radius: 2px; +#sumary { + color: #fff; + margin: 2px; + padding: 10px 30px; + font-size: 15px; + font-weight: bold; + border-radius: 2px; } -div.sumary_div{ - color: #FFF; - font-size: 20px; - font-weight: bold; - border-radius: 2px; - width: 120px; - height: 40px; - text-align: center; - display: table-cell; - vertical-align: middle; +div.sumary_div { + color: #fff; + font-size: 20px; + font-weight: bold; + border-radius: 2px; + width: 120px; + height: 40px; + text-align: center; + display: table-cell; + vertical-align: middle; } -div.div_groups_status{ - width: 350px; - background-color: white; - border: 1px solid #ECECEC; - border-radius: 5px; - margin: 20px; - float:left; +div.div_groups_status { + width: 350px; + background-color: white; + border: 1px solid #ececec; + border-radius: 5px; + margin: 20px; + float: left; } -.databox.data>tbody>tr>td{ - border-bottom: 1px solid #E2E2E2; +.databox.data > tbody > tr > td { + border-bottom: 1px solid #e2e2e2; } -.databox .search{ - margin-top: 0px; +.databox .search { + margin-top: 0px; } -.databox.data>tbody>tr>td.progress_bar img{ - border: 3px solid #000; - border-radius: 100px; +.databox.data > tbody > tr > td.progress_bar img { + border: 3px solid #000; + border-radius: 100px; } -.databox>tbody>tr>td{ - padding-left: 9px; - padding-right: 9px; - padding-top: 7px; - padding-bottom: 7px; -} -.databox.pies fieldset.tactical_set{ - width:70% !important; - height: 285px; +.databox.pies fieldset.tactical_set { + width: 70% !important; + height: 285px; } -.difference{ - border-left-width: 2px; - border-left-style: solid; - border-right-width: 2px; - border-right-style: solid; - border-color: #E2E2E2; +.difference { + border-left-width: 2px; + border-left-style: solid; + border-right-width: 2px; + border-right-style: solid; + border-color: #e2e2e2; } #title_menu { - color: #FFF; - float: right; - width: 70%; - letter-spacing: 0pt; - font-size: 8pt; - white-space: pre-wrap; + color: #fff; + float: right; + width: 70%; + letter-spacing: 0pt; + font-size: 8pt; + white-space: pre-wrap; } -.no_hidden_menu{ - background-position: 11% 50% !important; +.no_hidden_menu { + background-position: 11% 50% !important; } -#menu_tab li.nomn, #menu_tab li.nomn_high { - background-color: #ECECEC; - padding-right: 3px; - padding-left: 3px; - font-weight: bold; - text-decoration: none; - font-size: 14px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; - margin-top: -10px; +#menu_tab li.nomn, +#menu_tab li.nomn_high { + background-color: #ececec; + padding-right: 3px; + padding-left: 3px; + font-weight: bold; + text-decoration: none; + font-size: 14px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; + margin-top: -10px; } -#menu_tab li.nomn_high, #menu_tab li.nomn_high span { - color: #FFF; - background-color: #FFF; +#menu_tab li.nomn_high, +#menu_tab li.nomn_high span { + color: #fff; + background-color: #fff; } -#menu_tab li.nomn img, #menu_tab li img { - margin-top: 3px; - margin-left: 3px; +#menu_tab li.nomn img, +#menu_tab li img { + margin-top: 3px; + margin-left: 3px; } -#menu_tab li.tab_operation a, #menu_tab a.tab_operation{ - background: none !important ; +#menu_tab li.tab_operation a, +#menu_tab a.tab_operation { + background: none !important ; } -.subsubmenu{ - position: absolute; - float: right; - z-index: 9999; - display: none; - margin-top: 5px !important ; - left: 0px !important; +.agents_modules_table { + border: 1px solid #e2e2e2; + border-spacing: 0px; } -.subsubmenu li{ - margin-top: 0px !important ; +.agents_modules_table td { + border: 1px solid #e2e2e2; } -.agents_modules_table{ - border: 1px solid #E2E2E2; - border-spacing: 0px; -} -.agents_modules_table td{ - border: 1px solid #E2E2E2; -} -.agents_modules_table th{ - border: 1px solid #E2E2E2; +.databox.filters, +.databox.data, +.databox.profile_list { + margin-bottom: 20px; } -.databox.filters, .databox.data, .databox.profile_list{ - margin-bottom: 20px; +.databox.filters > tbody > tr > td { + padding: 10px; + padding-left: 20px; +} +.databox.profile_list > tbody > tr > td { + padding: 4px 1px; + padding-left: 5px; + border-bottom: 1px solid #e2e2e2; +} +.databox.profile_list > tbody > tr > a.tip > img { + margin: 0px; } -.databox.filters>tbody>tr>td{ - padding: 10px; - padding-left:20px; +.databox.filters > tbody > tr > td > img, +.databox.filters > tbody > tr > td > div > a > img, +.databox.filters > tbody > tr > td > span > img, +.databox.filters > tbody > tr > td > span > a > img, +.databox.filters > tbody > tr > td > a > img { + vertical-align: middle; + margin-left: 5px; } -.databox.profile_list>tbody>tr>td{ - padding: 4px 1px; - padding-left: 5px; - border-bottom: 1px solid #E2E2E2; -} -.databox.profile_list>tbody>tr>a.tip > img{ - margin: 0px; +.databox.data > tbody > tr > td > img, +.databox.data > thead > tr > th > img, +.databox.data > tbody > tr > td > div > a > img, +.databox.data > tbody > tr > td > span > img, +.databox.data > tbody > tr > td > span > a > img, +.databox.data > tbody > tr > td > a > img, +.databox.data > tbody > tr > td > form > a > img { + vertical-align: middle; } -.databox.filters>tbody>tr>td>img, .databox.filters>tbody>tr>td>div>a>img, -.databox.filters>tbody>tr>td>span>img, .databox.filters>tbody>tr>td>span>a>img, -.databox.filters>tbody>tr>td>a>img{ - vertical-align: middle; - margin-left: 5px; -} -.databox.data>tbody>tr>td>img,.databox.data>thead>tr>th>img, .databox.data>tbody>tr>td>div>a>img, -.databox.data>tbody>tr>td>span>img, .databox.data>tbody>tr>td>span>a>img, -.databox.data>tbody>tr>td>a>img, .databox.data>tbody>tr>td>form>a>img { - vertical-align: middle; - +.databox.filters > tbody > tr > td > a > img { + vertical-align: middle; } -.databox.filters>tbody>tr>td>a>img { - vertical-align: middle; +.databox.data > tbody > tr > td > input[type="checkbox"] { + margin: 0px; } -.databox.data>tbody>tr>td>input[type="checkbox"] { - margin: 0px; +.databox_color > tbody > tr > td { + padding-left: 10px; } -.databox_color>tbody>tr>td{ - padding-left: 10px; +.databox.agente > tbody > tr > td > div > canvas { + width: 100% !important; + text-align: left !important; +} +.databox.agente > tbody > tr > td > div.graph { + width: 100% !important; + text-align: left !important; } -.databox.agente>tbody>tr>td>div>canvas{ - width: 100% !important; - text-align: left !important; -} -.databox.agente>tbody>tr>td>div.graph{ - width: 100% !important; - text-align: left !important; +.green_title { + background-color: #82b92e; + font-weight: normal; + text-align: center; } -.godmode, .menu_icon ul li{ - background-color: #222; -} -.operation .menu_icon ul li{ - background-color: #333; +.dashboard { + top: 23px; } -.godmode{ - border-top: 4px solid #777 !important; - padding-bottom: 4px !important; - border-bottom-right-radius: 5px; - border-right-style: solid; - border-right-width: 0px; +.dashboard li a { + width: 158px !important; } -.green_title{ - background-color: #82B92E; - font-weight:normal; - text-align: center; -} - -.dashboard{ - top: 23px; -} - -.dashboard li a{ - width: 158px !important; -} - -.text_subDashboard{ - float: left; - margin-top: 5%; - margin-left: 3%; +.text_subDashboard { + float: left; + margin-top: 5%; + margin-left: 3%; } .title_um { - font-family: "open sans"; - font-size: 20px; - color: #82B92E; - text-align: center; + font-family: sans-serif; + font-size: 20px; + color: #82b92e; + text-align: center; } .text_um { - font-family: "open sans"; - font-size: 16px; - padding-left: 80px; + font-family: sans-serif; + font-size: 16px; + padding-left: 80px; } /* The items with the class 'spinner' will rotate */ /* Not supported on IE9 and below */ .spinner { - -webkit-animation: spinner 2s infinite linear; - animation: spinner 2s infinite linear; + -webkit-animation: spinner 2s infinite linear; + animation: spinner 2s infinite linear; } @-webkit-keyframes spinner { - 0% { - -ms-transform: rotate(0deg); /* IE */ - -moz-transform: rotate(0deg); /* FF */ - -o-transform: rotate(0deg); /* Opera */ - -webkit-transform: rotate(0deg); /* Safari and Chrome */ - transform: rotate(0deg); - } - 100% { - -ms-transform: rotate(359deg); /* IE */ - -moz-transform: rotate(359deg); /* FF */ - -o-transform: rotate(359deg); /* Opera */ - -webkit-transform: rotate(359deg); /* Safari and Chrome */ - transform: rotate(359deg); - } + 0% { + -ms-transform: rotate(0deg); /* IE */ + -moz-transform: rotate(0deg); /* FF */ + -o-transform: rotate(0deg); /* Opera */ + -webkit-transform: rotate(0deg); /* Safari and Chrome */ + transform: rotate(0deg); + } + 100% { + -ms-transform: rotate(359deg); /* IE */ + -moz-transform: rotate(359deg); /* FF */ + -o-transform: rotate(359deg); /* Opera */ + -webkit-transform: rotate(359deg); /* Safari and Chrome */ + transform: rotate(359deg); + } } @keyframes spinner { - 0% { - -ms-transform: rotate(0deg); /* IE */ - -moz-transform: rotate(0deg); /* FF */ - -o-transform: rotate(0deg); /* Opera */ - -webkit-transform: rotate(0deg); /* Safari and Chrome */ - transform: rotate(0deg); - } - 100% { - -ms-transform: rotate(359deg); /* IE */ - -moz-transform: rotate(359deg); /* FF */ - -o-transform: rotate(359deg); /* Opera */ - -webkit-transform: rotate(359deg); /* Safari and Chrome */ - transform: rotate(359deg); - } + 0% { + -ms-transform: rotate(0deg); /* IE */ + -moz-transform: rotate(0deg); /* FF */ + -o-transform: rotate(0deg); /* Opera */ + -webkit-transform: rotate(0deg); /* Safari and Chrome */ + transform: rotate(0deg); + } + 100% { + -ms-transform: rotate(359deg); /* IE */ + -moz-transform: rotate(359deg); /* FF */ + -o-transform: rotate(359deg); /* Opera */ + -webkit-transform: rotate(359deg); /* Safari and Chrome */ + transform: rotate(359deg); + } } /* * --------------------------------------------------------------------- - * - Styles for the new networkmap - + * - Styles for the new networkmap - * --------------------------------------------------------------------- */ - .zoom_controller { - width: 30px; - height: 210px; - background: blue; - border-radius: 15px; +.zoom_controller { + width: 30px; + height: 210px; + background: blue; + border-radius: 15px; - top: 50px; - left: 10px; - position: absolute; -} - - - -.vertical_range { - padding: 0; - -webkit-transform: rotate(270deg); - -moz-transform: rotate(270deg); - transform: rotate(270deg); - width: 200px; - height: 20px; - position: relative; - background: transparent !important; - border: 0px !important; + top: 50px; + left: 10px; + position: absolute; } .vertical_range { - left: -92px; - top: 93px; + padding: 0; + -webkit-transform: rotate(270deg); + -moz-transform: rotate(270deg); + transform: rotate(270deg); + width: 200px; + height: 20px; + position: relative; + background: transparent !important; + border: 0px !important; + + left: -92px; + top: 93px; } -@media screen and (-webkit-min-device-pixel-ratio:0) -{ - /* Only for chrome */ +@media screen and (-webkit-min-device-pixel-ratio: 0) { + /* Only for chrome */ - .vertical_range { - left: -87px; - top: 93px; - } + .vertical_range { + left: -87px; + top: 93px; + } } -.home_zoom { +/*.home_zoom { top: 310px; left: 10px; @@ -3367,1687 +3374,1191 @@ div.div_groups_status{ } .zoom_in { - top: 10px; - left: 10px; + top: 10px; + left: 10px; - display: table-cell; - position: absolute; - font-weight: bolder; - font-size: 20px; - background: blue; - color: white; - border-radius: 15px; - width: 30px; - height: 30px; - cursor:pointer; - text-align: center; - vertical-align: middle; + display: table-cell; + position: absolute; + font-weight: bolder; + font-size: 20px; + background: blue; + color: white; + border-radius: 15px; + width: 30px; + height: 30px; + cursor: pointer; + text-align: center; + vertical-align: middle; } .zoom_out { - top: 270px; - left: 10px; + top: 270px; + left: 10px; - display: table-cell; - position: absolute; - font-weight: bolder; - font-size: 20px; - background: blue; - color: white; - border-radius: 15px; - width: 30px; - height: 30px; - cursor:pointer; - text-align: center; - vertical-align: middle; + display: table-cell; + position: absolute; + font-weight: bolder; + font-size: 20px; + background: blue; + color: white; + border-radius: 15px; + width: 30px; + height: 30px; + cursor: pointer; + text-align: center; + vertical-align: middle; } .title_bar { - border-bottom: 1px solid black; + border-bottom: 1px solid black; } .title_bar .title { - font-weight: bolder; + font-weight: bolder; } .title_bar .open_click { - float: right; - display: table-cell; - font-weight: bolder; - font-size: 20px; - background: blue none repeat scroll 0% 0%; - color: white; - width: 17px; - height: 17px; - cursor: pointer; - text-align: center; - vertical-align: middle; - margin: 1px; + float: right; + display: table-cell; + font-weight: bolder; + font-size: 20px; + background: blue none repeat scroll 0% 0%; + color: white; + width: 17px; + height: 17px; + cursor: pointer; + text-align: center; + vertical-align: middle; + margin: 1px; } .title_bar .close_click { - float: right; - display: table-cell; - font-weight: bolder; - font-size: 20px; - background: blue none repeat scroll 0% 0%; - color: white; - width: 17px; - height: 17px; - cursor: pointer; - text-align: center; - vertical-align: middle; - margin: 1px; + float: right; + display: table-cell; + font-weight: bolder; + font-size: 20px; + background: blue none repeat scroll 0% 0%; + color: white; + width: 17px; + height: 17px; + cursor: pointer; + text-align: center; + vertical-align: middle; + margin: 1px; } +*/ -/* Visual map */ +/* + * --------------------------------------------------------------------- + * - VISUAL MAPS - + * --------------------------------------------------------------------- + */ div#vc-controls { - position: fixed; - top: 30px; - right: 20px; + position: fixed; + top: 30px; + right: 20px; } -div#vc-controls div.vc-title, div#vc-controls div.vc-refr { - margin-top: 6px; - margin-left: 3px; - margin-right: 3px; +div#vc-controls div.vc-title, +div#vc-controls div.vc-refr { + margin-top: 6px; + margin-left: 3px; + margin-right: 3px; } -div#vc-controls div.vc-refr>div { - display: inline; +div#vc-controls div.vc-refr > div { + display: inline; } div#vc-controls img.vc-qr { - margin-top: 6px; - margin-left: 8px; - margin-right: 8px; + margin-top: 6px; + margin-left: 8px; + margin-right: 8px; } -div.simple_value > span.text > p, -div.simple_value > span.text > p > span > strong, -div.simple_value > span.text > p > strong, -div.simple_value > a > span.text p -{ - font-family: monospace !important; - white-space: pre; +div.simple_value > span.text > p, +div.simple_value > span.text > p > span > strong, +div.simple_value > span.text > p > strong, +div.simple_value > a > span.text p { + font-family: monospace !important; + white-space: pre; } -/* Visual map */ +/* + * --------------------------------------------------------------------- + * - EVENTS - + * --------------------------------------------------------------------- + */ +/* Image open dialog in group events by agents*/ +#open_agent_groups { + cursor: pointer; +} + +/* + * --------------------------------------------------------------------- + * - modal window and edit user - + * --------------------------------------------------------------------- + */ +#alert_messages { + -moz-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; + z-index: 3; + position: fixed; + width: 750px; + max-width: 750px; + top: 20%; + background: white; + opacity: 0; + transition: opacity 0.5s; + -webkit-transition: opacity 0.5s; +} +.modalheader { + text-align: center; + width: 100%; + height: 37px; + left: 0px; + background-color: #82b92e; +} +.modalheadertext { + color: white; + position: relative; + font-family: Nunito; + font-size: 13pt; + top: 8px; +} +.modalheaderh1 { + text-align: center; + width: 100%; + height: 26px; + left: 0px; + padding-top: 10px; + background-color: #82b92e; + color: white; + position: relative; + font-family: Nunito; + font-size: 11pt; +} +.modalclosex { + cursor: pointer; + display: inline; + float: right; + margin-right: 10px; + margin-top: 10px; +} +.modalclosex:hover { + cursor: pointer; + display: inline; + float: right; + margin-right: 10px; + margin-top: 10px; +} +.modalcontent { + color: black; + background: white; +} +.modalcontentimg { + float: left; + margin-left: 30px; + margin-top: 30px; + margin-bottom: 30px; +} +.modalcontenttext { + float: left; + text-align: justify; + color: black; + font-size: 9.5pt; + line-height: 13pt; + margin-top: 30px; + width: 430px; + margin-left: 30px; +} +.modalokbutton { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + cursor: pointer; + text-align: center; + margin-right: 45px; + float: right; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + margin-bottom: 30px; + border-radius: 3px; + width: 90px; + height: 30px; + background-color: white; + border: 1px solid #82b92e; +} +.modalokbuttontext { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + color: #82b92e; + font-family: Nunito; + font-size: 10pt; + position: relative; + top: 6px; +} + +.modalokbutton:hover { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + background-color: #82b92e; +} + +.modalokbutton:hover .modalokbuttontext { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + color: white; +} + +.modaldeletebutton { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + cursor: pointer; + text-align: center; + margin-left: 45px; + float: left; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + margin-bottom: 30px; + border-radius: 3px; + width: 90px; + height: 30px; + background-color: white; + border: 1px solid #fa5858; +} + +.modaldeletebuttontext { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + color: #fa5858; + font-family: Nunito; + font-size: 10pt; + position: relative; + top: 6px; +} + +.modaldeletebutton:hover .modaldeletebuttontext { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + color: white; +} + +.modaldeletebutton:hover { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + background-color: #fa5858; +} + +.modalgobutton { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + cursor: pointer; + text-align: center; + margin-right: 15px; + margin-bottom: 30px; + float: right; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; + width: 240px; + height: 30px; + background-color: white; + border: 1px solid #82b92e; +} +.modalgobuttontext { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + color: #82b92e; + font-family: Nunito; + font-size: 10pt; + position: relative; + top: 6px; +} + +.modalgobutton:hover { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + background-color: #82b92e; +} + +.modalgobutton:hover .modalgobuttontext { + transition-property: background-color, color; + transition-duration: 1s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color, color; + -webkit-transition-duration: 1s; + -o-transition-property: background-color, color; + -o-transition-duration: 1s; + color: white; +} + +/* update manager online */ +#opacidad { + opacity: 0; + transition: opacity 3s; + -webkit-transition: opacity 3s; + z-index: 1; + width: 100%; + height: 100%; + position: absolute; + left: 0px; + top: 0px; +} + +.textodialogo { + margin-left: 0px; + color: #333; + padding: 20px; + font-size: 9pt; +} + +.cargatextodialogo { + max-width: 58.5%; + width: 58.5%; + min-width: 58.5%; + float: left; + margin-left: 0px; + font-size: 18pt; + padding: 20px; + text-align: center; +} + +.cargatextodialogo p, +.cargatextodialogo b, +.cargatextodialogo a { + font-size: 18pt; +} + +/* global */ +.readonly { + background-color: #dedede !important; +} + +.input_error { + border: 1px solid red; +} + +#toolbox > input { + border-width: 0px 1px 0px 0px; + border-color: lightgray; +} + +#toolbox > input.service_min { + border-width: 0px 0px 0px 0px; +} + +#toolbox > input.grid_min { + border-width: 0px 0px 0px 0px; +} + +#filter_event_status, +#filter_event_severity, +#filter_event_type { + width: 50%; +} + +.rowPair:hover, +.rowOdd:hover { + background-color: #eee; +} +.databox.data > tbody > tr:hover { + background-color: #eee; +} +.checkselected { + background-color: #eee; +} +.tag-wrapper { + padding: 0 10px 0 0; + overflow: auto; +} + +.pandora-tag { + float: left; + margin-bottom: 18px; + padding: 1px 6px 1px 0; +} + +.pandora-tag-title { + color: white; + background-color: #373737; + font-weight: bold; + padding: 6px 6px 6px 10px; + border: #373737; + border-width: 1px; + border-top-style: solid; + border-top-left-radius: 12px; + border-left-style: solid; + border-bottom-left-radius: 12px; + border-bottom-style: solid; +} + +.pandora-tag-value { + color: #373737; + font-weight: bold; + padding: 6px 10px 6px 6px; + border: #373737; + border-width: 1px; + border-top-style: solid; + border-top-right-radius: 12px; + border-right-style: solid; + border-bottom-right-radius: 12px; + border-bottom-style: solid; +} + +/* + * --------------------------------------------------------------------- + * - HELP MODAL WINDOWS - pandora_help.php - + * --------------------------------------------------------------------- + */ + +div#main_help_new { + text-align: center; + padding: 20px; + border-bottom: 1px solid #c2c2c2; +} + +div#main_help_new_content { + padding-left: 30px; + padding-right: 30px; + padding-bottom: 20px; + padding-top: 10px; + background: white; + height: 100%; + font-size: 12pt; + font-family: "lato-bolder", serif; +} + +div#main_help_new_content h1 { + font-family: "lato-boldest", serif; + font-size: 14pt; +} + +div#main_help_new_content p { + font-family: "lato-bolder", serif; + font-size: 12pt; +} +div#main_help_new_content b { + font-family: "lato-bolder", serif; + font-size: 12pt; +} + +div#main_help_new_content li { + font-family: "lato-bolder", serif; + font-size: 12pt; +} + +div#footer_help { + background: #333; + text-align: center; + padding: 10px; +} + +/* EVENTS - /ajax/events.php */ +/*view-agents lastest events for this agent*/ +#div_all_events_24h { + padding: 4px; +} + +/* + * --------------------------------------------------------------------- + * - REPORTS - graph_container.php - + * --------------------------------------------------------------------- + */ +.graph_conteiner_inside > .parent_graph { + width: 100% !important; +} + +.graph_conteiner_inside > .parent_graph > .menu_graph { + left: 90% !important; +} + +.graph_conteiner_inside > .parent_graph > .graph { + width: 90% !important; +} + +.graph_conteiner_inside > div > .nodata_container > .nodata_text { + display: none; +} + +.graph_conteiner_inside > div > .nodata_container { + background-size: 120px 80px !important; +} + +/* + * --------------------------------------------------------------------- + * - WUX VIEW - + * --------------------------------------------------------------------- + */ +#mssg_error_div { + color: red; + font-size: 12px; +} + +.wux_global_result_container { + width: 100%; + margin-top: 30px; + margin-bottom: 30px; +} + +.wux_global_result_title { + width: 100%; + text-align: center; + color: white; + background-color: #373737; + border: 1px solid #373737; + height: 28px; +} + +.wux_global_result_title p { + margin: 8px; +} + +.wux_global_result_content { + width: 100%; + border: 1px solid #e2e2e2; + height: 120px; +} + +.wux_global_result_content_left { + float: left; + width: 40%; + text-align: center; +} + +.wux_global_result_content_left ul { + display: inline-flex; + margin-top: 15px; +} + +.wux_global_result_content_left ul li p { + margin-top: 35px; + margin-right: 10px; + margin-left: 10px; +} + +.wux_global_result_content_left ul li p b { + font-size: 16px; +} + +.wux_global_result_content_right { + float: right; + width: 60%; +} + +.wux_global_result_content_right ul { + display: inline-flex; + margin-top: 15px; + margin-left: 100px; +} + +.wux_global_result_content_right ul li p { + margin-top: 36px; + margin-right: 10px; + margin-left: 10px; +} + +.wux_global_result_content_right ul li p b { + font-size: 16px; +} + +.wux_transaction_container { + width: 100%; + margin-bottom: 30px; +} + +.wux_result_transaction { + width: 33%; + float: left; +} + +.wux_transaction_graphs { + width: 33%; + float: left; +} + +.wux_transaction_graphs_pie { + width: 33%; + float: left; +} + +.pagination_show_more { + text-align: center; + margin-top: 10px; +} + +.dashed { + stroke-dasharray: 10; +} +.path { + stroke-dasharray: 500; + stroke-dashoffset: 500; + animation: dash 15s linear; +} + +@keyframes dash { + from { + stroke-dashoffset: 500; + } + to { + stroke-dashoffset: 0; + } +} + +.route { + fill: none; + transition: all 2s ease-in-out; +} + +.limit_scroll { + max-width: 800px; + overflow-x: scroll; +} +#is_favourite ul.container { + display: flex; + flex-flow: row wrap; + flex-direction: row; + align-content: center; + justify-content: center; +} + +#is_favourite ul.container a { + text-decoration: none; +} + +#is_favourite ul.container a:hover li { + background: #e2e2e2; +} + +#is_favourite ul.container a li { + min-width: 250px; + height: 80px; + margin: 10px; + display: flex; + flex-direction: row; + align-items: center; + background: #f9faf9; +} + +#is_favourite ul.container a li div.icon_img { + width: 30%; + text-align: center; +} + +#is_favourite ul.container a li div.text { + min-width: 50%; + font-family: sans-serif; + font-size: 18px; + color: #3f3f3f; + text-align: center; +} + +form ul.form_flex { + display: flex; + flex-flow: row wrap; + flex-direction: row; + align-content: center; + justify-content: space-around; + border: 1px solid #e2e2e2; + border-radius: 5px; + padding: 20px; + background: #f9faf9; +} + +form ul.form_flex li { + flex: auto; + display: flex; + justify-content: center; + align-items: center; +} + +form ul.form_flex li.first_elements { + min-width: 550px; +} + +form ul.form_flex li.second_elements { + min-width: 300px; +} + +form ul.form_flex li ul { + display: flex; + flex-direction: row; + justify-content: space-around; + flex-basis: 100%; +} + +form ul.form_flex li ul li { + height: 50px; + width: 100%; +} + +#modal_module_popup_close:hover { + cursor: pointer; +} + +.modal_module_list:hover { + cursor: pointer; +} + +/* snmp */ +#snmp_data { + background: #f9faf9; +} +#snmp_data .databox { + border: 0px; +} + +/* library for graphs */ +.yAxis.y1Axis > .tickLabel { + white-space: nowrap; + line-height: 1.05em !important; + width: auto !important; +} + +/* dialog */ +.pandora_confirm_dialog .ui-dialog-buttonset { + display: flex; + width: 100%; + margin-left: 10px; + float: none !important; +} + +.pandora_confirm_dialog .ui-dialog-buttonset button { + flex: 50%; +} + +#pandora_confirm_dialog_text h3 { + margin-left: 20px; + margin-right: 20px; + text-align: center; +} + +.pandora_upper { + text-transform: uppercase; +} + +.dialog-grayed { + background: #373737 !important; +} + +.dialog-grayed .ui-dialog-buttonpane { + background: #373737 !important; +} + +/* GIS MAP */ +a.down_arrow { + content: url("../../images/down.png"); + max-width: 21px; + max-height: 21px; +} + +a.up_arrow { + content: url("../../images/down.png"); + transform: rotate(180deg); + max-width: 21px; + max-height: 21px; +} + +tr:last-child > td > a.down_arrow, +tr:first-child > td > a.up_arrow { + visibility: hidden; +} + +/* system group status */ +.group_modules_status_box > tbody > tr > td { + border-bottom: 1px solid #e2e2e2; + border-collapse: collapse; + border-spacing: 0; + width: 10%; + height: 20px; +} + +.group_modules_status_div { + color: #fff; + width: 100%; + height: 100%; + text-align: left; + display: block; + vertical-align: middle; + line-height: 20px; +} + +/* extensions -> module groups */ +.tooltip_counters h3 { + font-size: 12pt; + padding-bottom: 10px !important; + text-align: center; +} + +.tooltip_counters li { + font-size: 8pt; + margin: 2px; + margin-left: 5px; +} +.tooltip_counters li div { + width: 12px; + height: 12px; + border-radius: 3px; + float: left; + margin-right: 5px; +} + +/* + * --------------------------------------------------------------------- + * - MESSAGE LIST POPUP - + * --------------------------------------------------------------------- + */ +div#dialog_messages table th { + text-align: left; +} + +div#dialog_messages table th:last-child { + text-align: right; +} + +/* --- JQUERY-UI --- */ +.ui-button-text-only .ui-button-text { + font-family: "nunito", sans-serif; + font-size: 9pt; + color: #82b92e; +} +.ui-datepicker .ui-datepicker-title *, +.ui-datepicker th * { + color: white; +} +.ui-datepicker .ui-datepicker-title select, +.ui-datepicker .ui-datepicker-title option { + color: #111 !important; +} +.ui-dialog .ui-dialog-titlebar { + display: inherit; + text-align: center; + padding: 0.4em 1em; + height: 30px; + position: relative; + background-color: #82b92e !important; +} +.ui-dialog .ui-dialog-title { + font-family: "Nunito", sans-serif; + margin: 0.1em 0 !important; + white-space: nowrap !important; + width: 100% !important; + overflow: hidden !important; + text-overflow: ellipsis !important; + font-size: 11pt; + position: relative; + top: 5px; + float: none !important; +} +.ui-dialog .ui-dialog-titlebar-close { + position: absolute !important; + right: 1em !important; + width: 21px !important; + margin: 0px 0 0 0 !important; + padding: 1px !important; + height: 20px !important; + bottom: 30% !important; + top: 20% !important; +} +.ui-dialog .ui-dialog-content { + position: relative !important; + border: 0; + padding: 0.5em 1em !important; + background: none !important; + overflow: auto !important; + margin-bottom: 1em; +} +.ui-dialog .ui-dialog-buttonpane { + text-align: left; + border-width: 1px 0 0 0; + background-image: none; + margin-top: 0.5em; + padding: 0.3em 1em 0.5em 0.4em; +} +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { + float: right; +} +.ui-dialog .ui-dialog-buttonpane button { + margin: 0.5em 1em 0.5em 0 !important; + cursor: pointer !important; + background: white !important; + background-color: white !important; + border: 1px solid #82b92e !important; + min-height: 35px !important; + width: 90px !important; +} +.ui-widget-content { + background: #ffffff url(include/styles/images/ui-bg_flat_75_ffffff_40x100.png) + 50% 50% repeat-x; +} +.ui-state-default, +.ui-widget-content .ui-state-default, +.ui-widget-header .ui-state-default { + margin-top: 3px; + border: 1px solid #d3d3d3 !important; + border-bottom: 0 !important; + background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% + repeat-x !important; + font-weight: normal !important; + color: #555555 !important; +} +.ui-corner-all, +.ui-corner-top, +.ui-corner-left, +.ui-corner-tl { + border-top-left-radius: 0 !important; +} +.ui-corner-all, +.ui-corner-top, +.ui-corner-right, +.ui-corner-tr { + border-top-right-radius: 0 !important; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-left, +.ui-corner-bl { + border-bottom-left-radius: 0 !important; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-right, +.ui-corner-br { + border-bottom-right-radius: 0 !important; +} +#ui-datepicker-div { + border-color: #b1b1b1; + background: #ffffff; +} +.ui-widget-header { + background: #b1b1b1 !important; + color: #ffffff !important; +} +.ui-datepicker-calendar th { + background-color: #3f3f3f; +} +.ui-dialog .ui-widget-header { + background-color: #82b92e; +} +.ui_tpicker_hour, +.ui_tpicker_minute, +.ui_tpicker_second, +.ui-slider-handle { + border: 1px solid #aaaaaa !important; +} +.ui-timepicker-div dd { + margin: 0px 15px 0px 15px; +} +.ui-timepicker-div .ui-datepicker-title { + color: white; +} +.ui-datepicker-buttonpane button { + border-color: #b1b1b1 !important; +} +.ui-datepicker-buttonpane .ui-datepicker-current { + margin-left: 0.2em !important; +} +.ui-dialog .ui-widget-content { + border: 0px !important; +} +.ui-dialog { + box-shadow: 5px 5px 19px #4e4e4e; + border: 0px !important; + padding: 0 !important; +} +.ui-dialog-titlebar { + border: 0px !important; +} +.ui-dialog-titlebar .ui-icon-closethick, +.ui-dialog-titlebar .ui-state-default, +.ui-dialog-titlebar .ui-state-hover, +.ui-dialog-titlebar button { + background: transparent; + border: 0px; +} + +.ui-dialog-title { + color: #ffffff; + font-size: 9pt; +} +.ui-widget input, +.ui-widget select, +.ui-widget textarea, +.ui-widget button { + font-family: Verdana, Arial, sans-serif !important; +} + +a.ui-button:active, +.ui-button:active, +.ui-button.ui-state-active:hover, +.ui-state-focus .ui-widget-content, +.ui-state-focus .ui-widget-header, +.ui-state-focus .ui-button:hover, +.ui-button:focus { + background: transparent !important; + border: none !important; +} + +.ui-state-hover, +.ui-widget-content .ui-state-hover, +.ui-widget-header .ui-state-hover { + border: 1px solid #999999 !important; + border-bottom: 0 !important; + background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% + repeat-x !important; +} + +.ui-state-active, +.ui-widget-content .ui-state-active, +.ui-widget-header .ui-state-active { + border: 1px solid #aaaaaa !important; + border-bottom: 0 !important; + background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% + repeat-x !important; + font-weight: normal !important; + color: #212121 !important; +} +.ui-state-active a, +.ui-state-active a:link, +.ui-state-active a:visited { + color: #212121 !important; +} + +ul.ui-front { + z-index: 1000000 !important; + padding-right: 0px !important; +} + +ul.ui-front li { + padding: 3px !important; +} + +ul.ui-front li:hover { + background-color: #e1e3e1 !important; +} + +ul.ui-front li a.ui-menu-item-wrapper { + background: transparent !important; + border: none !important; +} + +ul.ui-front li a.ui-menu-item-wrapper span { + padding-left: 5px !important; +} + +ul.ui-front li a.ui-menu-item-wrapper:hover { + text-decoration: none !important; +} +/* --- END - JQUERY-UI --- */ + +.toogle_switch { + position: relative; + display: inline-block; + width: 47px; + height: 24px; +} + +.toogle_switch input { + opacity: 0; + width: 0; + height: 0; +} + +.slider { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: #ccc; + -webkit-transition: 0.7s; + transition: 0.7s; + border-radius: 34px; +} + +.slider:before { + position: absolute; + content: ""; + height: 16px; + width: 16px; + left: 4px; + bottom: 4px; + background-color: white; + -webkit-transition: 0.7s; + transition: 0.7s; + border-radius: 50%; +} + +input:checked + .slider { + background-color: #82b92e; +} + +input:focus + .slider { + box-shadow: 0 0 1px #82b92e; +} + +input:checked + .slider:before { + -webkit-transform: translateX(26px); + -ms-transform: translateX(26px); + transform: translateX(26px); + background-color: rgb(197, 235, 192); +} /* jQuery dialog */ .no-close .ui-dialog-titlebar-close { display: none; } /* jQuery dialog */ - -/* Image open dialog in group events by agents*/ -#open_agent_groups { - cursor: pointer; -} - -/*Font ttf */ -@font-face -{ - font-family: 'DejaVuSerif-BoldFont'; - src: url('../fonts/DejaVuSerif-Bold.ttf') format('truetype'); -} - -.DejaVuSerif-Bold{ - font-family: DejaVuSerif-BoldFont; -} - -@font-face -{ - font-family: 'DejaVuSerif-BoldItalicFont'; - src: url('../fonts/DejaVuSerif-BoldItalic.ttf') format('truetype'); -} - -.DejaVuSerif-BoldItalic{ - font-family: DejaVuSerif-BoldItalicFont; -} - -@font-face -{ - font-family: 'DejaVuSerif-ItalicFont'; - src: url('../fonts/DejaVuSerif-Italic.ttf') format('truetype'); -} - -.DejaVuSerif-Italic{ - font-family: DejaVuSerif-ItalicFont; -} - -@font-face -{ - font-family: 'DejaVuSerifFont'; - src: url('../fonts/DejaVuSerif.ttf') format('truetype'); -} - -.DejaVuSerif{ - font-family: DejaVuSerifFont; -} - -@font-face -{ - font-family: 'DejaVuSerifCondensed-BoldFont'; - src: url('../fonts/DejaVuSerifCondensed-Bold.ttf') format('truetype'); -} - -.DejaVuSerifCondensed-Bold{ - font-family: DejaVuSerifCondensed-BoldFont; -} - -@font-face -{ - font-family: 'DejaVuSerifCondensed-BoldItalicFont'; - src: url('../fonts/DejaVuSerifCondensed-BoldItalic.ttf') format('truetype'); -} - -.DejaVuSerifCondensed-BoldItalic{ - font-family: DejaVuSerifCondensed-BoldItalicFont; -} - -@font-face -{ - font-family: 'DejaVuSerifCondensed-ItalicFont'; - src: url('../fonts/DejaVuSerifCondensed-Italic.ttf') format('truetype'); -} - -.DejaVuSerifCondensed-Italic{ - font-family: DejaVuSerifCondensed-ItalicFont; -} - -@font-face -{ - font-family: 'DejaVuSerifCondensedFont'; - src: url('../fonts/DejaVuSerifCondensed.ttf') format('truetype'); -} - -.DejaVuSerifCondensed{ - font-family: DejaVuSerifCondensedFont; -} - -@font-face -{ - font-family: 'FreeSansFont'; - src: url('../fonts/FreeSans.ttf') format('truetype'); -} - -.FreeSans{ - font-family: FreeSansFont; -} - -@font-face -{ - font-family: 'FreeSansBoldFont'; - src: url('../fonts/FreeSansBold.ttf') format('truetype'); -} - -.FreeSansBold{ - font-family: FreeSansBoldFont; -} - -@font-face -{ - font-family: 'smallfontFont'; - src: url('../fonts/smallfont.ttf') format('truetype'); -} - -.smallfont{ - font-family: smallfontFont; -} - -@font-face -{ - font-family: 'unicodeFont'; - src: url('../fonts/unicode.ttf') format('truetype'); -} - -@font-face -{ - font-family: 'roboto'; - src: url('../../fonts/roboto.woff2') format('woff2'); -} - -@font-face -{ - font-family: 'opensans'; - src: url('../../fonts/opensans.woff2') format('woff2'); -} - -@font-face -{ - font-family: 'lato'; - src: url('../../fonts/lato.woff2') format('woff2'); -} - -@font-face -{ - font-family: 'leaguegothic'; - src: url('../../fonts/leaguegothic.woff') format('woff'); -} - -.unicode{ - font-family: unicodeFont; -} - -#alert_messages{ - -moz-border-bottom-right-radius: 5px; - -webkit-border-bottom-left-radius: 5px; - border-bottom-right-radius: 5px; - border-bottom-left-radius: 5px; - z-index:3; - position:fixed; - width:750px; - max-width:750px; - top: 20%; - background:white; - opacity: 0; - transition: opacity 0.5s; - -webkit-transition: opacity 0.5s; -} -.modalheader{ - text-align:center; - width:100%; - height:37px; - left:0px; - background-color:#82b92e; -} -.modalheadertext{ - color:white; - position:relative; - font-family:Nunito; - font-size:13pt; - top:8px; -} -.modalheaderh1{ - text-align:center; - width:100%; - height:26px; - left:0px; - padding-top:10px; - background-color:#82b92e; - color:white; - position:relative; - font-family:Nunito; - font-size:11pt; -} -.modalclosex{ - cursor:pointer; - display:inline; - float:right; - margin-right:10px; - margin-top:10px; -} -.modalclosex:hover{ - cursor:pointer; - display:inline; - float:right; - margin-right:10px; - margin-top:10px; -} -.modalcontent{ - color:black; - background:white; -} -.modalcontentimg{ - float:left; - margin-left:30px; - margin-top:30px; - margin-bottom:30px; -} -.modalcontenttext{ - float:left; - text-align:justify; - color:black; - font-size: 9.5pt; - line-height:13pt; - margin-top:30px; - width:430px; - margin-left:30px; -} -.modalokbutton{ - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - cursor:pointer; - text-align:center; - margin-right:45px; - float:right; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - margin-bottom:30px; - border-radius: 3px;width:90px;height:30px;background-color:white;border: 1px solid #82b92e; -} -.modalokbuttontext{ - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - color:#82b92e;font-family:Nunito;font-size:10pt;position:relative;top:6px; -} - -.modalokbutton:hover { - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - background-color:#82b92e; -} - -.modalokbutton:hover .modalokbuttontext { - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - color:white; -} - -.modaldeletebutton{ - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - cursor:pointer; - text-align:center; - margin-left:45px; - float:left; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - margin-bottom:30px; - border-radius: 3px;width:90px;height:30px;background-color:white;border: 1px solid #FA5858; -} - -.modaldeletebuttontext{ - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - color:#FA5858;font-family:Nunito;font-size:10pt;position:relative;top:6px; -} - -.modaldeletebutton:hover .modaldeletebuttontext { - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - color:white; -} - -.modaldeletebutton:hover { - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - background-color:#FA5858; -} - -.modalgobutton{ - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - cursor:pointer;text-align:center;margin-right:15px;margin-bottom:30px;float:right;-moz-border-radius: 3px; - -webkit-border-radius: 3px;border-radius: 3px;width:240px;height:30px;background-color:white;border: 1px solid #82b92e; -} -.modalgobuttontext{ - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; -color:#82b92e;font-family:Nunito;font-size:10pt;position:relative;top:6px; -} - -.modalgobutton:hover { - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - background-color:#82b92e; -} - -.modalgobutton:hover .modalgobuttontext { - transition-property: background-color, color; - transition-duration: 1s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color, color; - -webkit-transition-duration: 1s; - -o-transition-property: background-color, color; - -o-transition-duration: 1s; - color:white; -} - - -#opacidad{ - opacity:0; - transition: opacity 3s; - -webkit-transition: opacity 3s; - z-index:1; - width:100%; - height:100%; - position:absolute; - left:0px; - top:0px; -} - -.textodialogo{ - margin-left: 0px; - color:#333; - padding:20px; - font-size:9pt; -} - -.cargatextodialogo{ - max-width:58.5%; - width:58.5%; - min-width:58.5%; - float:left; - margin-left: 0px; - font-size:18pt; - padding:20px; - text-align:center; -} - -.cargatextodialogo p, .cargatextodialogo b, .cargatextodialogo a{ - font-size:18pt; -} - -.readonly{ - background-color: #dedede !important; -} - -.input_error { - border: 1px solid red; -} - -#toolbox > input{ - border-width:0px 1px 0px 0px; - border-color: lightgray; -} - -#toolbox > input.service_min{ - border-width:0px 0px 0px 0px; -} - -#toolbox > input.grid_min{ - border-width:0px 0px 0px 0px; -} - -#tinymce{ - padding-top:20px; -} - -#filter_event_status, -#filter_event_severity, -#filter_event_type { - width:50%; -} - -.rowPair:hover, .rowOdd:hover{ - background-color: #eee; -} -.databox.data > tbody > tr:hover{ - background-color: #eee; -} -.checkselected{ - background-color: #eee; -} -.tag-wrapper{ - padding: 0 10px 0 0; - overflow: auto; -} - -.pandora-tag{ - float:left; - margin-bottom:18px; - padding:1px 6px 1px 0; -} - -.pandora-tag-title{ - color: white; - background-color: #373737; - font-weight: bold; - padding: 6px 6px 6px 10px; - border: #373737; - border-width: 1px; - border-top-style: solid; - border-top-left-radius: 12px; - border-left-style: solid; - border-bottom-left-radius: 12px; - border-bottom-style: solid; -} - -.pandora-tag-value{ - color: #373737; - font-weight: bold; - padding: 6px 10px 6px 6px; - border: #373737; - border-width: 1px; - border-top-style: solid; - border-top-right-radius: 12px; - border-right-style: solid; - border-bottom-right-radius: 12px; - border-bottom-style: solid; -} - -/* - styles header login -*/ -div#header_login{ - width: 100%; - height: 65px; - background-color: rgba(255, 255, 255, 0.06); -} - -div#icon_custom_pandora{ - float: left; - margin-top: 5px; - margin-left: 4%; -} - -div#list_icon_docs_support{ - float: right; - margin-top: 8px; - margin-right: 4%; -} - -div#list_icon_docs_support ul{ - margin-top: 5px; -} - -div#list_icon_docs_support ul li{ - display: inline-block; - color:white; - vertical-align: middle; - margin-right: 5px; - font-size: 10pt; -} - -li#li_margin_left{ - margin-left: 30px; -} - -/* - styles login form -*/ - -div.container_login{ - margin-top: 10%; - margin-left: 5%; - margin-right: 5%; - -} - -div.login_page { - width: 35%; - min-height: 600px; - float:left; -} - -div.login_page form { - border-right:1px solid #868686; - padding-top: 30px; - padding-bottom: 50px; - min-width: 400px; - max-height: 600px; -} - -div.login_logo_icon { - margin-bottom: 40px; - text-align: center; -} - -div.login_logo_icon img{ - margin: 0 auto; - width: 150px; -} - - -div.login_double_auth_code, -div.login_nick, -div.login_pass { - margin: 0 auto; - width: 70%; - height: 40px; - background-color: rgba(255, 255, 255, 0.20) !important; - margin-bottom: 25px; - min-width: 260px; -} - -div.login_nick img, -div.login_pass img{ - vertical-align: middle; - margin: 3px; -} - - -div.login_nick input, -div.login_pass input{ - background-color: rgba(255, 255, 255, 0.00) !important; - border:0px !important; - color:white !important; - border-radius: 0px; - width: 89%; - height: 40px; - font-size: 9pt; - padding: 0px !important; -} - - -div.login_nick input:focus, -div.login_pass input:focus{ - outline: none; -} - -div.login_nick input:-webkit-autofill, -div.login_nick input:-webkit-autofill:hover, -div.login_nick input:-webkit-autofill:focus, -div.login_nick input:-webkit-autofill:active, -div.login_pass input:-webkit-autofill, -div.login_pass input:-webkit-autofill:hover, -div.login_pass input:-webkit-autofill:focus, -div.login_pass input:-webkit-autofill:active { - transition: background-color 10000s ease-in-out 0s; - -webkit-box-shadow: 0 0 0px 0px transparent inset !important; - -webkit-text-fill-color: white !important; - border:0px; - width: 89%; -} - -div.login_nick input::-webkit-input-placeholder, -div.login_pass input::-webkit-input-placeholder { - color:white; -} - -div.login_pass img, -div.login_nick img{ - width: 30px; -} - -div.login_pass div, -div.login_nick div{ - float: left; - width: 11%; -} - -div.login_button{ - margin: 0 auto; - width: 70%; - height: 40px; - background-color: rgb(25, 25, 25); - border: 1px solid white; - min-width: 260px; -} - -div.login_button input { - width: 100%; - background-color: rgb(25, 25, 25) !important; - text-align: center; - border:0px; - border-radius: 0px; - height: 40px; - padding: 0px; - font-size: 9pt; - color: white; -} - -div.login_data { - width: 65%; - min-height: 600px; - float:left; -} - -div.text_banner_login{ - width: 100%; - margin-bottom: 60px; - color: white; - text-align: center; -} - -div.text_banner_login span{ - width: 100%; -} - -span.span1{ - font-size: 3vw; - font-family: 'lato-thin'; - color: white; -} - -span.span2{ - font-size: 3vw; - font-family: 'lato-bolder'; - color: white; -} - -div.img_banner_login{ - width: 100%; - text-align: center; -} - -div.img_banner_login img{ - max-width: 70%; - min-width: 70%; - max-height: 50%; - min-height: 50%; -} - -@media all and (max-width: 1200px) { - span.span1{ - font-size: 30pt; - } - span.span2{ - font-size: 30pt; - } -} - - -/*modal windows login*/ -div.content_alert{ - width: 98%; - margin-top: 20px; -} - -div.icon_message_alert{ - float: left; - width: 25%; - text-align: center; - -} - -div.icon_message_alert img{ - width: 85px; -} - -div.content_message_alert{ - - width: 75%; - float: right; -} - -div.text_message_alert{ - width: 100%; - margin-top: 10px; -} - -div.text_message_alert h1{ - margin: 0px; -} - -div.text_message_alert p{ - margin: 0px; - font-size: 10.3pt; - line-height: 14pt; -} - -div.button_message_alert{ - width: 100%; -} - -div.button_message_alert input{ - float: right; - width: 87px; - height: 33px; - color: #82b92e; - border: 1px solid #82b92e; - font-weight: bold; - margin-right: 20px; - margin-top: 20px; - font-size: 10pt; -} - -div.form_message_alert{ - width: 90%; - clear: both; - padding-top: 20px; - padding-left: 40px; -} - -div.form_message_alert ul li{ - display: inline-block; - padding: 10px; -} - -div.form_message_alert ul li input{ - border: none; - background-color: #dadada !important; - border-radius: 0px; - height: 17px; - width: 145px; - padding-left: 5px; -} - -div.form_message_alert ul li label{ - font-size: 10pt; - padding-right: 20px; -} - -div.form_message_alert h4{ - margin: 0px; - margin-bottom: 10px; -} - -div.button_message_alert_form input{ - float: right; - width: 87px; - height: 33px; - color: #82b92e; - border: 1px solid #82b92e; - font-weight: bold; - font-size: 10pt; - margin-right: 25px; -} - -.ui-dialog .ui-dialog-titlebar { - background-color: #82b92e !important; -} - -/* - styles help pandora -*/ - -div#main_help_new { - text-align: center; - padding: 20px; - border-bottom: 1px solid #c2c2c2; -} - -div#main_help_new_content { - padding-left: 30px; - padding-right: 30px; - padding-bottom: 20px; - padding-top: 10px; - background: white; - height: 100%; - font-size: 12pt; - font-family: 'lato-bolder'; -} - -div#main_help_new_content h1 { - font-family: 'lato-boldest'; - font-size: 14pt; -} - -div#main_help_new_content p { - font-family: 'lato-bolder'; - font-size: 12pt; -} -div#main_help_new_content b { - font-family: 'lato-bolder'; - font-size: 12pt; -} - -div#main_help_new_content li { - font-family: 'lato-bolder'; - font-size: 12pt; -} - -div#footer_help{ - background: #333; - text-align: center; - padding: 10px; -} - -/*center ui dialog center*/ -.ui-dialog-titlebar .ui-icon-closethick { - margin-top: -5px !important; -} - -/*view-agents lastest events for this agent*/ -#div_all_events_24h{ - padding: 4px; -} - -/*styles graph conteiner*/ -.graph_conteiner_inside > .parent_graph{ - width: 100% !important; -} - -.graph_conteiner_inside > .parent_graph > .menu_graph{ - left: 90% !important; -} - -.graph_conteiner_inside > .parent_graph > .graph{ - width: 90% !important; -} - -.graph_conteiner_inside > div > .nodata_container > .nodata_text { - display: none; -} - -.graph_conteiner_inside > div > .nodata_container{ - background-size: 120px 80px !important; -} - -#mssg_error_div{ - color: red; - font-size: 12px; -} - -/* -* View WUX -*/ - -.wux_global_result_container{ - width: 100%; - margin-top: 30px; - margin-bottom: 30px; -} - -.wux_global_result_title{ - width: 100%; - text-align: center; - color:white; - background-color: #373737; - border: 1px solid #373737; - height: 28px; -} - -.wux_global_result_title p { - margin: 8px; -} - -.wux_global_result_content{ - width: 100%; - border: 1px solid #e2e2e2; - height: 120px; -} - -.wux_global_result_content_left{ - float:left; - width: 40%; - text-align: center; -} - -.wux_global_result_content_left ul{ - display: inline-flex; - margin-top: 15px; -} - - -.wux_global_result_content_left ul li p{ - margin-top: 35px; - margin-right: 10px; - margin-left: 10px; -} - -.wux_global_result_content_left ul li p b{ - font-size: 16px; -} - -.wux_global_result_content_right{ - float:right; - width: 60%; -} - -.wux_global_result_content_right ul{ - display: inline-flex; - margin-top: 15px; - margin-left:100px; -} - -.wux_global_result_content_right ul li p{ - margin-top: 36px; - margin-right: 10px; - margin-left: 10px; -} - -.wux_global_result_content_right ul li p b{ - font-size: 16px; -} - -.wux_transaction_container{ - width: 100%; - margin-bottom: 30px; -} - -.wux_result_transaction{ - width: 33%; - float: left; -} - -.wux_transaction_graphs{ - width: 33%; - float: left; -} - -.wux_transaction_graphs_pie{ - width: 33%; - float: left; -} - -.pagination_show_more{ - text-align: center; - margin-top: 10px; -} - -.dashed{ - stroke-dasharray: 10; - -} -.path { - stroke-dasharray: 500; - stroke-dashoffset: 500; - animation: dash 15s linear; -} - -@keyframes dash { - from { - stroke-dashoffset: 500; - } - to { - stroke-dashoffset: 0; - } -} - -.route { - fill: none; - transition: all 2s ease-in-out; -} - -.limit_scroll{ - max-width: 800px; - overflow-x:scroll; -} -#is_favourite ul.container{ - display: flex; - flex-direction: row; - flex-flow: row wrap; - align-content: center; - justify-content: center; -} - -#is_favourite ul.container a { - text-decoration: none; -} - -#is_favourite ul.container a:hover li { - background: #E2E2E2; -} - -#is_favourite ul.container a li{ - min-width: 250px; - height: 80px; - margin: 10px; - display: flex; - flex-direction: row; - align-items: center; - background: #f9faf9; -} - -#is_favourite ul.container a li div.icon_img{ - width: 30%; - text-align: center; -} - -#is_favourite ul.container a li div.text{ - min-width: 50%; - font-family: Verdana; - font-size: 18px; - color: #3F3F3F; - text-align: center; -} - -form ul.form_flex{ - display: flex; - flex-direction: row; - flex-flow: row wrap; - align-content: center; - justify-content: space-around; - border: 1px solid #e2e2e2; - border-radius: 5px; - padding: 20px; - background: #f9faf9; -} - -form ul.form_flex li{ - flex: auto; - display: flex; - justify-content: center; - align-items: center; -} - -form ul.form_flex li.first_elements{ - min-width: 550px; -} - -form ul.form_flex li.second_elements{ - min-width: 300px; -} - -form ul.form_flex li ul{ - display: flex; - flex-direction: row; - justify-content: space-around; -} - -form ul.form_flex li ul{ - flex-basis: 100%; -} - -form ul.form_flex li ul li{ - height: 50px; - width: 100%; -} - -#modal_module_popup_close:hover{ - cursor: pointer; -} - -.modal_module_list:hover{ - cursor: pointer; - -} - -#main_cluster { - max-width:1770px; - margin:0 auto; -} - -.sub_cluster_1 { - width:400px; - float: left; - margin-left: 30px; - margin-bottom: 25px; - vertical-align: top; - border:1px solid #e7e9ea; - height:150px; - -} - -.sub_cluster_2 { - width:833px; - float: left; - margin-left: 30px; - margin-bottom: 25px; - vertical-align: top; - border:1px solid #e7e9ea; - height:150px; -} - -.sub_cluster_header { - width:100%; - height: 30px; - background-color: #373737; - color:white; - text-align:center; - font-size: 9pt; - display: flex; - justify-content: center; - align-content: center; - flex-direction: column; -} - -.sub_cluster_body { - width:100%; - height: 120px; - background-color: #f9faf9; - display: flex; - justify-content: center; - align-content: center; - flex-direction: column; -} - -.sub_cluster_body_3 { - width:100%; - height: 120px; - background-color: #f9faf9; - overflow-y: scroll; -} - -#cluster_map { - border:1px solid lightgray; - width:900px; - height:500px; - float: left; - margin-bottom: 30px; -} - -#cluster_status_content { - width: 90%; - height:30px; - margin:0px auto; -} - -#cluster_status_bar { - width: 85%; - height:100%; - float:left; -} - -.status_animation { - width: 1%; - height:100%; - left:0%; - background-color: red; - position:relative; -} - -#cluster_status_button { - float:left; - width:10%; - margin-left:5%;; -} - -#last_contact_content{ - width: 90%; - height:60px; - margin:0px auto; -} - - - -#last_contact_clock { - width: 15%; - height:100%; - float:left; -} - -#last_contact_date { - float:left; - height:60px; - width:80%; - margin-left:5%; - text-align:center; - display: flex; - justify-content: center; - align-content: center; - flex-direction: column; -} - -#last_contact_date_text { - font-size:14pt; -} - - -.balanced_module_item { - float:left; - margin-top: 11.5px; - margin-left: 5%; - height: 25px; - width:90%; -} - -.module_icon { - float:left; - width:10%; -} - -.modal_module_list { - float:left; - width: 90%; - height:100%; - display: flex; - justify-content: center; - align-content: center; - flex-direction: column; -} - -#snmp_data { - background: #f9faf9; -} -#snmp_data .databox { - border: 0px; -} - -.yAxis.y1Axis > .tickLabel { - white-space: nowrap; - line-height: 1.05em!important; - width: auto!important; -} - -.pandora_confirm_dialog .ui-dialog-buttonset { - display: flex; - width: 100%; - margin-left: 10px; - float: none !important; -} - -.pandora_confirm_dialog .ui-dialog-buttonset button{ - flex: 50%; -} - -#pandora_confirm_dialog_text h3{ - margin-left: 20px; - margin-right: 20px; - text-align: center; -} - -.pandora_upper { - text-transform: uppercase; -} - -.dialog-grayed { - background: #373737 !important; -} - -.dialog-grayed .ui-dialog-buttonpane { - background: #373737 !important; -} - -a.down_arrow { - content: url("../../images/down.png"); - max-width: 21px; - max-height: 21px; -} - -a.up_arrow { - content: url("../../images/down.png"); - transform: rotate(180deg); - max-width: 21px; - max-height: 21px; -} - -tr:last-child > td > a.down_arrow, tr:first-child > td > a.up_arrow { - visibility: hidden; -} - -.group_modules_status_box>tbody>tr>td{ - border-bottom: 1px solid #E2E2E2; - border-collapse: collapse; - border-spacing:0; - width: 10%; - height: 20px; -} - -.group_modules_status_div{ - color: #FFF; - width: 100%; - height: 100%; - text-align: left; - display: block; - vertical-align: middle; - line-height: 20px; -} - -.tooltip_counters h3{ - font-size: 12pt; - padding-bottom: 10px !important; - text-align: center; -} - -.tooltip_counters li{ - font-size: 8pt; - margin: 2px; - margin-left: 5px; - -} -.tooltip_counters li div{ - width: 12px; - height: 12px; - border-radius: 3px; - float: left; - margin-right: 5px; -} - -/* Message list popup */ -div#dialog_messages table th { - text-align: left; -} - -div#dialog_messages table th:last-child { - text-align: right; -} - -/* --- JQUERY-UI --- */ -.ui-button-text-only .ui-button-text { - font-family: nunito; - font-size: 9pt; - color: #82B92E -} -.ui-datepicker .ui-datepicker-title *, .ui-datepicker th * { - color: white; -} -.ui-datepicker .ui-datepicker-title select, .ui-datepicker .ui-datepicker-title option { - color: #111 !important; -} -.ui-dialog .ui-dialog-titlebar { - display: inherit; - text-align: center; - padding: .4em 1em; - height: 30px; - position: relative; -} -.ui-dialog .ui-dialog-title { - font-family: Nunito, sans-serif; - margin: .1em 0 !important; - white-space: nowrap !important; - width: 100% !important; - overflow: hidden !important; - text-overflow: ellipsis !important; - font-size: 11pt; - position: relative; - top: 5px; - float: none !important; -} -.ui-dialog .ui-dialog-titlebar-close { - position: absolute !important; - right: 1em !important; - width: 21px !important; - margin: 0px 0 0 0 !important; - padding: 1px !important; - height: 20px !important; - bottom: 30% !important; - top: 20% !important; -} -.ui-dialog .ui-dialog-content { - position: relative !important; - border: 0; - padding: .5em 1em !important; - background: none !important; - overflow: auto !important; - margin-bottom: 1em; -} -.ui-dialog .ui-dialog-buttonpane { - text-align: left; - border-width: 1px 0 0 0; - background-image: none; - margin-top: .5em; - padding: .3em 1em .5em .4em; -} -.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { - float: right; -} -.ui-dialog .ui-dialog-buttonpane button { - margin: .5em 1em .5em 0 !important; - cursor: pointer !important; - background: white !important; - background-color: white !important; - border: 1px solid #82b92e !important; - height:30px !important; - width:90px !important; -} -.ui-widget-content { - background: #ffffff url(include/styles/images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; -} -.ui-state-default, -.ui-widget-content .ui-state-default, -.ui-widget-header .ui-state-default { - margin-top: 3px; - border: 1px solid #d3d3d3 !important; - border-bottom:0 !important; - background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x !important; - font-weight: normal !important; - color: #555555 !important; -} -.ui-corner-all, -.ui-corner-top, -.ui-corner-left, -.ui-corner-tl { - border-top-left-radius: 0 !important; -} -.ui-corner-all, -.ui-corner-top, -.ui-corner-right, -.ui-corner-tr { - border-top-right-radius: 0 !important; -} -.ui-corner-all, -.ui-corner-bottom, -.ui-corner-left, -.ui-corner-bl { - border-bottom-left-radius: 0 !important; -} -.ui-corner-all, -.ui-corner-bottom, -.ui-corner-right, -.ui-corner-br { - border-bottom-right-radius: 0 !important; -} -#ui-datepicker-div { - border-color: #B1B1B1; - background: #ffffff; -} -.ui-widget-header { - background: #B1B1B1 !important; - color: #ffffff !important; -} -.ui-datepicker-calendar th { - background-color: #3F3F3F; -} -.ui-dialog .ui-widget-header { - background-color: #82b92e; -} -.ui_tpicker_hour, -.ui_tpicker_minute, -.ui_tpicker_second, -.ui-slider-handle { - border: 1px solid #AAAAAA !important; -} -.ui-timepicker-div dd { - margin: 0px 15px 0px 15px ; -} -.ui-timepicker-div .ui-datepicker-title { - color: white; -} -.ui-datepicker-buttonpane button { - border-color: #B1B1B1 !important; -} -.ui-datepicker-buttonpane .ui-datepicker-current { - margin-left: 0.2em !important; -} -.ui-dialog .ui-widget-content { - border: 0px !important; -} -.ui-dialog { - box-shadow: 5px 5px 19px #4e4e4e; - border: 0px !important; - padding: 0 !important; -} -.ui-dialog-titlebar { - border: 0px !important; -} -.ui-dialog-titlebar .ui-icon-closethick, -.ui-dialog-titlebar .ui-state-default, -.ui-dialog-titlebar .ui-state-hover, -.ui-dialog-titlebar button { - background: transparent; - border: 0px; -} -.ui-dialog-titlebar .ui-icon-closethick { - background-image: url("../../images/icono_cerrar.png") !important; -} -.ui-dialog-title { - color: #ffffff; - font-size: 9pt; -} -.ui-widget input, -.ui-widget select, -.ui-widget textarea, -.ui-widget button{ - font-family: Verdana,Arial,sans-serif !important; -} - -a.ui-button:active, .ui-button:active, -.ui-button.ui-state-active:hover, -.ui-state-focus .ui-widget-content, -.ui-state-focus .ui-widget-header, -.ui-state-focus .ui-button:hover, .ui-button:focus{ - background: transparent !important; - border: none !important; -} - -.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover{ - border: 1px solid #999999 !important; - border-bottom: 0 !important; - background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x !important; -} - -.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active{ - border: 1px solid #aaaaaa !important; - border-bottom: 0 !important; - background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x !important; - font-weight: normal !important; - color: #212121 !important; -} -.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited{ - color: #212121 !important; -} - -ul.ui-front{ - z-index: 1000000 !important; - padding-right: 0px !important; -} - -ul.ui-front li{ - padding: 3px !important; -} - -ul.ui-front li:hover{ - background-color: #e1e3e1 !important; -} - -ul.ui-front li a.ui-menu-item-wrapper{ - background: transparent !important; - border: none !important; -} - -ul.ui-front li a.ui-menu-item-wrapper span{ - padding-left: 5px !important; -} - -ul.ui-front li a.ui-menu-item-wrapper:hover{ - text-decoration: none !important; -} - -input[type=submit].ui-button-dialog{ - margin: .5em 1em .5em 0 !important; - cursor: pointer !important; - background: white !important; - background-color: white !important; - color: #82b92e !important; - text-align: center !important; - border: 1px solid #82b92e !important; - height:30px !important; - width:90px !important; -} -/* --- END - JQUERY-UI --- */ diff --git a/pandora_console/include/styles/pandora_black.css b/pandora_console/include/styles/pandora_black.css index b7e4cec6ca..169f078cea 100644 --- a/pandora_console/include/styles/pandora_black.css +++ b/pandora_console/include/styles/pandora_black.css @@ -25,335 +25,343 @@ Description: The default Pandora FMS theme layout @import url(tree.css); * { - font-family: verdana, sans-serif; - letter-spacing: 0.03pt; - font-size: 8pt; - color: #fff; + font-family: verdana, sans-serif; + letter-spacing: 0.03pt; + font-size: 8pt; + color: #fff; } svg * { - font-size: 11pt; - } + font-size: 11pt; +} body { - background-color: #5b5b5b; - margin: 0 auto; + background-color: #5b5b5b; + margin: 0 auto; } div#page { - background: #5b5b5b; - background-image: none; + background: #5b5b5b; + background-image: none; } body.pure { - background-color: #5b5b5b; + background-color: #5b5b5b; } -input, textarea { - border: 1px solid #ddd; +input, +textarea { + border: 1px solid #ddd; } textarea { - padding: 5px; - min-height: 100px; - width: 99%; + padding: 5px; + min-height: 100px; + width: 99%; } textarea.conf_editor { - padding: 5px; - width: 650px; - height: 350px; + padding: 5px; + width: 650px; + height: 350px; } textarea.conf_error { - background-image: url(../../images/err.png); - background-repeat: no-repeat; - background-position: top right; + background-image: url(../../images/err.png); + background-repeat: no-repeat; + background-position: top right; } input { - padding: 2px 3px 4px 3px; - vertical-align: middle; + padding: 2px 3px 4px 3px; + vertical-align: middle; } -input[type='checkbox'] { - display: inline !important; +input[type="checkbox"] { + display: inline !important; } select { - padding: 2px 3px 3px 3px; - vertical-align: middle; + padding: 2px 3px 3px 3px; + vertical-align: middle; } input.button { - font-family: Arial,Sans-serif; - border: 4px solid #ccc; - background: #5b5b5b; - padding: 2px 3px; - margin: 10px 15px; + font-family: Arial, Sans-serif; + border: 4px solid #ccc; + background: #5b5b5b; + padding: 2px 3px; + margin: 10px 15px; } -input[type=submit], input[type=button] { - cursor: pointer; +input[type="submit"], +input[type="button"] { + cursor: pointer; } select { - border: 1px solid #ddd; + border: 1px solid #ddd; } checkbox { - padding: 4px; - border: 1px solid #eee; + padding: 4px; + border: 1px solid #eee; } -h1, h2, h3, h4 { - font-weight: bold; - font-size: 1em; - font-family: Arial, Sans-serif; - text-transform: uppercase; - color: #fff; - padding-bottom: 4px; - padding-top: 7px; +h1, +h2, +h3, +h4 { + font-weight: bold; + font-size: 1em; + font-family: Arial, Sans-serif; + text-transform: uppercase; + color: #fff; + padding-bottom: 4px; + padding-top: 7px; } h1 { - font-size: 16px; + font-size: 16px; } h2 { - font-size: 15px; + font-size: 15px; } h3 { - font-size: 14px; + font-size: 14px; } h4 { - margin-bottom: 10px; - font-size: 13px; - color: #fff; - text-transform: none; + margin-bottom: 10px; + font-size: 13px; + color: #fff; + text-transform: none; } a { - color: #fff; - text-decoration: none; + color: #fff; + text-decoration: none; } a:hover { - color: #fff; - text-decoration: underline; + color: #fff; + text-decoration: underline; } a.white_bold { - color: #eee; - text-decoration: none; - font-weight: bold; + color: #eee; + text-decoration: none; + font-weight: bold; } a.white { - color: #eee; - text-decoration: none; + color: #eee; + text-decoration: none; } p.center { - text-align: center; + text-align: center; } h1#log_title { - font-size: 18px; - margin-bottom: 0px; - color: #FFF !important; - width:300px; + font-size: 18px; + margin-bottom: 0px; + color: #fff !important; + width: 300px; } div#log_msg { - display: none; + display: none; } div#error_buttons { - margin-top: 20px; + margin-top: 20px; } -div#error_buttons a{ - margin: 14px; +div#error_buttons a { + margin: 14px; } #noaccess { - position: relative; - margin-top:25px; - left: 15px; - padding-top: 5px; - background-color: #5b5b5b; - border-top-left-radius: 2px; - border-top-right-radius: 2px; - border-bottom-left-radius: 2px; - border-bottom-right-radius: 2px; + position: relative; + margin-top: 25px; + left: 15px; + padding-top: 5px; + background-color: #5b5b5b; + border-top-left-radius: 2px; + border-top-right-radius: 2px; + border-bottom-left-radius: 2px; + border-bottom-right-radius: 2px; } #noaccess-title { - color: #FFF; - font-weight: bold; - padding-top: 5px; - margin-left: 5px; - background: none repeat scroll 0% 0% #82b92e; - border-top-left-radius: 2px; - border-top-right-radius: 2px; - border-bottom-left-radius: 2px; - border-bottom-right-radius: 2px; - text-align: center; + color: #fff; + font-weight: bold; + padding-top: 5px; + margin-left: 5px; + background: none repeat scroll 0% 0% #82b92e; + border-top-left-radius: 2px; + border-top-right-radius: 2px; + border-bottom-left-radius: 2px; + border-bottom-right-radius: 2px; + text-align: center; } #noaccess-text { - font-size: 12px; - text-align: justify; - padding-top: 25px; - padding-right: 50px; - float:right; + font-size: 12px; + text-align: justify; + padding-top: 25px; + padding-right: 50px; + float: right; } #noaccess-image { - position: relative; - left: 10px; - top: 10px; - float:left; + position: relative; + left: 10px; + top: 10px; + float: left; } -div#activity{ - padding-top: 0px; - padding-bottom: 18px; +div#activity { + padding-top: 0px; + padding-bottom: 18px; } div#noa { - float: right; - padding-right: 50px; - margin-top: 25px; + float: right; + padding-right: 50px; + margin-top: 25px; } div#db_f { - text-align: justify; - margin: auto; - padding: 0.5em; - width: 55em; - margin-top: 3em; + text-align: justify; + margin: auto; + padding: 0.5em; + width: 55em; + margin-top: 3em; } div#db_ftxt { - float: right; - padding-top: 10px; + float: right; + padding-top: 10px; } div#container { - margin: 0 auto; - min-width: 960px; - text-align: left; - #border-left: solid 2px #000; - #border-right: solid 2px #000; - #border-top: solid 2px #000; - #margin-top: 5px; - height: 100%; - background: #5b5b5b; + margin: 0 auto; + min-width: 960px; + text-align: left; + #border-left: solid 2px #000; + #border-right: solid 2px #000; + #border-top: solid 2px #000; + #margin-top: 5px; + height: 100%; + background: #5b5b5b; } div#page { - width: 960px; - clear: both; + width: 960px; + clear: both; } div#main { - width: auto; - margin: 0px 2% 0px 0%; - float: right; - position: relative; - min-height: 850px; + width: auto; + margin: 0px 2% 0px 0%; + float: right; + position: relative; + min-height: 850px; } div#main_help { - width: 100%; - padding-left: 0px; - padding-top: 0px; - background-color: #5b5b5b; - margin-top: 0px; - margin-left: 0px; - margin-right: 0px; - border-radius: 10px; + width: 100%; + padding-left: 0px; + padding-top: 0px; + background-color: #5b5b5b; + margin-top: 0px; + margin-left: 0px; + margin-right: 0px; + border-radius: 10px; } -div#main_help div.databox, .license_databox { - background: F3F3F3; - -moz-border-radius: 8px; - -webkit-border-radius: 8px; - border-radius: 8px; - border: 0px; - padding-left: 25px; - padding-right: 25px; - margin-top: 10px; - -moz-box-shadow: -1px 1px 6px #aaa; - -webkit-box-shadow: -1px 1px 6px #aaa; - box-shadow: -1px 1px 6px #aaa; - +div#main_help div.databox, +.license_databox { + background: F3F3F3; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + border-radius: 8px; + border: 0px; + padding-left: 25px; + padding-right: 25px; + margin-top: 10px; + -moz-box-shadow: -1px 1px 6px #aaa; + -webkit-box-shadow: -1px 1px 6px #aaa; + box-shadow: -1px 1px 6px #aaa; } -div#main_help div.databox h1{ - padding-bottom: 0px; - margin-bottom: 0px; - font-weight: bold; - font-family: sans-serif, verdana; +div#main_help div.databox h1 { + padding-bottom: 0px; + margin-bottom: 0px; + font-weight: bold; + font-family: sans-serif, verdana; } -div#main_help div.databox h3, div#main_help div.databox h2 { - color: #6EB432; - font-family: sans-serif, verdana; +div#main_help div.databox h3, +div#main_help div.databox h2 { + color: #6eb432; + font-family: sans-serif, verdana; } div#main_help div.databox h3 { - font-size: 12px; + font-size: 12px; } -div#main_help a.footer, div#main_help span { - color: #999; +div#main_help a.footer, +div#main_help span { + color: #999; } -a.footer, a.footer span{ - font-size: 9px; - color: white; +a.footer, +a.footer span { + font-size: 9px; + color: white; } -div#main_help div.databox hr{ - width:100%; - border: 0px; - height: 1px; - background-color: #222; - margin: 0px; +div#main_help div.databox hr { + width: 100%; + border: 0px; + height: 1px; + background-color: #222; + margin: 0px; } -div#main_help div.databox p{ - line-height: 15px; - text-align: justify; +div#main_help div.databox p { + line-height: 15px; + text-align: justify; } div#menu_container { - -moz-border-top-right-radius: 6px; - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - z-index: 1010; - width: 40px; - height: 100%; + -moz-border-top-right-radius: 6px; + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + z-index: 1010; + width: 40px; + height: 100%; } div#menu { - width: 45px; - float: left; - z-index: 2000; - position: absolute; + width: 45px; + float: left; + z-index: 2000; + position: absolute; } div#head { - font-size: 8pt; - width: 100%; - height: 60px; - padding-top: 0px; - margin-bottom: 20px; - border-bottom-style: solid; - border-bottom-width: 3px; - border-color: #82b92e; - min-width: 882px; - background-color: #333; - color: white; - background-image: url("../../images/header_f2b.jpg"); + font-size: 8pt; + width: 100%; + height: 60px; + padding-top: 0px; + margin-bottom: 20px; + border-bottom-style: solid; + border-bottom-width: 3px; + border-color: #82b92e; + min-width: 882px; + background-color: #333; + color: white; + background-image: url("../../images/header_f2b.jpg"); } .fixed_header { - z-index: 9999; - position: fixed; - left: 0; - top: 0; - width: 100%; + z-index: 9999; + position: fixed; + left: 0; + top: 0; + width: 100%; } div#foot { - font-size: 6pt !important; - border-top: solid 2px #222; - padding-top: 8px; - padding-bottom: 5px; - text-align: center; - background: #333333; - height: 30px; - clear: both; - width: auto; + font-size: 6pt !important; + border-top: solid 2px #222; + padding-top: 8px; + padding-bottom: 5px; + text-align: center; + background: #333333; + height: 30px; + clear: both; + width: auto; } #ver { - margin-bottom: 25px; + margin-bottom: 25px; } /****************/ @@ -361,184 +369,187 @@ div#foot { /****************/ @font-face { - font-family: 'Nunito'; + font-family: "Nunito"; font-style: normal; font-weight: 400; - src: local('Nunito-Regular'), url(../../fonts/nunito.woff) format('woff'); + src: local("Nunito-Regular"), url(../../fonts/nunito.woff) format("woff"); } -@font-face -{ - font-family: 'roboto'; - src: url('../../fonts/roboto.woff2') format('woff2'); +@font-face { + font-family: "roboto"; + src: url("../../fonts/roboto.woff2") format("woff2"); } -@font-face -{ - font-family: 'opensans'; - src: url('../../fonts/opensans.woff2') format('woff2'); +@font-face { + font-family: "opensans"; + src: url("../../fonts/opensans.woff2") format("woff2"); } -@font-face -{ - font-family: 'lato'; - src: url('../../fonts/lato.woff2') format('woff2'); +@font-face { + font-family: "lato"; + src: url("../../fonts/lato.woff2") format("woff2"); } -@font-face -{ - font-family: 'leaguegothic'; - src: url('../../fonts/leaguegothic.woff') format('woff'); +@font-face { + font-family: "leaguegothic"; + src: url("../../fonts/leaguegothic.woff") format("woff"); } #login_body { - /* Set rules to fill background */ - min-height: 100%; - min-width: 1024px; - width: 100%; - z-index: -9999; - position: absolute; + /* Set rules to fill background */ + min-height: 100%; + min-width: 1024px; + width: 100%; + z-index: -9999; + position: absolute; } -@media screen and (max-width: 1024px) { /* Specific to this particular image */ - #login_body { - left: 50%; - margin-left: -512px; /* 50% */ - } +@media screen and (max-width: 1024px) { + /* Specific to this particular image */ + #login_body { + left: 50%; + margin-left: -512px; /* 50% */ + } } -@media screen and (max-width: 1100px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/fondo_madera_bn_1100.jpg"); - background-repeat: repeat; - background-position: center center; - } +@media screen and (max-width: 1100px) { + /* Specific to this particular image */ + #login_body { + background-image: url("../../images/backgrounds/fondo_madera_bn_1100.jpg"); + background-repeat: repeat; + background-position: center center; + } } -@media screen and (max-width: 1400px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/fondo_madera_bn_1400.jpg"); - background-repeat: repeat; - background-position: center center; - } +@media screen and (max-width: 1400px) { + /* Specific to this particular image */ + #login_body { + background-image: url("../../images/backgrounds/fondo_madera_bn_1400.jpg"); + background-repeat: repeat; + background-position: center center; + } } -@media screen and (max-width: 2000px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/fondo_madera_bn_2000.jpg"); - background-repeat: repeat; - background-position: center center; - } +@media screen and (max-width: 2000px) { + /* Specific to this particular image */ + #login_body { + background-image: url("../../images/backgrounds/fondo_madera_bn_2000.jpg"); + background-repeat: repeat; + background-position: center center; + } } -@media screen and (min-width: 2000px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/fondo_madera_bn_2500.jpg"); - background-repeat: repeat; - background-position: center center; - } +@media screen and (min-width: 2000px) { + /* Specific to this particular image */ + #login_body { + background-image: url("../../images/backgrounds/fondo_madera_bn_2500.jpg"); + background-repeat: repeat; + background-position: center center; + } } p.log_in { - color: #FFF !important; - padding: 0px 10px; - width:300px; + color: #fff !important; + padding: 0px 10px; + width: 300px; } h1#log_f { - color: #c00; - border-bottom: 1px solid #c00; - padding-bottom: 3px; + color: #c00; + border-bottom: 1px solid #c00; + padding-bottom: 3px; } div#login { - border-width: 2px 2px 2px 2px; - border-style: solid; - border-color: #000; - font-size: 12px !important; + border-width: 2px 2px 2px 2px; + border-style: solid; + border-color: #000; + font-size: 12px !important; } -div#login_in, #login_f { - /*margin: 0 auto 0 140px; +div#login_in, +#login_f { + /*margin: 0 auto 0 140px; width: 400px;*/ } -.databox_login, .databox_logout { - border-radius: 5px; - height: 200px; +.databox_login, +.databox_logout { + border-radius: 5px; + height: 200px; } #login_inner { - width: 100%; - height: 100%; - border-radius: 5px; - /* Browser without multibackground support */ - background-color: #373737 !important; - + width: 100%; + height: 100%; + border-radius: 5px; + /* Browser without multibackground support */ + background-color: #373737 !important; } #login_outer { - border-radius: 11px; - background-color: #000; - width: 500px !important; - color: #FFF !important; - margin: 0px auto; + border-radius: 11px; + background-color: #000; + width: 500px !important; + color: #fff !important; + margin: 0px auto; } -.version_login{ - transform: rotate(36deg); - /* Old browser support */ - -ms-transform: rotate(36deg); /* IE */ - -moz-transform: rotate(36deg); /* FF */ - -o-transform: rotate(36deg); /* Opera */ - -webkit-transform: rotate(36deg); /* Safari and Chrome */ - - float: right; - margin-top: 18px; - width: 80px; - height: 0px; - border-right: 13px solid transparent; - border-left: 25px solid transparent; - border-bottom: 18px solid #82b92e; - left: 16px; - position: relative; -} +.version_login { + transform: rotate(36deg); + /* Old browser support */ + -ms-transform: rotate(36deg); /* IE */ + -moz-transform: rotate(36deg); /* FF */ + -o-transform: rotate(36deg); /* Opera */ + -webkit-transform: rotate(36deg); /* Safari and Chrome */ + float: right; + margin-top: 18px; + width: 80px; + height: 0px; + border-right: 13px solid transparent; + border-left: 25px solid transparent; + border-bottom: 18px solid #82b92e; + left: 16px; + position: relative; +} #login_outer * { - font-family: Nunito, "Arial Rounded MT", Arial, Helvetica, sans-serif; - font-weight: bold; + font-family: Nunito, "Arial Rounded MT", Arial, Helvetica, sans-serif; + font-weight: bold; } -.login_border{ - border-right: 1px solid #FFF; - text-align: center; +.login_border { + border-right: 1px solid #fff; + text-align: center; } table#login_layout { - width: 100%; - height: 160px; - position:absolute; + width: 100%; + height: 160px; + position: absolute; } div#error_login { - text-align: center; - margin-top: 5px; - margin-left: 5px; - width: 75%; - float: right; - text-align: left; - top: 100px; + text-align: center; + margin-top: 5px; + margin-left: 5px; + width: 75%; + float: right; + text-align: left; + top: 100px; } div#error_login_icon { - #margin: 0 auto; - margin-top: 10px; - margin-right: 7px; - text-align: center; - #margin-left: 20px; - width: 20%; - float: right; + #margin: 0 auto; + margin-top: 10px; + margin-right: 7px; + text-align: center; + #margin-left: 20px; + width: 20%; + float: right; } div#login_f { - margin-top: 10px; - margin-bottom: 25px; + margin-top: 10px; + margin-bottom: 25px; } -a:focus, input:focus, button:focus { - utline-width: 0; - outline: 0; +a:focus, +input:focus, +button:focus { + utline-width: 0; + outline: 0; } /*DIV.login_links { @@ -669,303 +680,334 @@ input.login_password { */ .databox_error { - width: 657px !important; - height: 400px; - border: none !important; - background-color: #fafafa; - background: url(../../images/splash_error.png) no-repeat; + width: 657px !important; + height: 400px; + border: none !important; + background-color: #fafafa; + background: url(../../images/splash_error.png) no-repeat; } #ver_num { - margin: 0px auto; - width: 100%; - position: absolute; - bottom: 10px; - color: #FFF; - text-align: center; + margin: 0px auto; + width: 100%; + position: absolute; + bottom: 10px; + color: #fff; + text-align: center; } input:-webkit-autofill { - #-webkit-box-shadow: 0 0 0px 1000px #DDD inset; + #-webkit-box-shadow: 0 0 0px 1000px #ddd inset; } /***********************/ /* END OF LOGIN STYLES */ /***********************/ th > label { - padding-top: 7px; + padding-top: 7px; } input.chk { - margin-right: 0px; - border: 0px none; - height: 14px; + margin-right: 0px; + border: 0px none; + height: 14px; } input.datos { - background-color: #f5f5f5; + background-color: #f5f5f5; } input.datos_readonly { - background-color: #050505; + background-color: #050505; } input.sub { - font-weight: normal; + font-weight: normal; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - border-radius: 2px; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; + border-radius: 2px; - font-size: 8pt; + font-size: 8pt; - background-color: #333 !important; - background-repeat: no-repeat !important; - background-position: 92% 3px !important; + background-color: #333 !important; + background-repeat: no-repeat !important; + background-position: 92% 3px !important; - color: white !important; - padding: 3px 3px 5px 12px; + color: white !important; + padding: 3px 3px 5px 12px; - border-color: #333; + border-color: #333; } input.sub[disabled] { - color: #B4B4B4 !important; - background-color: #F3F3F3 !important; - border-color: #B6B6B6; - cursor: default; + color: #b4b4b4 !important; + background-color: #f3f3f3 !important; + border-color: #b6b6b6; + cursor: default; } -input.next, input.upd, input.ok, input.wand, input.delete, input.cog, -input.target, input.search, input.copy, input.add, input.graph, -input.percentile, input.binary, input.camera, input.config, -input.cancel, input.default, input.filter, input.pdf { - padding-right: 30px; - height: 23px; - +input.next, +input.upd, +input.ok, +input.wand, +input.delete, +input.cog, +input.target, +input.search, +input.copy, +input.add, +input.graph, +input.percentile, +input.binary, +input.camera, +input.config, +input.cancel, +input.default, +input.filter, +input.pdf { + padding-right: 30px; + height: 23px; } input.next { - background-image: url(../../images/input_go.png) !important; + background-image: url(../../images/input_go.png) !important; } input.upd { - background-image: url(../../images/input_update.png) !important; + background-image: url(../../images/input_update.png) !important; } input.wand { - background-image: url(../../images/input_wand.png) !important; + background-image: url(../../images/input_wand.png) !important; } input.wand:disabled { - background-image: url(../../images/input_wand.disabled.png) !important; + background-image: url(../../images/input_wand.disabled.png) !important; } input.search { - background-image: url(../../images/input_zoom.png) !important; + background-image: url(../../images/input_zoom.png) !important; } input.search:disabled { - background-image: url(../../images/input_zoom.disabled.png) !important; + background-image: url(../../images/input_zoom.disabled.png) !important; } input.ok { - background-image: url(../../images/input_tick.png) !important; + background-image: url(../../images/input_tick.png) !important; } input.ok:disabled { - background-image: url(../../images/input_tick.disabled.png) !important; + background-image: url(../../images/input_tick.disabled.png) !important; } input.add { - background-image: url(../../images/input_add.png) !important; + background-image: url(../../images/input_add.png) !important; } input.add:disabled { - background-image: url(../../images/input_add.disabled.png) !important; + background-image: url(../../images/input_add.disabled.png) !important; } input.cancel { - background-image: url(../../images/input_cross.png) !important; + background-image: url(../../images/input_cross.png) !important; } input.cancel:disabled { - background-image: url(../../images/input_cross.disabled.png) !important; + background-image: url(../../images/input_cross.disabled.png) !important; } input.delete { - background-image: url(../../images/input_delete.png) !important; + background-image: url(../../images/input_delete.png) !important; } input.delete:disabled { - background-image: url(../../images/input_delete.disabled.png) !important; + background-image: url(../../images/input_delete.disabled.png) !important; } input.cog { - background-image: url(../../images/input_cog.png) !important; + background-image: url(../../images/input_cog.png) !important; } input.cog:disabled { - background-image: url(../../images/input_cog.disabled.png) !important; + background-image: url(../../images/input_cog.disabled.png) !important; } input.config { - background-image: url(../../images/input_config.png) !important; + background-image: url(../../images/input_config.png) !important; } input.config:disabled { - background-image: url(../../images/input_config.disabled.png) !important; + background-image: url(../../images/input_config.disabled.png) !important; } input.filter { - background-image: url(../../images/input_filter.png) !important; + background-image: url(../../images/input_filter.png) !important; } input.filter:disabled { - background-image: url(../../images/input_filter.disabled.png) !important; + background-image: url(../../images/input_filter.disabled.png) !important; } input.pdf { - background-image: url(../../images/input_pdf.png) !important; + background-image: url(../../images/input_pdf.png) !important; } input.pdf:disabled { - background-image: url(../../images/input_pdf.disabled.png) !important; + background-image: url(../../images/input_pdf.disabled.png) !important; } input.camera { - background-image: url(../../images/input_camera.png) !important; + background-image: url(../../images/input_camera.png) !important; } #toolbox #auto_save { - padding-top: 5px; + padding-top: 5px; } #toolbox { - margin-top: 13px; + margin-top: 13px; } input.visual_editor_button_toolbox { - padding-right: 15px; - padding-top: 10px; - margin-top:5px; + padding-right: 15px; + padding-top: 10px; + margin-top: 5px; } input.delete_min { - background: #fefefe url(../../images/cross.png) no-repeat center !important; + background: #fefefe url(../../images/cross.png) no-repeat center !important; } input.delete_min[disabled] { - background: #fefefe url(../../images/cross.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/cross.disabled.png) no-repeat center !important; } input.graph_min { - background: #fefefe url(../../images/chart_curve.png) no-repeat center !important; + background: #fefefe url(../../images/chart_curve.png) no-repeat center !important; } input.graph_min[disabled] { - background: #fefefe url(../../images/chart_curve.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/chart_curve.disabled.png) no-repeat + center !important; } input.percentile_min { - background: #fefefe url(../../images/chart_bar.png) no-repeat center !important; + background: #fefefe url(../../images/chart_bar.png) no-repeat center !important; } input.percentile_min[disabled] { - background: #fefefe url(../../images/chart_bar.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/chart_bar.disabled.png) no-repeat center !important; } input.percentile_item_min { - background: #fefefe url(../../images/percentile_item.png) no-repeat center !important; + background: #fefefe url(../../images/percentile_item.png) no-repeat center !important; } input.percentile_item_min[disabled] { - background: #fefefe url(../../images/percentile_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/percentile_item.disabled.png) no-repeat + center !important; } input.binary_min { - background: #fefefe url(../../images/binary.png) no-repeat center !important; + background: #fefefe url(../../images/binary.png) no-repeat center !important; } input.binary_min[disabled] { - background: #fefefe url(../../images/binary.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/binary.disabled.png) no-repeat center !important; } input.camera_min { - background: #fefefe url(../../images/camera.png) no-repeat center !important; + background: #fefefe url(../../images/camera.png) no-repeat center !important; } input.camera_min[disabled] { - background: #fefefe url(../../images/camera.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/camera.disabled.png) no-repeat center !important; } input.config_min { - background: #fefefe url(../../images/config.png) no-repeat center !important; + background: #fefefe url(../../images/config.png) no-repeat center !important; } input.config_min[disabled] { - background: #fefefe url(../../images/config.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/config.disabled.png) no-repeat center !important; } input.label_min { - background: #fefefe url(../../images/tag_red.png) no-repeat center !important; + background: #fefefe url(../../images/tag_red.png) no-repeat center !important; } input.label_min[disabled] { - background: #fefefe url(../../images/tag_red.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/tag_red.disabled.png) no-repeat center !important; } input.icon_min { - background: #fefefe url(../../images/photo.png) no-repeat center !important; + background: #fefefe url(../../images/photo.png) no-repeat center !important; } input.icon_min[disabled] { - background: #fefefe url(../../images/photo.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/photo.disabled.png) no-repeat center !important; } input.box_item { - background: #fefefe url(../../images/box_item.png) no-repeat center !important; + background: #fefefe url(../../images/box_item.png) no-repeat center !important; } input.box_item[disabled] { - background: #fefefe url(../../images/box_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/box_item.disabled.png) no-repeat center !important; } input.line_item { - background: #fefefe url(../../images/line_item.png) no-repeat center !important; + background: #fefefe url(../../images/line_item.png) no-repeat center !important; } input.line_item[disabled] { - background: #fefefe url(../../images/line_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/line_item.disabled.png) no-repeat center !important; } input.copy_item { - background: #fefefe url(../../images/copy_visualmap.png) no-repeat center !important; + background: #fefefe url(../../images/copy_visualmap.png) no-repeat center !important; } input.copy_item[disabled] { - background: #fefefe url(../../images/copy_visualmap.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/copy_visualmap.disabled.png) no-repeat + center !important; } input.grid_min { - background: #fefefe url(../../images/grid.png) no-repeat center !important; + background: #fefefe url(../../images/grid.png) no-repeat center !important; } input.grid_min[disabled] { - background: #fefefe url(../../images/grid.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/grid.disabled.png) no-repeat center !important; } input.save_min { - background: #fefefe url(../../images/file.png) no-repeat center !important; + background: #fefefe url(../../images/file.png) no-repeat center !important; } input.save_min[disabled] { - background: #fefefe url(../../images/file.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/file.disabled.png) no-repeat center !important; } input.service_min { - background: #fefefe url(../../images/box.png) no-repeat center !important; + background: #fefefe url(../../images/box.png) no-repeat center !important; } input.service_min[disabled] { - background: #fefefe url(../../images/box.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/box.disabled.png) no-repeat center !important; } input.group_item_min { - background: #fefefe url(../../images/group_green.png) no-repeat center !important; + background: #fefefe url(../../images/group_green.png) no-repeat center !important; } input.group_item_min[disabled] { - background: #fefefe url(../../images/group_green.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/group_green.disabled.png) no-repeat + center !important; } div#cont { - position: fixed; - max-height: 320px; - overflow-y: auto; - overflow-x: hidden; + position: fixed; + max-height: 320px; + overflow-y: auto; + overflow-x: hidden; } -.termframe{ - background-color: #82b92e !important; +.termframe { + background-color: #82b92e !important; } -table, img { - border: 0px; +table, +img { + border: 0px; } -tr:first-child>th { - background-color: #373737; +tr:first-child > th { + background-color: #373737; } th { - color: #fff; - background-color: #666; - font-size: 7.5pt; - letter-spacing: 0.3pt; + color: #fff; + background-color: #666; + font-size: 7.5pt; + letter-spacing: 0.3pt; } -tr.datos, tr.datost, tr.datosb , tr.datos_id, +tr.datos, +tr.datost, +tr.datosb, +tr.datos_id, tr.datosf9 { - #background-color: #eaeaea; + #background-color: #eaeaea; } -tr.datos2, tr.datos2t, -tr.datos2b, tr.datos2_id , tr.datos2f9 { - #background-color: #f2f2f2; +tr.datos2, +tr.datos2t, +tr.datos2b, +tr.datos2_id, +tr.datos2f9 { + #background-color: #f2f2f2; } -tr.datos:hover, tr.datost:hover, tr.datosb:hover, tr.datos_id:hover, -tr.datosf9:hover, tr.datos2:hover, tr.datos2t:hover, -tr.datos2b:hover, tr.datos2_id:hover, tr.datos2f9:hover { - #background-color: #efefef; +tr.datos:hover, +tr.datost:hover, +tr.datosb:hover, +tr.datos_id:hover, +tr.datosf9:hover, +tr.datos2:hover, +tr.datos2t:hover, +tr.datos2b:hover, +tr.datos2_id:hover, +tr.datos2f9:hover { + #background-color: #efefef; } /* Checkbox styles */ -td input[type=checkbox] -{ +td input[type="checkbox"] { /* Double-sized Checkboxes */ -ms-transform: scale(1.3); /* IE */ -moz-transform: scale(1.3); /* FF */ @@ -976,210 +1018,252 @@ td input[type=checkbox] display: table-cell; } -td.datos3, td.datos3 * { - background-color: #666; - color: white !important; +td.datos3, +td.datos3 * { + background-color: #666; + color: white !important; } -td.datos4, td.datos4 * { - /*Add !important because in php the function html_print_table write style in cell and this is style head.*/ - text-align: center !important; - background-color: #666; - color: white !important; +td.datos4, +td.datos4 * { + /*Add !important because in php the function html_print_table write style in cell and this is style head.*/ + text-align: center !important; + background-color: #666; + color: white !important; } td.datos_id { - color: #1a313a; + color: #1a313a; } tr.disabled_row_user * { - color: grey; + color: grey; } -.bg { /* op menu */ - background: #82b92e; +.bg { + /* op menu */ + background: #82b92e; } -.bg2 { /* main page */ - background-color: #0A160C; +.bg2 { + /* main page */ + background-color: #0a160c; } -.bg3 { /* godmode */ - background: #666666; +.bg3 { + /* godmode */ + background: #666666; } -.bg4 { /* links */ - background-color: #989898; +.bg4 { + /* links */ + background-color: #989898; } -.bg, .bg2, .bg3, .bg4 { - position: relative; - width: 100%; +.bg, +.bg2, +.bg3, +.bg4 { + position: relative; + width: 100%; } .bg { - height: 20px; + height: 20px; } -.bg2, .bg3, .bg4 { - height: 18px; +.bg2, +.bg3, +.bg4 { + height: 18px; } -.f10, #ip { - font-size: 7pt; - text-align: center; +.f10, +#ip { + font-size: 7pt; + text-align: center; } -.f9, .f9i, .f9b, .datos_greyf9, .datos_bluef9, .datos_greenf9, -.datos_redf9, .datos_yellowf9, td.f9, td.f9i, td.datosf9, td.datos2f9 { - font-size: 6.5pt; +.f9, +.f9i, +.f9b, +.datos_greyf9, +.datos_bluef9, +.datos_greenf9, +.datos_redf9, +.datos_yellowf9, +td.f9, +td.f9i, +td.datosf9, +td.datos2f9 { + font-size: 6.5pt; } -.f9i, .redi { - font-style: italic; +.f9i, +.redi { + font-style: italic; } .tit { - padding: 6px 0px; - height: 14px; + padding: 6px 0px; + height: 14px; } -.tit, .titb { - font-weight: bold; - color: #fff; - text-align: center; +.tit, +.titb { + font-weight: bold; + color: #fff; + text-align: center; } .suc * { - color: #5a8629; + color: #5a8629; } -.info *{ - color: #006F9D; +.info * { + color: #006f9d; } -.error *{ - color: #f85858; +.error * { + color: #f85858; } -.warning *{ - color: #FAD403; +.warning * { + color: #fad403; } .help { - background: url(../../images/help.png) no-repeat; + background: url(../../images/help.png) no-repeat; } -.red, .redb, .redi, .error { - color: #c00; +.red, +.redb, +.redi, +.error { + color: #c00; } .sep { - margin-left: 30px; - border-bottom: 1px solid #708090; - width: 100%; + margin-left: 30px; + border-bottom: 1px solid #708090; + width: 100%; } .orange { - color: #fd7304; + color: #fd7304; } .green { - color: #5a8629; + color: #5a8629; } .yellow { - color: #F3C500; + color: #f3c500; } .greenb { - color: #00aa00; + color: #00aa00; } .grey { - color: #808080; - font-weight: bold; + color: #808080; + font-weight: bold; } .blue { - color: #5AB7E5; - font-weight: bold; + color: #5ab7e5; + font-weight: bold; } -.redb, .greenb, td.datos_id, td.datos2_id, f9b { - font-weight: bold; +.redb, +.greenb, +td.datos_id, +td.datos2_id, +f9b { + font-weight: bold; } .p10 { - padding-top: 1px; - padding-bottom: 0px; + padding-top: 1px; + padding-bottom: 0px; } .p21 { - padding-top: 2px; - padding-bottom: 1px; + padding-top: 2px; + padding-bottom: 1px; } .w120 { - width: 120px; + width: 120px; } -.w130, #table-agent-configuration select { - width: 130px; +.w130, +#table-agent-configuration select { + width: 130px; } .w135 { - width: 135px; + width: 135px; } -.w155, #table_layout_data select { - width: 155px; +.w155, +#table_layout_data select { + width: 155px; } -.top, .top_red, .bgt, td.datost, td.datos2t { - vertical-align: top; +.top, +.top_red, +.bgt, +td.datost, +td.datos2t { + vertical-align: top; } .top_red { - background: #ff0000; + background: #ff0000; } -.bot, .titb, td.datosb { - vertical-align: bottom; +.bot, +.titb, +td.datosb { + vertical-align: bottom; } .msg { - margin-top: 15px; - text-align: justify; + margin-top: 15px; + text-align: justify; } ul.mn { - list-style: none; - padding: 0px 0px 0px 0px; - margin: 0px 0px 0px 0px; - line-height: 15px; + list-style: none; + padding: 0px 0px 0px 0px; + margin: 0px 0px 0px 0px; + line-height: 15px; } .gr { - font-size: 10pt; - font-weight: bold; + font-size: 10pt; + font-weight: bold; } -a.mn, .gr { - font-family: Arial, Verdana, sans-serif, Helvetica; +a.mn, +.gr { + font-family: Arial, Verdana, sans-serif, Helvetica; } div.nf { - background: url(../../images/info.png) no-repeat scroll 0 50% transparent; - margin-left: 7px; - padding: 8px 1px 6px 25px; + background: url(../../images/info.png) no-repeat scroll 0 50% transparent; + margin-left: 7px; + padding: 8px 1px 6px 25px; } div.title_line { - background-color: #4e682c; - height: 5px; - width: 762px; + background-color: #4e682c; + height: 5px; + width: 762px; } .alpha50 { - filter:alpha(opacity=50); - -moz-opacity: 0.5; - opacity: 0.5; - -khtml-opacity: 0.5; + filter: alpha(opacity=50); + -moz-opacity: 0.5; + opacity: 0.5; + -khtml-opacity: 0.5; } - -#menu_tab_frame, #menu_tab_frame_view { - display: block !important; - border-bottom: 1px solid #82b92e; -/* float:left; */ - margin-left: 0px !important; - max-height: 31px; - min-height: 31px; - padding-right: 28px; - width: 100%; +#menu_tab_frame, +#menu_tab_frame_view { + display: block !important; + border-bottom: 1px solid #82b92e; + /* float:left; */ + margin-left: 0px !important; + max-height: 31px; + min-height: 31px; + padding-right: 28px; + width: 100%; } #menu_tab { - margin: 0px 0px 0px 0px !important; + margin: 0px 0px 0px 0px !important; } -#menu_tab .mn, #menu_tab ul, #menu_tab .mn ul { - padding: 0px; - list-style: none; - margin: 0px 0px 0px 0px; +#menu_tab .mn, +#menu_tab ul, +#menu_tab .mn ul { + padding: 0px; + list-style: none; + margin: 0px 0px 0px 0px; } #menu_tab .mn li { - float: right; - position: relative; - margin: 0px 0px 0px 0px; + float: right; + position: relative; + margin: 0px 0px 0px 0px; } /* #menu_tab li a, #menu_tab a { @@ -1205,463 +1289,494 @@ div.title_line { */ #menu_tab li.separator_view { - padding: 4px; + padding: 4px; } #menu_tab li.separator { - padding: 4px; + padding: 4px; } #menu_tab li.nomn_high a { - /*background: #82b92e;*/ - color: #fff; + /*background: #82b92e;*/ + color: #fff; } #menu_tab .mn li a { - display: block; - text-decoration: none; - padding: 0px; - margin: 0px; - height: 21px; - width: 21px; + display: block; + text-decoration: none; + padding: 0px; + margin: 0px; + height: 21px; + width: 21px; } -#menu_tab li.nomn:hover a, #menu_tab li:hover ul a:hover { - /*background: #82b92e;*/ - color: #fff; +#menu_tab li.nomn:hover a, +#menu_tab li:hover ul a:hover { + /*background: #82b92e;*/ + color: #fff; } #menu_tab li:hover a { - /*background: #b2b08a url("../../images/arrow.png") no-repeat right 3px;*/ + /*background: #b2b08a url("../../images/arrow.png") no-repeat right 3px;*/ } #menu_tab li.nomn { - min-width: 30px; - height: 28px; + min-width: 30px; + height: 28px; } #menu_tab li.nomn_high { - min-width: 30px; - height: 28px; + min-width: 30px; + height: 28px; } /* TAB TITLE */ #menu_tab_left { - margin-left: 0px !important; + margin-left: 0px !important; } -#menu_tab_left .mn, #menu_tab_left ul, #menu_tab_left .mn ul { - background-color: #000; - color: #fff; - font-weight: bold; - padding: 0px 0px 0px 0px; - list-style: none; - margin: 0px 0px 0px 0px; +#menu_tab_left .mn, +#menu_tab_left ul, +#menu_tab_left .mn ul { + background-color: #000; + color: #fff; + font-weight: bold; + padding: 0px 0px 0px 0px; + list-style: none; + margin: 0px 0px 0px 0px; } #menu_tab_left .mn li { - float: left; - position: relative; - height: 26px; - max-height: 26px; + float: left; + position: relative; + height: 26px; + max-height: 26px; } -#menu_tab_left li a, #menu_tab_left li span { -/* text-transform: uppercase; */ - padding: 0px 0px 0px 0px; - color: #fff; - font-size: 8.5pt; - font-weight: bold; - line-height: 20px; +#menu_tab_left li a, +#menu_tab_left li span { + /* text-transform: uppercase; */ + padding: 0px 0px 0px 0px; + color: #fff; + font-size: 8.5pt; + font-weight: bold; + line-height: 20px; } #menu_tab_left .mn li a { - display: block; - text-decoration: none; + display: block; + text-decoration: none; } #menu_tab_left li.view a { - padding: 2px 10px 2px 10px; - color: #fff; - font-weight: bold; - line-height: 18px; - display: none; + padding: 2px 10px 2px 10px; + color: #fff; + font-weight: bold; + line-height: 18px; + display: none; } #menu_tab_left li.view { - background: #82b92e; - max-width: 40%; - min-width: 20%; - padding: 5px 5px 0px; - text-align: center; - -moz-border-top-right-radius: 3px; - -webkit-border-top-right-radius: 3px; - border-top-right-radius: 3px; + background: #82b92e; + max-width: 40%; + min-width: 20%; + padding: 5px 5px 0px; + text-align: center; + -moz-border-top-right-radius: 3px; + -webkit-border-top-right-radius: 3px; + border-top-right-radius: 3px; - -moz-border-top-left-radius: 3px; - -webkit-border-top-left-radius: 3px; - border-top-left-radius: 3px; - margin-left:0px !important; - overflow-y: hidden; + -moz-border-top-left-radius: 3px; + -webkit-border-top-left-radius: 3px; + border-top-left-radius: 3px; + margin-left: 0px !important; + overflow-y: hidden; } #menu_tab_left li.view img.bottom { - width: 24px; - height: 24px; + width: 24px; + height: 24px; } -#menu_tab_frame *, #menu_tab_frame_view *{ - #margin: 0px 0px 0px 0px !important; +#menu_tab_frame *, +#menu_tab_frame_view * { + #margin: 0px 0px 0px 0px !important; } span.users { - background: url(../../images/group.png) no-repeat; + background: url(../../images/group.png) no-repeat; } span.agents { - background: url(../../images/bricks.png) no-repeat; + background: url(../../images/bricks.png) no-repeat; } span.data { - background: url(../../images/data.png) no-repeat; + background: url(../../images/data.png) no-repeat; } span.alerts { - background: url(../../images/bell.png) no-repeat; + background: url(../../images/bell.png) no-repeat; } span.time { - background: url(../../images/hourglass.png) no-repeat; + background: url(../../images/hourglass.png) no-repeat; } span.net { - background: url(../../images/network.png) no-repeat; + background: url(../../images/network.png) no-repeat; } span.master { - background: url(../../images/master.png) no-repeat; + background: url(../../images/master.png) no-repeat; } span.wmi { - background: url(../../images/wmi.png) no-repeat; + background: url(../../images/wmi.png) no-repeat; } span.prediction { - background: url(../../images/chart_bar.png) no-repeat; + background: url(../../images/chart_bar.png) no-repeat; } span.plugin { - background: url(../../images/plugin.png) no-repeat; + background: url(../../images/plugin.png) no-repeat; } span.export { - background: url(../../images/database_refresh.png) no-repeat; + background: url(../../images/database_refresh.png) no-repeat; } span.snmp { - background: url(../../images/snmp.png) no-repeat; + background: url(../../images/snmp.png) no-repeat; } span.binary { - background: url(../../images/binary.png) no-repeat; + background: url(../../images/binary.png) no-repeat; } span.recon { - background: url(../../images/recon.png) no-repeat; + background: url(../../images/recon.png) no-repeat; } span.rmess { - background: url(../../images/email_open.png) no-repeat; + background: url(../../images/email_open.png) no-repeat; } span.nrmess { - background: url(../../images/email.png) no-repeat; + background: url(../../images/email.png) no-repeat; } span.recon_server { - background: url(../../images/recon.png) no-repeat; + background: url(../../images/recon.png) no-repeat; } span.wmi_server { - background: url(../../images/wmi.png) no-repeat; + background: url(../../images/wmi.png) no-repeat; } span.export_server { - background: url(../../images/server_export.png) no-repeat; + background: url(../../images/server_export.png) no-repeat; } span.inventory_server { - background: url(../../images/page_white_text.png) no-repeat; + background: url(../../images/page_white_text.png) no-repeat; } span.web_server { - background: url(../../images/world.png) no-repeat; + background: url(../../images/world.png) no-repeat; } /* This kind of span do not have any sense, should be replaced on PHP code by a real img in code. They are not useful because insert too much margin around (for example, not valid to use in the table of server view */ -span.users, span.agents, span.data, span.alerts, span.time, span.net, -span.master, span.snmp, span.binary, span.recon, span.wmi, span.prediction, -span.plugin, span.plugin, span.export, span.recon_server, span.wmi_server, -span.export_server, span.inventory_server, span.web_server { - margin-left: 4px; - margin-top: 10px; - padding: 4px 8px 12px 30px; - display: block; +span.users, +span.agents, +span.data, +span.alerts, +span.time, +span.net, +span.master, +span.snmp, +span.binary, +span.recon, +span.wmi, +span.prediction, +span.plugin, +span.plugin, +span.export, +span.recon_server, +span.wmi_server, +span.export_server, +span.inventory_server, +span.web_server { + margin-left: 4px; + margin-top: 10px; + padding: 4px 8px 12px 30px; + display: block; } -span.rmess, span.nrmess { - margin-left: 14px; - padding: 1px 0px 10px 30px; - display: block; +span.rmess, +span.nrmess { + margin-left: 14px; + padding: 1px 0px 10px 30px; + display: block; } /* New styles for data box */ -.databox, .databox_color, .databox_frame { - margin-bottom: 5px; - margin-top: 0px; - margin-left: 0px; - border: 1px solid #e2e2e2; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; - +.databox, +.databox_color, +.databox_frame { + margin-bottom: 5px; + margin-top: 0px; + margin-left: 0px; + border: 1px solid #e2e2e2; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + border-radius: 4px; } -.databox_color{ - padding-top: 5px; +.databox_color { + padding-top: 5px; } table.databox { - background-color: #5b5b5b; - border-spacing: 0px; - -moz-box-shadow: 0px 0px 0px #DDD !important; - -webkit-box-shadow: 0px 0px 0px #DDD !important; - box-shadow: 0px 0px 0px #DDD !important; + background-color: #5b5b5b; + border-spacing: 0px; + -moz-box-shadow: 0px 0px 0px #ddd !important; + -webkit-box-shadow: 0px 0px 0px #ddd !important; + box-shadow: 0px 0px 0px #ddd !important; } .databox td { - -moz-border-radius: 0px; - -webkit-border-radius: 0px; - border-radius: 0px; - border: 0px none #E2E2E2; + -moz-border-radius: 0px; + -webkit-border-radius: 0px; + border-radius: 0px; + border: 0px none #e2e2e2; } .databox th { - padding: 9px 7px; - font-weight: normal; - color: #fff; + padding: 9px 7px; + font-weight: normal; + color: #fff; } .databox td { - #border-bottom: 1px solid #E2E2E2; + #border-bottom: 1px solid #e2e2e2; } .databox th * { - color: #fff; + color: #fff; } -.databox th input, .databox th textarea, .databox th select, .databox th select option { - color: #222 !important; +.databox th input, +.databox th textarea, +.databox th select, +.databox th select option { + color: #222 !important; } .tabletitle { - color: #333; + color: #333; } -.tactical_set legend{ - text-align:left; - color: #fff; +.tactical_set legend { + text-align: left; + color: #fff; } -.tactical_set{ - background: #5b5b5b; - border: 1px solid #E2E2E2; - margin-left: auto; - margin-right: auto; - width: auto; +.tactical_set { + background: #5b5b5b; + border: 1px solid #e2e2e2; + margin-left: auto; + margin-right: auto; + width: auto; } /* For use in Netflow */ table.databox_grid { - margin: 25px; + margin: 25px; } table.databox_grid th { - font-size: 12px; + font-size: 12px; } table.databox_grid td { - padding: 6px; - margin: 4px; - border-bottom: 1px solid #acacac; - border-right: 1px solid #acacac; + padding: 6px; + margin: 4px; + border-bottom: 1px solid #acacac; + border-right: 1px solid #acacac; } - -table.alternate tr:nth-child(odd) td{ - background-color: #5b5b5b; +table.alternate tr:nth-child(odd) td { + background-color: #5b5b5b; } -table.alternate tr:nth-child(even) td{ - background-color: #e4e5e4; +table.alternate tr:nth-child(even) td { + background-color: #e4e5e4; } table.rounded_cells td { - padding: 4px 4px 4px 10px; - -moz-border-radius: 6px !important; - -webkit-border-radius: 6px !important; - border-radius: 6px !important; + padding: 4px 4px 4px 10px; + -moz-border-radius: 6px !important; + -webkit-border-radius: 6px !important; + border-radius: 6px !important; } .databox_color { - background-color: #fafafa; + background-color: #fafafa; } #head_l { - float: left; - margin: 0; - padding: 0; + float: left; + margin: 0; + padding: 0; } #head_r { - float: right; - text-align: right; - margin-right: 10px; - padding-top: 0px; + float: right; + text-align: right; + margin-right: 10px; + padding-top: 0px; } #head_m { - position: absolute; - padding-top: 6px; - padding-left: 12em; + position: absolute; + padding-top: 6px; + padding-left: 12em; } span#logo_text1 { - font: bolder 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #eee; + font: bolder 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #eee; } span#logo_text2 { - font: 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #aaa; + font: 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #aaa; } div#logo_text3 { - text-align: right; - font: 2em Arial, Sans-serif; - letter-spacing: 6px; - color: #aaa; - font-weight: bold; - margin-top: 0px; - margin-left: 4px; - padding-top: 0px; + text-align: right; + font: 2em Arial, Sans-serif; + letter-spacing: 6px; + color: #aaa; + font-weight: bold; + margin-top: 0px; + margin-left: 4px; + padding-top: 0px; } .bb0 { - border-bottom: 0px; + border-bottom: 0px; } .bt0 { - border-top: 0px; + border-top: 0px; } .action-buttons { - text-align: right; + text-align: right; } -#table-add-item select, #table-add-sla select { - width: 180px; +#table-add-item select, +#table-add-sla select { + width: 180px; } /* end of classes for event priorities */ div#main_pure { - background-color: #fefefe; - text-align: left; - margin-bottom: 25px; - margin-top: 30px; - margin-left: 10px; - margin-right: 10px; - height: 1000px; - width: 98%; - position: static; + background-color: #fefefe; + text-align: left; + margin-bottom: 25px; + margin-top: 30px; + margin-left: 10px; + margin-right: 10px; + height: 1000px; + width: 98%; + position: static; } #table-agent-configuration radio { - margin-right: 40px; + margin-right: 40px; } .ui-draggable { - cursor:move; + cursor: move; } #layout_trash_drop { - float: right; - width: 300px; - height: 180px; - background: #fff url("../../images/trash.png") no-repeat bottom left; + float: right; + width: 300px; + height: 180px; + background: #fff url("../../images/trash.png") no-repeat bottom left; } #layout_trash_drop div { - display: block; + display: block; } #layout_editor_drop { - float: left; - width: 300px; + float: left; + width: 300px; } .agent_reporting { - margin: 5px; - padding: 5px; + margin: 5px; + padding: 5px; } -.report_table, .agent_reporting { - border: #CCC outset 3px; +.report_table, +.agent_reporting { + border: #ccc outset 3px; } .img_help { - cursor: help; + cursor: help; } #loading { - position:fixed; - width: 200px; - margin-left: 30%; - text-align:center; - top: 50%; - background-color: #999999; - padding: 20px; + position: fixed; + width: 200px; + margin-left: 30%; + text-align: center; + top: 50%; + background-color: #999999; + padding: 20px; } /* IE 7 Hack */ #editor { - *margin-top: 10px !important; + *margin-top: 10px !important; } /* big_data is used in tactical and logon_ok */ .big_data { - text-decoration: none; font: bold 2em Arial, Sans-serif; + text-decoration: none; + font: bold 2em Arial, Sans-serif; } .med_data { - text-decoration: none; font: bold 1.5em Arial, Sans-serif; + text-decoration: none; + font: bold 1.5em Arial, Sans-serif; } .notify { - background-color: #f7ffa5; - text-align: center; - font-weight: bold; - padding: 8px; - margin: 0px 0px 0px 0px !important; - z-index: -1; + background-color: #f7ffa5; + text-align: center; + font-weight: bold; + padding: 8px; + margin: 0px 0px 0px 0px !important; + z-index: -1; } .notify a { - color: #003a3a; - text-decoration: underline; + color: #003a3a; + text-decoration: underline; } .listing { - border-collapse: collapse; + border-collapse: collapse; } .listing td { - border-bottom: 1px solid #CCCCCC; - border-top: 1px solid #CCCCCC; + border-bottom: 1px solid #cccccc; + border-top: 1px solid #cccccc; } ul { - list-style-type: none; - padding-left: 0; - margin-left: 0; + list-style-type: none; + padding-left: 0; + margin-left: 0; } span.actions { - margin-left: 30px; + margin-left: 30px; } .actions { - min-width: 200px! important; + min-width: 200px !important; } -code, pre { - font-family: courier, serif; +code, +pre { + font-family: courier, serif; } -select#template, select#action { - width: 250px; +select#template, +select#action { + width: 250px; } #label-checkbox-matches_value, #label-checkbox-copy_modules, #label-checkbox-copy_alerts { - display: inline; - font-weight: normal; + display: inline; + font-weight: normal; } -input[type=image] { - border:0px; - background-color: transparent !important; +input[type="image"] { + border: 0px; + background-color: transparent !important; } table#simple select#id_module_type, table#alert_search select#id_agent, table#alert_search select#id_group, table#network_component select#type { - width: 200px; + width: 200px; } table#simple select#select_snmp_oid, table#simple select#id_plugin, table#network_component select#id_plugin { - width: 270px; + width: 270px; } table#simple select#prediction_id_group, table#simple select#prediction_id_agent, table#simple select#prediction_module { - width: 50%; - display: block; + width: 50%; + display: block; } table#simple input#text-plugin_parameter, table#simple input#text-snmp_oid, @@ -1671,2071 +1786,2357 @@ table#target_table select, table#filter_compound_table select, table#filter_compound_table #text-search, table#delete_table select { - width: 100%; + width: 100%; } table#simple select#network_component_group, table#simple select#network_component { - width: 90%; + width: 90%; } table#simple span#component_group, table#simple span#component { - width: 45%; - font-style: italic; + width: 45%; + font-style: italic; } table#simple label { - display: inline; - font-weight: normal; - font-style: italic; + display: inline; + font-weight: normal; + font-style: italic; } .clickable { - cursor: pointer; + cursor: pointer; } -table#agent_list tr, table.alert_list tr { - vertical-align: top; +table#agent_list tr, +table.alert_list tr { + vertical-align: top; +} +.toggle { + border-collapse: collapse; +} +.toggle td { + border-left: 1px solid #d3d3d3; } -.toggle { border-collapse: collapse;} -.toggle td { border-left: 1px solid #D3D3D3;} ul.actions_list { - list-style-image: url(../../images/arrow.png); - list-style-position: inside; - margin-top: 0; + list-style-image: url(../../images/arrow.png); + list-style-position: inside; + margin-top: 0; } div.loading { - background-color: #FFF1A8; - margin-left: auto; - margin-right: auto; - padding: 5px; - text-align: center; - font-style: italic; - width: 95%; + background-color: #fff1a8; + margin-left: auto; + margin-right: auto; + padding: 5px; + text-align: center; + font-style: italic; + width: 95%; } div.loading img { - float: right; + float: right; } /* Tablesorter jQuery pager */ div.pager { - margin-left: 10px; - margin-top: 5px; + margin-left: 10px; + margin-top: 5px; } -div.pager img{ - position: relative; - top: 4px; - padding-left: 5px; +div.pager img { + position: relative; + top: 4px; + padding-left: 5px; } div.pager input { - padding-left: 5px; + padding-left: 5px; } .pagedisplay { - border: 0; - width: 35px; + border: 0; + width: 35px; } /* Steps style */ ol.steps { - margin-bottom: 15px; - padding: 0; - list-style-type: none; - list-style-position: outside; + margin-bottom: 15px; + padding: 0; + list-style-type: none; + list-style-position: outside; } ol.steps li { - float: left; - background-color: #efefef; - padding: 5px; - margin-left: 5px; - width: 150px; + float: left; + background-color: #efefef; + padding: 5px; + margin-left: 5px; + width: 150px; } ol.steps li a { - color: #111; + color: #111; } ol.steps li.visited a { - color: #999; + color: #999; } ol.steps li span { - font-weight: normal; - display: block; + font-weight: normal; + display: block; } ol.steps li span { - color: #777; + color: #777; } ol.steps li.visited span { - color: #999; + color: #999; } ol.steps li.current { - border-left: 5px solid #778866; - margin-left: 0; - font-weight: bold; - background-color: #E9F3D2; + border-left: 5px solid #778866; + margin-left: 0; + font-weight: bold; + background-color: #e9f3d2; } ol.steps li.visited { - color: #999 !important; + color: #999 !important; } fieldset { - background-color:#5b5b5b; - border: 1px solid #E2E2E2; - padding:0.5em; - margin-bottom:20px; - position:relative; + background-color: #5b5b5b; + border: 1px solid #e2e2e2; + padding: 0.5em; + margin-bottom: 20px; + position: relative; } fieldset legend { - font-size:1.1em; - font-weight:bold; - #color:#3f4e2f; - line-height: 20px; - color: #3F3F3F; - #top:-2em; + font-size: 1.1em; + font-weight: bold; + #color: #3f4e2f; + line-height: 20px; + color: #3f3f3f; + #top: -2em; } fieldset .databox { - border: 0px solid; + border: 0px solid; } fieldset.databox { - padding: 14px !important; + padding: 14px !important; } fieldset legend span, span#latest_value { - font-style:italic; + font-style: italic; } span#latest_value span#value { - font-style:normal; + font-style: normal; } form#filter_form { - margin-bottom: 15px; + margin-bottom: 15px; } ul.action_list { - margin: 0; - list-style: none inside circle; + margin: 0; + list-style: none inside circle; } ul.action_list li div { - margin-left: 15px; + margin-left: 15px; } span.action_name { - float: none; + float: none; } div.actions_container { - overflow:auto; - width: 100%; - max-height: 200px; + overflow: auto; + width: 100%; + max-height: 200px; } div.actions_container label { - display: inline; - font-weight: normal; - font-style: italic; + display: inline; + font-weight: normal; + font-style: italic; } a.add_action { - clear: both; - display: block; + clear: both; + display: block; } /* timeEntry styles */ .timeEntry_control { - vertical-align: middle; - margin-left: 2px; + vertical-align: middle; + margin-left: 2px; } div#steps_clean { - clear:both; + clear: both; } div#event_control { - clear:right; + clear: right; } /* Autocomplete styles */ .ac_results { - padding: 0px; - border: 1px solid black; - background-color: white; - overflow: hidden; - z-index: 99999; + padding: 0px; + border: 1px solid black; + background-color: white; + overflow: hidden; + z-index: 99999; } .ac_results ul { - width: 100%; - list-style-position: outside; - list-style: none; - padding: 0; - margin: 0; - text-align: left; + width: 100%; + list-style-position: outside; + list-style: none; + padding: 0; + margin: 0; + text-align: left; } .ac_results li { - margin: 0px; - padding: 2px 5px; - cursor: default; - display: block; - /* + margin: 0px; + padding: 2px 5px; + cursor: default; + display: block; + /* if width will be 100% horizontal scrollbar will apear when scroll mode will be used */ - /*width: 100%;*/ - font: menu; - font-size: 12px; - /* + /*width: 100%;*/ + font: menu; + font-size: 12px; + /* it is very important, if line-height not setted or setted in relative units scroll will be broken in firefox */ - line-height: 16px; + line-height: 16px; } .ac_loading { - background: white url('../images/loading.gif') right center no-repeat; + background: white url("../images/loading.gif") right center no-repeat; } .ac_over { - background-color: #efefef; + background-color: #efefef; } span.ac_extra_field, span.ac_extra_field strong { - font-style: italic; - font-size: 9px; + font-style: italic; + font-size: 9px; } - div#pandora_logo_header { -/* Put here your company logo (139x60 pixels) like this: */ -/* background: url(../../images/MiniLogoArtica.jpg); */ - background: url(../../images/pandora_logo_head.png); - background-position: 0% 0%; - width: 139px; - height: 60px; - float: left; + /* Put here your company logo (139x60 pixels) like this: */ + /* background: url(../../images/MiniLogoArtica.jpg); */ + background: url(../../images/pandora_logo_head.png); + background-position: 0% 0%; + width: 139px; + height: 60px; + float: left; } #header_table img { - margin-top: 0px; + margin-top: 0px; } .autorefresh_disabled { - cursor: not-allowed !important; + cursor: not-allowed !important; } a.autorefresh { - padding-right: 8px; + padding-right: 8px; } #refrcounter { - color: white; + color: white; } #combo_refr select { - margin-right: 8px; + margin-right: 8px; } .disabled_module { - color: #aaa; + color: #aaa; } div.warn { - background: url(../../images/info.png) no-repeat; - margin-top: 7px; - padding: 2px 1px 6px 25px; + background: url(../../images/info.png) no-repeat; + margin-top: 7px; + padding: 2px 1px 6px 25px; } .submenu_not_selected { - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - -o-transition-timing-function: ease-out; - font-weight: normal !important; + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + -o-transition-timing-function: ease-out; + font-weight: normal !important; } /* Submenus havent borders */ -.submenu_not_selected, .submenu_selected, .submenu2 { - border: 0px !important; - min-height: 35px !important; +.submenu_not_selected, +.submenu_selected, +.submenu2 { + border: 0px !important; + min-height: 35px !important; } /* Pandora width style theme */ div#container { - width: 100%; + width: 100%; } div#page { - width: auto; + width: auto; } div#main { - max-width: 93%; - min-width: 93%; + max-width: 93%; + min-width: 93%; } ol.steps { - margin-bottom: 70px; + margin-bottom: 70px; } div#steps_clean { - display:none; + display: none; } -#menu_tab_frame, #menu_tab_frame_view { - width: 100%; - padding-right: 0px; - margin-left: 0px !important; - margin-bottom: 20px; - height: 31px; +#menu_tab_frame, +#menu_tab_frame_view { + width: 100%; + padding-right: 0px; + margin-left: 0px !important; + margin-bottom: 20px; + height: 31px; } div#events_list { - float: left; - width: 100%; + float: left; + width: 100%; } span#logo_text1 { - font: bolder 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #eee; + font: bolder 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #eee; } span#logo_text2 { - font: 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #aaa; + font: 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #aaa; } div#logo_text3 { - text-align: right; - font: 2em Arial, Sans-serif; - letter-spacing: 6px; - color: #aaa; - font-weight: bold; - margin-top: 0px; - margin-left: 4px; - padding-top: 0px; + text-align: right; + font: 2em Arial, Sans-serif; + letter-spacing: 6px; + color: #aaa; + font-weight: bold; + margin-top: 0px; + margin-left: 4px; + padding-top: 0px; } .pagination { - margin-top: 15px; - margin-bottom: 5px; + margin-top: 15px; + margin-bottom: 5px; } .pagination * { - margin-left: 0px !important; - margin-right: 0px !important; - vertical-align: middle; + margin-left: 0px !important; + margin-right: 0px !important; + vertical-align: middle; } /*CALENDAR TOOLTIP STYLE*/ /* Calendar background */ table.scw { - background-color: #82b92e; - border: 0 !important; - border-radius: 4px; + background-color: #82b92e; + border: 0 !important; + border-radius: 4px; } /* Week number heading */ td.scwWeekNumberHead { - color: #111; + color: #111; } td.scwWeek { - color: #111 !important; + color: #111 !important; } - Today selector -td.scwFoot { - background-color: #daedae; - color: #111; +Today selector td.scwFoot { + background-color: #daedae; + color: #111; } td.scwFootDisabled { - background-color: #000; - color: #FFFFFF; + background-color: #000; + color: #ffffff; } tfoot.scwFoot { - color: #111; + color: #111; } -.scwFoot :hover{ - color: #3F3F3F !important; +.scwFoot :hover { + color: #3f3f3f !important; } table.scwCells { - background-color: #5b5b5b !important; - color: #3c3c3c !important; + background-color: #5b5b5b !important; + color: #3c3c3c !important; } table.scwCells:hover { - background-color: #5b5b5b !important; + background-color: #5b5b5b !important; } td.scwCellsExMonth { - background-color: #eee !important; - color: #3c3c3c !important; + background-color: #eee !important; + color: #3c3c3c !important; } td.scwCellsWeekend { - background-color: #3c3c3c !important; - color: #fff !important; - border: 0 !important; + background-color: #3c3c3c !important; + color: #fff !important; + border: 0 !important; } td.scwInputDate { - background-color: #777 !important; - color: #ffffff !important; - border: 0 !important; + background-color: #777 !important; + color: #ffffff !important; + border: 0 !important; } td.scwFoot { - background-color: #5b5b5b !important; - color: #3c3c3c !important; - border: 0 !important; + background-color: #5b5b5b !important; + color: #3c3c3c !important; + border: 0 !important; } - - /* Cells divs to set individual styles with the table objects */ div.cellBold { - width: 100%; - height: 100%; - font-weight: bold; + width: 100%; + height: 100%; + font-weight: bold; } div.cellRight { - width: 100%; - height: 100%; - text-align: right; + width: 100%; + height: 100%; + text-align: right; } div.cellCenter { - width:100%; - height:100%; - text-align:center; + width: 100%; + height: 100%; + text-align: center; } div.cellWhite { - width: 100%; - height: 100%; - background: #5b5b5b; - color: #111; + width: 100%; + height: 100%; + background: #5b5b5b; + color: #111; } div.cellNormal { - width: 100%; - height: 100%; - background: #6EB432; - color: #fff; + width: 100%; + height: 100%; + background: #6eb432; + color: #fff; } div.cellCritical { - width: 100%; - height: 100%; - background: #f85858; - color: #fff; + width: 100%; + height: 100%; + background: #f85858; + color: #fff; } div.cellWarning { - width: 100%; - height: 100%; - background: #ffea59; - color: #111; + width: 100%; + height: 100%; + background: #ffea59; + color: #111; } div.cellUnknown { - width: 100%; - height: 100%; - background: #AAAAAA; - color: #FFFFFF; + width: 100%; + height: 100%; + background: #aaaaaa; + color: #ffffff; } div.cellNotInit { - width: 100%; - height: 100%; - background: #3BA0FF; - color: #FFFFFF; + width: 100%; + height: 100%; + background: #3ba0ff; + color: #ffffff; } div.cellAlert { - width: 100%; - height: 100%; - background: #FF8800; - color: #111; + width: 100%; + height: 100%; + background: #ff8800; + color: #111; } div.cellBorder1 { - width: 100%; - height: 100%; - border: 1px solid #666; + width: 100%; + height: 100%; + border: 1px solid #666; } div.cellBig { - width: 100%; - height: 100%; - font-size: 18px; + width: 100%; + height: 100%; + font-size: 18px; } .info_box { - background: #5b5b5b; - margin-top: 10px !important; - margin-bottom: 10px !important; - padding: 0px 5px 5px 10px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; - width: 100% !important; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; + background: #5b5b5b; + margin-top: 10px !important; + margin-bottom: 10px !important; + padding: 0px 5px 5px 10px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; + width: 100% !important; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + border-radius: 4px; } .info_box .title * { - font-size: 10pt !important; - font-weight: bolder; + font-size: 10pt !important; + font-weight: bolder; } .info_box .icon { - width: 30px !important; - text-align: center; + width: 30px !important; + text-align: center; } /* Standard styles for status colos (groups, events, backgrounds...) */ .opacity_cell { - filter:alpha(opacity=80); - -moz-opacity: 0.8; - opacity: 0.8; - -khtml-opacity: 0.8; + filter: alpha(opacity=80); + -moz-opacity: 0.8; + opacity: 0.8; + -khtml-opacity: 0.8; } - -tr.group_view_data, .group_view_data { - color: #3F3F3F; +tr.group_view_data, +.group_view_data { + color: #3f3f3f; } -tr.group_view_crit, .group_view_crit { - background-color: #FC4444; - color: #fff; +tr.group_view_crit, +.group_view_crit { + background-color: #fc4444; + color: #fff; } -tr.group_view_norm, .group_view_norm, tr.group_view_normal, .group_view_normal { - #background-color: #5b5b5b; +tr.group_view_norm, +.group_view_norm, +tr.group_view_normal, +.group_view_normal { + #background-color: #5b5b5b; } -tr.group_view_ok, .group_view_ok { - background-color: #82b92e; - color: #fff; +tr.group_view_ok, +.group_view_ok { + background-color: #82b92e; + color: #fff; } -tr.group_view_not_init, .group_view_not_init, tr.group_view_not_init, .group_view_not_init { - background-color: #5BB6E5; - color: #fff !important; +tr.group_view_not_init, +.group_view_not_init, +tr.group_view_not_init, +.group_view_not_init { + background-color: #5bb6e5; + color: #fff !important; } -tr.group_view_warn, .group_view_warn, tr.group_view_warn.a, a.group_view_warn, tr.a.group_view_warn { - background-color: #FAD403; - color: #3F3F3F !important; +tr.group_view_warn, +.group_view_warn, +tr.group_view_warn.a, +a.group_view_warn, +tr.a.group_view_warn { + background-color: #fad403; + color: #3f3f3f !important; } a.group_view_warn { - color: #FAD403 !important; + color: #fad403 !important; } -tr.group_view_alrm, .group_view_alrm { - background-color: #FFA631; - color: #FFF; +tr.group_view_alrm, +.group_view_alrm { + background-color: #ffa631; + color: #fff; } -tr.group_view_unk, .group_view_unk { - background-color: #B2B2B2 ; - color: #fff; +tr.group_view_unk, +.group_view_unk { + background-color: #b2b2b2; + color: #fff; } /* classes for event priorities. Sits now in functions.php */ -.datos_green, .datos_greenf9, .datos_green a, .datos_greenf9 a, .datos_green * { - background-color: #82b92e; - color: #fff; +.datos_green, +.datos_greenf9, +.datos_green a, +.datos_greenf9 a, +.datos_green * { + background-color: #82b92e; + color: #fff; } -.datos_red, .datos_redf9, .datos_red a, .datos_redf9 a, .datos_red *{ - background-color: #FC4444; - color: #fff !important; +.datos_red, +.datos_redf9, +.datos_red a, +.datos_redf9 a, +.datos_red * { + background-color: #fc4444; + color: #fff !important; } -.datos_yellow, .datos_yellowf9, .datos_yellow * { - background-color: #FAD403; - color: #111; +.datos_yellow, +.datos_yellowf9, +.datos_yellow * { + background-color: #fad403; + color: #111; } -a.datos_blue, .datos_bluef9, .datos_blue, .datos_blue * { - background-color: #4CA8E0; - color: #fff !important; +a.datos_blue, +.datos_bluef9, +.datos_blue, +.datos_blue * { + background-color: #4ca8e0; + color: #fff !important; } -.datos_grey, .datos_greyf9, .datos_grey * { - background-color: #999999; - color: #fff; +.datos_grey, +.datos_greyf9, +.datos_grey * { + background-color: #999999; + color: #fff; } -.datos_pink, .datos_pinkf9, .datos_pink * { - background-color: #fdc4ca; - color: #111; +.datos_pink, +.datos_pinkf9, +.datos_pink * { + background-color: #fdc4ca; + color: #111; } -.datos_brown, .datos_brownf9, .datos_brown * { - background-color: #A67C52; - color: #fff; +.datos_brown, +.datos_brownf9, +.datos_brown * { + background-color: #a67c52; + color: #fff; } -.datos_orange, .datos_orangef9, .datos_orange * { - background-color: #F7931E; - color: #111; +.datos_orange, +.datos_orangef9, +.datos_orange * { + background-color: #f7931e; + color: #111; } -td.datos_greyf9, td.datos_bluef9, td.datos_greenf9, td.datos_redf9, td.datos_yellowf9, td.datos_pinkf9, td.datos_brownf9 ,td.datos_orangef9 { - padding: 5px 5px 5px 5px; +td.datos_greyf9, +td.datos_bluef9, +td.datos_greenf9, +td.datos_redf9, +td.datos_yellowf9, +td.datos_pinkf9, +td.datos_brownf9, +td.datos_orangef9 { + padding: 5px 5px 5px 5px; } .menu li.selected { - font-weight: bold; + font-weight: bold; } -ul.operation li a:hover { - #font-weight: bold; +ul.operation li a:hover { + #font-weight: bold; } -.menu_icon{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - -o-transition-timing-function: ease-out; +.menu_icon { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + -o-transition-timing-function: ease-out; } -.menu_icon:hover{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - -o-transition-timing-function: ease-out; - background-color: #b1b1b1 !important; +.menu_icon:hover { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + -o-transition-timing-function: ease-out; + background-color: #b1b1b1 !important; } -.submenu_not_selected:hover{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - -o-transition-timing-function: ease-out; - background-color: #b1b1b1 !important; +.submenu_not_selected:hover { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + -o-transition-timing-function: ease-out; + background-color: #b1b1b1 !important; } -.submenu_selected:hover{ - background-color: #b1b1b1 !important; +.submenu_selected:hover { + background-color: #b1b1b1 !important; } -.sub_subMenu{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; +.sub_subMenu { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; } -.sub_subMenu:hover{ - transition-property: background-color; - transition-duration: 0.5s; - transition-timing-function: ease-out; - -webkit-transition-property: background-color; - -webkit-transition-duration: 0.5s; - -webkit-transition-timing-function: ease-out; - -moz-transition-property: background-color; - -moz-transition-duration: 0.5s; - -moz-transition-timing-function: ease-out; - -o-transition-property: background-color; - -o-transition-duration: 0.5s; - background-color: #b1b1b1 !important; +.sub_subMenu:hover { + transition-property: background-color; + transition-duration: 0.5s; + transition-timing-function: ease-out; + -webkit-transition-property: background-color; + -webkit-transition-duration: 0.5s; + -webkit-transition-timing-function: ease-out; + -moz-transition-property: background-color; + -moz-transition-duration: 0.5s; + -moz-transition-timing-function: ease-out; + -o-transition-property: background-color; + -o-transition-duration: 0.5s; + background-color: #b1b1b1 !important; } .submenu_text { - color: #fff; + color: #fff; } .menu li.selected { - box-shadow: inset 4px 0 #b1b1b1; + box-shadow: inset 4px 0 #b1b1b1; } -li.links a:hover { - #font-weight: bold; +li.links a:hover { + #font-weight: bold; } .is_submenu2 li { - background-color: #ff0000; + background-color: #ff0000; } .is_submenu2 { - background-color: #222222 !important; + background-color: #222222 !important; } .operation { - background-color: #333 !important; + background-color: #333 !important; } .operation .selected { - background-color: #b1b1b1 !important; + background-color: #b1b1b1 !important; } -.menu li, .menu .li.not_selected { - border-radius: 0px 0px 0px 0px; - display: block; - min-height: 35px; - border-bottom: 0px none #424242; - vertical-align: middle; +.menu li, +.menu .li.not_selected { + border-radius: 0px 0px 0px 0px; + display: block; + min-height: 35px; + border-bottom: 0px none #424242; + vertical-align: middle; } #menu_tab li.separator { - /* Empty */ + /* Empty */ } -.operation{ - border-top-right-radius: 5px; - border-right-style: solid; - border-right-width: 0px; - +.operation { + border-top-right-radius: 5px; + border-right-style: solid; + border-right-width: 0px; } -input#text-id_parent.ac_input, input, textarea, select { - background-color: #5b5b5b !important; - border: 1px solid #cbcbcb; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; +input#text-id_parent.ac_input, +input, +textarea, +select { + background-color: #5b5b5b !important; + border: 1px solid #cbcbcb; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; } span#plugin_description { - font-size: 9px; + font-size: 9px; } /*FOR TINYMCE*/ #tinymce { - text-align: left; + text-align: left; } -.visual_font_size_4pt, .visual_font_size_4pt > em, .visual_font_size_4pt > strong, .visual_font_size_4pt > strong > span, .visual_font_size_4pt > span, .visual_font_size_4pt > strong > em, .visual_font_size_4pt > em > strong, .visual_font_size_4pt em span, .visual_font_size_4pt span em { - font-size: 4pt !important; - line-height: 4pt; +.visual_font_size_4pt, +.visual_font_size_4pt > em, +.visual_font_size_4pt > strong, +.visual_font_size_4pt > strong > span, +.visual_font_size_4pt > span, +.visual_font_size_4pt > strong > em, +.visual_font_size_4pt > em > strong, +.visual_font_size_4pt em span, +.visual_font_size_4pt span em { + font-size: 4pt !important; + line-height: 4pt; } -.visual_font_size_6pt, .visual_font_size_6pt > em, .visual_font_size_6pt > strong, .visual_font_size_6pt > strong > span, .visual_font_size_6pt > span, .visual_font_size_6pt > strong > em, .visual_font_size_6pt > em > strong, .visual_font_size_6pt em span, .visual_font_size_6pt span em { - font-size: 6pt !important; - line-height: 6pt; +.visual_font_size_6pt, +.visual_font_size_6pt > em, +.visual_font_size_6pt > strong, +.visual_font_size_6pt > strong > span, +.visual_font_size_6pt > span, +.visual_font_size_6pt > strong > em, +.visual_font_size_6pt > em > strong, +.visual_font_size_6pt em span, +.visual_font_size_6pt span em { + font-size: 6pt !important; + line-height: 6pt; } -.visual_font_size_8pt, .visual_font_size_8pt > em, .visual_font_size_8pt > strong, .visual_font_size_8pt > strong > span , .visual_font_size_8pt > span, .visual_font_size_8pt > strong > em, .visual_font_size_8pt > em > strong, .visual_font_size_8pt em span, .visual_font_size_8pt span em { - font-size: 8pt !important; - line-height: 8pt; +.visual_font_size_8pt, +.visual_font_size_8pt > em, +.visual_font_size_8pt > strong, +.visual_font_size_8pt > strong > span, +.visual_font_size_8pt > span, +.visual_font_size_8pt > strong > em, +.visual_font_size_8pt > em > strong, +.visual_font_size_8pt em span, +.visual_font_size_8pt span em { + font-size: 8pt !important; + line-height: 8pt; } -.visual_font_size_10pt, .visual_font_size_10pt > em , .visual_font_size_10pt > strong, .visual_font_size_10pt > strong > em, .visual_font_size_10pt > em > strong, .visual_font_size_10pt em span, .visual_font_size_10pt span em { - font-size: 10pt !important; - line-height: 10pt; +.visual_font_size_10pt, +.visual_font_size_10pt > em, +.visual_font_size_10pt > strong, +.visual_font_size_10pt > strong > em, +.visual_font_size_10pt > em > strong, +.visual_font_size_10pt em span, +.visual_font_size_10pt span em { + font-size: 10pt !important; + line-height: 10pt; } -.visual_font_size_12pt, .visual_font_size_12pt > em , .visual_font_size_12pt > strong, .visual_font_size_12pt > strong > em, .visual_font_size_12pt > em > strong, .visual_font_size_12pt em span, .visual_font_size_12pt span em { - font-size: 12pt !important; - line-height: 12pt; +.visual_font_size_12pt, +.visual_font_size_12pt > em, +.visual_font_size_12pt > strong, +.visual_font_size_12pt > strong > em, +.visual_font_size_12pt > em > strong, +.visual_font_size_12pt em span, +.visual_font_size_12pt span em { + font-size: 12pt !important; + line-height: 12pt; } -.visual_font_size_14pt, .visual_font_size_14pt > em , .visual_font_size_14pt > strong, .visual_font_size_14pt > strong > span, .visual_font_size_14pt > span, .visual_font_size_14pt > strong > em, .visual_font_size_14pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 14pt !important; - line-height: 14pt; +.visual_font_size_14pt, +.visual_font_size_14pt > em, +.visual_font_size_14pt > strong, +.visual_font_size_14pt > strong > span, +.visual_font_size_14pt > span, +.visual_font_size_14pt > strong > em, +.visual_font_size_14pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 14pt !important; + line-height: 14pt; } -.visual_font_size_18pt, .visual_font_size_18pt > em , .visual_font_size_18pt > strong, .visual_font_size_18pt > strong > span, .visual_font_size_18pt > span, .visual_font_size_18pt > strong > em, .visual_font_size_18pt > em > strong, .visual_font_size_18pt em span, .visual_font_size_18pt span em { - font-size: 18pt !important; - line-height: 18pt; +.visual_font_size_18pt, +.visual_font_size_18pt > em, +.visual_font_size_18pt > strong, +.visual_font_size_18pt > strong > span, +.visual_font_size_18pt > span, +.visual_font_size_18pt > strong > em, +.visual_font_size_18pt > em > strong, +.visual_font_size_18pt em span, +.visual_font_size_18pt span em { + font-size: 18pt !important; + line-height: 18pt; } -.visual_font_size_24pt, .visual_font_size_24pt > em, .visual_font_size_24pt > strong, .visual_font_size_24pt > strong > span , .visual_font_size_24pt > span, .visual_font_size_24pt > strong > em, .visual_font_size_24pt > em > strong, .visual_font_size_24pt em span, .visual_font_size_24pt span em { - font-size: 24pt !important; - line-height: 24pt; +.visual_font_size_24pt, +.visual_font_size_24pt > em, +.visual_font_size_24pt > strong, +.visual_font_size_24pt > strong > span, +.visual_font_size_24pt > span, +.visual_font_size_24pt > strong > em, +.visual_font_size_24pt > em > strong, +.visual_font_size_24pt em span, +.visual_font_size_24pt span em { + font-size: 24pt !important; + line-height: 24pt; } -.visual_font_size_28pt, .visual_font_size_28pt > em, .visual_font_size_28pt > strong, .visual_font_size_28pt > strong > span , .visual_font_size_28pt > span, .visual_font_size_28pt > strong > em, .visual_font_size_28pt > em > strong, .visual_font_size_28pt em span, .visual_font_size_28pt span em { - font-size: 28pt !important; - line-height: 28pt; +.visual_font_size_28pt, +.visual_font_size_28pt > em, +.visual_font_size_28pt > strong, +.visual_font_size_28pt > strong > span, +.visual_font_size_28pt > span, +.visual_font_size_28pt > strong > em, +.visual_font_size_28pt > em > strong, +.visual_font_size_28pt em span, +.visual_font_size_28pt span em { + font-size: 28pt !important; + line-height: 28pt; } -.visual_font_size_36pt, .visual_font_size_36pt > em, .visual_font_size_36pt > strong, .visual_font_size_36pt > strong > span, .visual_font_size_36pt > span, .visual_font_size_36pt > strong > em, .visual_font_size_36pt > em > strong, .visual_font_size_36pt em span, .visual_font_size_36pt span em { - font-size: 36pt !important; - line-height: 36pt; +.visual_font_size_36pt, +.visual_font_size_36pt > em, +.visual_font_size_36pt > strong, +.visual_font_size_36pt > strong > span, +.visual_font_size_36pt > span, +.visual_font_size_36pt > strong > em, +.visual_font_size_36pt > em > strong, +.visual_font_size_36pt em span, +.visual_font_size_36pt span em { + font-size: 36pt !important; + line-height: 36pt; } -.visual_font_size_48pt, .visual_font_size_48pt > em, .visual_font_size_48pt > strong, .visual_font_size_48pt > strong > span, .visual_font_size_48pt > span, .visual_font_size_48pt > strong > em, .visual_font_size_48pt > em > strong, .visual_font_size_48pt em span, .visual_font_size_48pt span em { - font-size: 48pt !important; - line-height: 48pt; +.visual_font_size_48pt, +.visual_font_size_48pt > em, +.visual_font_size_48pt > strong, +.visual_font_size_48pt > strong > span, +.visual_font_size_48pt > span, +.visual_font_size_48pt > strong > em, +.visual_font_size_48pt > em > strong, +.visual_font_size_48pt em span, +.visual_font_size_48pt span em { + font-size: 48pt !important; + line-height: 48pt; } -.visual_font_size_60pt, .visual_font_size_60pt > em, .visual_font_size_60pt > strong, .visual_font_size_60pt > strong > span, .visual_font_size_60pt > span, .visual_font_size_60pt > strong > em, .visual_font_size_60pt > em > strong, .visual_font_size_60pt em span, .visual_font_size_60pt span em { - font-size: 60pt !important; - line-height: 60pt; +.visual_font_size_60pt, +.visual_font_size_60pt > em, +.visual_font_size_60pt > strong, +.visual_font_size_60pt > strong > span, +.visual_font_size_60pt > span, +.visual_font_size_60pt > strong > em, +.visual_font_size_60pt > em > strong, +.visual_font_size_60pt em span, +.visual_font_size_60pt span em { + font-size: 60pt !important; + line-height: 60pt; } -.visual_font_size_72pt, .visual_font_size_72pt > em, .visual_font_size_72pt > strong, .visual_font_size_72pt > strong > span, .visual_font_size_72pt > span, .visual_font_size_72pt > strong > em, .visual_font_size_72pt > em > strong, .visual_font_size_72pt em span, .visual_font_size_72pt span em { - font-size: 72pt !important; - line-height: 72pt; +.visual_font_size_72pt, +.visual_font_size_72pt > em, +.visual_font_size_72pt > strong, +.visual_font_size_72pt > strong > span, +.visual_font_size_72pt > span, +.visual_font_size_72pt > strong > em, +.visual_font_size_72pt > em > strong, +.visual_font_size_72pt em span, +.visual_font_size_72pt span em { + font-size: 72pt !important; + line-height: 72pt; } -.visual_font_size_84pt, .visual_font_size_84pt > em, .visual_font_size_84pt > strong, .visual_font_size_84pt > strong > span, .visual_font_size_84pt > span, .visual_font_size_84pt > strong > em, .visual_font_size_84pt > em > strong, .visual_font_size_84pt em span, .visual_font_size_84pt span em { - font-size: 84pt !important; - line-height: 84pt; +.visual_font_size_84pt, +.visual_font_size_84pt > em, +.visual_font_size_84pt > strong, +.visual_font_size_84pt > strong > span, +.visual_font_size_84pt > span, +.visual_font_size_84pt > strong > em, +.visual_font_size_84pt > em > strong, +.visual_font_size_84pt em span, +.visual_font_size_84pt span em { + font-size: 84pt !important; + line-height: 84pt; } -.visual_font_size_96pt, .visual_font_size_96pt > em, .visual_font_size_96pt > strong, .visual_font_size_96pt > strong > span, .visual_font_size_96pt > span, .visual_font_size_96pt > strong > em, .visual_font_size_96pt > em > strong, .visual_font_size_96pt em span, .visual_font_size_96pt span em { - font-size: 96pt !important; - line-height: 96pt; +.visual_font_size_96pt, +.visual_font_size_96pt > em, +.visual_font_size_96pt > strong, +.visual_font_size_96pt > strong > span, +.visual_font_size_96pt > span, +.visual_font_size_96pt > strong > em, +.visual_font_size_96pt > em > strong, +.visual_font_size_96pt em span, +.visual_font_size_96pt span em { + font-size: 96pt !important; + line-height: 96pt; } -.visual_font_size_116pt, .visual_font_size_116pt > em, .visual_font_size_116pt > strong, .visual_font_size_116pt > strong > span, .visual_font_size_116pt > span, .visual_font_size_116pt > strong > em, .visual_font_size_116pt > em > strong, .visual_font_size_116pt em span, .visual_font_size_116pt span em { - font-size: 116pt !important; - line-height: 116pt; +.visual_font_size_116pt, +.visual_font_size_116pt > em, +.visual_font_size_116pt > strong, +.visual_font_size_116pt > strong > span, +.visual_font_size_116pt > span, +.visual_font_size_116pt > strong > em, +.visual_font_size_116pt > em > strong, +.visual_font_size_116pt em span, +.visual_font_size_116pt span em { + font-size: 116pt !important; + line-height: 116pt; } -.visual_font_size_128pt, .visual_font_size_128pt > em, .visual_font_size_128pt > strong, .visual_font_size_128pt > strong > span, .visual_font_size_128pt > span, .visual_font_size_128pt > strong > em, .visual_font_size_128pt > em > strong, .visual_font_size_128pt em span, .visual_font_size_128pt span em { - font-size: 128pt !important; - line-height: 128pt; +.visual_font_size_128pt, +.visual_font_size_128pt > em, +.visual_font_size_128pt > strong, +.visual_font_size_128pt > strong > span, +.visual_font_size_128pt > span, +.visual_font_size_128pt > strong > em, +.visual_font_size_128pt > em > strong, +.visual_font_size_128pt em span, +.visual_font_size_128pt span em { + font-size: 128pt !important; + line-height: 128pt; } -.visual_font_size_140pt, .visual_font_size_140pt > em, .visual_font_size_140pt > strong, .visual_font_size_140pt > strong > span, .visual_font_size_140pt > span, .visual_font_size_140pt > strong > em, .visual_font_size_140pt > em > strong, .visual_font_size_140pt em span, .visual_font_size_140pt span em { - font-size: 140pt !important; - line-height: 140pt; +.visual_font_size_140pt, +.visual_font_size_140pt > em, +.visual_font_size_140pt > strong, +.visual_font_size_140pt > strong > span, +.visual_font_size_140pt > span, +.visual_font_size_140pt > strong > em, +.visual_font_size_140pt > em > strong, +.visual_font_size_140pt em span, +.visual_font_size_140pt span em { + font-size: 140pt !important; + line-height: 140pt; } -.visual_font_size_154pt, .visual_font_size_154pt > em, .visual_font_size_154pt > strong, .visual_font_size_154pt > strong > span, .visual_font_size_154pt > span, .visual_font_size_154pt > strong > em, .visual_font_size_154pt > em > strong, .visual_font_size_154pt em span, .visual_font_size_154pt span em { - font-size: 154pt !important; - line-height: 154pt; +.visual_font_size_154pt, +.visual_font_size_154pt > em, +.visual_font_size_154pt > strong, +.visual_font_size_154pt > strong > span, +.visual_font_size_154pt > span, +.visual_font_size_154pt > strong > em, +.visual_font_size_154pt > em > strong, +.visual_font_size_154pt em span, +.visual_font_size_154pt span em { + font-size: 154pt !important; + line-height: 154pt; } -.visual_font_size_196pt, .visual_font_size_196pt > em, .visual_font_size_196pt > strong, .visual_font_size_196pt > strong > span, .visual_font_size_196pt > span, .visual_font_size_196pt > strong > em, .visual_font_size_196pt > em > strong, .visual_font_size_196pt em span, .visual_font_size_196pt span em { - font-size: 196pt !important; - line-height: 196pt; +.visual_font_size_196pt, +.visual_font_size_196pt > em, +.visual_font_size_196pt > strong, +.visual_font_size_196pt > strong > span, +.visual_font_size_196pt > span, +.visual_font_size_196pt > strong > em, +.visual_font_size_196pt > em > strong, +.visual_font_size_196pt em span, +.visual_font_size_196pt span em { + font-size: 196pt !important; + line-height: 196pt; } - - -.resize_visual_font_size_8pt, .resize_visual_font_size_8pt > em, .resize_visual_font_size_8pt > strong, .resize_visual_font_size_8pt > strong > span, .resize_visual_font_size_8pt > span, .resize_visual_font_size_8pt > strong > em, .resize_visual_font_size_8pt > em > strong, .visual_font_size_8pt em span, .visual_font_size_8pt span em { - font-size: 4pt !important; - line-height: 4pt; +.resize_visual_font_size_8pt, +.resize_visual_font_size_8pt > em, +.resize_visual_font_size_8pt > strong, +.resize_visual_font_size_8pt > strong > span, +.resize_visual_font_size_8pt > span, +.resize_visual_font_size_8pt > strong > em, +.resize_visual_font_size_8pt > em > strong, +.visual_font_size_8pt em span, +.visual_font_size_8pt span em { + font-size: 4pt !important; + line-height: 4pt; } -.resize_visual_font_size_14pt, .resize_visual_font_size_14pt > em , .resize_visual_font_size_14pt > strong, .resize_visual_font_size_14pt > strong > span, .resize_visual_font_size_14pt > span, .resize_visual_font_size_14pt > strong > em, .resize_visual_font_size_14pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 7pt !important; - line-height: 7pt; +.resize_visual_font_size_14pt, +.resize_visual_font_size_14pt > em, +.resize_visual_font_size_14pt > strong, +.resize_visual_font_size_14pt > strong > span, +.resize_visual_font_size_14pt > span, +.resize_visual_font_size_14pt > strong > em, +.resize_visual_font_size_14pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 7pt !important; + line-height: 7pt; } -.resize_visual_font_size_24pt, .resize_visual_font_size_24pt > em, .resize_visual_font_size_24pt > strong, .resize_visual_font_size_24pt > strong > span, .resize_visual_font_size_24pt > span, .resize_visual_font_size_24pt > strong > em, .resize_visual_font_size_24pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 12pt !important; - line-height: 12pt; +.resize_visual_font_size_24pt, +.resize_visual_font_size_24pt > em, +.resize_visual_font_size_24pt > strong, +.resize_visual_font_size_24pt > strong > span, +.resize_visual_font_size_24pt > span, +.resize_visual_font_size_24pt > strong > em, +.resize_visual_font_size_24pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 12pt !important; + line-height: 12pt; } -.resize_visual_font_size_36pt, .resize_visual_font_size_36pt > em, .resize_visual_font_size_36pt > strong, .resize_visual_font_size_36pt > strong > span, .resize_visual_font_size_36pt > span, .resize_visual_font_size_36pt > strong > em, .resize_visual_font_size_36pt > em > strong, .visual_font_size_36pt em span, .visual_font_size_36pt span em { - font-size: 18pt !important; - line-height: 18pt; +.resize_visual_font_size_36pt, +.resize_visual_font_size_36pt > em, +.resize_visual_font_size_36pt > strong, +.resize_visual_font_size_36pt > strong > span, +.resize_visual_font_size_36pt > span, +.resize_visual_font_size_36pt > strong > em, +.resize_visual_font_size_36pt > em > strong, +.visual_font_size_36pt em span, +.visual_font_size_36pt span em { + font-size: 18pt !important; + line-height: 18pt; } -.resize_visual_font_size_72pt, .resize_visual_font_size_72pt > em, .resize_visual_font_size_72pt > strong, .resize_visual_font_size_72pt > strong > span, .resize_visual_font_size_72pt > span, .resize_visual_font_size_72pt > strong > em, .resize_visual_font_size_72pt > em > strong, .visual_font_size_72pt em span, .visual_font_size_72pt span em { - font-size: 36pt !important; - line-height: 36pt; +.resize_visual_font_size_72pt, +.resize_visual_font_size_72pt > em, +.resize_visual_font_size_72pt > strong, +.resize_visual_font_size_72pt > strong > span, +.resize_visual_font_size_72pt > span, +.resize_visual_font_size_72pt > strong > em, +.resize_visual_font_size_72pt > em > strong, +.visual_font_size_72pt em span, +.visual_font_size_72pt span em { + font-size: 36pt !important; + line-height: 36pt; } /*SIDEBAR*/ .menu_sidebar { - color:#111; - background: #3f3f3f; + color: #111; + background: #3f3f3f; - margin-left: 10px; - padding-left: 0px; - padding-right: 0px; - padding-top: 10px; - text-align: left; - font-family:arial,sans-serif,verdana; - font-size:10px; - border:1px solid #000; - position:absolute; - margin:0; - width:400px; - height:260px; + margin-left: 10px; + padding-left: 0px; + padding-right: 0px; + padding-top: 10px; + text-align: left; + font-family: arial, sans-serif, verdana; + font-size: 10px; + border: 1px solid #000; + position: absolute; + margin: 0; + width: 400px; + height: 260px; - -moz-box-shadow: 0px 4px 4px #010E1B !important; - -webkit-box-shadow: 0px 4px 4px #010E1B !important; - box-shadow: 0px 4px 4px #010E1B !important; + -moz-box-shadow: 0px 4px 4px #010e1b !important; + -webkit-box-shadow: 0px 4px 4px #010e1b !important; + box-shadow: 0px 4px 4px #010e1b !important; - filter:alpha(opacity=97); - -moz-opacity: 0.97; - opacity: 0.97; + filter: alpha(opacity=97); + -moz-opacity: 0.97; + opacity: 0.97; } .menu_sidebar_radius_left { - -moz-border-top-left-radius: 8px; - -webkit-border-top-left-radius: 8px; - border-top-left-radius: 8px; + -moz-border-top-left-radius: 8px; + -webkit-border-top-left-radius: 8px; + border-top-left-radius: 8px; - -moz-border-bottom-left-radius: 8px; - -webkit-border-bottom-left-radius: 8px; - border-bottom-left-radius: 8px; + -moz-border-bottom-left-radius: 8px; + -webkit-border-bottom-left-radius: 8px; + border-bottom-left-radius: 8px; - border-right:0px solid #000; + border-right: 0px solid #000; } .menu_sidebar_radius_right { - -moz-border-top-right-radius: 8px; - -webkit-border-top-right-radius: 8px; - border-top-right-radius: 8px; - -moz-border-bottom-right-radius: 8px; - -webkit-border-bottom-right-radius: 8px; - border-bottom-right-radius: 8px; + -moz-border-top-right-radius: 8px; + -webkit-border-top-right-radius: 8px; + border-top-right-radius: 8px; + -moz-border-bottom-right-radius: 8px; + -webkit-border-bottom-right-radius: 8px; + border-bottom-right-radius: 8px; } .menu_sidebar_outer { - margin-left: 3px; - background: #ECECEC; - width: 100%; - text-align: center; - -moz-border-radius: 6px; - -webkit-border-radius: 6px; - border-radius: 6px; - padding: 8px; + margin-left: 3px; + background: #ececec; + width: 100%; + text-align: center; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: 8px; } /*Groupsview*/ .groupsview { - border-spacing: 0px 4px; + border-spacing: 0px 4px; } .groupsview tr { - background-color: #666; + background-color: #666; } .groupsview th { - font-size: 12px; - padding: 5px; + font-size: 12px; + padding: 5px; } -.groupsview td.first, .groupsview th.first { - -moz-border-top-left-radius: 10px; - -webkit-border-top-left-radius: 10px; - border-top-left-radius: 10px; +.groupsview td.first, +.groupsview th.first { + -moz-border-top-left-radius: 10px; + -webkit-border-top-left-radius: 10px; + border-top-left-radius: 10px; - -moz-border-bottom-left-radius: 10px; - -webkit-border-bottom-left-radius: 10px; - border-bottom-left-radius: 10px; + -moz-border-bottom-left-radius: 10px; + -webkit-border-bottom-left-radius: 10px; + border-bottom-left-radius: 10px; } -.groupsview td.last, .groupsview th.last { - -moz-border-top-right-radius: 10px; - -webkit-border-top-right-radius: 10px; - border-top-right-radius: 10px; - -moz-border-bottom-right-radius: 10px; - -webkit-border-bottom-right-radius: 10px; - border-bottom-right-radius: 10px; +.groupsview td.last, +.groupsview th.last { + -moz-border-top-right-radius: 10px; + -webkit-border-top-right-radius: 10px; + border-top-right-radius: 10px; + -moz-border-bottom-right-radius: 10px; + -webkit-border-bottom-right-radius: 10px; + border-bottom-right-radius: 10px; } a.tip { - display: inline !important; - cursor: help; + display: inline !important; + cursor: help; } -a.tip>img { - margin-left: 2px; - margin-right: 2px; +a.tip > img { + margin-left: 2px; + margin-right: 2px; } input.search_input { - background: white url('../../images/input_zoom.png') no-repeat right; - padding: 0px; - padding-left:5px; - margin: 0; - width: 80%; - height: 19px; - margin-bottom: 5px; - margin-left: 2px; - padding-right: 25px; - color: #999; + background: white url("../../images/input_zoom.png") no-repeat right; + padding: 0px; + padding-left: 5px; + margin: 0; + width: 80%; + height: 19px; + margin-bottom: 5px; + margin-left: 2px; + padding-right: 25px; + color: #999; } -.vertical_fields td input, .vertical_fields td select { - margin-top: 8px !important; +.vertical_fields td input, +.vertical_fields td select { + margin-top: 8px !important; } -a[id^='tgl_ctrl_']>img, a[id^='tgl_ctrl_']>b>img{ - vertical-align:middle; +a[id^="tgl_ctrl_"] > img, +a[id^="tgl_ctrl_"] > b > img { + vertical-align: middle; } .noshadow { - -moz-box-shadow: 0px !important; - -webkit-box-shadow: 0px !important; - box-shadow: 0px !important; + -moz-box-shadow: 0px !important; + -webkit-box-shadow: 0px !important; + box-shadow: 0px !important; } /* Images forced title */ -DIV.forced_title_layer { - display: block; - text-decoration: none; - position: absolute; - z-index: 100000; - border: 1px solid #708090; - background-color: #666; - color: #FFF; - padding: 4px 5px; - font-weight: bold; - font-size: small; - font-size: 11px; - /* IE 8 */ - -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=9)"; - /* Netscape */ - -moz-opacity: 0.9; - opacity: 0.9; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; +div.forced_title_layer { + display: block; + text-decoration: none; + position: absolute; + z-index: 100000; + border: 1px solid #708090; + background-color: #666; + color: #fff; + padding: 4px 5px; + font-weight: bold; + font-size: small; + font-size: 11px; + /* IE 8 */ + -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=9)"; + /* Netscape */ + -moz-opacity: 0.9; + opacity: 0.9; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; } /* Graphs styles */ -div.legend>div { - pointer-events: none; /* Allow to click the graphs below */ - opacity: 0.65 !important; +div.legend > div { + pointer-events: none; /* Allow to click the graphs below */ + opacity: 0.65 !important; } div.nodata_text { - padding: 5px 12px 0px 68px; - font-weight: bold; - color: #C1C1C1; - text-transform: uppercase; - display: table-cell; - vertical-align: middle; - text-align: left; + padding: 5px 12px 0px 68px; + font-weight: bold; + color: #c1c1c1; + text-transform: uppercase; + display: table-cell; + vertical-align: middle; + text-align: left; } div.nodata_container { - width:150px; - height:100px; - background-repeat:no-repeat; - background-position: center; - margin: auto auto; - display: table; + width: 150px; + height: 100px; + background-repeat: no-repeat; + background-position: center; + margin: auto auto; + display: table; } #snmp_data { - width: 40%; - position: absolute; - top:0; - right:20px; + width: 40%; + position: absolute; + top: 0; + right: 20px; - #background-color: #5b5b5b; - #padding: 10px; + #background-color: #5b5b5b; + #padding: 10px; } #rmf_data { - width: 40%; - height: 80%; - position: absolute; - top:0; - right:20px; - overflow: auto; + width: 40%; + height: 80%; + position: absolute; + top: 0; + right: 20px; + overflow: auto; - #background-color: #5b5b5b; - #padding: 10px; + #background-color: #5b5b5b; + #padding: 10px; } /* Subtab styles */ ul.subsubmenu { - border-bottom-right-radius: 5px; - border-bottom-left-radius: 5px; - -moz-border-bottom-right-radius: 5px; - -moz-border-bottom-left-radius: 5px; - -webkit-border-bottom-right-radius: 5px; - -webkit-border-bottom-left-radius: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; + -moz-border-bottom-right-radius: 5px; + -moz-border-bottom-left-radius: 5px; + -webkit-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; - background: #ECECEC !important; + background: #ececec !important; } -ul.subsubmenu li{ - background-color: #ECECEC; - font-weight: bold; - text-decoration: none; - font-size: 14px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; +ul.subsubmenu li { + background-color: #ececec; + font-weight: bold; + text-decoration: none; + font-size: 14px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; } -ul.subsubmenu li a{ - padding: 0px 10px 5px; +ul.subsubmenu li a { + padding: 0px 10px 5px; } div#agent_wizard_subtabs { - position: absolute; - margin-left: 0px; - display: none; - padding-bottom: 3px; - z-index: 1000; + position: absolute; + margin-left: 0px; + display: none; + padding-bottom: 3px; + z-index: 1000; } .agent_wizard_tab:hover { - cursor: default; + cursor: default; } #container_servicemap_legend { - position: absolute; - width: 200px; - background: #5b5b5b; - margin-top: 10px; - right: 2px; - border: 1px solid #E2E2E2; - border-radius: 5px; - padding: 10px; - opacity: .90; + position: absolute; + width: 200px; + background: #5b5b5b; + margin-top: 10px; + right: 2px; + border: 1px solid #e2e2e2; + border-radius: 5px; + padding: 10px; + opacity: 0.9; } #container_servicemap_legend table { - text-align: left; + text-align: left; } .legend_square { - width: 20px; - padding-left: 20px; - padding-right: 10px; + width: 20px; + padding-left: 20px; + padding-right: 10px; } .legend_square_simple { - padding-left:0px; - padding-right: 10px; - padding-bottom: 3px; + padding-left: 0px; + padding-right: 10px; + padding-bottom: 3px; } -.legend_square div, .legend_square_simple div { - width: 20px; - height: 20px; - border-radius: 3px; +.legend_square div, +.legend_square_simple div { + width: 20px; + height: 20px; + border-radius: 3px; } .legend_basic { - background: #F4F4F4; - margin-top: 10px; - border-radius: 5px; - padding: 10px; + background: #f4f4f4; + margin-top: 10px; + border-radius: 5px; + padding: 10px; } .agents_modules_table th { - background: #3F3F3F; + background: #3f3f3f; } .agents_modules_table th * { - color: #FFFFFF; + color: #ffffff; } /* * LOAD_ENTERPRISE.PHP */ #code_license_dialog { - padding: 50px; - padding-top: 10px; + padding: 50px; + padding-top: 10px; } #code_license_dialog #logo { - margin-bottom: 20px; - text-align: center; + margin-bottom: 20px; + text-align: center; } -#code_license_dialog, #code_license_dialog * { - font-size: 14px; +#code_license_dialog, +#code_license_dialog * { + font-size: 14px; } #code_license_dialog ul { - padding-left: 30px; - list-style-image: url("../../images/input_tick.png"); + padding-left: 30px; + list-style-image: url("../../images/input_tick.png"); } #code_license_dialog li { - margin-bottom: 12px; + margin-bottom: 12px; } #code_license_dialog #code { - font-weight: bolder; - font-size: 20px; - border: 1px solid #dddddd; - padding: 5px; - text-align: center; - -moz-border-radius: 8px; - -webkit-border-radius: 8px; - border-radius: 8px; + font-weight: bolder; + font-size: 20px; + border: 1px solid #dddddd; + padding: 5px; + text-align: center; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + border-radius: 8px; } #code_license_dialog a { - text-decoration: underline; + text-decoration: underline; } /* GRAPHS CSS */ .parent_graph { - position: relative; + position: relative; } -.menu_graph, .timestamp_graph { - position: absolute !important; +.menu_graph, +.timestamp_graph { + position: absolute !important; } .menu_graph { - -moz-border-top-right-radius: 6px; - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - -moz-border-top-left-radius: 6px; - -webkit-border-top-left-radius: 6px; - border-top-left-radius: 6px; + -moz-border-top-right-radius: 6px; + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + -moz-border-top-left-radius: 6px; + -webkit-border-top-left-radius: 6px; + border-top-left-radius: 6px; } .legend_graph { - margin: 0px; - padding: 0px; - text-align: left; + margin: 0px; + padding: 0px; + text-align: left; } .legendColorBox * { - font-size: 0px; - padding: 0px 4px; - overflow: visible !important; + font-size: 0px; + padding: 0px 4px; + overflow: visible !important; } /* GIS CSS */ .olLayerDiv { - z-index: 102 !important; + z-index: 102 !important; } /* Alert view */ -table.alert_days th, table.alert_time th{ - height: 30px; - vertical-align: middle; +table.alert_days th, +table.alert_time th { + height: 30px; + vertical-align: middle; } table.alert_escalation th img { - width: 18px; + width: 18px; } - td.used_field { - #border: solid #6EB432; - background: #6EB432 !important; - color: #FFFFFF; - font-weight: bold; + #border: solid #6eb432; + background: #6eb432 !important; + color: #ffffff; + font-weight: bold; } td.overrided_field { - color: #666; + color: #666; } td.unused_field { - color: #888; + color: #888; } td.empty_field { - background: url('../../images/long_arrow.png') no-repeat 100% center; + background: url("../../images/long_arrow.png") no-repeat 100% center; } #table_macros textarea { - width: 96%; + width: 96%; } /* Policies styles */ table#policy_modules td * { - display: inline; + display: inline; } .context_help_title { - font-weight: bolder; - text-align: left; + font-weight: bolder; + text-align: left; } .context_help_body { - text-align: left; + text-align: left; } #left_column_logon_ok { - width: 750px; - float:left; + width: 750px; + float: left; } #news_board { - min-width: 530px; + min-width: 530px; } #right_column_logon_ok { - width: 350px; - float: right; - margin-right: 20px; + width: 350px; + float: right; + margin-right: 20px; } #clippy_head_title { - font-weight: bold; - background: #82b92e; - color: #ffffff; - margin-top: -15px; - margin-left: -15px; - margin-right: -15px; - padding: 5px; - margin-bottom: 10px; - border-top-left-radius: 2px; - border-top-right-radius: 2px; + font-weight: bold; + background: #82b92e; + color: #ffffff; + margin-top: -15px; + margin-left: -15px; + margin-right: -15px; + padding: 5px; + margin-bottom: 10px; + border-top-left-radius: 2px; + border-top-right-radius: 2px; } .clippy_body { - color: black; + color: black; } #dialog-double_auth-container { - width: 100%; - text-align: center; - vertical-align: middle; + width: 100%; + text-align: center; + vertical-align: middle; } .center_align { - text-align: center; + text-align: center; } .left_align { - text-align: left; + text-align: left; } -.status_tactical{ - width: 100%; - margin-left: auto; - margin-right: auto; - background-color: #5b5b5b !important; - padding: 10px; - border: 1px solid #E2E2E2; - margin-top: 5%; - text-align: left; +.status_tactical { + width: 100%; + margin-left: auto; + margin-right: auto; + background-color: #5b5b5b !important; + padding: 10px; + border: 1px solid #e2e2e2; + margin-top: 5%; + text-align: left; } .status_tactical img { - border: 3px solid #000; - border-radius: 100px; + border: 3px solid #000; + border-radius: 100px; } -#sumary{ - color: #FFF; - margin: 15px; - padding: 10px 30px; - font-size: 20px; - font-weight: bold; - height: 66px; - width: 191px; - border-radius: 2px; +#sumary { + color: #fff; + margin: 15px; + padding: 10px 30px; + font-size: 20px; + font-weight: bold; + height: 66px; + width: 191px; + border-radius: 2px; } -.databox.data td{ - border-bottom: 1px solid #E2E2E2; +.databox.data td { + border-bottom: 1px solid #e2e2e2; } -.databox .search{ - margin-top: 0px; +.databox .search { + margin-top: 0px; } -.databox.data td.progress_bar img{ - border: 3px solid #000; - border-radius: 100px; +.databox.data td.progress_bar img { + border: 3px solid #000; + border-radius: 100px; } -.databox td{ - padding-left: 9px; - padding-right: 9px; - padding-top: 7px; - padding-bottom: 7px; +.databox td { + padding-left: 9px; + padding-right: 9px; + padding-top: 7px; + padding-bottom: 7px; } -.databox.pies fieldset.tactical_set{ - width:70% !important; - height: 285px; +.databox.pies fieldset.tactical_set { + width: 70% !important; + height: 285px; } -.difference{ - border-left-width: 2px; - border-left-style: solid; - border-right-width: 2px; - border-right-style: solid; - border-color: #E2E2E2; +.difference { + border-left-width: 2px; + border-left-style: solid; + border-right-width: 2px; + border-right-style: solid; + border-color: #e2e2e2; } #title_menu { - color: #FFF; - float: right; - width: 70%; - letter-spacing: 0pt; - font-size: 8pt; - white-space: pre-wrap; + color: #fff; + float: right; + width: 70%; + letter-spacing: 0pt; + font-size: 8pt; + white-space: pre-wrap; } -.no_hidden_menu{ - background-position: 11% 50% !important; +.no_hidden_menu { + background-position: 11% 50% !important; } -#menu_tab li.nomn, #menu_tab li.nomn_high { - background-color: #ECECEC; - padding-right: 3px; - padding-left: 3px; - font-weight: bold; - text-decoration: none; - font-size: 14px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; - margin-top: -10px; +#menu_tab li.nomn, +#menu_tab li.nomn_high { + background-color: #ececec; + padding-right: 3px; + padding-left: 3px; + font-weight: bold; + text-decoration: none; + font-size: 14px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; + margin-top: -10px; } -#menu_tab li.nomn_high, #menu_tab li.nomn_high span { - color: #FFF; - background-color: #5b5b5b; +#menu_tab li.nomn_high, +#menu_tab li.nomn_high span { + color: #fff; + background-color: #5b5b5b; } -#menu_tab li.nomn img, #menu_tab li img { - margin-top: 3px; - margin-left: 3px; +#menu_tab li.nomn img, +#menu_tab li img { + margin-top: 3px; + margin-left: 3px; } -#menu_tab li.tab_operation a, #menu_tab a.tab_operation{ - background: none !important ; +#menu_tab li.tab_operation a, +#menu_tab a.tab_operation { + background: none !important ; } -.subsubmenu{ - position: absolute; - float: right; - z-index: 9999; - display: none; - margin-top: 6px !important ; - left: 0px !important; +.subsubmenu { + position: absolute; + float: right; + z-index: 9999; + display: none; + margin-top: 6px !important ; + left: 0px !important; } -.subsubmenu li{ - margin-top: 0px !important ; +.subsubmenu li { + margin-top: 0px !important ; } -.agents_modules_table{ - border: 1px solid #E2E2E2; - border-spacing: 0px; +.agents_modules_table { + border: 1px solid #e2e2e2; + border-spacing: 0px; } -.agents_modules_table td{ - border: 1px solid #E2E2E2; +.agents_modules_table td { + border: 1px solid #e2e2e2; } -.agents_modules_table th{ - border: 1px solid #E2E2E2; +.agents_modules_table th { + border: 1px solid #e2e2e2; } -.databox.filters, .databox.data, .databox.profile_list{ - margin-bottom: 20px; +.databox.filters, +.databox.data, +.databox.profile_list { + margin-bottom: 20px; } -.databox.filters td{ - padding: 10px; - padding-left:20px; +.databox.filters td { + padding: 10px; + padding-left: 20px; } -.databox.profile_list td{ - padding: 4px 1px; - padding-left: 5px; - border-bottom: 1px solid #E2E2E2; +.databox.profile_list td { + padding: 4px 1px; + padding-left: 5px; + border-bottom: 1px solid #e2e2e2; } -.databox.profile_list a.tip > img{ - margin: 0px; +.databox.profile_list a.tip > img { + margin: 0px; } -.databox.filters td>img, .databox.filters td>div>a>img, -.databox.filters td>span>img, .databox.filters td>span>a>img, -.databox.filters td>a>img{ - vertical-align: middle; - margin-left: 5px; +.databox.filters td > img, +.databox.filters td > div > a > img, +.databox.filters td > span > img, +.databox.filters td > span > a > img, +.databox.filters td > a > img { + vertical-align: middle; + margin-left: 5px; } -.databox.data td>img,.databox.data th>img, .databox.data td>div>a>img, -.databox.data td>span>img, .databox.data td>span>a>img, -.databox.data td>a>img, .databox.data td>form>a>img { - vertical-align: middle; - +.databox.data td > img, +.databox.data th > img, +.databox.data td > div > a > img, +.databox.data td > span > img, +.databox.data td > span > a > img, +.databox.data td > a > img, +.databox.data td > form > a > img { + vertical-align: middle; } -.databox.filters td>a>img { - vertical-align: middle; +.databox.filters td > a > img { + vertical-align: middle; } -.databox.data td>input[type="checkbox"] { - margin: 0px; +.databox.data td > input[type="checkbox"] { + margin: 0px; } -.databox_color td{ - padding-left: 10px; +.databox_color td { + padding-left: 10px; } -.databox.agente td>div>canvas{ - width: 100% !important; - text-align: left !important; +.databox.agente td > div > canvas { + width: 100% !important; + text-align: left !important; } -.databox.agente td>div.graph{ - width: 100% !important; - text-align: left !important; +.databox.agente td > div.graph { + width: 100% !important; + text-align: left !important; } -.godmode, .menu_icon ul li{ - background-color: #222; +.godmode, +.menu_icon ul li { + background-color: #222; } -.operation .menu_icon ul li{ - background-color: #333; +.operation .menu_icon ul li { + background-color: #333; } -.godmode{ - border-top: 4px solid !important; - padding-bottom: 4px !important; - border-bottom-right-radius: 5px; - border-right-style: solid; - border-right-width: 0px; +.godmode { + border-top: 4px solid !important; + padding-bottom: 4px !important; + border-bottom-right-radius: 5px; + border-right-style: solid; + border-right-width: 0px; } -.green_title{ - background-color: #82b92e; - font-weight:normal; - text-align: center; +.green_title { + background-color: #82b92e; + font-weight: normal; + text-align: center; } -.dashboard{ - top: 23px; +.dashboard { + top: 23px; } -.dashboard li a{ - width: 158px !important; +.dashboard li a { + width: 158px !important; } -.text_subDashboard{ - float: left; - margin-top: 5%; - margin-left: 3%; +.text_subDashboard { + float: left; + margin-top: 5%; + margin-left: 3%; } /* The items with the class 'spinner' will rotate */ /* Not supported on IE9 and below */ .spinner { - -webkit-animation: spinner 2s infinite linear; - animation: spinner 2s infinite linear; + -webkit-animation: spinner 2s infinite linear; + animation: spinner 2s infinite linear; } @-webkit-keyframes spinner { - 0% { - -ms-transform: rotate(0deg); /* IE */ - -moz-transform: rotate(0deg); /* FF */ - -o-transform: rotate(0deg); /* Opera */ - -webkit-transform: rotate(0deg); /* Safari and Chrome */ - transform: rotate(0deg); - } - 100% { - -ms-transform: rotate(359deg); /* IE */ - -moz-transform: rotate(359deg); /* FF */ - -o-transform: rotate(359deg); /* Opera */ - -webkit-transform: rotate(359deg); /* Safari and Chrome */ - transform: rotate(359deg); - } + 0% { + -ms-transform: rotate(0deg); /* IE */ + -moz-transform: rotate(0deg); /* FF */ + -o-transform: rotate(0deg); /* Opera */ + -webkit-transform: rotate(0deg); /* Safari and Chrome */ + transform: rotate(0deg); + } + 100% { + -ms-transform: rotate(359deg); /* IE */ + -moz-transform: rotate(359deg); /* FF */ + -o-transform: rotate(359deg); /* Opera */ + -webkit-transform: rotate(359deg); /* Safari and Chrome */ + transform: rotate(359deg); + } } @keyframes spinner { - 0% { - -ms-transform: rotate(0deg); /* IE */ - -moz-transform: rotate(0deg); /* FF */ - -o-transform: rotate(0deg); /* Opera */ - -webkit-transform: rotate(0deg); /* Safari and Chrome */ - transform: rotate(0deg); - } - 100% { - -ms-transform: rotate(359deg); /* IE */ - -moz-transform: rotate(359deg); /* FF */ - -o-transform: rotate(359deg); /* Opera */ - -webkit-transform: rotate(359deg); /* Safari and Chrome */ - transform: rotate(359deg); - } + 0% { + -ms-transform: rotate(0deg); /* IE */ + -moz-transform: rotate(0deg); /* FF */ + -o-transform: rotate(0deg); /* Opera */ + -webkit-transform: rotate(0deg); /* Safari and Chrome */ + transform: rotate(0deg); + } + 100% { + -ms-transform: rotate(359deg); /* IE */ + -moz-transform: rotate(359deg); /* FF */ + -o-transform: rotate(359deg); /* Opera */ + -webkit-transform: rotate(359deg); /* Safari and Chrome */ + transform: rotate(359deg); + } } -#alert_messages{ - -moz-border-bottom-right-radius: 5px; - -webkit-border-bottom-left-radius: 5px; - border-bottom-right-radius: 5px; - border-bottom-left-radius: 5px; - z-index:3; - position:fixed; - width:750px; - max-width:750px; - min-width:750px; - top: 20%; - background:white; +#alert_messages { + -moz-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; + z-index: 3; + position: fixed; + width: 750px; + max-width: 750px; + min-width: 750px; + top: 20%; + background: white; } -.modalheader{ - text-align:center; - width:100%; - height:37px; - left:0px; - background-color:#82b92e; +.modalheader { + text-align: center; + width: 100%; + height: 37px; + left: 0px; + background-color: #82b92e; } -.modalheadertext{ - color:white; - position:relative; - font-family:Nunito; - font-size:13pt; - top:8px; +.modalheadertext { + color: white; + position: relative; + font-family: Nunito; + font-size: 13pt; + top: 8px; } -.modalclosex{ - cursor:pointer; - display:inline; - float:right; - margin-right:10px; - margin-top:10px; +.modalclosex { + cursor: pointer; + display: inline; + float: right; + margin-right: 10px; + margin-top: 10px; } -.modalcontent{ - color:black; - background:white; +.modalcontent { + color: black; + background: white; } -.modalcontentimg{ - float:left; - margin-left:30px; - margin-top:30px; - margin-bottom:30px; +.modalcontentimg { + float: left; + margin-left: 30px; + margin-top: 30px; + margin-bottom: 30px; } -.modalcontenttext{ - float:left; - text-align:justify; - color: #666; - font-size: 9.5pt; - line-height:13pt; - margin-top:30px; - width:430px; - margin-left:30px; +.modalcontenttext { + float: left; + text-align: justify; + color: #666; + font-size: 9.5pt; + line-height: 13pt; + margin-top: 30px; + width: 430px; + margin-left: 30px; } -.modalcontenttext > p{ - color: black; +.modalcontenttext > p { + color: black; } -.modalcontenttext > p > a{ - color: black; +.modalcontenttext > p > a { + color: black; } -.modalokbutton{ - transition-property: background-color, color; - transition-duration: 1s; +.modalokbutton { + transition-property: background-color, color; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - cursor:pointer; - text-align:center; - margin-right:45px; - float:right; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - margin-bottom:30px; - border-radius: 3px;width:90px;height:30px;background-color:white;border: 1px solid #82b92e; + cursor: pointer; + text-align: center; + margin-right: 45px; + float: right; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + margin-bottom: 30px; + border-radius: 3px; + width: 90px; + height: 30px; + background-color: white; + border: 1px solid #82b92e; } -.modalokbuttontext{ - transition-property: background-color, color; - transition-duration: 1s; +.modalokbuttontext { + transition-property: background-color, color; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - color:#82b92e;font-family:Nunito;font-size:10pt;position:relative;top:6px; + color: #82b92e; + font-family: Nunito; + font-size: 10pt; + position: relative; + top: 6px; } .modalokbutton:hover { transition-property: background-color, color; - transition-duration: 1s; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - background-color:#82b92e; + background-color: #82b92e; } .modalokbutton:hover .modalokbuttontext { transition-property: background-color, color; - transition-duration: 1s; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - color:white; + color: white; } -.modalgobutton{ - transition-property: background-color, color; - transition-duration: 1s; +.modalgobutton { + transition-property: background-color, color; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - cursor:pointer;text-align:center;margin-right:15px;margin-bottom:30px;float:right;-moz-border-radius: 3px; - -webkit-border-radius: 3px;border-radius: 3px;width:240px;height:30px;background-color:white;border: 1px solid #82b92e; + cursor: pointer; + text-align: center; + margin-right: 15px; + margin-bottom: 30px; + float: right; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; + width: 240px; + height: 30px; + background-color: white; + border: 1px solid #82b92e; } -.modalgobuttontext{ - transition-property: background-color, color; - transition-duration: 1s; +.modalgobuttontext { + transition-property: background-color, color; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; -color:#82b92e;font-family:Nunito;font-size:10pt;position:relative;top:6px; + color: #82b92e; + font-family: Nunito; + font-size: 10pt; + position: relative; + top: 6px; } .modalgobutton:hover { transition-property: background-color, color; - transition-duration: 1s; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - background-color:#82b92e; + background-color: #82b92e; } .modalgobutton:hover .modalgobuttontext { transition-property: background-color, color; - transition-duration: 1s; + transition-duration: 1s; transition-timing-function: ease-out; -webkit-transition-property: background-color, color; -webkit-transition-duration: 1s; -o-transition-property: background-color, color; -o-transition-duration: 1s; - color:white; + color: white; } -#opacidad{ - opacity:0.5; - z-index:1; - width:100%; - height:100%; - position:absolute; - left:0px; - top:0px; +#opacidad { + opacity: 0.5; + z-index: 1; + width: 100%; + height: 100%; + position: absolute; + left: 0px; + top: 0px; } -.textodialogo{ - margin-left: 0px; - color: black; - font-size:9pt; +.textodialogo { + margin-left: 0px; + color: black; + font-size: 9pt; } -.cargatextodialogo{ - max-width:58.5%; - width:58.5%; - min-width:58.5%; - float:left; - margin-left: 0px; - font-size:18pt; - padding:20px; - text-align:center; +.cargatextodialogo { + max-width: 58.5%; + width: 58.5%; + min-width: 58.5%; + float: left; + margin-left: 0px; + font-size: 18pt; + padding: 20px; + text-align: center; } -.cargatextodialogo b{ - color: black; +.cargatextodialogo b { + color: black; } -.cargatextodialogo p{ - color: black; +.cargatextodialogo p { + color: black; } -.cargatextodialogo b{ - color: black; +.cargatextodialogo b { + color: black; } -.cargatextodialogo a{ - color: black; +.cargatextodialogo a { + color: black; } -.cargatextodialogo > div{ - color: black; +.cargatextodialogo > div { + color: black; } -.cargatextodialogo p, .cargatextodialogo b, .cargatextodialogo a{ - font-size:18pt; +.cargatextodialogo p, +.cargatextodialogo b, +.cargatextodialogo a { + font-size: 18pt; } -#toolbox > input{ - border-width:0px 1px 0px 0px; - border-color: lightgray; +#toolbox > input { + border-width: 0px 1px 0px 0px; + border-color: lightgray; } -#toolbox > input.service_min{ - border-width:0px 0px 0px 0px; +#toolbox > input.service_min { + border-width: 0px 0px 0px 0px; } -#toolbox > input.grid_min{ - border-width:0px 0px 0px 0px; +#toolbox > input.grid_min { + border-width: 0px 0px 0px 0px; } -#tinymce{ - padding-top:20px; +#tinymce { + padding-top: 20px; } -.rowPair:hover, .rowOdd:hover{ - background-color: #6E6E6E; +.rowPair:hover, +.rowOdd:hover { + background-color: #6e6e6e; } -.databox.data > tbody > tr:hover{ - background-color: #6E6E6E; +.databox.data > tbody > tr:hover { + background-color: #6e6e6e; } -.checkselected{ - background-color: #eee; +.checkselected { + background-color: #eee; } -#login_help_dialog *{ - color: #222222; +#login_help_dialog * { + color: #222222; } -.introjs-tooltip *{ - color: #222222; +.introjs-tooltip * { + color: #222222; } -.dd_widget_content *{ - color: #222222; +.dd_widget_content * { + color: #222222; } -#dialog_add_new_widget *{ - color: #222222; +#dialog_add_new_widget * { + color: #222222; } -.widget_configuration_form table tbody tr td:first-child{ - color: #222222; +.widget_configuration_form table tbody tr td:first-child { + color: #222222; } -.widget_configuration_form .container *{ - color: #222222; +.widget_configuration_form .container * { + color: #222222; } -.widget_configuration_form b{ - color: #222222; +.widget_configuration_form b { + color: #222222; } -form[action='index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list'] *{ - color: #222222; +form[action="index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list"] + * { + color: #222222; } -form[action='index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list'] input{ - color: white; +form[action="index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list"] + input { + color: white; } -form[action='index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list'] select{ - color: white; +form[action="index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list"] + select { + color: white; } .notify { - color: black; + color: black; } -.notify *{ - color: black; +.notify * { + color: black; } -#login_logout *{ - color: #222222; +#login_logout * { + color: #222222; } /*modal windows login*/ -div.content_alert{ - width: 98%; - margin-top: 20px; +div.content_alert { + width: 98%; + margin-top: 20px; } -div.icon_message_alert{ - float: left; - width: 25%; - text-align: center; - +div.icon_message_alert { + float: left; + width: 25%; + text-align: center; } -div.icon_message_alert img{ - width: 85px; +div.icon_message_alert img { + width: 85px; } -div.content_message_alert{ - width: 75%; - float: right; +div.content_message_alert { + width: 75%; + float: right; } -div.content_message_alert *{ - color: black; +div.content_message_alert * { + color: black; } -div.text_message_alert{ - width: 100%; - margin-top: 10px; +div.text_message_alert { + width: 100%; + margin-top: 10px; } -div.text_message_alert h1{ - margin: 0px; +div.text_message_alert h1 { + margin: 0px; } -div.text_message_alert p{ - margin: 0px; - font-size: 10.3pt; - line-height: 14pt; +div.text_message_alert p { + margin: 0px; + font-size: 10.3pt; + line-height: 14pt; } -div.button_message_alert{ - width: 100%; +div.button_message_alert { + width: 100%; } -div.button_message_alert input{ - float: right; - width: 87px; - height: 33px; - color: #82b92e; - border: 1px solid #82b92e; - font-weight: bold; - margin-right: 20px; - margin-top: 20px; - font-size: 10pt; +div.button_message_alert input { + float: right; + width: 87px; + height: 33px; + color: #82b92e; + border: 1px solid #82b92e; + font-weight: bold; + margin-right: 20px; + margin-top: 20px; + font-size: 10pt; } -div.form_message_alert{ - width: 90%; - clear: both; - padding-top: 20px; - padding-left: 40px; +div.form_message_alert { + width: 90%; + clear: both; + padding-top: 20px; + padding-left: 40px; } -div.form_message_alert ul li{ - display: inline-block; - padding: 10px; +div.form_message_alert ul li { + display: inline-block; + padding: 10px; } -div.form_message_alert ul li input{ - border: none; - background-color: #dadada !important; - border-radius: 0px; - height: 17px; - width: 145px; - padding-left: 5px; +div.form_message_alert ul li input { + border: none; + background-color: #dadada !important; + border-radius: 0px; + height: 17px; + width: 145px; + padding-left: 5px; } -div.form_message_alert ul li label{ - font-size: 10pt; - padding-right: 20px; +div.form_message_alert ul li label { + font-size: 10pt; + padding-right: 20px; } -div.form_message_alert h4{ - margin: 0px; - margin-bottom: 10px; +div.form_message_alert h4 { + margin: 0px; + margin-bottom: 10px; } -div.button_message_alert_form input{ - float: right; - width: 87px; - height: 33px; - color: #82b92e; - border: 1px solid #82b92e; - font-weight: bold; - font-size: 10pt; - margin-right: 25px; +div.button_message_alert_form input { + float: right; + width: 87px; + height: 33px; + color: #82b92e; + border: 1px solid #82b92e; + font-weight: bold; + font-size: 10pt; + margin-right: 25px; } .ui-dialog .ui-dialog-titlebar { - background-color: #82b92e !important; + background-color: #82b92e !important; } /* styles header login */ -div#header_login{ - width: 100%; - height: 65px; - background-color: rgba(255, 255, 255, 0.06); +div#header_login { + width: 100%; + height: 65px; + background-color: rgba(255, 255, 255, 0.06); } -div#icon_custom_pandora{ - float: left; - margin-top: 5px; - margin-left: 4%; +div#icon_custom_pandora { + float: left; + margin-top: 5px; + margin-left: 4%; } -div#list_icon_docs_support{ - float: right; - margin-top: 8px; - margin-right: 4%; +div#list_icon_docs_support { + float: right; + margin-top: 8px; + margin-right: 4%; } -div#list_icon_docs_support ul{ - margin-top: 5px; +div#list_icon_docs_support ul { + margin-top: 5px; } -div#list_icon_docs_support ul li{ - display: inline-block; - color:white; - vertical-align: middle; - margin-right: 5px; - font-size: 10pt; +div#list_icon_docs_support ul li { + display: inline-block; + color: white; + vertical-align: middle; + margin-right: 5px; + font-size: 10pt; } -li#li_margin_left{ - margin-left: 30px; +li#li_margin_left { + margin-left: 30px; } /* styles login form */ -div.container_login{ - margin-top: 10%; - margin-left: 5%; - margin-right: 5%; - +div.container_login { + margin-top: 10%; + margin-left: 5%; + margin-right: 5%; } div.login_page { - width: 35%; - min-height: 600px; - float:left; + width: 35%; + min-height: 600px; + float: left; } div.login_page form { - border-right:1px solid #868686; - padding-top: 30px; - padding-bottom: 50px; - min-width: 400px; - max-height: 600px; + border-right: 1px solid #868686; + padding-top: 30px; + padding-bottom: 50px; + min-width: 400px; + max-height: 600px; } div.login_logo_icon { - margin-bottom: 40px; - text-align: center; + margin-bottom: 40px; + text-align: center; } -div.login_logo_icon img{ - margin: 0 auto; - width: 150px; +div.login_logo_icon img { + margin: 0 auto; + width: 150px; } div.login_double_auth_code, div.login_nick, div.login_pass { - margin: 0 auto; - width: 70%; - height: 40px; - background-color: rgba(255, 255, 255, 0.20) !important; - margin-bottom: 25px; - min-width: 260px; + margin: 0 auto; + width: 70%; + height: 40px; + background-color: rgba(255, 255, 255, 0.2) !important; + margin-bottom: 25px; + min-width: 260px; } div.login_nick img, -div.login_pass img{ - vertical-align: middle; - margin: 3px; +div.login_pass img { + vertical-align: middle; + margin: 3px; } - div.login_nick input, -div.login_pass input{ - background-color: rgba(255, 255, 255, 0.00) !important; - border:0px !important; - color:white !important; - border-radius: 0px; - width: 89%; - height: 40px; - font-size: 9pt; - padding: 0px !important; +div.login_pass input { + background-color: rgba(255, 255, 255, 0) !important; + border: 0px !important; + color: white !important; + border-radius: 0px; + width: 89%; + height: 40px; + font-size: 9pt; + padding: 0px !important; } - div.login_nick input:focus, -div.login_pass input:focus{ - outline: none; +div.login_pass input:focus { + outline: none; } div.login_nick input:-webkit-autofill, @@ -3746,111 +4147,116 @@ div.login_pass input:-webkit-autofill, div.login_pass input:-webkit-autofill:hover, div.login_pass input:-webkit-autofill:focus, div.login_pass input:-webkit-autofill:active { - transition: background-color 10000s ease-in-out 0s; - -webkit-box-shadow: 0 0 0px 0px transparent inset !important; - -webkit-text-fill-color: white !important; - border:0px; - width: 89%; + transition: background-color 10000s ease-in-out 0s; + -webkit-box-shadow: 0 0 0px 0px transparent inset !important; + -webkit-text-fill-color: white !important; + border: 0px; + width: 89%; } div.login_nick input::-webkit-input-placeholder, div.login_pass input::-webkit-input-placeholder { - color:white; + color: white; } div.login_pass img, -div.login_nick img{ - width: 30px; +div.login_nick img { + width: 30px; } div.login_pass div, -div.login_nick div{ - float: left; - width: 11%; +div.login_nick div { + float: left; + width: 11%; } -div.login_button{ - margin: 0 auto; - width: 70%; - height: 40px; - background-color: rgb(25, 25, 25); - border: 1px solid white; - min-width: 260px; +div.login_button { + margin: 0 auto; + width: 70%; + height: 40px; + background-color: rgb(25, 25, 25); + border: 1px solid white; + min-width: 260px; } div.login_button input { - width: 100%; - background-color: rgb(25, 25, 25) !important; - text-align: center; - border:0px; - border-radius: 0px; - height: 40px; - padding: 0px; - font-size: 9pt; - color: white; + width: 100%; + background-color: rgb(25, 25, 25) !important; + text-align: center; + border: 0px; + border-radius: 0px; + height: 40px; + padding: 0px; + font-size: 9pt; + color: white; } div.login_data { - width: 65%; - min-height: 600px; - float:left; + width: 65%; + min-height: 600px; + float: left; } -div.text_banner_login{ - width: 100%; - margin-bottom: 60px; - color: white; - text-align: center; +div.text_banner_login { + width: 100%; + margin-bottom: 60px; + color: white; + text-align: center; } -div.text_banner_login span{ - width: 100%; +div.text_banner_login span { + width: 100%; } -span.span1{ - font-size: 3vw; - font-family: 'lato-thin'; - color: white; +span.span1 { + font-size: 3vw; + font-family: "lato-thin"; + color: white; } -span.span2{ - font-size: 3vw; - font-family: 'lato-bolder'; - color: white; +span.span2 { + font-size: 3vw; + font-family: "lato-bolder"; + color: white; } -div.img_banner_login{ - width: 100%; - text-align: center; +div.img_banner_login { + width: 100%; + text-align: center; } -div.img_banner_login img{ - max-width: 70%; - min-width: 70%; - max-height: 50%; - min-height: 50%; +div.img_banner_login img { + max-width: 70%; + min-width: 70%; + max-height: 50%; + min-height: 50%; } @media all and (max-width: 1200px) { - span.span1{ - font-size: 30pt; - } - span.span2{ - font-size: 30pt; - } + span.span1 { + font-size: 30pt; + } + span.span2 { + font-size: 30pt; + } } -.new_task p, .new_task h3, .new_task h2, .new_task a, .new_task strong{ - color: #222222; +.new_task p, +.new_task h3, +.new_task h2, +.new_task a, +.new_task strong { + color: #222222; } .item p { - color: #222222; + color: #222222; } .item span { - color: #222222; + color: #222222; } -.widget_config_advice, .widget_config_advice *{ - color: black; +.widget_config_advice, +.widget_config_advice * { + color: black; } diff --git a/pandora_console/include/styles/pandora_forms.css b/pandora_console/include/styles/pandora_forms.css index 16e25e1396..e104a22fca 100644 --- a/pandora_console/include/styles/pandora_forms.css +++ b/pandora_console/include/styles/pandora_forms.css @@ -21,35 +21,36 @@ Description: Forms based on fieldset and labels to improve accesibility */ fieldset { - background-color:#fafafa; - border: 1px solid #f2f2f2; - padding:0.5em; - margin-top:0.5em; - margin-bottom:1em; - position:relative; + background-color: #fafafa; + border: 1px solid #f2f2f2; + padding: 0.5em; + margin-top: 0.5em; + margin-bottom: 1em; + position: relative; } fieldset legend { - font-size:1.3em; - font-weight:bold; - color:#3f4e2f; - top:-2em; + font-size: 1.3em; + font-weight: bold; + color: #3f4e2f; + top: -2em; } fieldset label { - font-weight: bold; - display:block; - margin-right:1em; - margin-left:1em; - margin-bottom:1em; - width:25%; - float:left; + font-weight: bold; + display: block; + margin-right: 1em; + margin-left: 1em; + margin-bottom: 1em; + width: 25%; + float: left; } -fieldset select, fieldset input { - position:relative; - right:1em; - margin-bottom:0.5em; +fieldset select, +fieldset input { + position: relative; + right: 1em; + margin-bottom: 0.5em; } fieldset br { - clear:left; + clear: left; } /*.pandora_form input.sub { @@ -61,35 +62,33 @@ fieldset br { /* Calendar background */ table.scw { - background-color: #daedae; + background-color: #daedae; } /* Week number heading */ td.scwWeekNumberHead { - color: #000; + color: #000; } td.scwWeek { - color: #000 !important; + color: #000 !important; } /* Today selector */ td.scwFoot { - background-color: #daedae; - color: #000; + background-color: #daedae; + color: #000; } td.scwFootDisabled { - background-color: #000; - color: #FFFFFF; + background-color: #000; + color: #ffffff; } tfoot.scwFoot { - color: #000; + color: #000; } -.scwFoot :hover{ - color: #FFA500 !important; +.scwFoot :hover { + color: #ffa500 !important; } - - diff --git a/pandora_console/include/styles/pandora_green_old.css b/pandora_console/include/styles/pandora_green_old.css index a99a9a275d..c27229aeb2 100644 --- a/pandora_console/include/styles/pandora_green_old.css +++ b/pandora_console/include/styles/pandora_green_old.css @@ -25,335 +25,343 @@ Description: The default Pandora FMS theme layout @import url(tree.css); * { - font-family: verdana, sans-serif; - letter-spacing: 0.03pt; - font-size: 8pt; - color: #3F3F3F; + font-family: verdana, sans-serif; + letter-spacing: 0.03pt; + font-size: 8pt; + color: #3f3f3f; } svg * { - font-size: 11pt; - } + font-size: 11pt; +} body { - background-color: #FFF; - margin: 0 auto; + background-color: #fff; + margin: 0 auto; } div#page { - background: #FFF; - background-image: none; + background: #fff; + background-image: none; } body.pure { - background-color: #fff; + background-color: #fff; } -input, textarea { - border: 1px solid #ddd; +input, +textarea { + border: 1px solid #ddd; } textarea { - padding: 5px; - min-height: 100px; - width: 99%; + padding: 5px; + min-height: 100px; + width: 99%; } textarea.conf_editor { - padding: 5px; - width: 650px; - height: 350px; + padding: 5px; + width: 650px; + height: 350px; } textarea.conf_error { - background-image: url(../../images/err.png); - background-repeat: no-repeat; - background-position: top right; + background-image: url(../../images/err.png); + background-repeat: no-repeat; + background-position: top right; } input { - padding: 2px 3px 4px 3px; - vertical-align: middle; + padding: 2px 3px 4px 3px; + vertical-align: middle; } -input[type='checkbox'] { - display: inline !important; +input[type="checkbox"] { + display: inline !important; } select { - padding: 2px 3px 3px 3px; - vertical-align: middle; + padding: 2px 3px 3px 3px; + vertical-align: middle; } input.button { - font-family: Arial,Sans-serif; - border: 4px solid #ccc; - background: #fff; - padding: 2px 3px; - margin: 10px 15px; + font-family: Arial, Sans-serif; + border: 4px solid #ccc; + background: #fff; + padding: 2px 3px; + margin: 10px 15px; } -input[type=submit], input[type=button] { - cursor: pointer; +input[type="submit"], +input[type="button"] { + cursor: pointer; } select { - border: 1px solid #ddd; + border: 1px solid #ddd; } checkbox { - padding: 4px; - border: 1px solid #eee; + padding: 4px; + border: 1px solid #eee; } -h1, h2, h3, h4 { - font-weight: bold; - font-size: 1em; - font-family: Arial, Sans-serif; - text-transform: uppercase; - color: #3F3F3F; - padding-bottom: 4px; - padding-top: 7px; +h1, +h2, +h3, +h4 { + font-weight: bold; + font-size: 1em; + font-family: Arial, Sans-serif; + text-transform: uppercase; + color: #3f3f3f; + padding-bottom: 4px; + padding-top: 7px; } h1 { - font-size: 16px; + font-size: 16px; } h2 { - font-size: 15px; + font-size: 15px; } h3 { - font-size: 14px; + font-size: 14px; } h4 { - margin-bottom: 10px; - font-size: 13px; - color: #3F3F3F; - text-transform: none; + margin-bottom: 10px; + font-size: 13px; + color: #3f3f3f; + text-transform: none; } a { - color: #3F3F3F; - text-decoration: none; + color: #3f3f3f; + text-decoration: none; } a:hover { - color: #373737; - text-decoration: underline; + color: #373737; + text-decoration: underline; } a.white_bold { - color: #eee; - text-decoration: none; - font-weight: bold; + color: #eee; + text-decoration: none; + font-weight: bold; } a.white { - color: #eee; - text-decoration: none; + color: #eee; + text-decoration: none; } p.center { - text-align: center; + text-align: center; } h1#log_title { - font-size: 18px; - margin-bottom: 0px; - color: #FFF !important; - width:300px; + font-size: 18px; + margin-bottom: 0px; + color: #fff !important; + width: 300px; } div#log_msg { - display: none; + display: none; } div#error_buttons { - margin-top: 20px; + margin-top: 20px; } -div#error_buttons a{ - margin: 14px; +div#error_buttons a { + margin: 14px; } #noaccess { - position: relative; - margin-top:25px; - left: 15px; - padding-top: 5px; - background-color: #FFFFFF; - border-top-left-radius: 2px; - border-top-right-radius: 2px; - border-bottom-left-radius: 2px; - border-bottom-right-radius: 2px; + position: relative; + margin-top: 25px; + left: 15px; + padding-top: 5px; + background-color: #ffffff; + border-top-left-radius: 2px; + border-top-right-radius: 2px; + border-bottom-left-radius: 2px; + border-bottom-right-radius: 2px; } #noaccess-title { - color: #FFF; - font-weight: bold; - padding-top: 5px; - margin-left: 5px; - background: none repeat scroll 0% 0% #80ab51; - border-top-left-radius: 2px; - border-top-right-radius: 2px; - border-bottom-left-radius: 2px; - border-bottom-right-radius: 2px; - text-align: center; + color: #fff; + font-weight: bold; + padding-top: 5px; + margin-left: 5px; + background: none repeat scroll 0% 0% #80ab51; + border-top-left-radius: 2px; + border-top-right-radius: 2px; + border-bottom-left-radius: 2px; + border-bottom-right-radius: 2px; + text-align: center; } #noaccess-text { - font-size: 12px; - text-align: justify; - padding-top: 25px; - padding-right: 50px; - float:right; + font-size: 12px; + text-align: justify; + padding-top: 25px; + padding-right: 50px; + float: right; } #noaccess-image { - position: relative; - left: 10px; - top: 10px; - float:left; + position: relative; + left: 10px; + top: 10px; + float: left; } -div#activity{ - padding-top: 0px; - padding-bottom: 18px; +div#activity { + padding-top: 0px; + padding-bottom: 18px; } div#noa { - float: right; - padding-right: 50px; - margin-top: 25px; + float: right; + padding-right: 50px; + margin-top: 25px; } div#db_f { - text-align: justify; - margin: auto; - padding: 0.5em; - width: 55em; - margin-top: 3em; + text-align: justify; + margin: auto; + padding: 0.5em; + width: 55em; + margin-top: 3em; } div#db_ftxt { - float: right; - padding-top: 10px; + float: right; + padding-top: 10px; } div#container { - margin: 0 auto; - min-width: 960px; - text-align: left; - #border-left: solid 2px #000; - #border-right: solid 2px #000; - #border-top: solid 2px #000; - #margin-top: 5px; - height: 100%; - background: #FFF; + margin: 0 auto; + min-width: 960px; + text-align: left; + #border-left: solid 2px #000; + #border-right: solid 2px #000; + #border-top: solid 2px #000; + #margin-top: 5px; + height: 100%; + background: #fff; } div#page { - width: 960px; - clear: both; + width: 960px; + clear: both; } div#main { - width: auto; - margin: 0px 2% 0px 0%; - float: right; - position: relative; - min-height: 850px; + width: auto; + margin: 0px 2% 0px 0%; + float: right; + position: relative; + min-height: 850px; } div#main_help { - width: 100%; - padding-left: 0px; - padding-top: 0px; - background-color: #ffffff; - margin-top: 0px; - margin-left: 0px; - margin-right: 0px; - border-radius: 10px; + width: 100%; + padding-left: 0px; + padding-top: 0px; + background-color: #ffffff; + margin-top: 0px; + margin-left: 0px; + margin-right: 0px; + border-radius: 10px; } -div#main_help div.databox, .license_databox { - background: F3F3F3; - -moz-border-radius: 8px; - -webkit-border-radius: 8px; - border-radius: 8px; - border: 0px; - padding-left: 25px; - padding-right: 25px; - margin-top: 10px; - -moz-box-shadow: -1px 1px 6px #aaa; - -webkit-box-shadow: -1px 1px 6px #aaa; - box-shadow: -1px 1px 6px #aaa; - +div#main_help div.databox, +.license_databox { + background: F3F3F3; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + border-radius: 8px; + border: 0px; + padding-left: 25px; + padding-right: 25px; + margin-top: 10px; + -moz-box-shadow: -1px 1px 6px #aaa; + -webkit-box-shadow: -1px 1px 6px #aaa; + box-shadow: -1px 1px 6px #aaa; } -div#main_help div.databox h1{ - padding-bottom: 0px; - margin-bottom: 0px; - font-weight: bold; - font-family: sans-serif, verdana; +div#main_help div.databox h1 { + padding-bottom: 0px; + margin-bottom: 0px; + font-weight: bold; + font-family: sans-serif, verdana; } -div#main_help div.databox h3, div#main_help div.databox h2 { - color: #6EB432; - font-family: sans-serif, verdana; +div#main_help div.databox h3, +div#main_help div.databox h2 { + color: #6eb432; + font-family: sans-serif, verdana; } div#main_help div.databox h3 { - font-size: 12px; + font-size: 12px; } -div#main_help a.footer, div#main_help span { - color: #999; +div#main_help a.footer, +div#main_help span { + color: #999; } -a.footer, a.footer span{ - font-size: 9px; - color: white; +a.footer, +a.footer span { + font-size: 9px; + color: white; } -div#main_help div.databox hr{ - width:100%; - border: 0px; - height: 1px; - background-color: #222; - margin: 0px; +div#main_help div.databox hr { + width: 100%; + border: 0px; + height: 1px; + background-color: #222; + margin: 0px; } -div#main_help div.databox p{ - line-height: 15px; - text-align: justify; +div#main_help div.databox p { + line-height: 15px; + text-align: justify; } div#menu_container { - -moz-border-top-right-radius: 6px; - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - z-index: 1010; - width: 40px; - height: 100%; + -moz-border-top-right-radius: 6px; + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + z-index: 1010; + width: 40px; + height: 100%; } div#menu { - width: 45px; - float: left; - z-index: 2000; - position: absolute; + width: 45px; + float: left; + z-index: 2000; + position: absolute; } div#head { - font-size: 8pt; - width: 100%; - height: 60px; - padding-top: 0px; - margin-bottom: 20px; - border-bottom-style: solid; - border-bottom-width: 3px; - border-color: #80ab51; - min-width: 882px; - background-color: #333; - color: white; - background-image: url("../../images/header.jpg"); + font-size: 8pt; + width: 100%; + height: 60px; + padding-top: 0px; + margin-bottom: 20px; + border-bottom-style: solid; + border-bottom-width: 3px; + border-color: #80ab51; + min-width: 882px; + background-color: #333; + color: white; + background-image: url("../../images/header.jpg"); } .fixed_header { - z-index: 9999; - position: fixed; - left: 0; - top: 0; - width: 100%; + z-index: 9999; + position: fixed; + left: 0; + top: 0; + width: 100%; } div#foot { - font-size: 6pt !important; - border-top: solid 2px #222; - padding-top: 8px; - padding-bottom: 5px; - text-align: center; - background: #333333; - height: 30px; - clear: both; - width: auto; + font-size: 6pt !important; + border-top: solid 2px #222; + padding-top: 8px; + padding-bottom: 5px; + text-align: center; + background: #333333; + height: 30px; + clear: both; + width: auto; } #ver { - margin-bottom: 25px; + margin-bottom: 25px; } /****************/ @@ -361,609 +369,647 @@ div#foot { /****************/ @font-face { - font-family: 'Nunito'; + font-family: "Nunito"; font-style: normal; font-weight: 400; - src: local('Nunito-Regular'), url(../../fonts/nunito.woff) format('woff'); + src: local("Nunito-Regular"), url(../../fonts/nunito.woff) format("woff"); } -@font-face -{ - font-family: 'roboto'; - src: url('../../fonts/roboto.woff2') format('woff2'); +@font-face { + font-family: "roboto"; + src: url("../../fonts/roboto.woff2") format("woff2"); } -@font-face -{ - font-family: 'opensans'; - src: url('../../fonts/opensans.woff2') format('woff2'); +@font-face { + font-family: "opensans"; + src: url("../../fonts/opensans.woff2") format("woff2"); } -@font-face -{ - font-family: 'lato'; - src: url('../../fonts/lato.woff2') format('woff2'); +@font-face { + font-family: "lato"; + src: url("../../fonts/lato.woff2") format("woff2"); } -@font-face -{ - font-family: 'leaguegothic'; - src: url('../../fonts/leaguegothic.woff') format('woff'); +@font-face { + font-family: "leaguegothic"; + src: url("../../fonts/leaguegothic.woff") format("woff"); } #login_body { - /* Set rules to fill background */ - min-height: 100%; - min-width: 1024px; - width: 100%; - z-index: -9999; - position: absolute; + /* Set rules to fill background */ + min-height: 100%; + min-width: 1024px; + width: 100%; + z-index: -9999; + position: absolute; } -@media screen and (max-width: 1024px) { /* Specific to this particular image */ - #login_body { - left: 50%; - margin-left: -512px; /* 50% */ - } +@media screen and (max-width: 1024px) { + /* Specific to this particular image */ + #login_body { + left: 50%; + margin-left: -512px; /* 50% */ + } } -@media screen and (max-width: 1100px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/fondo_madera_bn_1100.jpg"); - background-repeat: repeat; - background-position: center center; - } +@media screen and (max-width: 1100px) { + /* Specific to this particular image */ + #login_body { + background-image: url("../../images/backgrounds/fondo_madera_bn_1100.jpg"); + background-repeat: repeat; + background-position: center center; + } } -@media screen and (max-width: 1400px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/fondo_madera_bn_1400.jpg"); - background-repeat: repeat; - background-position: center center; - } +@media screen and (max-width: 1400px) { + /* Specific to this particular image */ + #login_body { + background-image: url("../../images/backgrounds/fondo_madera_bn_1400.jpg"); + background-repeat: repeat; + background-position: center center; + } } -@media screen and (max-width: 2000px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/fondo_madera_bn_2000.jpg"); - background-repeat: repeat; - background-position: center center; - } +@media screen and (max-width: 2000px) { + /* Specific to this particular image */ + #login_body { + background-image: url("../../images/backgrounds/fondo_madera_bn_2000.jpg"); + background-repeat: repeat; + background-position: center center; + } } -@media screen and (min-width: 2000px) { /* Specific to this particular image */ - #login_body { - background-image: url("../../images/backgrounds/fondo_madera_bn_2500.jpg"); - background-repeat: repeat; - background-position: center center; - } +@media screen and (min-width: 2000px) { + /* Specific to this particular image */ + #login_body { + background-image: url("../../images/backgrounds/fondo_madera_bn_2500.jpg"); + background-repeat: repeat; + background-position: center center; + } } p.log_in { - color: #FFF !important; - padding: 0px 10px; - width:300px; + color: #fff !important; + padding: 0px 10px; + width: 300px; } h1#log_f { - color: #c00; - border-bottom: 1px solid #c00; - padding-bottom: 3px; + color: #c00; + border-bottom: 1px solid #c00; + padding-bottom: 3px; } div#login { - border-width: 2px 2px 2px 2px; - border-style: solid; - border-color: #000; - font-size: 12px !important; + border-width: 2px 2px 2px 2px; + border-style: solid; + border-color: #000; + font-size: 12px !important; } -div#login_in, #login_f { - /*margin: 0 auto 0 140px; +div#login_in, +#login_f { + /*margin: 0 auto 0 140px; width: 400px;*/ } -.databox_login, .databox_logout { - border-radius: 5px; - height: 200px; +.databox_login, +.databox_logout { + border-radius: 5px; + height: 200px; } #login_inner { - width: 100%; - height: 100%; - border-radius: 5px; - /* Browser without multibackground support */ - background-color: #373737 !important; - + width: 100%; + height: 100%; + border-radius: 5px; + /* Browser without multibackground support */ + background-color: #373737 !important; } #login_outer { - border-radius: 11px; - background-color: #000; - width: 500px !important; - color: #FFF !important; - margin: 0px auto; + border-radius: 11px; + background-color: #000; + width: 500px !important; + color: #fff !important; + margin: 0px auto; } -.version_login{ - transform: rotate(36deg); - /* Old browser support */ - -ms-transform: rotate(36deg); /* IE */ - -moz-transform: rotate(36deg); /* FF */ - -o-transform: rotate(36deg); /* Opera */ - -webkit-transform: rotate(36deg); /* Safari and Chrome */ - - float: right; - margin-top: 18px; - width: 80px; - height: 0px; - border-right: 13px solid transparent; - border-left: 25px solid transparent; - border-bottom: 18px solid #80ab51; - left: 16px; - position: relative; -} +.version_login { + transform: rotate(36deg); + /* Old browser support */ + -ms-transform: rotate(36deg); /* IE */ + -moz-transform: rotate(36deg); /* FF */ + -o-transform: rotate(36deg); /* Opera */ + -webkit-transform: rotate(36deg); /* Safari and Chrome */ + float: right; + margin-top: 18px; + width: 80px; + height: 0px; + border-right: 13px solid transparent; + border-left: 25px solid transparent; + border-bottom: 18px solid #80ab51; + left: 16px; + position: relative; +} #login_outer * { - font-family: Nunito, "Arial Rounded MT", Arial, Helvetica, sans-serif; - font-weight: bold; + font-family: Nunito, "Arial Rounded MT", Arial, Helvetica, sans-serif; + font-weight: bold; } -.login_border{ - border-right: 1px solid #FFF; - text-align: center; +.login_border { + border-right: 1px solid #fff; + text-align: center; } table#login_layout { - width: 100%; - height: 160px; - position:absolute; + width: 100%; + height: 160px; + position: absolute; } div#error_login { - text-align: center; - margin-top: 5px; - margin-left: 5px; - width: 75%; - float: right; - text-align: left; - top: 100px; + text-align: center; + margin-top: 5px; + margin-left: 5px; + width: 75%; + float: right; + text-align: left; + top: 100px; } div#error_login_icon { - #margin: 0 auto; - margin-top: 10px; - margin-right: 7px; - text-align: center; - #margin-left: 20px; - width: 20%; - float: right; + #margin: 0 auto; + margin-top: 10px; + margin-right: 7px; + text-align: center; + #margin-left: 20px; + width: 20%; + float: right; } div#login_f { - margin-top: 10px; - margin-bottom: 25px; + margin-top: 10px; + margin-bottom: 25px; } -a:focus, input:focus, button:focus { - utline-width: 0; - outline: 0; +a:focus, +input:focus, +button:focus { + utline-width: 0; + outline: 0; } -DIV.login_links { - margin: 10px 0px 0px; - color: #FFF; - text-align: center; +div.login_links { + margin: 10px 0px 0px; + color: #fff; + text-align: center; } -DIV.login_links>a { - color: #FFF; +div.login_links > a { + color: #fff; } -DIV.login_button{ - text-align:right; - width: 100%; - margin-top: 15px; +div.login_button { + text-align: right; + width: 100%; + margin-top: 15px; } -DIV.login_button>input{ - background-color: #373737 !important; - border: 0px none; - background-image: url("../../images/input_go.png") !important; - padding-right: 25px !important; +div.login_button > input { + background-color: #373737 !important; + border: 0px none; + background-image: url("../../images/input_go.png") !important; + padding-right: 25px !important; } -.login_page{ - height: 200px; - padding-top: 10%; - text-align: center; - width: 100%; - position: absolute; +.login_page { + height: 200px; + padding-top: 10%; + text-align: center; + width: 100%; + position: absolute; } input.next_login { - padding-right: 12px !important; - padding-left: 12px !important; - height: 23px; - text-align: center; - font-weight: 600 !important; - letter-spacing: 0.5pt; - font-size: 12px !important; - border-radius: 3px !important; + padding-right: 12px !important; + padding-left: 12px !important; + height: 23px; + text-align: center; + font-weight: 600 !important; + letter-spacing: 0.5pt; + font-size: 12px !important; + border-radius: 3px !important; } -DIV.login_nick, DIV.login_pass { - text-align:left; - padding-left: 15px; - margin-top: 10px; +div.login_nick, +div.login_pass { + text-align: left; + padding-left: 15px; + margin-top: 10px; } -DIV.login_nick>input, DIV.login_pass>input { - height: 20px; - border-radius:0px; - margin-left: 10px; +div.login_nick > input, +div.login_pass > input { + height: 20px; + border-radius: 0px; + margin-left: 10px; } -DIV.login_nick>input:focus,DIV.login_pass>input:focus { - outline-width: 0px; - border-color: #80ab51; - background-color: #80ab51; - font-size: 12px; - height: 20px; - box-shadow: 0px 0px 3px 3px #80ab51; +div.login_nick > input:focus, +div.login_pass > input:focus { + outline-width: 0px; + border-color: #80ab51; + background-color: #80ab51; + font-size: 12px; + height: 20px; + box-shadow: 0px 0px 3px 3px #80ab51; } -DIV.login_nick>img, DIV.login_pass>img { - vertical-align: middle; +div.login_nick > img, +div.login_pass > img { + vertical-align: middle; } -DIV.login_links a { - letter-spacing: 0.8pt; +div.login_links a { + letter-spacing: 0.8pt; } -DIV.login_links a:first-child { - margin-right: 5px; +div.login_links a:first-child { + margin-right: 5px; } -DIV.login_links a:last-child { - margin-left: 5px; +div.login_links a:last-child { + margin-left: 5px; } -DIV.login_nick_text { - text-align: left; - margin-bottom: 3px; - width: 191px; - margin: 5px 0px; - font-size: 12px; - letter-spacing: 0.4pt; +div.login_nick_text { + text-align: left; + margin-bottom: 3px; + width: 191px; + margin: 5px 0px; + font-size: 12px; + letter-spacing: 0.4pt; } -DIV.login_pass_text { - text-align: left; - width: 191px; - margin: 13px 0px 5px 0px; - font-size: 12px; - letter-spacing: 0.4pt; +div.login_pass_text { + text-align: left; + width: 191px; + margin: 13px 0px 5px 0px; + font-size: 12px; + letter-spacing: 0.4pt; } -DIV.login_pass { +div.login_pass { } input.login { - border: 0px none; - margin: 0px 0px; - width: 135px; - height: 18px; - font-weight: 100 !important; + border: 0px none; + margin: 0px 0px; + width: 135px; + height: 18px; + font-weight: 100 !important; - letter-spacing: 0.3pt; + letter-spacing: 0.3pt; } input.login_user { - /* Browser without multibackground support */ - color: #373737 !important; - padding-left: 8px; - width: 179px; - color: #222; - height: 18px; + /* Browser without multibackground support */ + color: #373737 !important; + padding-left: 8px; + width: 179px; + color: #222; + height: 18px; } input.login_password { - /* Browser without multibackground support */ - padding-left: 8px; - width: 179px; - color: #222; - height: 20px; + /* Browser without multibackground support */ + padding-left: 8px; + width: 179px; + color: #222; + height: 20px; } .databox_error { - width: 657px !important; - height: 400px; - border: none !important; - background-color: #fafafa; - background: url(../../images/splash_error.png) no-repeat; + width: 657px !important; + height: 400px; + border: none !important; + background-color: #fafafa; + background: url(../../images/splash_error.png) no-repeat; } #ver_num { - margin: 0px auto; - width: 100%; - position: absolute; - bottom: 10px; - color: #FFF; - text-align: center; + margin: 0px auto; + width: 100%; + position: absolute; + bottom: 10px; + color: #fff; + text-align: center; } input:-webkit-autofill { - #-webkit-box-shadow: 0 0 0px 1000px #DDD inset; + #-webkit-box-shadow: 0 0 0px 1000px #ddd inset; } /***********************/ /* END OF LOGIN STYLES */ /***********************/ th > label { - padding-top: 7px; + padding-top: 7px; } input.chk { - margin-right: 0px; - border: 0px none; - height: 14px; + margin-right: 0px; + border: 0px none; + height: 14px; } input.datos { - background-color: #f5f5f5; + background-color: #f5f5f5; } input.datos_readonly { - background-color: #050505; + background-color: #050505; } input.sub { - font-weight: normal; + font-weight: normal; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; - border-radius: 2px; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; + border-radius: 2px; - font-size: 8pt; + font-size: 8pt; - background-color: #333 !important; - background-repeat: no-repeat !important; - background-position: 92% 3px !important; + background-color: #333 !important; + background-repeat: no-repeat !important; + background-position: 92% 3px !important; - color: white !important; - padding: 3px 3px 5px 12px; + color: white !important; + padding: 3px 3px 5px 12px; - border-color: #333; + border-color: #333; } input.sub[disabled] { - color: #B4B4B4 !important; - background-color: #F3F3F3 !important; - border-color: #B6B6B6; - cursor: default; + color: #b4b4b4 !important; + background-color: #f3f3f3 !important; + border-color: #b6b6b6; + cursor: default; } -input.next, input.upd, input.ok, input.wand, input.delete, input.cog, -input.target, input.search, input.copy, input.add, input.graph, -input.percentile, input.binary, input.camera, input.config, -input.cancel, input.default, input.filter, input.pdf { - padding-right: 30px; - height: 23px; - +input.next, +input.upd, +input.ok, +input.wand, +input.delete, +input.cog, +input.target, +input.search, +input.copy, +input.add, +input.graph, +input.percentile, +input.binary, +input.camera, +input.config, +input.cancel, +input.default, +input.filter, +input.pdf { + padding-right: 30px; + height: 23px; } input.next { - background-image: url(../../images/input_go.png) !important; + background-image: url(../../images/input_go.png) !important; } input.upd { - background-image: url(../../images/input_update.png) !important; + background-image: url(../../images/input_update.png) !important; } input.wand { - background-image: url(../../images/input_wand.png) !important; + background-image: url(../../images/input_wand.png) !important; } input.wand:disabled { - background-image: url(../../images/input_wand.disabled.png) !important; + background-image: url(../../images/input_wand.disabled.png) !important; } input.search { - background-image: url(../../images/input_zoom.png) !important; + background-image: url(../../images/input_zoom.png) !important; } input.search:disabled { - background-image: url(../../images/input_zoom.disabled.png) !important; + background-image: url(../../images/input_zoom.disabled.png) !important; } input.ok { - background-image: url(../../images/input_tick.png) !important; + background-image: url(../../images/input_tick.png) !important; } input.ok:disabled { - background-image: url(../../images/input_tick.disabled.png) !important; + background-image: url(../../images/input_tick.disabled.png) !important; } input.add { - background-image: url(../../images/input_add.png) !important; + background-image: url(../../images/input_add.png) !important; } input.add:disabled { - background-image: url(../../images/input_add.disabled.png) !important; + background-image: url(../../images/input_add.disabled.png) !important; } input.cancel { - background-image: url(../../images/input_cross.png) !important; + background-image: url(../../images/input_cross.png) !important; } input.cancel:disabled { - background-image: url(../../images/input_cross.disabled.png) !important; + background-image: url(../../images/input_cross.disabled.png) !important; } input.delete { - background-image: url(../../images/input_delete.png) !important; + background-image: url(../../images/input_delete.png) !important; } input.delete:disabled { - background-image: url(../../images/input_delete.disabled.png) !important; + background-image: url(../../images/input_delete.disabled.png) !important; } input.cog { - background-image: url(../../images/input_cog.png) !important; + background-image: url(../../images/input_cog.png) !important; } input.cog:disabled { - background-image: url(../../images/input_cog.disabled.png) !important; + background-image: url(../../images/input_cog.disabled.png) !important; } input.config { - background-image: url(../../images/input_config.png) !important; + background-image: url(../../images/input_config.png) !important; } input.config:disabled { - background-image: url(../../images/input_config.disabled.png) !important; + background-image: url(../../images/input_config.disabled.png) !important; } input.filter { - background-image: url(../../images/input_filter.png) !important; + background-image: url(../../images/input_filter.png) !important; } input.filter:disabled { - background-image: url(../../images/input_filter.disabled.png) !important; + background-image: url(../../images/input_filter.disabled.png) !important; } input.pdf { - background-image: url(../../images/input_pdf.png) !important; + background-image: url(../../images/input_pdf.png) !important; } input.pdf:disabled { - background-image: url(../../images/input_pdf.disabled.png) !important; + background-image: url(../../images/input_pdf.disabled.png) !important; } input.camera { - background-image: url(../../images/input_camera.png) !important; + background-image: url(../../images/input_camera.png) !important; } #toolbox #auto_save { - padding-top: 5px; + padding-top: 5px; } #toolbox { - margin-top: 13px; + margin-top: 13px; } input.visual_editor_button_toolbox { - padding-right: 15px; - padding-top: 10px; - margin-top:5px; + padding-right: 15px; + padding-top: 10px; + margin-top: 5px; } input.delete_min { - background: #fefefe url(../../images/cross.png) no-repeat center !important; + background: #fefefe url(../../images/cross.png) no-repeat center !important; } input.delete_min[disabled] { - background: #fefefe url(../../images/cross.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/cross.disabled.png) no-repeat center !important; } input.graph_min { - background: #fefefe url(../../images/chart_curve.png) no-repeat center !important; + background: #fefefe url(../../images/chart_curve.png) no-repeat center !important; } input.graph_min[disabled] { - background: #fefefe url(../../images/chart_curve.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/chart_curve.disabled.png) no-repeat + center !important; } input.percentile_min { - background: #fefefe url(../../images/chart_bar.png) no-repeat center !important; + background: #fefefe url(../../images/chart_bar.png) no-repeat center !important; } input.percentile_min[disabled] { - background: #fefefe url(../../images/chart_bar.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/chart_bar.disabled.png) no-repeat center !important; } input.percentile_item_min { - background: #fefefe url(../../images/percentile_item.png) no-repeat center !important; + background: #fefefe url(../../images/percentile_item.png) no-repeat center !important; } input.percentile_item_min[disabled] { - background: #fefefe url(../../images/percentile_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/percentile_item.disabled.png) no-repeat + center !important; } input.binary_min { - background: #fefefe url(../../images/binary.png) no-repeat center !important; + background: #fefefe url(../../images/binary.png) no-repeat center !important; } input.binary_min[disabled] { - background: #fefefe url(../../images/binary.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/binary.disabled.png) no-repeat center !important; } input.camera_min { - background: #fefefe url(../../images/camera.png) no-repeat center !important; + background: #fefefe url(../../images/camera.png) no-repeat center !important; } input.camera_min[disabled] { - background: #fefefe url(../../images/camera.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/camera.disabled.png) no-repeat center !important; } input.config_min { - background: #fefefe url(../../images/config.png) no-repeat center !important; + background: #fefefe url(../../images/config.png) no-repeat center !important; } input.config_min[disabled] { - background: #fefefe url(../../images/config.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/config.disabled.png) no-repeat center !important; } input.label_min { - background: #fefefe url(../../images/tag_red.png) no-repeat center !important; + background: #fefefe url(../../images/tag_red.png) no-repeat center !important; } input.label_min[disabled] { - background: #fefefe url(../../images/tag_red.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/tag_red.disabled.png) no-repeat center !important; } input.icon_min { - background: #fefefe url(../../images/photo.png) no-repeat center !important; + background: #fefefe url(../../images/photo.png) no-repeat center !important; } input.icon_min[disabled] { - background: #fefefe url(../../images/photo.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/photo.disabled.png) no-repeat center !important; } input.box_item { - background: #fefefe url(../../images/box_item.png) no-repeat center !important; + background: #fefefe url(../../images/box_item.png) no-repeat center !important; } input.box_item[disabled] { - background: #fefefe url(../../images/box_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/box_item.disabled.png) no-repeat center !important; } input.line_item { - background: #fefefe url(../../images/line_item.png) no-repeat center !important; + background: #fefefe url(../../images/line_item.png) no-repeat center !important; } input.line_item[disabled] { - background: #fefefe url(../../images/line_item.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/line_item.disabled.png) no-repeat center !important; } input.copy_item { - background: #fefefe url(../../images/copy_visualmap.png) no-repeat center !important; + background: #fefefe url(../../images/copy_visualmap.png) no-repeat center !important; } input.copy_item[disabled] { - background: #fefefe url(../../images/copy_visualmap.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/copy_visualmap.disabled.png) no-repeat + center !important; } input.grid_min { - background: #fefefe url(../../images/grid.png) no-repeat center !important; + background: #fefefe url(../../images/grid.png) no-repeat center !important; } input.grid_min[disabled] { - background: #fefefe url(../../images/grid.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/grid.disabled.png) no-repeat center !important; } input.save_min { - background: #fefefe url(../../images/file.png) no-repeat center !important; + background: #fefefe url(../../images/file.png) no-repeat center !important; } input.save_min[disabled] { - background: #fefefe url(../../images/file.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/file.disabled.png) no-repeat center !important; } input.service_min { - background: #fefefe url(../../images/box.png) no-repeat center !important; + background: #fefefe url(../../images/box.png) no-repeat center !important; } input.service_min[disabled] { - background: #fefefe url(../../images/box.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/box.disabled.png) no-repeat center !important; } input.group_item_min { - background: #fefefe url(../../images/group_green.png) no-repeat center !important; + background: #fefefe url(../../images/group_green.png) no-repeat center !important; } input.group_item_min[disabled] { - background: #fefefe url(../../images/group_green.disabled.png) no-repeat center !important; + background: #fefefe url(../../images/group_green.disabled.png) no-repeat + center !important; } div#cont { - position: fixed; - max-height: 320px; - overflow-y: auto; - overflow-x: hidden; + position: fixed; + max-height: 320px; + overflow-y: auto; + overflow-x: hidden; } -.termframe{ - background-color: #80BA27 !important; +.termframe { + background-color: #80ba27 !important; } -table, img { - border: 0px; +table, +img { + border: 0px; } -tr:first-child>th { - background-color: #373737; +tr:first-child > th { + background-color: #373737; } th { - color: #fff; - background-color: #666; - font-size: 7.5pt; - letter-spacing: 0.3pt; + color: #fff; + background-color: #666; + font-size: 7.5pt; + letter-spacing: 0.3pt; } -tr.datos, tr.datost, tr.datosb , tr.datos_id, +tr.datos, +tr.datost, +tr.datosb, +tr.datos_id, tr.datosf9 { - #background-color: #eaeaea; + #background-color: #eaeaea; } -tr.datos2, tr.datos2t, -tr.datos2b, tr.datos2_id , tr.datos2f9 { - #background-color: #f2f2f2; +tr.datos2, +tr.datos2t, +tr.datos2b, +tr.datos2_id, +tr.datos2f9 { + #background-color: #f2f2f2; } -tr.datos:hover, tr.datost:hover, tr.datosb:hover, tr.datos_id:hover, -tr.datosf9:hover, tr.datos2:hover, tr.datos2t:hover, -tr.datos2b:hover, tr.datos2_id:hover, tr.datos2f9:hover { - #background-color: #efefef; +tr.datos:hover, +tr.datost:hover, +tr.datosb:hover, +tr.datos_id:hover, +tr.datosf9:hover, +tr.datos2:hover, +tr.datos2t:hover, +tr.datos2b:hover, +tr.datos2_id:hover, +tr.datos2f9:hover { + #background-color: #efefef; } /* Checkbox styles */ -td input[type=checkbox] -{ +td input[type="checkbox"] { /* Double-sized Checkboxes */ -ms-transform: scale(1.3); /* IE */ -moz-transform: scale(1.3); /* FF */ @@ -974,213 +1020,255 @@ td input[type=checkbox] display: table-cell; } -td.datos3, td.datos3 * { - background-color: #666; - color: white !important; +td.datos3, +td.datos3 * { + background-color: #666; + color: white !important; } -td.datos4, td.datos4 * { - /*Add !important because in php the function html_print_table write style in cell and this is style head.*/ - text-align: center !important; - background-color: #666; - color: white !important; +td.datos4, +td.datos4 * { + /*Add !important because in php the function html_print_table write style in cell and this is style head.*/ + text-align: center !important; + background-color: #666; + color: white !important; } td.datos_id { - color: #1a313a; + color: #1a313a; } tr.disabled_row_user * { - color: grey; + color: grey; } -.bg { /* op menu */ - background: #80ab51; +.bg { + /* op menu */ + background: #80ab51; } -.bg2 { /* main page */ - background-color: #0A160C; +.bg2 { + /* main page */ + background-color: #0a160c; } -.bg3 { /* godmode */ - background: #666666; +.bg3 { + /* godmode */ + background: #666666; } -.bg4 { /* links */ - background-color: #989898; +.bg4 { + /* links */ + background-color: #989898; } -.bg, .bg2, .bg3, .bg4 { - position: relative; - width: 100%; +.bg, +.bg2, +.bg3, +.bg4 { + position: relative; + width: 100%; } .bg { - height: 20px; + height: 20px; } -.bg2, .bg3, .bg4 { - height: 18px; +.bg2, +.bg3, +.bg4 { + height: 18px; } -.f10, #ip { - font-size: 7pt; - text-align: center; +.f10, +#ip { + font-size: 7pt; + text-align: center; } -.f9, .f9i, .f9b, .datos_greyf9, .datos_bluef9, .datos_greenf9, -.datos_redf9, .datos_yellowf9, td.f9, td.f9i, td.datosf9, td.datos2f9 { - font-size: 6.5pt; +.f9, +.f9i, +.f9b, +.datos_greyf9, +.datos_bluef9, +.datos_greenf9, +.datos_redf9, +.datos_yellowf9, +td.f9, +td.f9i, +td.datosf9, +td.datos2f9 { + font-size: 6.5pt; } -.f9i, .redi { - font-style: italic; +.f9i, +.redi { + font-style: italic; } .tit { - padding: 6px 0px; - height: 14px; + padding: 6px 0px; + height: 14px; } -.tit, .titb { - font-weight: bold; - color: #fff; - text-align: center; +.tit, +.titb { + font-weight: bold; + color: #fff; + text-align: center; } .suc * { - color: #5a8629; + color: #5a8629; } -.info *{ - color: #006F9D; +.info * { + color: #006f9d; } -.error *{ - color: #f85858; +.error * { + color: #f85858; } -.warning *{ - color: #FAD403; +.warning * { + color: #fad403; } .help { - background: url(../../images/help.png) no-repeat; + background: url(../../images/help.png) no-repeat; } -.red, .redb, .redi, .error { - color: #c00; +.red, +.redb, +.redi, +.error { + color: #c00; } .sep { - margin-left: 30px; - border-bottom: 1px solid #708090; - width: 100%; + margin-left: 30px; + border-bottom: 1px solid #708090; + width: 100%; } .orange { - color: #fd7304; + color: #fd7304; } .green { - color: #5a8629; + color: #5a8629; } .yellow { - color: #F3C500; + color: #f3c500; } .greenb { - color: #00aa00; + color: #00aa00; } .grey { - color: #808080; - font-weight: bold; + color: #808080; + font-weight: bold; } .blue { - color: #5AB7E5; - font-weight: bold; + color: #5ab7e5; + font-weight: bold; } -.redb, .greenb, td.datos_id, td.datos2_id, f9b { - font-weight: bold; +.redb, +.greenb, +td.datos_id, +td.datos2_id, +f9b { + font-weight: bold; } .p10 { - padding-top: 1px; - padding-bottom: 0px; + padding-top: 1px; + padding-bottom: 0px; } .p21 { - padding-top: 2px; - padding-bottom: 1px; + padding-top: 2px; + padding-bottom: 1px; } .w120 { - width: 120px; + width: 120px; } -.w130, #table-agent-configuration select { - width: 130px; +.w130, +#table-agent-configuration select { + width: 130px; } .w135 { - width: 135px; + width: 135px; } -.w155, #table_layout_data select { - width: 155px; +.w155, +#table_layout_data select { + width: 155px; } -.top, .top_red, .bgt, td.datost, td.datos2t { - vertical-align: top; +.top, +.top_red, +.bgt, +td.datost, +td.datos2t { + vertical-align: top; } .top_red { - background: #ff0000; + background: #ff0000; } -.bot, .titb, td.datosb { - vertical-align: bottom; +.bot, +.titb, +td.datosb { + vertical-align: bottom; } .msg { - margin-top: 15px; - text-align: justify; + margin-top: 15px; + text-align: justify; } ul.mn { - list-style: none; - padding: 0px 0px 0px 0px; - margin: 0px 0px 0px 0px; - line-height: 15px; + list-style: none; + padding: 0px 0px 0px 0px; + margin: 0px 0px 0px 0px; + line-height: 15px; } .gr { - font-size: 10pt; - font-weight: bold; + font-size: 10pt; + font-weight: bold; } -a.mn, .gr { - font-family: Arial, Verdana, sans-serif, Helvetica; +a.mn, +.gr { + font-family: Arial, Verdana, sans-serif, Helvetica; } div.nf { - background: url(../../images/info.png) no-repeat scroll 0 50% transparent; - margin-left: 7px; - padding: 8px 1px 6px 25px; + background: url(../../images/info.png) no-repeat scroll 0 50% transparent; + margin-left: 7px; + padding: 8px 1px 6px 25px; } div.title_line { - background-color: #4e682c; - height: 5px; - width: 762px; + background-color: #4e682c; + height: 5px; + width: 762px; } .alpha50 { - filter:alpha(opacity=50); - -moz-opacity: 0.5; - opacity: 0.5; - -khtml-opacity: 0.5; + filter: alpha(opacity=50); + -moz-opacity: 0.5; + opacity: 0.5; + -khtml-opacity: 0.5; } - -#menu_tab_frame, #menu_tab_frame_view { - display: block !important; - border-bottom: 1px solid #80BA27; -/* float:left; */ - margin-left: 0px !important; - max-height: 42px; - min-height: 42px; - padding-right: 28px; - width: 100%; +#menu_tab_frame, +#menu_tab_frame_view { + display: block !important; + border-bottom: 1px solid #80ba27; + /* float:left; */ + margin-left: 0px !important; + max-height: 42px; + min-height: 42px; + padding-right: 28px; + width: 100%; } #menu_tab { - margin: 0px 0px 0px 0px !important; - position: absolute; - right: 0px; - top: 10px; + margin: 0px 0px 0px 0px !important; + position: absolute; + right: 0px; + top: 10px; } -#menu_tab .mn, #menu_tab ul, #menu_tab .mn ul { - padding: 0px; - list-style: none; - margin: 0px 0px 0px 0px; +#menu_tab .mn, +#menu_tab ul, +#menu_tab .mn ul { + padding: 0px; + list-style: none; + margin: 0px 0px 0px 0px; } #menu_tab .mn li { - float: right; - position: relative; - margin: 0px 0px 0px 0px; + float: right; + position: relative; + margin: 0px 0px 0px 0px; } /* #menu_tab li a, #menu_tab a { @@ -1206,463 +1294,494 @@ div.title_line { */ #menu_tab li.separator_view { - padding: 4px; + padding: 4px; } #menu_tab li.separator { - padding: 4px; + padding: 4px; } #menu_tab li.nomn_high a { - /*background: #80ab51;*/ - color: #fff; + /*background: #80ab51;*/ + color: #fff; } #menu_tab .mn li a { - display: block; - text-decoration: none; - padding: 0px; - margin: 0px; - height: 21px; - width: 21px; + display: block; + text-decoration: none; + padding: 0px; + margin: 0px; + height: 21px; + width: 21px; } -#menu_tab li.nomn:hover a, #menu_tab li:hover ul a:hover { - /*background: #80ab51;*/ - color: #fff; +#menu_tab li.nomn:hover a, +#menu_tab li:hover ul a:hover { + /*background: #80ab51;*/ + color: #fff; } #menu_tab li:hover a { - /*background: #b2b08a url("../../images/arrow.png") no-repeat right 3px;*/ + /*background: #b2b08a url("../../images/arrow.png") no-repeat right 3px;*/ } #menu_tab li.nomn { - min-width: 30px; - height: 28px; + min-width: 30px; + height: 28px; } #menu_tab li.nomn_high { - min-width: 30px; - height: 28px; + min-width: 30px; + height: 28px; } /* TAB TITLE */ #menu_tab_left { - margin-left: 0px !important; + margin-left: 0px !important; } -#menu_tab_left .mn, #menu_tab_left ul, #menu_tab_left .mn ul { - background-color: #000; - color: #fff; - font-weight: bold; - padding: 0px 0px 0px 0px; - list-style: none; - margin: 0px 0px 0px 0px; +#menu_tab_left .mn, +#menu_tab_left ul, +#menu_tab_left .mn ul { + background-color: #000; + color: #fff; + font-weight: bold; + padding: 0px 0px 0px 0px; + list-style: none; + margin: 0px 0px 0px 0px; } #menu_tab_left .mn li { - float: left; - position: relative; - height: 26px; - max-height: 26px; + float: left; + position: relative; + height: 26px; + max-height: 26px; } -#menu_tab_left li a, #menu_tab_left li span { -/* text-transform: uppercase; */ - padding: 0px 0px 0px 0px; - color: #fff; - font-size: 8.5pt; - font-weight: bold; - line-height: 20px; +#menu_tab_left li a, +#menu_tab_left li span { + /* text-transform: uppercase; */ + padding: 0px 0px 0px 0px; + color: #fff; + font-size: 8.5pt; + font-weight: bold; + line-height: 20px; } #menu_tab_left .mn li a { - display: block; - text-decoration: none; + display: block; + text-decoration: none; } #menu_tab_left li.view a { - padding: 2px 10px 2px 10px; - color: #fff; - font-weight: bold; - line-height: 18px; - display: none; + padding: 2px 10px 2px 10px; + color: #fff; + font-weight: bold; + line-height: 18px; + display: none; } #menu_tab_left li.view { - background: #80ab51; - max-width: 100%; - min-width: 100%; - padding: 5px 5px 0px; - text-align: left; - -moz-border-top-right-radius: 3px; - -webkit-border-top-right-radius: 3px; - border-top-right-radius: 3px; + background: #80ab51; + max-width: 100%; + min-width: 100%; + padding: 5px 5px 0px; + text-align: left; + -moz-border-top-right-radius: 3px; + -webkit-border-top-right-radius: 3px; + border-top-right-radius: 3px; - -moz-border-top-left-radius: 3px; - -webkit-border-top-left-radius: 3px; - border-top-left-radius: 3px; - margin-left:0px !important; - overflow-y: hidden; + -moz-border-top-left-radius: 3px; + -webkit-border-top-left-radius: 3px; + border-top-left-radius: 3px; + margin-left: 0px !important; + overflow-y: hidden; } #menu_tab_left li.view img.bottom { - width: 24px; - height: 24px; + width: 24px; + height: 24px; } -#menu_tab_frame *, #menu_tab_frame_view *{ - #margin: 0px 0px 0px 0px !important; +#menu_tab_frame *, +#menu_tab_frame_view * { + #margin: 0px 0px 0px 0px !important; } span.users { - background: url(../../images/group.png) no-repeat; + background: url(../../images/group.png) no-repeat; } span.agents { - background: url(../../images/bricks.png) no-repeat; + background: url(../../images/bricks.png) no-repeat; } span.data { - background: url(../../images/data.png) no-repeat; + background: url(../../images/data.png) no-repeat; } span.alerts { - background: url(../../images/bell.png) no-repeat; + background: url(../../images/bell.png) no-repeat; } span.time { - background: url(../../images/hourglass.png) no-repeat; + background: url(../../images/hourglass.png) no-repeat; } span.net { - background: url(../../images/network.png) no-repeat; + background: url(../../images/network.png) no-repeat; } span.master { - background: url(../../images/master.png) no-repeat; + background: url(../../images/master.png) no-repeat; } span.wmi { - background: url(../../images/wmi.png) no-repeat; + background: url(../../images/wmi.png) no-repeat; } span.prediction { - background: url(../../images/chart_bar.png) no-repeat; + background: url(../../images/chart_bar.png) no-repeat; } span.plugin { - background: url(../../images/plugin.png) no-repeat; + background: url(../../images/plugin.png) no-repeat; } span.export { - background: url(../../images/database_refresh.png) no-repeat; + background: url(../../images/database_refresh.png) no-repeat; } span.snmp { - background: url(../../images/snmp.png) no-repeat; + background: url(../../images/snmp.png) no-repeat; } span.binary { - background: url(../../images/binary.png) no-repeat; + background: url(../../images/binary.png) no-repeat; } span.recon { - background: url(../../images/recon.png) no-repeat; + background: url(../../images/recon.png) no-repeat; } span.rmess { - background: url(../../images/email_open.png) no-repeat; + background: url(../../images/email_open.png) no-repeat; } span.nrmess { - background: url(../../images/email.png) no-repeat; + background: url(../../images/email.png) no-repeat; } span.recon_server { - background: url(../../images/recon.png) no-repeat; + background: url(../../images/recon.png) no-repeat; } span.wmi_server { - background: url(../../images/wmi.png) no-repeat; + background: url(../../images/wmi.png) no-repeat; } span.export_server { - background: url(../../images/server_export.png) no-repeat; + background: url(../../images/server_export.png) no-repeat; } span.inventory_server { - background: url(../../images/page_white_text.png) no-repeat; + background: url(../../images/page_white_text.png) no-repeat; } span.web_server { - background: url(../../images/world.png) no-repeat; + background: url(../../images/world.png) no-repeat; } /* This kind of span do not have any sense, should be replaced on PHP code by a real img in code. They are not useful because insert too much margin around (for example, not valid to use in the table of server view */ -span.users, span.agents, span.data, span.alerts, span.time, span.net, -span.master, span.snmp, span.binary, span.recon, span.wmi, span.prediction, -span.plugin, span.plugin, span.export, span.recon_server, span.wmi_server, -span.export_server, span.inventory_server, span.web_server { - margin-left: 4px; - margin-top: 10px; - padding: 4px 8px 12px 30px; - display: block; +span.users, +span.agents, +span.data, +span.alerts, +span.time, +span.net, +span.master, +span.snmp, +span.binary, +span.recon, +span.wmi, +span.prediction, +span.plugin, +span.plugin, +span.export, +span.recon_server, +span.wmi_server, +span.export_server, +span.inventory_server, +span.web_server { + margin-left: 4px; + margin-top: 10px; + padding: 4px 8px 12px 30px; + display: block; } -span.rmess, span.nrmess { - margin-left: 14px; - padding: 1px 0px 10px 30px; - display: block; +span.rmess, +span.nrmess { + margin-left: 14px; + padding: 1px 0px 10px 30px; + display: block; } /* New styles for data box */ -.databox, .databox_color, .databox_frame { - margin-bottom: 5px; - margin-top: 0px; - margin-left: 0px; - border: 1px solid #e2e2e2; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; - +.databox, +.databox_color, +.databox_frame { + margin-bottom: 5px; + margin-top: 0px; + margin-left: 0px; + border: 1px solid #e2e2e2; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + border-radius: 4px; } -.databox_color{ - padding-top: 5px; +.databox_color { + padding-top: 5px; } table.databox { - background-color: #f9faf9; - border-spacing: 0px; - -moz-box-shadow: 0px 0px 0px #DDD !important; - -webkit-box-shadow: 0px 0px 0px #DDD !important; - box-shadow: 0px 0px 0px #DDD !important; + background-color: #f9faf9; + border-spacing: 0px; + -moz-box-shadow: 0px 0px 0px #ddd !important; + -webkit-box-shadow: 0px 0px 0px #ddd !important; + box-shadow: 0px 0px 0px #ddd !important; } .databox td { - -moz-border-radius: 0px; - -webkit-border-radius: 0px; - border-radius: 0px; - border: 0px none #E2E2E2; + -moz-border-radius: 0px; + -webkit-border-radius: 0px; + border-radius: 0px; + border: 0px none #e2e2e2; } .databox th { - padding: 9px 7px; - font-weight: normal; - color: #fff; + padding: 9px 7px; + font-weight: normal; + color: #fff; } .databox td { - #border-bottom: 1px solid #E2E2E2; + #border-bottom: 1px solid #e2e2e2; } .databox th * { - color: #fff; + color: #fff; } -.databox th input, .databox th textarea, .databox th select, .databox th select option { - color: #222 !important; +.databox th input, +.databox th textarea, +.databox th select, +.databox th select option { + color: #222 !important; } .tabletitle { - color: #333; + color: #333; } -.tactical_set legend{ - text-align:left; - color: #3F3F3F; +.tactical_set legend { + text-align: left; + color: #3f3f3f; } -.tactical_set{ - background: #FFF; - border: 1px solid #E2E2E2; - margin-left: auto; - margin-right: auto; - width: auto; +.tactical_set { + background: #fff; + border: 1px solid #e2e2e2; + margin-left: auto; + margin-right: auto; + width: auto; } /* For use in Netflow */ table.databox_grid { - margin: 25px; + margin: 25px; } table.databox_grid th { - font-size: 12px; + font-size: 12px; } table.databox_grid td { - padding: 6px; - margin: 4px; - border-bottom: 1px solid #acacac; - border-right: 1px solid #acacac; + padding: 6px; + margin: 4px; + border-bottom: 1px solid #acacac; + border-right: 1px solid #acacac; } - -table.alternate tr:nth-child(odd) td{ - background-color: #ffffff; +table.alternate tr:nth-child(odd) td { + background-color: #ffffff; } -table.alternate tr:nth-child(even) td{ - background-color: #e4e5e4; +table.alternate tr:nth-child(even) td { + background-color: #e4e5e4; } table.rounded_cells td { - padding: 4px 4px 4px 10px; - -moz-border-radius: 6px !important; - -webkit-border-radius: 6px !important; - border-radius: 6px !important; + padding: 4px 4px 4px 10px; + -moz-border-radius: 6px !important; + -webkit-border-radius: 6px !important; + border-radius: 6px !important; } .databox_color { - background-color: #fafafa; + background-color: #fafafa; } #head_l { - float: left; - margin: 0; - padding: 0; + float: left; + margin: 0; + padding: 0; } #head_r { - float: right; - text-align: right; - margin-right: 10px; - padding-top: 0px; + float: right; + text-align: right; + margin-right: 10px; + padding-top: 0px; } #head_m { - position: absolute; - padding-top: 6px; - padding-left: 12em; + position: absolute; + padding-top: 6px; + padding-left: 12em; } span#logo_text1 { - font: bolder 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #eee; + font: bolder 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #eee; } span#logo_text2 { - font: 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #aaa; + font: 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #aaa; } div#logo_text3 { - text-align: right; - font: 2em Arial, Sans-serif; - letter-spacing: 6px; - color: #aaa; - font-weight: bold; - margin-top: 0px; - margin-left: 4px; - padding-top: 0px; + text-align: right; + font: 2em Arial, Sans-serif; + letter-spacing: 6px; + color: #aaa; + font-weight: bold; + margin-top: 0px; + margin-left: 4px; + padding-top: 0px; } .bb0 { - border-bottom: 0px; + border-bottom: 0px; } .bt0 { - border-top: 0px; + border-top: 0px; } .action-buttons { - text-align: right; + text-align: right; } -#table-add-item select, #table-add-sla select { - width: 180px; +#table-add-item select, +#table-add-sla select { + width: 180px; } /* end of classes for event priorities */ div#main_pure { - background-color: #fefefe; - text-align: left; - margin-bottom: 25px; - margin-top: 30px; - margin-left: 10px; - margin-right: 10px; - height: 1000px; - width: 98%; - position: static; + background-color: #fefefe; + text-align: left; + margin-bottom: 25px; + margin-top: 30px; + margin-left: 10px; + margin-right: 10px; + height: 1000px; + width: 98%; + position: static; } #table-agent-configuration radio { - margin-right: 40px; + margin-right: 40px; } .ui-draggable { - cursor:move; + cursor: move; } #layout_trash_drop { - float: right; - width: 300px; - height: 180px; - background: #fff url("../../images/trash.png") no-repeat bottom left; + float: right; + width: 300px; + height: 180px; + background: #fff url("../../images/trash.png") no-repeat bottom left; } #layout_trash_drop div { - display: block; + display: block; } #layout_editor_drop { - float: left; - width: 300px; + float: left; + width: 300px; } .agent_reporting { - margin: 5px; - padding: 5px; + margin: 5px; + padding: 5px; } -.report_table, .agent_reporting { - border: #CCC outset 3px; +.report_table, +.agent_reporting { + border: #ccc outset 3px; } .img_help { - cursor: help; + cursor: help; } #loading { - position:fixed; - width: 200px; - margin-left: 30%; - text-align:center; - top: 50%; - background-color: #999999; - padding: 20px; + position: fixed; + width: 200px; + margin-left: 30%; + text-align: center; + top: 50%; + background-color: #999999; + padding: 20px; } /* IE 7 Hack */ #editor { - *margin-top: 10px !important; + *margin-top: 10px !important; } /* big_data is used in tactical and logon_ok */ .big_data { - text-decoration: none; font: bold 2em Arial, Sans-serif; + text-decoration: none; + font: bold 2em Arial, Sans-serif; } .med_data { - text-decoration: none; font: bold 1.5em Arial, Sans-serif; + text-decoration: none; + font: bold 1.5em Arial, Sans-serif; } .notify { - background-color: #f7ffa5; - text-align: center; - font-weight: bold; - padding: 8px; - margin: 0px 0px 0px 0px !important; - z-index: -1; + background-color: #f7ffa5; + text-align: center; + font-weight: bold; + padding: 8px; + margin: 0px 0px 0px 0px !important; + z-index: -1; } .notify a { - color: #003a3a; - text-decoration: underline; + color: #003a3a; + text-decoration: underline; } .listing { - border-collapse: collapse; + border-collapse: collapse; } .listing td { - border-bottom: 1px solid #CCCCCC; - border-top: 1px solid #CCCCCC; + border-bottom: 1px solid #cccccc; + border-top: 1px solid #cccccc; } ul { - list-style-type: none; - padding-left: 0; - margin-left: 0; + list-style-type: none; + padding-left: 0; + margin-left: 0; } span.actions { - margin-left: 30px; + margin-left: 30px; } .actions { - min-width: 200px! important; + min-width: 200px !important; } -code, pre { - font-family: courier, serif; +code, +pre { + font-family: courier, serif; } -select#template, select#action { - width: 250px; +select#template, +select#action { + width: 250px; } #label-checkbox-matches_value, #label-checkbox-copy_modules, #label-checkbox-copy_alerts { - display: inline; - font-weight: normal; + display: inline; + font-weight: normal; } -input[type=image] { - border:0px; - background-color: transparent !important; +input[type="image"] { + border: 0px; + background-color: transparent !important; } table#simple select#id_module_type, table#alert_search select#id_agent, table#alert_search select#id_group, table#network_component select#type { - width: 200px; + width: 200px; } table#simple select#select_snmp_oid, table#simple select#id_plugin, table#network_component select#id_plugin { - width: 270px; + width: 270px; } table#simple select#prediction_id_group, table#simple select#prediction_id_agent, table#simple select#prediction_module { - width: 50%; - display: block; + width: 50%; + display: block; } table#simple input#text-plugin_parameter, table#simple input#text-snmp_oid, @@ -1672,1726 +1791,2001 @@ table#target_table select, table#filter_compound_table select, table#filter_compound_table #text-search, table#delete_table select { - width: 100%; + width: 100%; } table#simple select#network_component_group, table#simple select#network_component { - width: 90%; + width: 90%; } table#simple span#component_group, table#simple span#component { - width: 45%; - font-style: italic; + width: 45%; + font-style: italic; } table#simple label { - display: inline; - font-weight: normal; - font-style: italic; + display: inline; + font-weight: normal; + font-style: italic; } .clickable { - cursor: pointer; + cursor: pointer; } -table#agent_list tr, table.alert_list tr { - vertical-align: top; +table#agent_list tr, +table.alert_list tr { + vertical-align: top; +} +.toggle { + border-collapse: collapse; +} +.toggle td { + border-left: 1px solid #d3d3d3; } -.toggle { border-collapse: collapse;} -.toggle td { border-left: 1px solid #D3D3D3;} ul.actions_list { - list-style-image: url(../../images/arrow.png); - list-style-position: inside; - margin-top: 0; + list-style-image: url(../../images/arrow.png); + list-style-position: inside; + margin-top: 0; } div.loading { - background-color: #FFF1A8; - margin-left: auto; - margin-right: auto; - padding: 5px; - text-align: center; - font-style: italic; - width: 95%; + background-color: #fff1a8; + margin-left: auto; + margin-right: auto; + padding: 5px; + text-align: center; + font-style: italic; + width: 95%; } div.loading img { - float: right; + float: right; } /* Tablesorter jQuery pager */ div.pager { - margin-left: 10px; - margin-top: 5px; + margin-left: 10px; + margin-top: 5px; } -div.pager img{ - position: relative; - top: 4px; - padding-left: 5px; +div.pager img { + position: relative; + top: 4px; + padding-left: 5px; } div.pager input { - padding-left: 5px; + padding-left: 5px; } .pagedisplay { - border: 0; - width: 35px; + border: 0; + width: 35px; } /* Steps style */ ol.steps { - margin-bottom: 15px; - padding: 0; - list-style-type: none; - list-style-position: outside; + margin-bottom: 15px; + padding: 0; + list-style-type: none; + list-style-position: outside; } ol.steps li { - float: left; - background-color: #efefef; - padding: 5px; - margin-left: 5px; - width: 150px; + float: left; + background-color: #efefef; + padding: 5px; + margin-left: 5px; + width: 150px; } ol.steps li a { - color: #111; + color: #111; } ol.steps li.visited a { - color: #999; + color: #999; } ol.steps li span { - font-weight: normal; - display: block; + font-weight: normal; + display: block; } ol.steps li span { - color: #777; + color: #777; } ol.steps li.visited span { - color: #999; + color: #999; } ol.steps li.current { - border-left: 5px solid #778866; - margin-left: 0; - font-weight: bold; - background-color: #E9F3D2; + border-left: 5px solid #778866; + margin-left: 0; + font-weight: bold; + background-color: #e9f3d2; } ol.steps li.visited { - color: #999 !important; + color: #999 !important; } fieldset { - background-color:#F9FAF9; - border: 1px solid #E2E2E2; - padding:0.5em; - margin-bottom:20px; - position:relative; + background-color: #f9faf9; + border: 1px solid #e2e2e2; + padding: 0.5em; + margin-bottom: 20px; + position: relative; } fieldset legend { - font-size:1.1em; - font-weight:bold; - #color:#3f4e2f; - line-height: 20px; - color: #3F3F3F; - #top:-2em; + font-size: 1.1em; + font-weight: bold; + #color: #3f4e2f; + line-height: 20px; + color: #3f3f3f; + #top: -2em; } fieldset .databox { - border: 0px solid; + border: 0px solid; } fieldset.databox { - padding: 14px !important; + padding: 14px !important; } fieldset legend span, span#latest_value { - font-style:italic; + font-style: italic; } span#latest_value span#value { - font-style:normal; + font-style: normal; } form#filter_form { - margin-bottom: 15px; + margin-bottom: 15px; } ul.action_list { - margin: 0; - list-style: none inside circle; + margin: 0; + list-style: none inside circle; } ul.action_list li div { - margin-left: 15px; + margin-left: 15px; } span.action_name { - float: none; + float: none; } div.actions_container { - overflow:auto; - width: 100%; - max-height: 200px; + overflow: auto; + width: 100%; + max-height: 200px; } div.actions_container label { - display: inline; - font-weight: normal; - font-style: italic; + display: inline; + font-weight: normal; + font-style: italic; } a.add_action { - clear: both; - display: block; + clear: both; + display: block; } /* timeEntry styles */ .timeEntry_control { - vertical-align: middle; - margin-left: 2px; + vertical-align: middle; + margin-left: 2px; } div#steps_clean { - clear:both; + clear: both; } div#event_control { - clear:right; + clear: right; } /* Autocomplete styles */ .ac_results { - padding: 0px; - border: 1px solid black; - background-color: white; - overflow: hidden; - z-index: 99999; + padding: 0px; + border: 1px solid black; + background-color: white; + overflow: hidden; + z-index: 99999; } .ac_results ul { - width: 100%; - list-style-position: outside; - list-style: none; - padding: 0; - margin: 0; - text-align: left; + width: 100%; + list-style-position: outside; + list-style: none; + padding: 0; + margin: 0; + text-align: left; } .ac_results li { - margin: 0px; - padding: 2px 5px; - cursor: default; - display: block; - /* + margin: 0px; + padding: 2px 5px; + cursor: default; + display: block; + /* if width will be 100% horizontal scrollbar will apear when scroll mode will be used */ - /*width: 100%;*/ - font: menu; - font-size: 12px; - /* + /*width: 100%;*/ + font: menu; + font-size: 12px; + /* it is very important, if line-height not setted or setted in relative units scroll will be broken in firefox */ - line-height: 16px; + line-height: 16px; } .ac_loading { - background: white url('../images/loading.gif') right center no-repeat; + background: white url("../images/loading.gif") right center no-repeat; } .ac_over { - background-color: #efefef; + background-color: #efefef; } span.ac_extra_field, span.ac_extra_field strong { - font-style: italic; - font-size: 9px; + font-style: italic; + font-size: 9px; } - div#pandora_logo_header { -/* Put here your company logo (139x60 pixels) like this: */ -/* background: url(../../images/MiniLogoArtica.jpg); */ - background: url(../../images/pandora_logo_head.png); - background-position: 0% 0%; - width: 139px; - height: 60px; - float: left; + /* Put here your company logo (139x60 pixels) like this: */ + /* background: url(../../images/MiniLogoArtica.jpg); */ + background: url(../../images/pandora_logo_head.png); + background-position: 0% 0%; + width: 139px; + height: 60px; + float: left; } #header_table img { - margin-top: 0px; + margin-top: 0px; } .autorefresh_disabled { - cursor: not-allowed !important; + cursor: not-allowed !important; } a.autorefresh { - padding-right: 8px; + padding-right: 8px; } #refrcounter { - color: white; + color: white; } #combo_refr select { - margin-right: 8px; + margin-right: 8px; } .disabled_module { - color: #aaa; + color: #aaa; } div.warn { - background: url(../../images/info.png) no-repeat; - margin-top: 7px; - padding: 2px 1px 6px 25px; + background: url(../../images/info.png) no-repeat; + margin-top: 7px; + padding: 2px 1px 6px 25px; } .submenu_not_selected { - font-weight: normal !important; + font-weight: normal !important; } /* Submenus havent borders */ -.submenu_not_selected, .submenu_selected, .submenu2 { - border: 0px !important; - min-height: 35px !important; +.submenu_not_selected, +.submenu_selected, +.submenu2 { + border: 0px !important; + min-height: 35px !important; } /* Pandora width style theme */ div#container { - width: 100%; + width: 100%; } div#page { - width: auto; + width: auto; } div#main { - max-width: 93%; - min-width: 93%; + max-width: 93%; + min-width: 93%; } ol.steps { - margin-bottom: 70px; + margin-bottom: 70px; } div#steps_clean { - display:none; + display: none; } -#menu_tab_frame, #menu_tab_frame_view { - width: 100%; - padding-right: 0px; - margin-left: 0px !important; - margin-bottom: 20px; - height: 31px; +#menu_tab_frame, +#menu_tab_frame_view { + width: 100%; + padding-right: 0px; + margin-left: 0px !important; + margin-bottom: 20px; + height: 31px; } div#events_list { - float: left; - width: 100%; + float: left; + width: 100%; } span#logo_text1 { - font: bolder 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #eee; + font: bolder 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #eee; } span#logo_text2 { - font: 3em Arial, Sans-serif; - letter-spacing: -2px; - color: #aaa; + font: 3em Arial, Sans-serif; + letter-spacing: -2px; + color: #aaa; } div#logo_text3 { - text-align: right; - font: 2em Arial, Sans-serif; - letter-spacing: 6px; - color: #aaa; - font-weight: bold; - margin-top: 0px; - margin-left: 4px; - padding-top: 0px; + text-align: right; + font: 2em Arial, Sans-serif; + letter-spacing: 6px; + color: #aaa; + font-weight: bold; + margin-top: 0px; + margin-left: 4px; + padding-top: 0px; } .pagination { - margin-top: 15px; - margin-bottom: 5px; + margin-top: 15px; + margin-bottom: 5px; } .pagination * { - margin-left: 0px !important; - margin-right: 0px !important; - vertical-align: middle; + margin-left: 0px !important; + margin-right: 0px !important; + vertical-align: middle; } /*CALENDAR TOOLTIP STYLE*/ /* Calendar background */ table.scw { - background-color: #80ab51; - border: 0 !important; - border-radius: 4px; + background-color: #80ab51; + border: 0 !important; + border-radius: 4px; } /* Week number heading */ td.scwWeekNumberHead { - color: #111; + color: #111; } td.scwWeek { - color: #111 !important; + color: #111 !important; } - Today selector -td.scwFoot { - background-color: #daedae; - color: #111; +Today selector td.scwFoot { + background-color: #daedae; + color: #111; } td.scwFootDisabled { - background-color: #000; - color: #FFFFFF; + background-color: #000; + color: #ffffff; } tfoot.scwFoot { - color: #111; + color: #111; } -.scwFoot :hover{ - color: #3F3F3F !important; +.scwFoot :hover { + color: #3f3f3f !important; } table.scwCells { - background-color: #fff !important; - color: #3c3c3c !important; + background-color: #fff !important; + color: #3c3c3c !important; } table.scwCells:hover { - background-color: #fff !important; + background-color: #fff !important; } td.scwCellsExMonth { - background-color: #eee !important; - color: #3c3c3c !important; + background-color: #eee !important; + color: #3c3c3c !important; } td.scwCellsWeekend { - background-color: #3c3c3c !important; - color: #fff !important; - border: 0 !important; + background-color: #3c3c3c !important; + color: #fff !important; + border: 0 !important; } td.scwInputDate { - background-color: #777 !important; - color: #ffffff !important; - border: 0 !important; + background-color: #777 !important; + color: #ffffff !important; + border: 0 !important; } td.scwFoot { - background-color: #fff !important; - color: #3c3c3c !important; - border: 0 !important; + background-color: #fff !important; + color: #3c3c3c !important; + border: 0 !important; } - - /* Cells divs to set individual styles with the table objects */ div.cellBold { - width: 100%; - height: 100%; - font-weight: bold; + width: 100%; + height: 100%; + font-weight: bold; } div.cellRight { - width: 100%; - height: 100%; - text-align: right; + width: 100%; + height: 100%; + text-align: right; } div.cellCenter { - width:100%; - height:100%; - text-align:center; + width: 100%; + height: 100%; + text-align: center; } div.cellWhite { - width: 100%; - height: 100%; - background: #fff; - color: #111; + width: 100%; + height: 100%; + background: #fff; + color: #111; } div.cellNormal { - width: 100%; - height: 100%; - background: #6EB432; - color: #fff; + width: 100%; + height: 100%; + background: #6eb432; + color: #fff; } div.cellCritical { - width: 100%; - height: 100%; - background: #f85858; - color: #fff; + width: 100%; + height: 100%; + background: #f85858; + color: #fff; } div.cellWarning { - width: 100%; - height: 100%; - background: #ffea59; - color: #111; + width: 100%; + height: 100%; + background: #ffea59; + color: #111; } div.cellUnknown { - width: 100%; - height: 100%; - background: #AAAAAA; - color: #FFFFFF; + width: 100%; + height: 100%; + background: #aaaaaa; + color: #ffffff; } div.cellNotInit { - width: 100%; - height: 100%; - background: #3BA0FF; - color: #FFFFFF; + width: 100%; + height: 100%; + background: #3ba0ff; + color: #ffffff; } div.cellAlert { - width: 100%; - height: 100%; - background: #FF8800; - color: #111; + width: 100%; + height: 100%; + background: #ff8800; + color: #111; } div.cellBorder1 { - width: 100%; - height: 100%; - border: 1px solid #666; + width: 100%; + height: 100%; + border: 1px solid #666; } div.cellBig { - width: 100%; - height: 100%; - font-size: 18px; + width: 100%; + height: 100%; + font-size: 18px; } .info_box { - background: #F9FAF9; - margin-top: 10px !important; - margin-bottom: 10px !important; - padding: 0px 5px 5px 10px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; - width: 100% !important; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; + background: #f9faf9; + margin-top: 10px !important; + margin-bottom: 10px !important; + padding: 0px 5px 5px 10px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; + width: 100% !important; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + border-radius: 4px; } .info_box .title * { - font-size: 10pt !important; - font-weight: bolder; + font-size: 10pt !important; + font-weight: bolder; } .info_box .icon { - width: 30px !important; - text-align: center; + width: 30px !important; + text-align: center; } /* Standard styles for status colos (groups, events, backgrounds...) */ .opacity_cell { - filter:alpha(opacity=80); - -moz-opacity: 0.8; - opacity: 0.8; - -khtml-opacity: 0.8; + filter: alpha(opacity=80); + -moz-opacity: 0.8; + opacity: 0.8; + -khtml-opacity: 0.8; } - -tr.group_view_data, .group_view_data { - color: #3F3F3F; +tr.group_view_data, +.group_view_data { + color: #3f3f3f; } -tr.group_view_crit, .group_view_crit { - background-color: #FC4444; - color: #fff; +tr.group_view_crit, +.group_view_crit { + background-color: #fc4444; + color: #fff; } -tr.group_view_norm, .group_view_norm, tr.group_view_normal, .group_view_normal { - #background-color: #ffffff; +tr.group_view_norm, +.group_view_norm, +tr.group_view_normal, +.group_view_normal { + #background-color: #ffffff; } -tr.group_view_ok, .group_view_ok { - background-color: #80BA27; - color: #fff; +tr.group_view_ok, +.group_view_ok { + background-color: #80ba27; + color: #fff; } -tr.group_view_not_init, .group_view_not_init, tr.group_view_not_init, .group_view_not_init { - background-color: #5BB6E5; - color: #fff !important; +tr.group_view_not_init, +.group_view_not_init, +tr.group_view_not_init, +.group_view_not_init { + background-color: #5bb6e5; + color: #fff !important; } -tr.group_view_warn, .group_view_warn, tr.group_view_warn.a, a.group_view_warn, tr.a.group_view_warn { - background-color: #FAD403; - color: #3F3F3F !important; +tr.group_view_warn, +.group_view_warn, +tr.group_view_warn.a, +a.group_view_warn, +tr.a.group_view_warn { + background-color: #fad403; + color: #3f3f3f !important; } a.group_view_warn { - color: #FAD403 !important; + color: #fad403 !important; } -tr.group_view_alrm, .group_view_alrm { - background-color: #FFA631; - color: #FFF; +tr.group_view_alrm, +.group_view_alrm { + background-color: #ffa631; + color: #fff; } -tr.group_view_unk, .group_view_unk { - background-color: #B2B2B2 ; - color: #fff; +tr.group_view_unk, +.group_view_unk { + background-color: #b2b2b2; + color: #fff; } /* classes for event priorities. Sits now in functions.php */ -.datos_green, .datos_greenf9, .datos_green a, .datos_greenf9 a, .datos_green * { - background-color: #80BA27; - color: #fff; +.datos_green, +.datos_greenf9, +.datos_green a, +.datos_greenf9 a, +.datos_green * { + background-color: #80ba27; + color: #fff; } -.datos_red, .datos_redf9, .datos_red a, .datos_redf9 a, .datos_red *{ - background-color: #FC4444; - color: #fff !important; +.datos_red, +.datos_redf9, +.datos_red a, +.datos_redf9 a, +.datos_red * { + background-color: #fc4444; + color: #fff !important; } -.datos_yellow, .datos_yellowf9, .datos_yellow * { - background-color: #FAD403; - color: #111; +.datos_yellow, +.datos_yellowf9, +.datos_yellow * { + background-color: #fad403; + color: #111; } -a.datos_blue, .datos_bluef9, .datos_blue, .datos_blue * { - background-color: #4CA8E0; - color: #fff !important; +a.datos_blue, +.datos_bluef9, +.datos_blue, +.datos_blue * { + background-color: #4ca8e0; + color: #fff !important; } -.datos_grey, .datos_greyf9, .datos_grey * { - background-color: #999999; - color: #fff; +.datos_grey, +.datos_greyf9, +.datos_grey * { + background-color: #999999; + color: #fff; } -.datos_pink, .datos_pinkf9, .datos_pink * { - background-color: #fdc4ca; - color: #111; +.datos_pink, +.datos_pinkf9, +.datos_pink * { + background-color: #fdc4ca; + color: #111; } -.datos_brown, .datos_brownf9, .datos_brown * { - background-color: #A67C52; - color: #fff; +.datos_brown, +.datos_brownf9, +.datos_brown * { + background-color: #a67c52; + color: #fff; } -.datos_orange, .datos_orangef9, .datos_orange * { - background-color: #F7931E; - color: #111; +.datos_orange, +.datos_orangef9, +.datos_orange * { + background-color: #f7931e; + color: #111; } -td.datos_greyf9, td.datos_bluef9, td.datos_greenf9, td.datos_redf9, td.datos_yellowf9, td.datos_pinkf9, td.datos_brownf9 ,td.datos_orangef9 { - padding: 5px 5px 5px 5px; +td.datos_greyf9, +td.datos_bluef9, +td.datos_greenf9, +td.datos_redf9, +td.datos_yellowf9, +td.datos_pinkf9, +td.datos_brownf9, +td.datos_orangef9 { + padding: 5px 5px 5px 5px; } .menu li.selected { - font-weight: bold; + font-weight: bold; } -ul.operation li a:hover { - #font-weight: bold; +ul.operation li a:hover { + #font-weight: bold; } - - .submenu_text { - color: #fff; + color: #fff; } .submenu_not_selected { - color: #fff !important; + color: #fff !important; } .operation .menu_icon:hover { - background-color: #d9fb86 !important; + background-color: #d9fb86 !important; } .operation .submenu_text:hover { - color: #585858 !important; + color: #585858 !important; } .operation .submenu_not_selected:hover { - background-color: #d9fb86 !important; - color: #585858 !important; + background-color: #d9fb86 !important; + color: #585858 !important; } .operation .submenu_selected:hover { - background-color: #d9fb86 !important; - color: #585858 !important; + background-color: #d9fb86 !important; + color: #585858 !important; } .operation .sub_subMenu:hover { - background-color: #d9fb86 !important; - color: #585858 !important; + background-color: #d9fb86 !important; + color: #585858 !important; } .operation .selected .submenu_not_selected * { - color: #fff !important; + color: #fff !important; } .operation .selected .submenu_not_selected *:hover { - color: #585858 !important; + color: #585858 !important; } .operation { - background-color: #80ab51 !important; + background-color: #80ab51 !important; } .operation .selected { - background-color: #d9fb86 !important; + background-color: #d9fb86 !important; } .operation li.selected { - box-shadow: inset 4px 0 #80ab51; + box-shadow: inset 4px 0 #80ab51; } .operation .selected .submenu_text_middle { - color: #585858; + color: #585858; } .operation .submenu_selected .selected .submenu_text { - color: #585858; + color: #585858; } .operation .submenu_selected .selected { - color: #585858; + color: #585858; } - - .godmode .menu_icon:hover { - background-color: #A77853 !important; + background-color: #a77853 !important; } .godmode .submenu_text:hover { - color: #3f3f3f !important; + color: #3f3f3f !important; } .godmode .submenu_not_selected:hover { - background-color: #A77853 !important; - color: #2f2f2f !important; + background-color: #a77853 !important; + color: #2f2f2f !important; } .godmode .submenu_selected:hover { - background-color: #A77853 !important; - color: #2f2f2f !important; + background-color: #a77853 !important; + color: #2f2f2f !important; } .godmode .sub_subMenu:hover { - background-color: #A77853 !important; - color: #2f2f2f !important; + background-color: #a77853 !important; + color: #2f2f2f !important; } .godmode .selected .submenu_not_selected * { - color: #fff !important; + color: #fff !important; } .godmode .selected .submenu_not_selected *:hover { - color: #2f2f2f !important; + color: #2f2f2f !important; } .godmode { - background-color: #e79b5d !important; + background-color: #e79b5d !important; } .godmode .selected { - background-color: #A77853 !important; + background-color: #a77853 !important; } .godmode li.selected { - box-shadow: inset 4px 0 #e79b5d; + box-shadow: inset 4px 0 #e79b5d; } .godmode .selected .submenu_text_middle { - color: #2f2f2f; + color: #2f2f2f; } .godmode .submenu_selected .selected .submenu_text { - color: #2f2f2f; + color: #2f2f2f; } .godmode .submenu_selected .selected { - color: #2f2f2f; + color: #2f2f2f; } - - -li.links a:hover { - #font-weight: bold; +li.links a:hover { + #font-weight: bold; } .is_submenu2 li { - background-color: #ff0000; + background-color: #ff0000; } .is_submenu2 { - background-color: #222222 !important; + background-color: #222222 !important; } - - - - - -.menu li, .menu .li.not_selected { - border-radius: 0px 0px 0px 0px; - display: block; - min-height: 35px; - border-bottom: 0px none #424242; - vertical-align: middle; +.menu li, +.menu .li.not_selected { + border-radius: 0px 0px 0px 0px; + display: block; + min-height: 35px; + border-bottom: 0px none #424242; + vertical-align: middle; } #menu_tab li.separator { - /* Empty */ + /* Empty */ } .operation { - border-top-right-radius: 5px; - border-right-style: solid; - border-right-width: 0px; - + border-top-right-radius: 5px; + border-right-style: solid; + border-right-width: 0px; } -input#text-id_parent.ac_input, input, textarea, select { - background-color: #ffffff !important; - border: 1px solid #cbcbcb; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; +input#text-id_parent.ac_input, +input, +textarea, +select { + background-color: #ffffff !important; + border: 1px solid #cbcbcb; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; } span#plugin_description { - font-size: 9px; + font-size: 9px; } /*FOR TINYMCE*/ #tinymce { - text-align: left; + text-align: left; } -.visual_font_size_4pt, .visual_font_size_4pt > em, .visual_font_size_4pt > strong, .visual_font_size_4pt > strong > span, .visual_font_size_4pt > span, .visual_font_size_4pt > strong > em, .visual_font_size_4pt > em > strong, .visual_font_size_4pt em span, .visual_font_size_4pt span em { - font-size: 4pt !important; - line-height: 4pt; +.visual_font_size_4pt, +.visual_font_size_4pt > em, +.visual_font_size_4pt > strong, +.visual_font_size_4pt > strong > span, +.visual_font_size_4pt > span, +.visual_font_size_4pt > strong > em, +.visual_font_size_4pt > em > strong, +.visual_font_size_4pt em span, +.visual_font_size_4pt span em { + font-size: 4pt !important; + line-height: 4pt; } -.visual_font_size_6pt, .visual_font_size_6pt > em, .visual_font_size_6pt > strong, .visual_font_size_6pt > strong > span, .visual_font_size_6pt > span, .visual_font_size_6pt > strong > em, .visual_font_size_6pt > em > strong, .visual_font_size_6pt em span, .visual_font_size_6pt span em { - font-size: 6pt !important; - line-height: 6pt; +.visual_font_size_6pt, +.visual_font_size_6pt > em, +.visual_font_size_6pt > strong, +.visual_font_size_6pt > strong > span, +.visual_font_size_6pt > span, +.visual_font_size_6pt > strong > em, +.visual_font_size_6pt > em > strong, +.visual_font_size_6pt em span, +.visual_font_size_6pt span em { + font-size: 6pt !important; + line-height: 6pt; } -.visual_font_size_8pt, .visual_font_size_8pt > em, .visual_font_size_8pt > strong, .visual_font_size_8pt > strong > span , .visual_font_size_8pt > span, .visual_font_size_8pt > strong > em, .visual_font_size_8pt > em > strong, .visual_font_size_8pt em span, .visual_font_size_8pt span em { - font-size: 8pt !important; - line-height: 8pt; +.visual_font_size_8pt, +.visual_font_size_8pt > em, +.visual_font_size_8pt > strong, +.visual_font_size_8pt > strong > span, +.visual_font_size_8pt > span, +.visual_font_size_8pt > strong > em, +.visual_font_size_8pt > em > strong, +.visual_font_size_8pt em span, +.visual_font_size_8pt span em { + font-size: 8pt !important; + line-height: 8pt; } -.visual_font_size_10pt, .visual_font_size_10pt > em , .visual_font_size_10pt > strong, .visual_font_size_10pt > strong > em, .visual_font_size_10pt > em > strong, .visual_font_size_10pt em span, .visual_font_size_10pt span em { - font-size: 10pt !important; - line-height: 10pt; +.visual_font_size_10pt, +.visual_font_size_10pt > em, +.visual_font_size_10pt > strong, +.visual_font_size_10pt > strong > em, +.visual_font_size_10pt > em > strong, +.visual_font_size_10pt em span, +.visual_font_size_10pt span em { + font-size: 10pt !important; + line-height: 10pt; } -.visual_font_size_12pt, .visual_font_size_12pt > em , .visual_font_size_12pt > strong, .visual_font_size_12pt > strong > em, .visual_font_size_12pt > em > strong, .visual_font_size_12pt em span, .visual_font_size_12pt span em { - font-size: 12pt !important; - line-height: 12pt; +.visual_font_size_12pt, +.visual_font_size_12pt > em, +.visual_font_size_12pt > strong, +.visual_font_size_12pt > strong > em, +.visual_font_size_12pt > em > strong, +.visual_font_size_12pt em span, +.visual_font_size_12pt span em { + font-size: 12pt !important; + line-height: 12pt; } -.visual_font_size_14pt, .visual_font_size_14pt > em , .visual_font_size_14pt > strong, .visual_font_size_14pt > strong > span, .visual_font_size_14pt > span, .visual_font_size_14pt > strong > em, .visual_font_size_14pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 14pt !important; - line-height: 14pt; +.visual_font_size_14pt, +.visual_font_size_14pt > em, +.visual_font_size_14pt > strong, +.visual_font_size_14pt > strong > span, +.visual_font_size_14pt > span, +.visual_font_size_14pt > strong > em, +.visual_font_size_14pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 14pt !important; + line-height: 14pt; } -.visual_font_size_18pt, .visual_font_size_18pt > em , .visual_font_size_18pt > strong, .visual_font_size_18pt > strong > span, .visual_font_size_18pt > span, .visual_font_size_18pt > strong > em, .visual_font_size_18pt > em > strong, .visual_font_size_18pt em span, .visual_font_size_18pt span em { - font-size: 18pt !important; - line-height: 18pt; +.visual_font_size_18pt, +.visual_font_size_18pt > em, +.visual_font_size_18pt > strong, +.visual_font_size_18pt > strong > span, +.visual_font_size_18pt > span, +.visual_font_size_18pt > strong > em, +.visual_font_size_18pt > em > strong, +.visual_font_size_18pt em span, +.visual_font_size_18pt span em { + font-size: 18pt !important; + line-height: 18pt; } -.visual_font_size_24pt, .visual_font_size_24pt > em, .visual_font_size_24pt > strong, .visual_font_size_24pt > strong > span , .visual_font_size_24pt > span, .visual_font_size_24pt > strong > em, .visual_font_size_24pt > em > strong, .visual_font_size_24pt em span, .visual_font_size_24pt span em { - font-size: 24pt !important; - line-height: 24pt; +.visual_font_size_24pt, +.visual_font_size_24pt > em, +.visual_font_size_24pt > strong, +.visual_font_size_24pt > strong > span, +.visual_font_size_24pt > span, +.visual_font_size_24pt > strong > em, +.visual_font_size_24pt > em > strong, +.visual_font_size_24pt em span, +.visual_font_size_24pt span em { + font-size: 24pt !important; + line-height: 24pt; } -.visual_font_size_28pt, .visual_font_size_28pt > em, .visual_font_size_28pt > strong, .visual_font_size_28pt > strong > span , .visual_font_size_28pt > span, .visual_font_size_28pt > strong > em, .visual_font_size_28pt > em > strong, .visual_font_size_28pt em span, .visual_font_size_28pt span em { - font-size: 28pt !important; - line-height: 28pt; +.visual_font_size_28pt, +.visual_font_size_28pt > em, +.visual_font_size_28pt > strong, +.visual_font_size_28pt > strong > span, +.visual_font_size_28pt > span, +.visual_font_size_28pt > strong > em, +.visual_font_size_28pt > em > strong, +.visual_font_size_28pt em span, +.visual_font_size_28pt span em { + font-size: 28pt !important; + line-height: 28pt; } -.visual_font_size_36pt, .visual_font_size_36pt > em, .visual_font_size_36pt > strong, .visual_font_size_36pt > strong > span, .visual_font_size_36pt > span, .visual_font_size_36pt > strong > em, .visual_font_size_36pt > em > strong, .visual_font_size_36pt em span, .visual_font_size_36pt span em { - font-size: 36pt !important; - line-height: 36pt; +.visual_font_size_36pt, +.visual_font_size_36pt > em, +.visual_font_size_36pt > strong, +.visual_font_size_36pt > strong > span, +.visual_font_size_36pt > span, +.visual_font_size_36pt > strong > em, +.visual_font_size_36pt > em > strong, +.visual_font_size_36pt em span, +.visual_font_size_36pt span em { + font-size: 36pt !important; + line-height: 36pt; } -.visual_font_size_48pt, .visual_font_size_48pt > em, .visual_font_size_48pt > strong, .visual_font_size_48pt > strong > span, .visual_font_size_48pt > span, .visual_font_size_48pt > strong > em, .visual_font_size_48pt > em > strong, .visual_font_size_48pt em span, .visual_font_size_48pt span em { - font-size: 48pt !important; - line-height: 48pt; +.visual_font_size_48pt, +.visual_font_size_48pt > em, +.visual_font_size_48pt > strong, +.visual_font_size_48pt > strong > span, +.visual_font_size_48pt > span, +.visual_font_size_48pt > strong > em, +.visual_font_size_48pt > em > strong, +.visual_font_size_48pt em span, +.visual_font_size_48pt span em { + font-size: 48pt !important; + line-height: 48pt; } -.visual_font_size_60pt, .visual_font_size_60pt > em, .visual_font_size_60pt > strong, .visual_font_size_60pt > strong > span, .visual_font_size_60pt > span, .visual_font_size_60pt > strong > em, .visual_font_size_60pt > em > strong, .visual_font_size_60pt em span, .visual_font_size_60pt span em { - font-size: 60pt !important; - line-height: 60pt; +.visual_font_size_60pt, +.visual_font_size_60pt > em, +.visual_font_size_60pt > strong, +.visual_font_size_60pt > strong > span, +.visual_font_size_60pt > span, +.visual_font_size_60pt > strong > em, +.visual_font_size_60pt > em > strong, +.visual_font_size_60pt em span, +.visual_font_size_60pt span em { + font-size: 60pt !important; + line-height: 60pt; } -.visual_font_size_72pt, .visual_font_size_72pt > em, .visual_font_size_72pt > strong, .visual_font_size_72pt > strong > span, .visual_font_size_72pt > span, .visual_font_size_72pt > strong > em, .visual_font_size_72pt > em > strong, .visual_font_size_72pt em span, .visual_font_size_72pt span em { - font-size: 72pt !important; - line-height: 72pt; +.visual_font_size_72pt, +.visual_font_size_72pt > em, +.visual_font_size_72pt > strong, +.visual_font_size_72pt > strong > span, +.visual_font_size_72pt > span, +.visual_font_size_72pt > strong > em, +.visual_font_size_72pt > em > strong, +.visual_font_size_72pt em span, +.visual_font_size_72pt span em { + font-size: 72pt !important; + line-height: 72pt; } -.visual_font_size_84pt, .visual_font_size_84pt > em, .visual_font_size_84pt > strong, .visual_font_size_84pt > strong > span, .visual_font_size_84pt > span, .visual_font_size_84pt > strong > em, .visual_font_size_84pt > em > strong, .visual_font_size_84pt em span, .visual_font_size_84pt span em { - font-size: 84pt !important; - line-height: 84pt; +.visual_font_size_84pt, +.visual_font_size_84pt > em, +.visual_font_size_84pt > strong, +.visual_font_size_84pt > strong > span, +.visual_font_size_84pt > span, +.visual_font_size_84pt > strong > em, +.visual_font_size_84pt > em > strong, +.visual_font_size_84pt em span, +.visual_font_size_84pt span em { + font-size: 84pt !important; + line-height: 84pt; } -.visual_font_size_96pt, .visual_font_size_96pt > em, .visual_font_size_96pt > strong, .visual_font_size_96pt > strong > span, .visual_font_size_96pt > span, .visual_font_size_96pt > strong > em, .visual_font_size_96pt > em > strong, .visual_font_size_96pt em span, .visual_font_size_96pt span em { - font-size: 96pt !important; - line-height: 96pt; +.visual_font_size_96pt, +.visual_font_size_96pt > em, +.visual_font_size_96pt > strong, +.visual_font_size_96pt > strong > span, +.visual_font_size_96pt > span, +.visual_font_size_96pt > strong > em, +.visual_font_size_96pt > em > strong, +.visual_font_size_96pt em span, +.visual_font_size_96pt span em { + font-size: 96pt !important; + line-height: 96pt; } -.visual_font_size_116pt, .visual_font_size_116pt > em, .visual_font_size_116pt > strong, .visual_font_size_116pt > strong > span, .visual_font_size_116pt > span, .visual_font_size_116pt > strong > em, .visual_font_size_116pt > em > strong, .visual_font_size_116pt em span, .visual_font_size_116pt span em { - font-size: 116pt !important; - line-height: 116pt; +.visual_font_size_116pt, +.visual_font_size_116pt > em, +.visual_font_size_116pt > strong, +.visual_font_size_116pt > strong > span, +.visual_font_size_116pt > span, +.visual_font_size_116pt > strong > em, +.visual_font_size_116pt > em > strong, +.visual_font_size_116pt em span, +.visual_font_size_116pt span em { + font-size: 116pt !important; + line-height: 116pt; } -.visual_font_size_128pt, .visual_font_size_128pt > em, .visual_font_size_128pt > strong, .visual_font_size_128pt > strong > span, .visual_font_size_128pt > span, .visual_font_size_128pt > strong > em, .visual_font_size_128pt > em > strong, .visual_font_size_128pt em span, .visual_font_size_128pt span em { - font-size: 128pt !important; - line-height: 128pt; +.visual_font_size_128pt, +.visual_font_size_128pt > em, +.visual_font_size_128pt > strong, +.visual_font_size_128pt > strong > span, +.visual_font_size_128pt > span, +.visual_font_size_128pt > strong > em, +.visual_font_size_128pt > em > strong, +.visual_font_size_128pt em span, +.visual_font_size_128pt span em { + font-size: 128pt !important; + line-height: 128pt; } -.visual_font_size_140pt, .visual_font_size_140pt > em, .visual_font_size_140pt > strong, .visual_font_size_140pt > strong > span, .visual_font_size_140pt > span, .visual_font_size_140pt > strong > em, .visual_font_size_140pt > em > strong, .visual_font_size_140pt em span, .visual_font_size_140pt span em { - font-size: 140pt !important; - line-height: 140pt; +.visual_font_size_140pt, +.visual_font_size_140pt > em, +.visual_font_size_140pt > strong, +.visual_font_size_140pt > strong > span, +.visual_font_size_140pt > span, +.visual_font_size_140pt > strong > em, +.visual_font_size_140pt > em > strong, +.visual_font_size_140pt em span, +.visual_font_size_140pt span em { + font-size: 140pt !important; + line-height: 140pt; } -.visual_font_size_154pt, .visual_font_size_154pt > em, .visual_font_size_154pt > strong, .visual_font_size_154pt > strong > span, .visual_font_size_154pt > span, .visual_font_size_154pt > strong > em, .visual_font_size_154pt > em > strong, .visual_font_size_154pt em span, .visual_font_size_154pt span em { - font-size: 154pt !important; - line-height: 154pt; +.visual_font_size_154pt, +.visual_font_size_154pt > em, +.visual_font_size_154pt > strong, +.visual_font_size_154pt > strong > span, +.visual_font_size_154pt > span, +.visual_font_size_154pt > strong > em, +.visual_font_size_154pt > em > strong, +.visual_font_size_154pt em span, +.visual_font_size_154pt span em { + font-size: 154pt !important; + line-height: 154pt; } -.visual_font_size_196pt, .visual_font_size_196pt > em, .visual_font_size_196pt > strong, .visual_font_size_196pt > strong > span, .visual_font_size_196pt > span, .visual_font_size_196pt > strong > em, .visual_font_size_196pt > em > strong, .visual_font_size_196pt em span, .visual_font_size_196pt span em { - font-size: 196pt !important; - line-height: 196pt; +.visual_font_size_196pt, +.visual_font_size_196pt > em, +.visual_font_size_196pt > strong, +.visual_font_size_196pt > strong > span, +.visual_font_size_196pt > span, +.visual_font_size_196pt > strong > em, +.visual_font_size_196pt > em > strong, +.visual_font_size_196pt em span, +.visual_font_size_196pt span em { + font-size: 196pt !important; + line-height: 196pt; } - - -.resize_visual_font_size_8pt, .resize_visual_font_size_8pt > em, .resize_visual_font_size_8pt > strong, .resize_visual_font_size_8pt > strong > span, .resize_visual_font_size_8pt > span, .resize_visual_font_size_8pt > strong > em, .resize_visual_font_size_8pt > em > strong, .visual_font_size_8pt em span, .visual_font_size_8pt span em { - font-size: 4pt !important; - line-height: 4pt; +.resize_visual_font_size_8pt, +.resize_visual_font_size_8pt > em, +.resize_visual_font_size_8pt > strong, +.resize_visual_font_size_8pt > strong > span, +.resize_visual_font_size_8pt > span, +.resize_visual_font_size_8pt > strong > em, +.resize_visual_font_size_8pt > em > strong, +.visual_font_size_8pt em span, +.visual_font_size_8pt span em { + font-size: 4pt !important; + line-height: 4pt; } -.resize_visual_font_size_14pt, .resize_visual_font_size_14pt > em , .resize_visual_font_size_14pt > strong, .resize_visual_font_size_14pt > strong > span, .resize_visual_font_size_14pt > span, .resize_visual_font_size_14pt > strong > em, .resize_visual_font_size_14pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 7pt !important; - line-height: 7pt; +.resize_visual_font_size_14pt, +.resize_visual_font_size_14pt > em, +.resize_visual_font_size_14pt > strong, +.resize_visual_font_size_14pt > strong > span, +.resize_visual_font_size_14pt > span, +.resize_visual_font_size_14pt > strong > em, +.resize_visual_font_size_14pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 7pt !important; + line-height: 7pt; } -.resize_visual_font_size_24pt, .resize_visual_font_size_24pt > em, .resize_visual_font_size_24pt > strong, .resize_visual_font_size_24pt > strong > span, .resize_visual_font_size_24pt > span, .resize_visual_font_size_24pt > strong > em, .resize_visual_font_size_24pt > em > strong, .visual_font_size_14pt em span, .visual_font_size_14pt span em { - font-size: 12pt !important; - line-height: 12pt; +.resize_visual_font_size_24pt, +.resize_visual_font_size_24pt > em, +.resize_visual_font_size_24pt > strong, +.resize_visual_font_size_24pt > strong > span, +.resize_visual_font_size_24pt > span, +.resize_visual_font_size_24pt > strong > em, +.resize_visual_font_size_24pt > em > strong, +.visual_font_size_14pt em span, +.visual_font_size_14pt span em { + font-size: 12pt !important; + line-height: 12pt; } -.resize_visual_font_size_36pt, .resize_visual_font_size_36pt > em, .resize_visual_font_size_36pt > strong, .resize_visual_font_size_36pt > strong > span, .resize_visual_font_size_36pt > span, .resize_visual_font_size_36pt > strong > em, .resize_visual_font_size_36pt > em > strong, .visual_font_size_36pt em span, .visual_font_size_36pt span em { - font-size: 18pt !important; - line-height: 18pt; +.resize_visual_font_size_36pt, +.resize_visual_font_size_36pt > em, +.resize_visual_font_size_36pt > strong, +.resize_visual_font_size_36pt > strong > span, +.resize_visual_font_size_36pt > span, +.resize_visual_font_size_36pt > strong > em, +.resize_visual_font_size_36pt > em > strong, +.visual_font_size_36pt em span, +.visual_font_size_36pt span em { + font-size: 18pt !important; + line-height: 18pt; } -.resize_visual_font_size_72pt, .resize_visual_font_size_72pt > em, .resize_visual_font_size_72pt > strong, .resize_visual_font_size_72pt > strong > span, .resize_visual_font_size_72pt > span, .resize_visual_font_size_72pt > strong > em, .resize_visual_font_size_72pt > em > strong, .visual_font_size_72pt em span, .visual_font_size_72pt span em { - font-size: 36pt !important; - line-height: 36pt; +.resize_visual_font_size_72pt, +.resize_visual_font_size_72pt > em, +.resize_visual_font_size_72pt > strong, +.resize_visual_font_size_72pt > strong > span, +.resize_visual_font_size_72pt > span, +.resize_visual_font_size_72pt > strong > em, +.resize_visual_font_size_72pt > em > strong, +.visual_font_size_72pt em span, +.visual_font_size_72pt span em { + font-size: 36pt !important; + line-height: 36pt; } /*SIDEBAR*/ .menu_sidebar { - color:#111; - background: #3f3f3f; + color: #111; + background: #3f3f3f; - margin-left: 10px; - padding-left: 0px; - padding-right: 0px; - padding-top: 10px; - text-align: left; - font-family:arial,sans-serif,verdana; - font-size:10px; - border:1px solid #000; - position:absolute; - margin:0; - width:400px; - height:260px; + margin-left: 10px; + padding-left: 0px; + padding-right: 0px; + padding-top: 10px; + text-align: left; + font-family: arial, sans-serif, verdana; + font-size: 10px; + border: 1px solid #000; + position: absolute; + margin: 0; + width: 400px; + height: 260px; - -moz-box-shadow: 0px 4px 4px #010E1B !important; - -webkit-box-shadow: 0px 4px 4px #010E1B !important; - box-shadow: 0px 4px 4px #010E1B !important; + -moz-box-shadow: 0px 4px 4px #010e1b !important; + -webkit-box-shadow: 0px 4px 4px #010e1b !important; + box-shadow: 0px 4px 4px #010e1b !important; - filter:alpha(opacity=97); - -moz-opacity: 0.97; - opacity: 0.97; + filter: alpha(opacity=97); + -moz-opacity: 0.97; + opacity: 0.97; } .menu_sidebar_radius_left { - -moz-border-top-left-radius: 8px; - -webkit-border-top-left-radius: 8px; - border-top-left-radius: 8px; + -moz-border-top-left-radius: 8px; + -webkit-border-top-left-radius: 8px; + border-top-left-radius: 8px; - -moz-border-bottom-left-radius: 8px; - -webkit-border-bottom-left-radius: 8px; - border-bottom-left-radius: 8px; + -moz-border-bottom-left-radius: 8px; + -webkit-border-bottom-left-radius: 8px; + border-bottom-left-radius: 8px; - border-right:0px solid #000; + border-right: 0px solid #000; } .menu_sidebar_radius_right { - -moz-border-top-right-radius: 8px; - -webkit-border-top-right-radius: 8px; - border-top-right-radius: 8px; - -moz-border-bottom-right-radius: 8px; - -webkit-border-bottom-right-radius: 8px; - border-bottom-right-radius: 8px; + -moz-border-top-right-radius: 8px; + -webkit-border-top-right-radius: 8px; + border-top-right-radius: 8px; + -moz-border-bottom-right-radius: 8px; + -webkit-border-bottom-right-radius: 8px; + border-bottom-right-radius: 8px; } .menu_sidebar_outer { - margin-left: 3px; - background: #ECECEC; - width: 100%; - text-align: center; - -moz-border-radius: 6px; - -webkit-border-radius: 6px; - border-radius: 6px; - padding: 8px; + margin-left: 3px; + background: #ececec; + width: 100%; + text-align: center; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: 8px; } /*Groupsview*/ .groupsview { - border-spacing: 0px 4px; + border-spacing: 0px 4px; } .groupsview tr { - background-color: #666; + background-color: #666; } .groupsview th { - font-size: 12px; - padding: 5px; + font-size: 12px; + padding: 5px; } -.groupsview td.first, .groupsview th.first { - -moz-border-top-left-radius: 10px; - -webkit-border-top-left-radius: 10px; - border-top-left-radius: 10px; +.groupsview td.first, +.groupsview th.first { + -moz-border-top-left-radius: 10px; + -webkit-border-top-left-radius: 10px; + border-top-left-radius: 10px; - -moz-border-bottom-left-radius: 10px; - -webkit-border-bottom-left-radius: 10px; - border-bottom-left-radius: 10px; + -moz-border-bottom-left-radius: 10px; + -webkit-border-bottom-left-radius: 10px; + border-bottom-left-radius: 10px; } -.groupsview td.last, .groupsview th.last { - -moz-border-top-right-radius: 10px; - -webkit-border-top-right-radius: 10px; - border-top-right-radius: 10px; - -moz-border-bottom-right-radius: 10px; - -webkit-border-bottom-right-radius: 10px; - border-bottom-right-radius: 10px; +.groupsview td.last, +.groupsview th.last { + -moz-border-top-right-radius: 10px; + -webkit-border-top-right-radius: 10px; + border-top-right-radius: 10px; + -moz-border-bottom-right-radius: 10px; + -webkit-border-bottom-right-radius: 10px; + border-bottom-right-radius: 10px; } a.tip { - display: inline !important; - cursor: help; + display: inline !important; + cursor: help; } -a.tip>img { - margin-left: 2px; - margin-right: 2px; +a.tip > img { + margin-left: 2px; + margin-right: 2px; } input.search_input { - background: white url('../../images/input_zoom.png') no-repeat right; - padding: 0px; - padding-left:5px; - margin: 0; - width: 80%; - height: 19px; - margin-bottom: 5px; - margin-left: 2px; - padding-right: 25px; - color: #999; + background: white url("../../images/input_zoom.png") no-repeat right; + padding: 0px; + padding-left: 5px; + margin: 0; + width: 80%; + height: 19px; + margin-bottom: 5px; + margin-left: 2px; + padding-right: 25px; + color: #999; } -.vertical_fields td input, .vertical_fields td select { - margin-top: 8px !important; +.vertical_fields td input, +.vertical_fields td select { + margin-top: 8px !important; } -a[id^='tgl_ctrl_']>img, a[id^='tgl_ctrl_']>b>img{ - vertical-align:middle; +a[id^="tgl_ctrl_"] > img, +a[id^="tgl_ctrl_"] > b > img { + vertical-align: middle; } .noshadow { - -moz-box-shadow: 0px !important; - -webkit-box-shadow: 0px !important; - box-shadow: 0px !important; + -moz-box-shadow: 0px !important; + -webkit-box-shadow: 0px !important; + box-shadow: 0px !important; } /* Images forced title */ -DIV.forced_title_layer { - display: block; - text-decoration: none; - position: absolute; - z-index: 100000; - border: 1px solid #708090; - background-color: #666; - color: #FFF; - padding: 4px 5px; - font-weight: bold; - font-size: small; - font-size: 11px; - /* IE 8 */ - -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=9)"; - /* Netscape */ - -moz-opacity: 0.9; - opacity: 0.9; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; +div.forced_title_layer { + display: block; + text-decoration: none; + position: absolute; + z-index: 100000; + border: 1px solid #708090; + background-color: #666; + color: #fff; + padding: 4px 5px; + font-weight: bold; + font-size: small; + font-size: 11px; + /* IE 8 */ + -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=9)"; + /* Netscape */ + -moz-opacity: 0.9; + opacity: 0.9; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; } /* Graphs styles */ -div.legend>div { - pointer-events: none; /* Allow to click the graphs below */ - opacity: 0.65 !important; +div.legend > div { + pointer-events: none; /* Allow to click the graphs below */ + opacity: 0.65 !important; } div.nodata_text { - padding: 5px 12px 0px 68px; - font-weight: bold; - color: #C1C1C1; - text-transform: uppercase; - display: table-cell; - vertical-align: middle; - text-align: left; + padding: 5px 12px 0px 68px; + font-weight: bold; + color: #c1c1c1; + text-transform: uppercase; + display: table-cell; + vertical-align: middle; + text-align: left; } div.nodata_container { - width:150px; - height:100px; - background-repeat:no-repeat; - background-position: center; - margin: auto auto; - display: table; + width: 150px; + height: 100px; + background-repeat: no-repeat; + background-position: center; + margin: auto auto; + display: table; } #snmp_data { - width: 40%; - position: absolute; - top:0; - right:20px; + width: 40%; + position: absolute; + top: 0; + right: 20px; - #background-color: #fff; - #padding: 10px; + #background-color: #fff; + #padding: 10px; } #rmf_data { - width: 40%; - height: 80%; - position: absolute; - top:0; - right:20px; - overflow: auto; + width: 40%; + height: 80%; + position: absolute; + top: 0; + right: 20px; + overflow: auto; - #background-color: #fff; - #padding: 10px; + #background-color: #fff; + #padding: 10px; } /* Subtab styles */ ul.subsubmenu { - border-bottom-right-radius: 5px; - border-bottom-left-radius: 5px; - -moz-border-bottom-right-radius: 5px; - -moz-border-bottom-left-radius: 5px; - -webkit-border-bottom-right-radius: 5px; - -webkit-border-bottom-left-radius: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; + -moz-border-bottom-right-radius: 5px; + -moz-border-bottom-left-radius: 5px; + -webkit-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; - background: #ECECEC !important; + background: #ececec !important; } -ul.subsubmenu li{ - background-color: #ECECEC; - font-weight: bold; - text-decoration: none; - font-size: 14px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; +ul.subsubmenu li { + background-color: #ececec; + font-weight: bold; + text-decoration: none; + font-size: 14px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; } -ul.subsubmenu li a{ - padding: 0px 10px 5px; +ul.subsubmenu li a { + padding: 0px 10px 5px; } div#agent_wizard_subtabs { - position: absolute; - margin-left: 0px; - display: none; - padding-bottom: 3px; - z-index: 1000; + position: absolute; + margin-left: 0px; + display: none; + padding-bottom: 3px; + z-index: 1000; } .agent_wizard_tab:hover { - cursor: default; + cursor: default; } #container_servicemap_legend { - position: absolute; - width: 200px; - background: #FFF; - margin-top: 10px; - right: 2px; - border: 1px solid #E2E2E2; - border-radius: 5px; - padding: 10px; - opacity: .90; + position: absolute; + width: 200px; + background: #fff; + margin-top: 10px; + right: 2px; + border: 1px solid #e2e2e2; + border-radius: 5px; + padding: 10px; + opacity: 0.9; } #container_servicemap_legend table { - text-align: left; + text-align: left; } .legend_square { - width: 20px; - padding-left: 20px; - padding-right: 10px; + width: 20px; + padding-left: 20px; + padding-right: 10px; } .legend_square_simple { - padding-left:0px; - padding-right: 10px; - padding-bottom: 3px; + padding-left: 0px; + padding-right: 10px; + padding-bottom: 3px; } -.legend_square div, .legend_square_simple div { - width: 20px; - height: 20px; - border-radius: 3px; +.legend_square div, +.legend_square_simple div { + width: 20px; + height: 20px; + border-radius: 3px; } .legend_basic { - background: #F4F4F4; - margin-top: 10px; - border-radius: 5px; - padding: 10px; + background: #f4f4f4; + margin-top: 10px; + border-radius: 5px; + padding: 10px; } .agents_modules_table th { - background: #3F3F3F; + background: #3f3f3f; } .agents_modules_table th * { - color: #FFFFFF; + color: #ffffff; } /* * LOAD_ENTERPRISE.PHP */ #code_license_dialog { - padding: 50px; - padding-top: 10px; + padding: 50px; + padding-top: 10px; } #code_license_dialog #logo { - margin-bottom: 20px; - text-align: center; + margin-bottom: 20px; + text-align: center; } -#code_license_dialog, #code_license_dialog * { - font-size: 14px; +#code_license_dialog, +#code_license_dialog * { + font-size: 14px; } #code_license_dialog ul { - padding-left: 30px; - list-style-image: url("../../images/input_tick.png"); + padding-left: 30px; + list-style-image: url("../../images/input_tick.png"); } #code_license_dialog li { - margin-bottom: 12px; + margin-bottom: 12px; } #code_license_dialog #code { - font-weight: bolder; - font-size: 20px; - border: 1px solid #dddddd; - padding: 5px; - text-align: center; - -moz-border-radius: 8px; - -webkit-border-radius: 8px; - border-radius: 8px; + font-weight: bolder; + font-size: 20px; + border: 1px solid #dddddd; + padding: 5px; + text-align: center; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + border-radius: 8px; } #code_license_dialog a { - text-decoration: underline; + text-decoration: underline; } /* GRAPHS CSS */ .parent_graph { - position: relative; + position: relative; } -.menu_graph, .timestamp_graph { - position: absolute !important; +.menu_graph, +.timestamp_graph { + position: absolute !important; } .menu_graph { - -moz-border-top-right-radius: 6px; - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - -moz-border-top-left-radius: 6px; - -webkit-border-top-left-radius: 6px; - border-top-left-radius: 6px; + -moz-border-top-right-radius: 6px; + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + -moz-border-top-left-radius: 6px; + -webkit-border-top-left-radius: 6px; + border-top-left-radius: 6px; } .legend_graph { - margin: 0px; - padding: 0px; - text-align: left; + margin: 0px; + padding: 0px; + text-align: left; } .legendColorBox * { - font-size: 0px; - padding: 0px 4px; - overflow: visible !important; + font-size: 0px; + padding: 0px 4px; + overflow: visible !important; } /* GIS CSS */ .olLayerDiv { - z-index: 102 !important; + z-index: 102 !important; } /* Alert view */ -table.alert_days th, table.alert_time th{ - height: 30px; - vertical-align: middle; +table.alert_days th, +table.alert_time th { + height: 30px; + vertical-align: middle; } table.alert_escalation th img { - width: 18px; + width: 18px; } - td.used_field { - #border: solid #6EB432; - background: #6EB432 !important; - color: #FFFFFF; - font-weight: bold; + #border: solid #6eb432; + background: #6eb432 !important; + color: #ffffff; + font-weight: bold; } td.overrided_field { - color: #666; + color: #666; } td.unused_field { - color: #888; + color: #888; } td.empty_field { - background: url('../../images/long_arrow.png') no-repeat 100% center; + background: url("../../images/long_arrow.png") no-repeat 100% center; } #table_macros textarea { - width: 96%; + width: 96%; } /* Policies styles */ table#policy_modules td * { - display: inline; + display: inline; } .context_help_title { - font-weight: bolder; - text-align: left; + font-weight: bolder; + text-align: left; } .context_help_body { - text-align: left; + text-align: left; } #left_column_logon_ok { - width: 750px; - float:left; + width: 750px; + float: left; } #news_board { - min-width: 530px; + min-width: 530px; } #right_column_logon_ok { - width: 350px; - float: right; - margin-right: 20px; + width: 350px; + float: right; + margin-right: 20px; } #clippy_head_title { - font-weight: bold; - background: #80ab51; - color: #ffffff; - margin-top: -15px; - margin-left: -15px; - margin-right: -15px; - padding: 5px; - margin-bottom: 10px; - border-top-left-radius: 2px; - border-top-right-radius: 2px; + font-weight: bold; + background: #80ab51; + color: #ffffff; + margin-top: -15px; + margin-left: -15px; + margin-right: -15px; + padding: 5px; + margin-bottom: 10px; + border-top-left-radius: 2px; + border-top-right-radius: 2px; } #dialog-double_auth-container { - width: 100%; - text-align: center; - vertical-align: middle; + width: 100%; + text-align: center; + vertical-align: middle; } .center_align { - text-align: center; + text-align: center; } .left_align { - text-align: left; + text-align: left; } -.status_tactical{ - width: 100%; - margin-left: auto; - margin-right: auto; - background-color: #FFF !important; - padding: 10px; - border: 1px solid #E2E2E2; - margin-top: 5%; - text-align: left; +.status_tactical { + width: 100%; + margin-left: auto; + margin-right: auto; + background-color: #fff !important; + padding: 10px; + border: 1px solid #e2e2e2; + margin-top: 5%; + text-align: left; } .status_tactical img { - border: 3px solid #000; - border-radius: 100px; + border: 3px solid #000; + border-radius: 100px; } -#sumary{ - color: #FFF; - margin: 15px; - padding: 10px 30px; - font-size: 20px; - font-weight: bold; - height: 66px; - width: 191px; - border-radius: 2px; +#sumary { + color: #fff; + margin: 15px; + padding: 10px 30px; + font-size: 20px; + font-weight: bold; + height: 66px; + width: 191px; + border-radius: 2px; } -.databox.data td{ - border-bottom: 1px solid #E2E2E2; +.databox.data td { + border-bottom: 1px solid #e2e2e2; } -.databox .search{ - margin-top: 0px; +.databox .search { + margin-top: 0px; } -.databox.data td.progress_bar img{ - border: 3px solid #000; - border-radius: 100px; +.databox.data td.progress_bar img { + border: 3px solid #000; + border-radius: 100px; } -.databox td{ - padding-left: 9px; - padding-right: 9px; - padding-top: 7px; - padding-bottom: 7px; +.databox td { + padding-left: 9px; + padding-right: 9px; + padding-top: 7px; + padding-bottom: 7px; } -.databox.pies fieldset.tactical_set{ - width:70% !important; - height: 285px; +.databox.pies fieldset.tactical_set { + width: 70% !important; + height: 285px; } -.difference{ - border-left-width: 2px; - border-left-style: solid; - border-right-width: 2px; - border-right-style: solid; - border-color: #E2E2E2; +.difference { + border-left-width: 2px; + border-left-style: solid; + border-right-width: 2px; + border-right-style: solid; + border-color: #e2e2e2; } #title_menu { - color: #FFF; - float: right; - width: 70%; - letter-spacing: 0pt; - font-size: 8pt; - white-space: pre-wrap; + color: #fff; + float: right; + width: 70%; + letter-spacing: 0pt; + font-size: 8pt; + white-space: pre-wrap; } -.no_hidden_menu{ - background-position: 11% 50% !important; +.no_hidden_menu { + background-position: 11% 50% !important; } -#menu_tab li.nomn, #menu_tab li.nomn_high { - background-color: #ECECEC; - padding-right: 3px; - padding-left: 3px; - font-weight: bold; - text-decoration: none; - font-size: 14px; - border-color: #E2E2E2; - border-style: solid; - border-width: 1px; - margin-top: -10px; +#menu_tab li.nomn, +#menu_tab li.nomn_high { + background-color: #ececec; + padding-right: 3px; + padding-left: 3px; + font-weight: bold; + text-decoration: none; + font-size: 14px; + border-color: #e2e2e2; + border-style: solid; + border-width: 1px; + margin-top: -10px; } -#menu_tab li.nomn_high, #menu_tab li.nomn_high span { - color: #FFF; - background-color: #FFF; +#menu_tab li.nomn_high, +#menu_tab li.nomn_high span { + color: #fff; + background-color: #fff; } -#menu_tab li.nomn img, #menu_tab li img { - margin-top: 3px; - margin-left: 3px; +#menu_tab li.nomn img, +#menu_tab li img { + margin-top: 3px; + margin-left: 3px; } -#menu_tab li.tab_operation a, #menu_tab a.tab_operation{ - background: none !important ; +#menu_tab li.tab_operation a, +#menu_tab a.tab_operation { + background: none !important ; } -.subsubmenu{ - position: absolute; - float: right; - z-index: 9999; - display: none; - margin-top: 6px !important ; - left: 0px !important; +.subsubmenu { + position: absolute; + float: right; + z-index: 9999; + display: none; + margin-top: 6px !important ; + left: 0px !important; } -.subsubmenu li{ - margin-top: 0px !important ; +.subsubmenu li { + margin-top: 0px !important ; } -.agents_modules_table{ - border: 1px solid #E2E2E2; - border-spacing: 0px; +.agents_modules_table { + border: 1px solid #e2e2e2; + border-spacing: 0px; } -.agents_modules_table td{ - border: 1px solid #E2E2E2; +.agents_modules_table td { + border: 1px solid #e2e2e2; } -.agents_modules_table th{ - border: 1px solid #E2E2E2; +.agents_modules_table th { + border: 1px solid #e2e2e2; } -.databox.filters, .databox.data, .databox.profile_list{ - margin-bottom: 20px; +.databox.filters, +.databox.data, +.databox.profile_list { + margin-bottom: 20px; } -.databox.filters td{ - padding: 10px; - padding-left:20px; +.databox.filters td { + padding: 10px; + padding-left: 20px; } -.databox.profile_list td{ - padding: 4px 1px; - padding-left: 5px; - border-bottom: 1px solid #E2E2E2; +.databox.profile_list td { + padding: 4px 1px; + padding-left: 5px; + border-bottom: 1px solid #e2e2e2; } -.databox.profile_list a.tip > img{ - margin: 0px; +.databox.profile_list a.tip > img { + margin: 0px; } -.databox.filters td>img, .databox.filters td>div>a>img, -.databox.filters td>span>img, .databox.filters td>span>a>img, -.databox.filters td>a>img{ - vertical-align: middle; - margin-left: 5px; +.databox.filters td > img, +.databox.filters td > div > a > img, +.databox.filters td > span > img, +.databox.filters td > span > a > img, +.databox.filters td > a > img { + vertical-align: middle; + margin-left: 5px; } -.databox.data td>img,.databox.data th>img, .databox.data td>div>a>img, -.databox.data td>span>img, .databox.data td>span>a>img, -.databox.data td>a>img, .databox.data td>form>a>img { - vertical-align: middle; - +.databox.data td > img, +.databox.data th > img, +.databox.data td > div > a > img, +.databox.data td > span > img, +.databox.data td > span > a > img, +.databox.data td > a > img, +.databox.data td > form > a > img { + vertical-align: middle; } -.databox.filters td>a>img { - vertical-align: middle; +.databox.filters td > a > img { + vertical-align: middle; } -.databox.data td>input[type="checkbox"] { - margin: 0px; +.databox.data td > input[type="checkbox"] { + margin: 0px; } -.databox_color td{ - padding-left: 10px; +.databox_color td { + padding-left: 10px; } -.databox.agente td>div>canvas{ - width: 100% !important; - text-align: left !important; +.databox.agente td > div > canvas { + width: 100% !important; + text-align: left !important; } -.databox.agente td>div.graph{ - width: 100% !important; - text-align: left !important; +.databox.agente td > div.graph { + width: 100% !important; + text-align: left !important; } -.godmode, .menu_icon ul li{ - background-color: #222; +.godmode, +.menu_icon ul li { + background-color: #222; } -.operation .menu_icon ul li{ - background-color: #333; +.operation .menu_icon ul li { + background-color: #333; } -.godmode{ - border-top: 4px solid !important; - padding-bottom: 4px !important; - border-bottom-right-radius: 5px; - border-right-style: solid; - border-right-width: 0px; +.godmode { + border-top: 4px solid !important; + padding-bottom: 4px !important; + border-bottom-right-radius: 5px; + border-right-style: solid; + border-right-width: 0px; } -.green_title{ - background-color: #80ab51; - font-weight:normal; - text-align: center; +.green_title { + background-color: #80ab51; + font-weight: normal; + text-align: center; } -.dashboard{ - top: 23px; +.dashboard { + top: 23px; } -.dashboard li a{ - width: 158px !important; +.dashboard li a { + width: 158px !important; } -.text_subDashboard{ - float: left; - margin-top: 5%; - margin-left: 3%; +.text_subDashboard { + float: left; + margin-top: 5%; + margin-left: 3%; } /* The items with the class 'spinner' will rotate */ /* Not supported on IE9 and below */ .spinner { - -webkit-animation: spinner 2s infinite linear; - animation: spinner 2s infinite linear; + -webkit-animation: spinner 2s infinite linear; + animation: spinner 2s infinite linear; } @-webkit-keyframes spinner { - 0% { - -ms-transform: rotate(0deg); /* IE */ - -moz-transform: rotate(0deg); /* FF */ - -o-transform: rotate(0deg); /* Opera */ - -webkit-transform: rotate(0deg); /* Safari and Chrome */ - transform: rotate(0deg); - } - 100% { - -ms-transform: rotate(359deg); /* IE */ - -moz-transform: rotate(359deg); /* FF */ - -o-transform: rotate(359deg); /* Opera */ - -webkit-transform: rotate(359deg); /* Safari and Chrome */ - transform: rotate(359deg); - } + 0% { + -ms-transform: rotate(0deg); /* IE */ + -moz-transform: rotate(0deg); /* FF */ + -o-transform: rotate(0deg); /* Opera */ + -webkit-transform: rotate(0deg); /* Safari and Chrome */ + transform: rotate(0deg); + } + 100% { + -ms-transform: rotate(359deg); /* IE */ + -moz-transform: rotate(359deg); /* FF */ + -o-transform: rotate(359deg); /* Opera */ + -webkit-transform: rotate(359deg); /* Safari and Chrome */ + transform: rotate(359deg); + } } @keyframes spinner { - 0% { - -ms-transform: rotate(0deg); /* IE */ - -moz-transform: rotate(0deg); /* FF */ - -o-transform: rotate(0deg); /* Opera */ - -webkit-transform: rotate(0deg); /* Safari and Chrome */ - transform: rotate(0deg); - } - 100% { - -ms-transform: rotate(359deg); /* IE */ - -moz-transform: rotate(359deg); /* FF */ - -o-transform: rotate(359deg); /* Opera */ - -webkit-transform: rotate(359deg); /* Safari and Chrome */ - transform: rotate(359deg); - } + 0% { + -ms-transform: rotate(0deg); /* IE */ + -moz-transform: rotate(0deg); /* FF */ + -o-transform: rotate(0deg); /* Opera */ + -webkit-transform: rotate(0deg); /* Safari and Chrome */ + transform: rotate(0deg); + } + 100% { + -ms-transform: rotate(359deg); /* IE */ + -moz-transform: rotate(359deg); /* FF */ + -o-transform: rotate(359deg); /* Opera */ + -webkit-transform: rotate(359deg); /* Safari and Chrome */ + transform: rotate(359deg); + } } -#alert_messages{ - -moz-border-bottom-right-radius: 5px; - -webkit-border-bottom-left-radius: 5px; - border-bottom-right-radius: 5px; - border-bottom-left-radius: 5px; - z-index:3; - position:fixed; - width:750px; - max-width:750px; - min-width:750px; - top: 20%; - background:white; +#alert_messages { + -moz-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; + z-index: 3; + position: fixed; + width: 750px; + max-width: 750px; + min-width: 750px; + top: 20%; + background: white; } -.modalheader{ - text-align:center; - width:100%; - height:37px; - left:0px; - background-color:#82b92e; +.modalheader { + text-align: center; + width: 100%; + height: 37px; + left: 0px; + background-color: #82b92e; } -.modalheadertext{ - color:white; - position:relative; - font-family:Nunito; - font-size:13pt; - top:8px; +.modalheadertext { + color: white; + position: relative; + font-family: Nunito; + font-size: 13pt; + top: 8px; } -.modalclosex{ - cursor:pointer; - display:inline; - float:right; - margin-right:10px; - margin-top:10px; +.modalclosex { + cursor: pointer; + display: inline; + float: right; + margin-right: 10px; + margin-top: 10px; } -.modalcontent{ - color:black; - background:white; +.modalcontent { + color: black; + background: white; } -.modalcontentimg{ - float:left; - margin-left:30px; - margin-top:30px; - margin-bottom:30px; +.modalcontentimg { + float: left; + margin-left: 30px; + margin-top: 30px; + margin-bottom: 30px; } -.modalcontenttext{ - float:left; - text-align:justify; - color:black; - font-size: 9.5pt; - line-height:13pt; - margin-top:30px; - width:430px; - margin-left:30px; +.modalcontenttext { + float: left; + text-align: justify; + color: black; + font-size: 9.5pt; + line-height: 13pt; + margin-top: 30px; + width: 430px; + margin-left: 30px; } -.modalokbutton{ - cursor:pointer; - text-align:center; - margin-right:45px; - float:right; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - margin-bottom:30px; - border-radius: 3px;width:90px;height:30px;background-color:white;border: 1px solid #82b92e; +.modalokbutton { + cursor: pointer; + text-align: center; + margin-right: 45px; + float: right; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + margin-bottom: 30px; + border-radius: 3px; + width: 90px; + height: 30px; + background-color: white; + border: 1px solid #82b92e; } -.modalokbuttontext{ - color:#82b92e;font-family:Nunito;font-size:10pt;position:relative;top:6px; +.modalokbuttontext { + color: #82b92e; + font-family: Nunito; + font-size: 10pt; + position: relative; + top: 6px; } -.modalgobutton{ - cursor:pointer;text-align:center;margin-right:15px;margin-bottom:30px;float:right;-moz-border-radius: 3px; - -webkit-border-radius: 3px;border-radius: 3px;width:240px;height:30px;background-color:white;border: 1px solid #82b92e; +.modalgobutton { + cursor: pointer; + text-align: center; + margin-right: 15px; + margin-bottom: 30px; + float: right; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; + width: 240px; + height: 30px; + background-color: white; + border: 1px solid #82b92e; } -.modalgobuttontext{ -color:#82b92e;font-family:Nunito;font-size:10pt;position:relative;top:6px; +.modalgobuttontext { + color: #82b92e; + font-family: Nunito; + font-size: 10pt; + position: relative; + top: 6px; } - -#opacidad{ - opacity:0.5; - z-index:1; - width:100%; - height:100%; - position:absolute; - left:0px; - top:0px; +#opacidad { + opacity: 0.5; + z-index: 1; + width: 100%; + height: 100%; + position: absolute; + left: 0px; + top: 0px; } -.textodialogo{ - margin-left: 0px; - color:#333; - padding:20px; - font-size:9pt; +.textodialogo { + margin-left: 0px; + color: #333; + padding: 20px; + font-size: 9pt; } -.cargatextodialogo{ - max-width:58.5%; - width:58.5%; - min-width:58.5%; - float:left; - margin-left: 0px; - font-size:18pt; - padding:20px; - text-align:center; +.cargatextodialogo { + max-width: 58.5%; + width: 58.5%; + min-width: 58.5%; + float: left; + margin-left: 0px; + font-size: 18pt; + padding: 20px; + text-align: center; } -.cargatextodialogo p, .cargatextodialogo b, .cargatextodialogo a{ - font-size:18pt; +.cargatextodialogo p, +.cargatextodialogo b, +.cargatextodialogo a { + font-size: 18pt; } -#toolbox > input{ - border-width:0px 1px 0px 0px; - border-color: lightgray; +#toolbox > input { + border-width: 0px 1px 0px 0px; + border-color: lightgray; } -#toolbox > input.service_min{ - border-width:0px 0px 0px 0px; +#toolbox > input.service_min { + border-width: 0px 0px 0px 0px; } -#toolbox > input.grid_min{ - border-width:0px 0px 0px 0px; +#toolbox > input.grid_min { + border-width: 0px 0px 0px 0px; } -#tinymce{ - padding-top:20px; +#tinymce { + padding-top: 20px; } -.rowPair:hover, .rowOdd:hover{ - background-color: #eee; +.rowPair:hover, +.rowOdd:hover { + background-color: #eee; } -.databox.data > tbody > tr:hover{ - background-color: #eee; +.databox.data > tbody > tr:hover { + background-color: #eee; +} +.checkselected { + background-color: #eee; } -.checkselected{ - background-color: #eee; -} \ No newline at end of file diff --git a/pandora_console/include/styles/pandora_minimal.css b/pandora_console/include/styles/pandora_minimal.css index d17e06d430..8c9649888d 100644 --- a/pandora_console/include/styles/pandora_minimal.css +++ b/pandora_console/include/styles/pandora_minimal.css @@ -22,154 +22,160 @@ Exclude css from visual styles */ * { - font-family: verdana, sans-serif; - font-size: 8pt; + font-family: verdana, sans-serif; + font-size: 8pt; } body { - text-align: center; + text-align: center; } h1 { - font: bold 1em Arial, Sans-serif; - text-transform: uppercase; - color: #786; - padding-bottom: 5px; - padding-top: 7px; - font-size: 16px; + font: bold 1em Arial, Sans-serif; + text-transform: uppercase; + color: #786; + padding-bottom: 5px; + padding-top: 7px; + font-size: 16px; } a { - color: #486787; - text-decoration: none; + color: #486787; + text-decoration: none; } a:hover { - color: #003a3a; - text-decoration: underline; + color: #003a3a; + text-decoration: underline; } input { - padding: 2px 3px 4px 3px; - border: 1px solid #ddd; - font-family: verdana, sans-serif; - font-size: 8pt + padding: 2px 3px 4px 3px; + border: 1px solid #ddd; + font-family: verdana, sans-serif; + font-size: 8pt; } input:hover { - background-color: #d4dccd; + background-color: #d4dccd; } input.login { - border-color: #786; - background-color: #f5f5f5; - margin: 2px 0 8px; - width: 90px; + border-color: #786; + background-color: #f5f5f5; + margin: 2px 0 8px; + width: 90px; } -table, img { - border: 0px; +table, +img { + border: 0px; } -.f9, .f9i, .f9b, td.f9, td.f9i, td.datosf9, td.datos2f9 { - font-size: 6.5pt; +.f9, +.f9i, +.f9b, +td.f9, +td.f9i, +td.datosf9, +td.datos2f9 { + font-size: 6.5pt; } -.databox, .databox_frame { - margin-bottom: 15px; - margin-top: 5px; - margin-left: 0px; - border: 1px solid #f2f2f2; +.databox, +.databox_frame { + margin-bottom: 15px; + margin-top: 5px; + margin-left: 0px; + border: 1px solid #f2f2f2; } .databox { - background-color: #fafafa; + background-color: #fafafa; } #show_menu { } #loading { - position:fixed; - width: 200px; - margin-left: 35%; - text-align:center; - top:300px; - background-color: #999999; - padding: 20px; + position: fixed; + width: 200px; + margin-left: 35%; + text-align: center; + top: 300px; + background-color: #999999; + padding: 20px; } tr.rowPair { - background-color: #fff; + background-color: #fff; } tr.rowOdd { - background-color: #888; + background-color: #888; } tr.rowPair:hover { - background-color: #bbb; + background-color: #bbb; } tr.rowOdd:hover { - background-color: #444; + background-color: #444; } .disabled_module { - color: #98c2ed; + color: #98c2ed; } /*CALENDAR TOOLTIP STYLE*/ /* Calendar background */ table.scw { - background-color: #FFF; + background-color: #fff; } /* Week number heading */ td.scwWeekNumberHead { - color: #000; + color: #000; } td.scwWeek { - color: #000 !important; + color: #000 !important; } /* Today selector */ td.scwFoot { - background-color: #FFF; - color: #000; + background-color: #fff; + color: #000; } td.scwFootDisabled { - background-color: #000; - color: #FFFFFF; + background-color: #000; + color: #ffffff; } tfoot.scwFoot { - color: #000; + color: #000; } -.scwFoot :hover{ - color: #FFA500 !important; +.scwFoot :hover { + color: #ffa500 !important; } input.next { - background: #e5e5e5 url(../../images/go.png) no-repeat 98% 2px; + background: #e5e5e5 url(../../images/go.png) no-repeat 98% 2px; } input.next { - padding-right: 21px; + padding-right: 21px; } .info_box { - background: #EBEBEB; - margin: 10px auto; - padding: 5px; - border: 1px solid #A8A8A8; - width: 85% !important; - -moz-box-shadow: 0px 2px 2px #010E1B !important; - -webkit-box-shadow: 0px 2px 2px #010E1B !important; - box-shadow: 0px 2px 2px #010E1B !important; + background: #ebebeb; + margin: 10px auto; + padding: 5px; + border: 1px solid #a8a8a8; + width: 85% !important; + -moz-box-shadow: 0px 2px 2px #010e1b !important; + -webkit-box-shadow: 0px 2px 2px #010e1b !important; + box-shadow: 0px 2px 2px #010e1b !important; } .info_box .title * { - font-size: 10pt !important; - font-weight: bolder; + font-size: 10pt !important; + font-weight: bolder; } .info_box .icon { - width: 30px !important; - text-align: center; + width: 30px !important; + text-align: center; } - - diff --git a/pandora_console/include/styles/tooltipster-light.css b/pandora_console/include/styles/tooltipster-light.css deleted file mode 100644 index 945aa699a1..0000000000 --- a/pandora_console/include/styles/tooltipster-light.css +++ /dev/null @@ -1,12 +0,0 @@ -.tooltipster-light { - border-radius: 5px; - border: 1px solid #cccccc; - background: #ededed; - color: #666666; -} -.tooltipster-light .tooltipster-content { - font-family: Arial, sans-serif; - font-size: 14px; - line-height: 16px; - padding: 8px 10px; -} \ No newline at end of file diff --git a/pandora_console/include/styles/tooltipster-noir.css b/pandora_console/include/styles/tooltipster-noir.css deleted file mode 100644 index fc695f507e..0000000000 --- a/pandora_console/include/styles/tooltipster-noir.css +++ /dev/null @@ -1,12 +0,0 @@ -.tooltipster-noir { - border-radius: 0px; - border: 3px solid #82B92E; - background: #fff; - color: #2c2c2c; -} -.tooltipster-noir .tooltipster-content { - font-family: 'Georgia', serif; - font-size: 14px; - line-height: 16px; - padding: 8px 10px; -} diff --git a/pandora_console/include/styles/tooltipster-punk.css b/pandora_console/include/styles/tooltipster-punk.css deleted file mode 100644 index 3c78973a7d..0000000000 --- a/pandora_console/include/styles/tooltipster-punk.css +++ /dev/null @@ -1,12 +0,0 @@ -.tooltipster-punk { - border-radius: 5px; - border-bottom: 3px solid #82B92E; - background: #ccc; - color: #fff; -} -.tooltipster-punk .tooltipster-content { - font-family: 'Courier', monospace; - font-size: 14px; - line-height: 16px; - padding: 8px 10px; -} diff --git a/pandora_console/include/styles/tooltipster-shadow.css b/pandora_console/include/styles/tooltipster-shadow.css deleted file mode 100644 index e869c5ecfc..0000000000 --- a/pandora_console/include/styles/tooltipster-shadow.css +++ /dev/null @@ -1,12 +0,0 @@ -.tooltipster-shadow { - border-radius: 5px; - background: #fff; - box-shadow: 0px 0px 14px rgba(0,0,0,0.3); - color: #2c2c2c; -} -.tooltipster-shadow .tooltipster-content { - font-family: 'Arial', sans-serif; - font-size: 14px; - line-height: 16px; - padding: 8px 10px; -} \ No newline at end of file diff --git a/pandora_console/include/styles/tooltipster.css b/pandora_console/include/styles/tooltipster.css deleted file mode 100644 index 66fd282f39..0000000000 --- a/pandora_console/include/styles/tooltipster.css +++ /dev/null @@ -1,274 +0,0 @@ -/* This is the default Tooltipster theme (feel free to modify or duplicate and create multiple themes!): */ -.tooltipster-default { - border-radius: 5px; - border: 2px solid #000; - background: #4c4c4c; - color: #fff; -} - -/* Use this next selector to style things like font-size and line-height: */ -.tooltipster-default .tooltipster-content { - font-family: Arial, sans-serif; - font-size: 14px; - line-height: 16px; - padding: 8px 10px; - overflow: hidden; -} - -/* This next selector defines the color of the border on the outside of the arrow. This will automatically match the color and size of the border set on the main tooltip styles. Set display: none; if you would like a border around the tooltip but no border around the arrow */ -.tooltipster-default .tooltipster-arrow .tooltipster-arrow-border { - /* border-color: ... !important; */ -} - - -/* If you're using the icon option, use this next selector to style them */ -.tooltipster-icon { - cursor: help; - margin-left: 4px; -} - - - - - - - - -/* This is the base styling required to make all Tooltipsters work */ -.tooltipster-base { - padding: 0; - font-size: 0; - line-height: 0; - position: absolute; - left: 0; - top: 0; - z-index: 9999999; - pointer-events: none; - width: auto; - overflow: visible; -} -.tooltipster-base .tooltipster-content { - overflow: hidden; -} - - -/* These next classes handle the styles for the little arrow attached to the tooltip. By default, the arrow will inherit the same colors and border as what is set on the main tooltip itself. */ -.tooltipster-arrow { - display: block; - text-align: center; - width: 100%; - height: 100%; - position: absolute; - top: 0; - left: 0; - z-index: -1; -} -.tooltipster-arrow span, .tooltipster-arrow-border { - display: block; - width: 0; - height: 0; - position: absolute; -} -.tooltipster-arrow-top span, .tooltipster-arrow-top-right span, .tooltipster-arrow-top-left span { - border-left: 8px solid transparent !important; - border-right: 8px solid transparent !important; - border-top: 8px solid; - bottom: -7px; -} -.tooltipster-arrow-top .tooltipster-arrow-border, .tooltipster-arrow-top-right .tooltipster-arrow-border, .tooltipster-arrow-top-left .tooltipster-arrow-border { - border-left: 9px solid transparent !important; - border-right: 9px solid transparent !important; - border-top: 9px solid; - bottom: -7px; -} - -.tooltipster-arrow-bottom span, .tooltipster-arrow-bottom-right span, .tooltipster-arrow-bottom-left span { - border-left: 8px solid transparent !important; - border-right: 8px solid transparent !important; - border-bottom: 8px solid; - top: -7px; -} -.tooltipster-arrow-bottom .tooltipster-arrow-border, .tooltipster-arrow-bottom-right .tooltipster-arrow-border, .tooltipster-arrow-bottom-left .tooltipster-arrow-border { - border-left: 9px solid transparent !important; - border-right: 9px solid transparent !important; - border-bottom: 9px solid; - top: -7px; -} -.tooltipster-arrow-top span, .tooltipster-arrow-top .tooltipster-arrow-border, .tooltipster-arrow-bottom span, .tooltipster-arrow-bottom .tooltipster-arrow-border { - left: 0; - right: 0; - margin: 0 auto; -} -.tooltipster-arrow-top-left span, .tooltipster-arrow-bottom-left span { - left: 6px; -} -.tooltipster-arrow-top-left .tooltipster-arrow-border, .tooltipster-arrow-bottom-left .tooltipster-arrow-border { - left: 5px; -} -.tooltipster-arrow-top-right span, .tooltipster-arrow-bottom-right span { - right: 6px; -} -.tooltipster-arrow-top-right .tooltipster-arrow-border, .tooltipster-arrow-bottom-right .tooltipster-arrow-border { - right: 5px; -} -.tooltipster-arrow-left span, .tooltipster-arrow-left .tooltipster-arrow-border { - border-top: 8px solid transparent !important; - border-bottom: 8px solid transparent !important; - border-left: 8px solid; - top: 50%; - margin-top: -7px; - right: -7px; -} -.tooltipster-arrow-left .tooltipster-arrow-border { - border-top: 9px solid transparent !important; - border-bottom: 9px solid transparent !important; - border-left: 9px solid; - margin-top: -8px; -} -.tooltipster-arrow-right span, .tooltipster-arrow-right .tooltipster-arrow-border { - border-top: 8px solid transparent !important; - border-bottom: 8px solid transparent !important; - border-right: 8px solid; - top: 50%; - margin-top: -7px; - left: -7px; -} -.tooltipster-arrow-right .tooltipster-arrow-border { - border-top: 9px solid transparent !important; - border-bottom: 9px solid transparent !important; - border-right: 9px solid; - margin-top: -8px; -} - - -/* Some CSS magic for the awesome animations - feel free to make your own custom animations and reference it in your Tooltipster settings! */ - -.tooltipster-fade { - opacity: 0; - -webkit-transition-property: opacity; - -moz-transition-property: opacity; - -o-transition-property: opacity; - -ms-transition-property: opacity; - transition-property: opacity; -} -.tooltipster-fade-show { - opacity: 1; -} - -.tooltipster-grow { - -webkit-transform: scale(0,0); - -moz-transform: scale(0,0); - -o-transform: scale(0,0); - -ms-transform: scale(0,0); - transform: scale(0,0); - -webkit-transition-property: -webkit-transform; - -moz-transition-property: -moz-transform; - -o-transition-property: -o-transform; - -ms-transition-property: -ms-transform; - transition-property: transform; - -webkit-backface-visibility: hidden; -} -.tooltipster-grow-show { - -webkit-transform: scale(1,1); - -moz-transform: scale(1,1); - -o-transform: scale(1,1); - -ms-transform: scale(1,1); - transform: scale(1,1); - -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1); - -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -} - -.tooltipster-swing { - opacity: 0; - -webkit-transform: rotateZ(4deg); - -moz-transform: rotateZ(4deg); - -o-transform: rotateZ(4deg); - -ms-transform: rotateZ(4deg); - transform: rotateZ(4deg); - -webkit-transition-property: -webkit-transform, opacity; - -moz-transition-property: -moz-transform; - -o-transition-property: -o-transform; - -ms-transition-property: -ms-transform; - transition-property: transform; -} -.tooltipster-swing-show { - opacity: 1; - -webkit-transform: rotateZ(0deg); - -moz-transform: rotateZ(0deg); - -o-transform: rotateZ(0deg); - -ms-transform: rotateZ(0deg); - transform: rotateZ(0deg); - -webkit-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 1); - -webkit-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); - -moz-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); - -ms-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); - -o-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); - transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); -} - -.tooltipster-fall { - top: 0; - -webkit-transition-property: top; - -moz-transition-property: top; - -o-transition-property: top; - -ms-transition-property: top; - transition-property: top; - -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1); - -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -} -.tooltipster-fall-show { -} -.tooltipster-fall.tooltipster-dying { - -webkit-transition-property: all; - -moz-transition-property: all; - -o-transition-property: all; - -ms-transition-property: all; - transition-property: all; - top: 0px !important; - opacity: 0; -} - -.tooltipster-slide { - left: -40px; - -webkit-transition-property: left; - -moz-transition-property: left; - -o-transition-property: left; - -ms-transition-property: left; - transition-property: left; - -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1); - -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); - transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -} -.tooltipster-slide.tooltipster-slide-show { -} -.tooltipster-slide.tooltipster-dying { - -webkit-transition-property: all; - -moz-transition-property: all; - -o-transition-property: all; - -ms-transition-property: all; - transition-property: all; - left: 0px !important; - opacity: 0; -} - - -/* CSS transition for when contenting is changing in a tooltip that is still open. The only properties that will NOT transition are: width, height, top, and left */ -.tooltipster-content-changing { - opacity: 0.5; - -webkit-transform: scale(1.1, 1.1); - -moz-transform: scale(1.1, 1.1); - -o-transform: scale(1.1, 1.1); - -ms-transform: scale(1.1, 1.1); - transform: scale(1.1, 1.1); -} diff --git a/pandora_console/include/styles/tree.css b/pandora_console/include/styles/tree.css index 13bc4888e9..e86edfe90b 100644 --- a/pandora_console/include/styles/tree.css +++ b/pandora_console/include/styles/tree.css @@ -1,138 +1,139 @@ .tree-root { - margin-top: 0px; - margin-bottom: 0px; + margin-top: 0px; + margin-bottom: 0px; } .tree-group { - margin-left: 16px; - padding-top: 1px; + margin-left: 16px; + padding-top: 1px; } .tree-node { - white-space: nowrap; + white-space: nowrap; - background-image: url(../../images/tree/branch.png); - background-position: 0px 0px; - background-repeat: repeat-y; + background-image: url(../../images/tree/branch.png); + background-position: 0px 0px; + background-repeat: repeat-y; - min-height: 26px; + min-height: 26px; } .tree-node:last-child { - background: 0 0; + background: 0 0; } .node-content { - height: 16px; + height: 16px; } -.node-content>img { - position: relative; - top: -2px; +.node-content > img { + position: relative; + top: -2px; } .node-content:hover { - background-color: #FFF; + background-color: #fff; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; - border-radius: 3px; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; } .leaf-icon { - width: 18px; - height: 20px; + width: 18px; + height: 20px; } -.node-content, .leaf-icon { - display: inline-block; +.node-content, +.leaf-icon { + display: inline-block; } -.node-content>img, .node-content>div { - display: inline; +.node-content > img, +.node-content > div { + display: inline; } -.tree-node.leaf-open>.leaf-icon { - background-image: url(../../images/tree/last_expanded.png); - cursor: pointer; +.tree-node.leaf-open > .leaf-icon { + background-image: url(../../images/tree/last_expanded.png); + cursor: pointer; } -.tree-node.tree-first.leaf-open>.leaf-icon { - background-image: url(../../images/tree/first_expanded.png); - cursor: pointer; +.tree-node.tree-first.leaf-open > .leaf-icon { + background-image: url(../../images/tree/first_expanded.png); + cursor: pointer; } -.tree-node.leaf-closed>.leaf-icon { - background-image: url(../../images/tree/last_closed.png); - cursor: pointer; +.tree-node.leaf-closed > .leaf-icon { + background-image: url(../../images/tree/last_closed.png); + cursor: pointer; } -.tree-node.tree-first.leaf-closed>.leaf-icon { - background-image: url(../../images/tree/first_closed.png); - cursor: pointer; +.tree-node.tree-first.leaf-closed > .leaf-icon { + background-image: url(../../images/tree/first_closed.png); + cursor: pointer; } -.tree-node.leaf-loading>.leaf-icon { - background-image: url(../../images/tree/last_expanded.png); +.tree-node.leaf-loading > .leaf-icon { + background-image: url(../../images/tree/last_expanded.png); } -.tree-node.leaf-empty>.leaf-icon { - background-image: url(../../images/tree/last_leaf.png); +.tree-node.leaf-empty > .leaf-icon { + background-image: url(../../images/tree/last_leaf.png); } -.tree-node.tree-first.leaf-empty>.leaf-icon { - background-image: url(../../images/tree/first_leaf.png); +.tree-node.tree-first.leaf-empty > .leaf-icon { + background-image: url(../../images/tree/first_leaf.png); } -.tree-node.leaf-error>.leaf-icon { - background-image: url(../../images/tree/last_leaf.png); +.tree-node.leaf-error > .leaf-icon { + background-image: url(../../images/tree/last_leaf.png); } -.tree-node>.leaf-icon { - background-position: 0px 0px; - background-repeat: no-repeat; +.tree-node > .leaf-icon { + background-position: 0px 0px; + background-repeat: no-repeat; } -.tree-node>.node-content>img { - max-height: 20px; - /*max-width: 20px;*/ +.tree-node > .node-content > img { + max-height: 20px; + /*max-width: 20px;*/ } -.tree-node>.node-content>img.module-data, -.tree-node>.node-content>img.module-graph { - cursor: pointer; - padding-right: 3px; +.tree-node > .node-content > img.module-data, +.tree-node > .node-content > img.module-graph { + cursor: pointer; + padding-right: 3px; } -.tree-node>.node-content>img.module-server-type, -.tree-node>.node-content>img.agent-status, -.tree-node>.node-content>img.agent-alerts-fired, -.tree-node>.node-content>img.agent-quiet, -.tree-node>.node-content>img.module-status, -.tree-node>.node-content>img.module-alerts { - padding-right: 3px; +.tree-node > .node-content > img.module-server-type, +.tree-node > .node-content > img.agent-status, +.tree-node > .node-content > img.agent-alerts-fired, +.tree-node > .node-content > img.agent-quiet, +.tree-node > .node-content > img.module-status, +.tree-node > .node-content > img.module-alerts { + padding-right: 3px; } -.tree-node>.node-content>.tree-node-counters, -.tree-node>.node-content>.tree-node-counters>.tree-node-counter { - display: inline; +.tree-node > .node-content > .tree-node-counters, +.tree-node > .node-content > .tree-node-counters > .tree-node-counter { + display: inline; } -.tree-node>.node-content>.tree-node-counters { - +.tree-node > .node-content > .tree-node-counters { } -.tree-node>.node-content>img { - vertical-align: middle; +.tree-node > .node-content > img { + vertical-align: middle; } -.tree-node>.node-content>.tree-node-counters>.tree-node-counter { - font-weight: bold; - font-size: 7pt; - cursor: default; +.tree-node > .node-content > .tree-node-counters > .tree-node-counter { + font-weight: bold; + font-size: 7pt; + cursor: default; } div#tree-controller-recipient { - text-align: left; - width: 98%; - margin-top: 10px; + text-align: left; + width: 98%; + margin-top: 10px; } diff --git a/pandora_console/include/test.js b/pandora_console/include/test.js index e47d8a5e41..0425b97755 100644 --- a/pandora_console/include/test.js +++ b/pandora_console/include/test.js @@ -1,26 +1,19 @@ -var webPage = require('webpage'); +var webPage = require("webpage"); var page = webPage.create(); -var url = "http://nova/pandora_console/operation/agentes/stat_win.php?type=sparse&period=86400&id=136574&label=QXJ0aWNhJiN4MjA7d2ViJiN4MjA7cGFnZSYjeDIwO2V4YW1wbGU%3D&refresh=600&draw_events=0"; +var url = + "http://nova/pandora_console/operation/agentes/stat_win.php?type=sparse&period=86400&id=136574&label=QXJ0aWNhJiN4MjA7d2ViJiN4MjA7cGFnZSYjeDIwO2V4YW1wbGU%3D&refresh=600&draw_events=0"; var r = page.addCookie({ - 'name' : 'PHPSESSID', /* required property */ - 'value' : '23qu7l1sgb3iq3bkaedr724hp3', /* required property */ - 'path' : '/pandora_console', - 'domain' : 'nova', + name: "PHPSESSID" /* required property */, + value: "23qu7l1sgb3iq3bkaedr724hp3" /* required property */, + path: "/pandora_console", + domain: "nova" }); console.log(r); - - - - - - page.viewportSize = { width: 750, height: 350 }; page.open(url, function start(status) { - page.render('output.jpeg', {format: 'jpeg', quality: '100'}); + page.render("output.jpeg", { format: "jpeg", quality: "100" }); phantom.exit(); }); - - diff --git a/pandora_console/include/web2image.js b/pandora_console/include/web2image.js index f94c8420b3..bf183a73c4 100644 --- a/pandora_console/include/web2image.js +++ b/pandora_console/include/web2image.js @@ -1,68 +1,77 @@ -var system = require('system'); +var system = require("system"); if (system.args.length < 3 || system.args.length > 11) { - phantom.exit(1); + phantom.exit(1); } -var url = system.args[1]; -var type_graph_pdf = system.args[2]; -var url_params = system.args[3]; +var url = system.args[1]; +var type_graph_pdf = system.args[2]; +var url_params = system.args[3]; var url_params_comb = system.args[4]; var url_module_list = system.args[5]; var output_filename = system.args[6]; -var viewport_width = system.args[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 session_id = system.args[9]; +var base_64 = system.args[10]; if (!viewport_width) { - viewport_width = 750; + viewport_width = 750; } if (!viewport_height) { - viewport_height = 350; + viewport_height = 350; } -if(type_graph_pdf == 'combined'){ - post_data = "data=" + url_params + - "&data_combined=" + url_params_comb + - "&data_module_list=" + url_module_list + - "&type_graph_pdf=" + type_graph_pdf + - "&session_id=" + session_id; -} -else{ - post_data = "data=" + url_params + - "&type_graph_pdf=" + type_graph_pdf + - "&session_id=" + session_id; +if (type_graph_pdf == "combined") { + post_data = + "data=" + + url_params + + "&data_combined=" + + url_params_comb + + "&data_module_list=" + + url_module_list + + "&type_graph_pdf=" + + type_graph_pdf + + "&session_id=" + + session_id; +} else { + post_data = + "data=" + + url_params + + "&type_graph_pdf=" + + type_graph_pdf + + "&session_id=" + + session_id; } - - -var page = require('webpage').create(); - +var page = require("webpage").create(); page.viewportSize = { - width: viewport_width, - height: viewport_height + width: viewport_width, + height: viewport_height }; page.zoomFactor = 1; - -page.onCallback = function (st){ - if(!base_64){ - page.render(output_filename, {format: 'png'}); - } else{ - var base64 = page.renderBase64('png'); - // do not remove this console.output - console.log(base64); - } - phantom.exit(); - +page.onConsoleMessage = function(msg) { + console.log(msg); }; +page.onError = function(msg) { + console.log(msg); + page.close(); +}; -page.open(url, 'POST', post_data, function (status) { -}); +page.onCallback = function(st) { + if (!base_64) { + page.render(output_filename, { format: "png" }); + } else { + var base64 = page.renderBase64("png"); + // do not remove this console.output + console.log(base64); + } + phantom.exit(); +}; +page.open(url, "POST", post_data, function(status) {}); diff --git a/pandora_console/index.php b/pandora_console/index.php index 776e0d8eb2..ad4b93465a 100755 --- a/pandora_console/index.php +++ b/pandora_console/index.php @@ -4,19 +4,29 @@ // ================================================== // Copyright (c) 2005-2012 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; version 2 - // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +// Enable profiler for testing +if (!defined('__PAN_XHPROF__')) { + define('__PAN_XHPROF__', 0); +} -//Set character encoding to UTF-8 - fixes a lot of multibyte character headaches -if (function_exists ('mb_internal_encoding')) { - mb_internal_encoding ("UTF-8"); +if (__PAN_XHPROF__ === 1) { + if (function_exists('tideways_xhprof_enable')) { + tideways_xhprof_enable(); + } else { + error_log('Cannot find tideways_xhprof_enable function'); + } +} + +// Set character encoding to UTF-8 - fixes a lot of multibyte character headaches +if (function_exists('mb_internal_encoding')) { + mb_internal_encoding('UTF-8'); } // Set to 1 to do not check for installer or config file (for development!). @@ -24,898 +34,952 @@ if (function_exists ('mb_internal_encoding')) { $develop_bypass = 0; if ($develop_bypass != 1) { - // If no config file, automatically try to install - if (! file_exists ("include/config.php")) { - if (! file_exists ("install.php")) { - $url = explode('/', $_SERVER['REQUEST_URI']); - $flag_url =0; - foreach ($url as $key => $value) { - if (strpos($value, 'index.php') !== false || $flag_url) { - $flag_url=1; - unset($url[$key]); - } - else if(strpos($value, 'enterprise') !== false || $flag_url){ - $flag_url=1; - unset($url[$key]); - } - } - $config["homeurl"] = rtrim(join("/", $url),"/"); - $config["homeurl_static"] = $config["homeurl"]; - $login_screen = 'error_noconfig'; - $ownDir = dirname(__FILE__) . DIRECTORY_SEPARATOR; - $config['homedir'] = $ownDir; - require('general/error_screen.php'); - exit; - } - else { - include ("install.php"); - exit; - } - } - - if (filesize("include/config.php") == 0) { - include ("install.php"); - exit; - } + // If no config file, automatically try to install + if (! file_exists('include/config.php')) { + if (! file_exists('install.php')) { + $url = explode('/', $_SERVER['REQUEST_URI']); + $flag_url = 0; + foreach ($url as $key => $value) { + if (strpos($value, 'index.php') !== false || $flag_url) { + $flag_url = 1; + unset($url[$key]); + } else if (strpos($value, 'enterprise') !== false || $flag_url) { + $flag_url = 1; + unset($url[$key]); + } + } - if (isset($_POST["rename_file"])){ - $rename_file_install = (bool)$_POST["rename_file"]; - if ($rename_file_install) { - $salida_rename = rename("install.php", "install_old.php"); - } - } + $config['homeurl'] = rtrim(join('/', $url), '/'); + $config['homeurl_static'] = $config['homeurl']; + $login_screen = 'error_noconfig'; + $ownDir = dirname(__FILE__).DIRECTORY_SEPARATOR; + $config['homedir'] = $ownDir; + include 'general/error_screen.php'; + exit; + } else { + include 'install.php'; + exit; + } + } - // Check for installer presence - if (file_exists ("install.php")) { - $login_screen = 'error_install'; - require('general/error_screen.php'); - exit; - } - // Check perms for config.php - if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { - if ((substr (sprintf ('%o', fileperms('include/config.php')), -4) != "0600") && - (substr (sprintf ('%o', fileperms('include/config.php')), -4) != "0660") && - (substr (sprintf ('%o', fileperms('include/config.php')), -4) != "0640")) { - $url = explode('/', $_SERVER['REQUEST_URI']); - $flag_url =0; - foreach ($url as $key => $value) { - if (strpos($value, 'index.php') !== false || $flag_url) { - $flag_url=1; - unset($url[$key]); - } - else if(strpos($value, 'enterprise') !== false || $flag_url){ - $flag_url=1; - unset($url[$key]); - } - } - $config["homeurl"] = rtrim(join("/", $url),"/"); - $config["homeurl_static"] = $config["homeurl"]; - $ownDir = dirname(__FILE__) . DIRECTORY_SEPARATOR; - $config['homedir'] = $ownDir; - $login_screen = 'error_perms'; - require('general/error_screen.php'); - exit; - } - } + if (filesize('include/config.php') == 0) { + include 'install.php'; + exit; + } + + if (isset($_POST['rename_file'])) { + $rename_file_install = (bool) $_POST['rename_file']; + if ($rename_file_install) { + $salida_rename = rename('install.php', 'install_old.php'); + } + } + + // Check for installer presence + if (file_exists('install.php')) { + $login_screen = 'error_install'; + include 'general/error_screen.php'; + exit; + } + + // Check perms for config.php + if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') { + if ((substr(sprintf('%o', fileperms('include/config.php')), -4) != '0600') + && (substr(sprintf('%o', fileperms('include/config.php')), -4) != '0660') + && (substr(sprintf('%o', fileperms('include/config.php')), -4) != '0640') + ) { + $url = explode('/', $_SERVER['REQUEST_URI']); + $flag_url = 0; + foreach ($url as $key => $value) { + if (strpos($value, 'index.php') !== false || $flag_url) { + $flag_url = 1; + unset($url[$key]); + } else if (strpos($value, 'enterprise') !== false || $flag_url) { + $flag_url = 1; + unset($url[$key]); + } + } + + $config['homeurl'] = rtrim(join('/', $url), '/'); + $config['homeurl_static'] = $config['homeurl']; + $ownDir = dirname(__FILE__).DIRECTORY_SEPARATOR; + $config['homedir'] = $ownDir; + $login_screen = 'error_perms'; + include 'general/error_screen.php'; + exit; + } + } } -if ((! file_exists ("include/config.php")) || (! is_readable ("include/config.php"))) { - $login_screen = 'error_noconfig'; - require('general/error_screen.php'); - exit; +if ((! file_exists('include/config.php')) || (! is_readable('include/config.php'))) { + $login_screen = 'error_noconfig'; + include 'general/error_screen.php'; + exit; } -////////////////////////////////////// -//// PLEASE DO NOT CHANGE ORDER ////// -////////////////////////////////////// -require_once ("include/config.php"); -require_once ("include/functions_config.php"); +// +// PLEASE DO NOT CHANGE ORDER ////// +// +require_once 'include/config.php'; +require_once 'include/functions_config.php'; -if (isset($config["error"])) { - $login_screen = $config["error"]; - require('general/error_screen.php'); - exit; +if (isset($config['error'])) { + $login_screen = $config['error']; + include 'general/error_screen.php'; + exit; } // If metaconsole activated, redirect to it if ($config['metaconsole'] == 1 && $config['enterprise_installed'] == 1) { - header ("Location: " . $config['homeurl'] . "enterprise/meta"); - exit; //Always exit after sending location headers + header('Location: '.$config['homeurl'].'enterprise/meta'); + exit; + // Always exit after sending location headers } -if (file_exists (ENTERPRISE_DIR . "/include/functions_login.php")) { - include_once (ENTERPRISE_DIR . "/include/functions_login.php"); +if (file_exists(ENTERPRISE_DIR.'/include/functions_login.php')) { + include_once ENTERPRISE_DIR.'/include/functions_login.php'; } -//////////////////////////////////////// -if (!empty ($config["https"]) && empty ($_SERVER['HTTPS'])) { - $query = ''; - if (sizeof ($_REQUEST)) - //Some (old) browsers don't like the ?&key=var - $query .= '?1=1'; - - //We don't clean these variables up as they're only being passed along - foreach ($_GET as $key => $value) { - if ($key == 1) - continue; - $query .= '&'.$key.'='.$value; - } - foreach ($_POST as $key => $value) { - $query .= '&'.$key.'='.$value; - } - $url = ui_get_full_url($query); - - // Prevent HTTP response splitting attacks - // http://en.wikipedia.org/wiki/HTTP_response_splitting - $url = str_replace ("\n", "", $url); - - header ('Location: '.$url); - exit; //Always exit after sending location headers +if (!empty($config['https']) && empty($_SERVER['HTTPS'])) { + $query = ''; + if (sizeof($_REQUEST)) { + // Some (old) browsers don't like the ?&key=var + $query .= '?1=1'; + } + + // We don't clean these variables up as they're only being passed along + foreach ($_GET as $key => $value) { + if ($key == 1) { + continue; + } + + $query .= '&'.$key.'='.$value; + } + + foreach ($_POST as $key => $value) { + $query .= '&'.$key.'='.$value; + } + + $url = ui_get_full_url($query); + + // Prevent HTTP response splitting attacks + // http://en.wikipedia.org/wiki/HTTP_response_splitting + $url = str_replace("\n", '', $url); + + header('Location: '.$url); + exit; + // Always exit after sending location headers } // Pure mode (without menu, header and footer). -$config["pure"] = (bool) get_parameter ("pure"); +$config['pure'] = (bool) get_parameter('pure'); // Auto Refresh page (can now be disabled anywhere in the script) -if (get_parameter ("refr")) - $config["refr"] = (int) get_parameter ("refr"); - -$delete_file = get_parameter("del_file"); -if ($delete_file == 'yes_delete'){ - $salida_delete = shell_exec('rm /var/www/html/pandora_console/install.php'); +if (get_parameter('refr')) { + $config['refr'] = (int) get_parameter('refr'); } -ob_start (); -echo '' . - "\n"; -echo '' . "\n"; -echo '' . "\n"; +$delete_file = get_parameter('del_file'); +if ($delete_file == 'yes_delete') { + $salida_delete = shell_exec('rm /var/www/html/pandora_console/install.php'); +} -//This starts the page head. In the call back function, things from $page['head'] array will be processed into the head -ob_start ('ui_process_page_head'); +ob_start(); +echo ''."\n"; +echo ''."\n"; +echo ''."\n"; -// Enterprise main -enterprise_include ('index.php'); +// This starts the page head. In the call back function, things from $page['head'] array will be processed into the head +ob_start('ui_process_page_head'); + +// Enterprise main +enterprise_include('index.php'); echo ''; // This tag is included in the buffer passed to ui_process_page_head so // technically it can be stripped -echo '' . "\n"; +echo ''."\n"; -require_once ("include/functions_themes.php"); -ob_start ('ui_process_page_body'); +require_once 'include/functions_themes.php'; +ob_start('ui_process_page_body'); -$config["remote_addr"] = $_SERVER['REMOTE_ADDR']; +$config['remote_addr'] = $_SERVER['REMOTE_ADDR']; -$sec2 = get_parameter_get ('sec2'); -$sec2 = safe_url_extraclean ($sec2); -$page = $sec2; //Reference variable for old time sake - -$sec = get_parameter_get ('sec'); -$sec = safe_url_extraclean ($sec); +$sec2 = get_parameter_get('sec2'); +$sec2 = safe_url_extraclean($sec2); +$page = $sec2; +// Reference variable for old time sake +$sec = get_parameter_get('sec'); +$sec = safe_url_extraclean($sec); $process_login = false; // Update user password $change_pass = get_parameter_post('renew_password', 0); - -if ($change_pass == 1) { - $password_old = (string) get_parameter_post ('old_password', ''); - $password_new = (string) get_parameter_post ('new_password', ''); - $password_confirm = (string) get_parameter_post ('confirm_new_password', ''); - $id = (string) get_parameter_post ('login', ''); - - $changed_pass = login_update_password_check ($password_old, $password_new, $password_confirm, $id); +if ($change_pass == 1) { + $password_old = (string) get_parameter_post('old_password', ''); + $password_new = (string) get_parameter_post('new_password', ''); + $password_confirm = (string) get_parameter_post('confirm_new_password', ''); + $id = (string) get_parameter_post('login', ''); + + $changed_pass = login_update_password_check($password_old, $password_new, $password_confirm, $id); } $minor_release_message = false; $searchPage = false; -$search = get_parameter_get("head_search_keywords"); +$search = get_parameter_get('head_search_keywords'); if (strlen($search) > 0) { - $config['search_keywords'] = io_safe_input(trim(io_safe_output(get_parameter('keywords')))); - // If not search category providad, we'll use an agent search - $config['search_category'] = get_parameter('search_category', 'all'); - if (($config['search_keywords'] != 'Enter keywords to search') && (strlen($config['search_keywords']) > 0)) - $searchPage = true; + $config['search_keywords'] = io_safe_input(trim(io_safe_output(get_parameter('keywords')))); + // If not search category providad, we'll use an agent search + $config['search_category'] = get_parameter('search_category', 'all'); + if (($config['search_keywords'] != 'Enter keywords to search') && (strlen($config['search_keywords']) > 0)) { + $searchPage = true; + } } // Login process -if (! isset ($config['id_user'])) { - if (isset ($_GET["login"])) { - include_once('include/functions_db.php'); //Include it to use escape_string_sql function - - $config["auth_error"] = ""; //Set this to the error message from the authorization mechanism - $nick = get_parameter_post ("nick"); //This is the variable with the login - $pass = get_parameter_post ("pass"); //This is the variable with the password - $nick = db_escape_string_sql($nick); - $pass = db_escape_string_sql($pass); - - //Since now, only the $pass variable are needed - unset ($_GET['pass'], $_POST['pass'], $_REQUEST['pass']); - - // If the auth_code exists, we assume the user has come through the double auth page - if (isset ($_POST['auth_code'])) { - $double_auth_success = false; - - // The double authentication is activated and the user has surpassed the first step (the login). - // Now the authentication code provided will be checked. - if (isset ($_SESSION['prepared_login_da'])) { - if (isset ($_SESSION['prepared_login_da']['id_user']) - && isset ($_SESSION['prepared_login_da']['timestamp'])) { - - // The user has a maximum of 5 minutes to introduce the double auth code - $dauth_period = SECONDS_2MINUTES; - $now = time(); - $dauth_time = $_SESSION['prepared_login_da']['timestamp']; - - if ($now - $dauth_period < $dauth_time) { - // Nick - $nick = $_SESSION["prepared_login_da"]['id_user']; - // Code - $code = (string) get_parameter_post ("auth_code"); - - if (!empty($code)) { - $result = validate_double_auth_code($nick, $code); - - if ($result === true) { - // Double auth success - $double_auth_success = true; - } - else { - // Screen - $login_screen = 'double_auth'; - // Error message - $config["auth_error"] = __("Invalid code"); - - if (!isset($_SESSION['prepared_login_da']['attempts'])) - $_SESSION['prepared_login_da']['attempts'] = 0; - $_SESSION['prepared_login_da']['attempts']++; - } - } - else { - // Screen - $login_screen = 'double_auth'; - // Error message - $config["auth_error"] = __("The code shouldn't be empty"); - - if (!isset($_SESSION['prepared_login_da']['attempts'])) - $_SESSION['prepared_login_da']['attempts'] = 0; - $_SESSION['prepared_login_da']['attempts']++; - } - } - else { - // Expired login - unset ($_SESSION['prepared_login_da']); - - // Error message - $config["auth_error"] = __('Expired login'); - } - } - else { - // If the code doesn't exist, remove the prepared login - unset ($_SESSION['prepared_login_da']); - - // Error message - $config["auth_error"] = __('Login error'); - } - } - // If $_SESSION['prepared_login_da'] doesn't exist, the user have to do the login again - else { - // Error message - $config["auth_error"] = __('Login error'); - } - - // Remove the authenticator code - unset ($_POST['auth_code'], $code); - - if (!$double_auth_success) { - $login_failed = true; - require_once ('general/login_page.php'); - db_pandora_audit("Logon Failed", "Invalid double auth login: " - .$_SERVER['REMOTE_ADDR'], $_SERVER['REMOTE_ADDR']); - while (@ob_end_flush ()); - exit (""); - } - } - $login_button_saml = get_parameter("login_button_saml", false); - if (isset ($double_auth_success) && $double_auth_success) { - // This values are true cause there are checked before complete the 2nd auth step - $nick_in_db = $_SESSION["prepared_login_da"]['id_user']; - $expired_pass = false; - } - else if (($config['auth'] == 'saml') && ($login_button_saml)) { - include_once(ENTERPRISE_DIR . "/include/auth/saml.php"); - - $saml_user_id = saml_process_user_login(); - - $nick_in_db = $saml_user_id; - if (!$nick_in_db) { - require_once($config['saml_path'] . 'simplesamlphp/lib/_autoload.php'); - $as = new SimpleSAML_Auth_Simple('PandoraFMS'); - $as->logout(); - } - } - else { - // process_user_login is a virtual function which should be defined in each auth file. - // It accepts username and password. The rest should be internal to the auth file. - // The auth file can set $config["auth_error"] to an informative error output or reference their internal error messages to it - // process_user_login should return false in case of errors or invalid login, the nickname if correct - $nick_in_db = process_user_login ($nick, $pass); - - $expired_pass = false; - - if (($nick_in_db != false) && ((!is_user_admin($nick) - || $config['enable_pass_policy_admin'])) - && (file_exists (ENTERPRISE_DIR . "/load_enterprise.php")) - && ($config['enable_pass_policy'])) { - include_once(ENTERPRISE_DIR . "/include/auth/mysql.php"); - - $blocked = login_check_blocked($nick); - - if ($blocked) { - require_once ('general/login_page.php'); - db_pandora_audit("Password expired", "Password expired: ".io_safe_output($nick), io_safe_output($nick)); - while (@ob_end_flush ()); - exit (""); - } - - //Checks if password has expired - $check_status = check_pass_status($nick, $pass); - - switch ($check_status) { - case PASSSWORD_POLICIES_FIRST_CHANGE: //first change - case PASSSWORD_POLICIES_EXPIRED: //pass expired - $expired_pass = true; - login_change_password($nick, '',$check_status); - break; - } - } - } - - if (($nick_in_db !== false) && $expired_pass) { - //login ok and password has expired - - require_once ('general/login_page.php'); - db_pandora_audit("Password expired", - "Password expired: " . io_safe_output($nick), $nick); - while (@ob_end_flush ()); - exit (""); - } - else if (($nick_in_db !== false) && (!$expired_pass)) { - //login ok and password has not expired - - // Double auth check - if ((!isset ($double_auth_success) || !$double_auth_success) && is_double_auth_enabled($nick_in_db)) { - // Store this values in the session to know if the user login was correct - $_SESSION['prepared_login_da'] = array( - 'id_user' => $nick_in_db, - 'timestamp' => time(), - 'attempts' => 0 - ); - - // Load the page to introduce the double auth code - $login_screen = 'double_auth'; - require_once ('general/login_page.php'); - while (@ob_end_flush ()); - exit (""); - } - - //login ok and password has not expired - $process_login = true; - - if (is_user_admin($nick)) - echo ""; - else - echo ""; - - if (!isset($_GET["sec2"]) && !isset($_GET["sec"])) { - // Avoid the show homepage when the user go to - // a specific section of pandora - // for example when timeout the sesion - - unset ($_GET["sec2"]); - $_GET["sec"] = "general/logon_ok"; - $home_page =''; - if (isset($nick)) { - $user_info = users_get_user_by_id($nick); - $home_page = io_safe_output($user_info['section']); - $home_url = $user_info['data_section']; - if ($home_page != '') { - switch ($home_page) { - case 'Event list': - $_GET["sec"] = "eventos"; - $_GET["sec2"] = "operation/events/events"; - break; - case 'Group view': - $_GET["sec"] = "estado"; - $_GET["sec2"] = "operation/agentes/group_view"; - break; - case 'Alert detail': - $_GET["sec"] = "estado"; - $_GET["sec2"] = "operation/agentes/alerts_status"; - break; - case 'Tactical view': - $_GET["sec"] = "estado"; - $_GET["sec2"] = "operation/agentes/tactical"; - break; - case 'Default': - $_GET["sec"] = "general/logon_ok"; - break; - case 'Dashboard': - $_GET["sec"] = "reporting"; - $_GET["sec2"] = ENTERPRISE_DIR.'/dashboard/main_dashboard'; - $id_dashboard_select = - db_get_value('id', 'tdashboard', 'name', $home_url); - $_GET['id_dashboard_select'] = $id_dashboard_select; - $_GET['d_from_main_page'] = 1; - break; - case 'Visual console': - $_GET["sec"] = "network"; - $_GET["sec2"] = "operation/visual_console/index"; - break; - case 'Other': - $home_url = io_safe_output($home_url); - $url_array = parse_url($home_url); - parse_str ($url_array['query'], $res); - foreach ($res as $key => $param) { - $_GET[$key] = $param; - } - break; - } - } - else { - $_GET["sec"] = "general/logon_ok"; - } - } - - } - - db_logon ($nick_in_db, $_SERVER['REMOTE_ADDR']); - $_SESSION['id_usuario'] = $nick_in_db; - $config['id_user'] = $nick_in_db; - - // Check if connection goes through F5 balancer. If it does, then don't call config_prepare_session() or user will be back to login all the time - $prepare_session = true; - foreach ($_COOKIE as $key=>$value) { - if (preg_match('/BIGipServer*/',$key) ) { - $prepare_session = false; - } - } - if ($prepare_session){ - config_prepare_session(); - } +if (! isset($config['id_user'])) { + if (isset($_GET['login'])) { + include_once 'include/functions_db.php'; + // Include it to use escape_string_sql function + $config['auth_error'] = ''; + // Set this to the error message from the authorization mechanism + $nick = get_parameter_post('nick'); + // This is the variable with the login + $pass = get_parameter_post('pass'); + // This is the variable with the password + $nick = db_escape_string_sql($nick); + $pass = db_escape_string_sql($pass); - if (is_user_admin($config['id_user'])) { - // PHP configuration values - $PHPupload_max_filesize = config_return_in_bytes(ini_get('upload_max_filesize')); - $PHPmemory_limit = config_return_in_bytes(ini_get('memory_limit')); - $PHPmax_execution_time = ini_get('max_execution_time'); - - if ($PHPmax_execution_time !== '0') { - set_time_limit(0); - } - - $PHPupload_max_filesize_min = config_return_in_bytes('800M'); - - if ($PHPupload_max_filesize < $PHPupload_max_filesize_min) { - ini_set('upload_max_filesize', config_return_in_bytes('800M')); - } - - $PHPmemory_limit_min = config_return_in_bytes('500M'); - - if ($PHPmemory_limit < $PHPmemory_limit_min && $PHPmemory_limit !== '-1') { - ini_set('memory_limit', config_return_in_bytes('500M')); - } - - set_time_limit((int)$PHPmax_execution_time); - ini_set('upload_max_filesize', $PHPupload_max_filesize); - ini_set('memory_limit', $PHPmemory_limit); - } - - //========================================================== - //-------- SET THE CUSTOM CONFIGS OF USER ------------------ - - config_user_set_custom_config(); - //========================================================== - - //Remove everything that might have to do with people's passwords or logins - unset ($pass, $login_good); - - $user_language = get_user_language($config['id_user']); - - $l10n = NULL; - if (file_exists ('./include/languages/' . $user_language . '.mo')) { - $l10n = new gettext_reader (new CachedFileReader ('./include/languages/'.$user_language.'.mo')); - $l10n->load_tables(); - } - } - else { //login wrong - $blocked = false; - - if ((!is_user_admin($nick) || $config['enable_pass_policy_admin']) && file_exists (ENTERPRISE_DIR . "/load_enterprise.php")) { - $blocked = login_check_blocked($nick); - } - $nick_usable = io_safe_output($nick); - if (!$blocked) { - if (file_exists (ENTERPRISE_DIR . "/load_enterprise.php")) { - login_check_failed($nick); //Checks failed attempts - } - $login_failed = true; - require_once ('general/login_page.php'); - db_pandora_audit("Logon Failed", "Invalid login: ".$nick_usable, $nick_usable); - while (@ob_end_flush ()); - exit (""); - } - else { - require_once ('general/login_page.php'); - db_pandora_audit("Logon Failed", "Invalid login: ".$nick_usable, $nick_usable); - while (@ob_end_flush ()); - exit (""); - } - } - // Form the url - $query_params_redirect = $_GET; - // Visual console do not want sec2 - if($home_page == 'Visual console') unset($query_params_redirect["sec2"]); - $redirect_url = '?logged=1'; - foreach ($query_params_redirect as $key => $value) { - if ($key == "login") continue; - $redirect_url .= '&'.safe_url_extraclean($key).'='.safe_url_extraclean($value); - } - header("Location: ".$config['homeurl']."index.php".$redirect_url); - exit; //Always exit after sending location headers - } - // Hash login process - elseif (isset ($_GET["loginhash"])) { - $loginhash_data = get_parameter("loginhash_data", ""); - $loginhash_user = str_rot13(get_parameter("loginhash_user", "")); - - if ($config["loginhash_pwd"] != "" && $loginhash_data == md5($loginhash_user.io_output_password($config["loginhash_pwd"]))) { - db_logon ($loginhash_user, $_SERVER['REMOTE_ADDR']); - $_SESSION['id_usuario'] = $loginhash_user; - $config["id_user"] = $loginhash_user; - } - else { - require_once ('general/login_page.php'); - db_pandora_audit("Logon Failed (loginhash", "", "system"); - while (@ob_end_flush ()); - exit (""); - } - } - // There is no user connected - else { - if ($config['enterprise_installed']) { - enterprise_include_once ('include/functions_reset_pass.php'); - } + // Since now, only the $pass variable are needed + unset($_GET['pass'], $_POST['pass'], $_REQUEST['pass']); - $correct_pass_change = (boolean)get_parameter('correct_pass_change', 0); - $reset = (boolean)get_parameter('reset', 0); - $first = (boolean)get_parameter('first', 0); - $reset_hash = get_parameter('reset_hash', ""); + // If the auth_code exists, we assume the user has come through the double auth page + if (isset($_POST['auth_code'])) { + $double_auth_success = false; - if ($correct_pass_change) { - $correct_reset_pass_process = ""; - $process_error_message = ""; - $pass1 = get_parameter('pass1'); - $pass2 = get_parameter('pass2'); - $id_user = get_parameter('id_user'); + // The double authentication is activated and the user has surpassed the first step (the login). + // Now the authentication code provided will be checked. + if (isset($_SESSION['prepared_login_da'])) { + if (isset($_SESSION['prepared_login_da']['id_user']) + && isset($_SESSION['prepared_login_da']['timestamp']) + ) { + // The user has a maximum of 5 minutes to introduce the double auth code + $dauth_period = SECONDS_2MINUTES; + $now = time(); + $dauth_time = $_SESSION['prepared_login_da']['timestamp']; - if ($pass1 == $pass2) { - $res = update_user_password ($id_user, $pass1); - if ($res) { - - db_process_sql_insert ('tsesion', array('id_sesion' => '','id_usuario' => $id_user,'ip_origen' => $_SERVER['REMOTE_ADDR'],'accion' => 'Reset change', - 'descripcion' => 'Successful reset password process ','fecha' => date("Y-m-d H:i:s"),'utimestamp' => time())); - - $correct_reset_pass_process = __('Password changed successfully'); + if (($now - $dauth_period) < $dauth_time) { + // Nick + $nick = $_SESSION['prepared_login_da']['id_user']; + // Code + $code = (string) get_parameter_post('auth_code'); - register_pass_change_try($id_user, 1); - } - else { - register_pass_change_try($id_user, 0); + if (!empty($code)) { + $result = validate_double_auth_code($nick, $code); - $process_error_message = __('Failed to change password'); - } - } - else { - register_pass_change_try($id_user, 0); + if ($result === true) { + // Double auth success + $double_auth_success = true; + } else { + // Screen + $login_screen = 'double_auth'; + // Error message + $config['auth_error'] = __('Invalid code'); - $process_error_message = __('Passwords must be the same'); - } - require_once ('general/login_page.php'); - } - else { - if ($reset_hash != "") { - $hash_data = explode(":::", $reset_hash); - $id_user = $hash_data[0]; - $codified_hash = $hash_data[1]; + if (!isset($_SESSION['prepared_login_da']['attempts'])) { + $_SESSION['prepared_login_da']['attempts'] = 0; + } - $db_reset_pass_entry = db_get_value_filter('reset_time', 'treset_pass', array('id_user' => $id_user, 'cod_hash' => $id_user . ":::" . $codified_hash)); - $process_error_message = ""; + $_SESSION['prepared_login_da']['attempts']++; + } + } else { + // Screen + $login_screen = 'double_auth'; + // Error message + $config['auth_error'] = __("The code shouldn't be empty"); - if ($db_reset_pass_entry) { - if (($db_reset_pass_entry + SECONDS_2HOUR) < time()) { - register_pass_change_try($id_user, 0); - $process_error_message = __('Too much time since password change request'); - delete_reset_pass_entry($id_user); - require_once ('general/login_page.php'); - } - else { - delete_reset_pass_entry($id_user); - require_once ('enterprise/include/process_reset_pass.php'); - } - } - else { - register_pass_change_try($id_user, 0); - $process_error_message = __('This user has not requested a password change'); - require_once ('general/login_page.php'); - } - } - else { - if (!$reset) { - require_once ('general/login_page.php'); - } - else { - $user_reset_pass = get_parameter('user_reset_pass', ""); - $error = ""; - $mail = ""; - $show_error = false; + if (!isset($_SESSION['prepared_login_da']['attempts'])) { + $_SESSION['prepared_login_da']['attempts'] = 0; + } - if (!$first) { - if ($reset) { - if ($user_reset_pass == '') { - $reset = false; - $error = __('Id user cannot be empty'); - $show_error = true; - } - else { - $check_user = check_user_id($user_reset_pass); + $_SESSION['prepared_login_da']['attempts']++; + } + } else { + // Expired login + unset($_SESSION['prepared_login_da']); - if (!$check_user) { - $reset = false; - register_pass_change_try($user_reset_pass, 0); - $error = __('Error in reset password request'); - $show_error = true; - } - else { - $check_mail = check_user_have_mail($user_reset_pass); + // Error message + $config['auth_error'] = __('Expired login'); + } + } else { + // If the code doesn't exist, remove the prepared login + unset($_SESSION['prepared_login_da']); - if (!$check_mail) { - $reset = false; - register_pass_change_try($user_reset_pass, 0); - $error = __('This user doesn\'t have a valid email address'); - $show_error = true; - } - else { - $mail = $check_mail; - } - } - } - } + // Error message + $config['auth_error'] = __('Login error'); + } + } + // If $_SESSION['prepared_login_da'] doesn't exist, the user have to do the login again + else { + // Error message + $config['auth_error'] = __('Login error'); + } - if (!$reset) { - if ($config['enterprise_installed']) { - require_once ('enterprise/include/reset_pass.php'); - } - } - else { - - $cod_hash = $user_reset_pass . "::::" . md5(rand(10, 1000000) . rand(10, 1000000) . rand(10, 1000000)); + // Remove the authenticator code + unset($_POST['auth_code'], $code); - $subject = '[' . get_product_name() . '] '.__('Reset password'); - $body = __('This is an automatically sent message for user '); - $body .= ' "' . $user_reset_pass . '"'; - $body .= '

                      '; - $body .= __('Please click the link below to reset your password'); - $body .= '

                      '; - $body .= '' . __('Reset your password') . ''; - $body .= '

                      '; - $body .= get_product_name(); - $body .= '

                      '; - $body .= ''.__('Please do not reply to this email.').''; - - $result = send_email_to_user($mail, $body, $subject); - - $process_error_message = ""; - if (!$result) { - $process_error_message = __('Error at sending the email'); - } - else { - send_token_to_db($user_reset_pass, $cod_hash); - } + if (!$double_auth_success) { + $login_failed = true; + include_once 'general/login_page.php'; + db_pandora_audit( + 'Logon Failed', + 'Invalid double auth login: '.$_SERVER['REMOTE_ADDR'], + $_SERVER['REMOTE_ADDR'] + ); + while (@ob_end_flush()) { + } - require_once ('general/login_page.php'); - } - } - else { - require_once ('enterprise/include/reset_pass.php'); - } - } - } - } - - while (@ob_end_flush ()); - exit (""); - } -} -else { - if (isset($_GET["loginhash_data"])) { + exit(''); + } + } - $loginhash_data = get_parameter("loginhash_data", ""); - $loginhash_user = str_rot13(get_parameter("loginhash_user", "")); - $iduser = $_SESSION["id_usuario"]; - //logoff_db ($iduser, $_SERVER["REMOTE_ADDR"]); check why is not available - unset($_SESSION["id_usuario"]); + $login_button_saml = get_parameter('login_button_saml', false); + if (isset($double_auth_success) && $double_auth_success) { + // This values are true cause there are checked before complete the 2nd auth step + $nick_in_db = $_SESSION['prepared_login_da']['id_user']; + $expired_pass = false; + } else if (($config['auth'] == 'saml') && ($login_button_saml)) { + include_once ENTERPRISE_DIR.'/include/auth/saml.php'; + + $saml_user_id = saml_process_user_login(); + + $nick_in_db = $saml_user_id; + if (!$nick_in_db) { + include_once $config['saml_path'].'simplesamlphp/lib/_autoload.php'; + $as = new SimpleSAML_Auth_Simple('PandoraFMS'); + $as->logout(); + } + } else { + // process_user_login is a virtual function which should be defined in each auth file. + // It accepts username and password. The rest should be internal to the auth file. + // The auth file can set $config["auth_error"] to an informative error output or reference their internal error messages to it + // process_user_login should return false in case of errors or invalid login, the nickname if correct + $nick_in_db = process_user_login($nick, $pass); + + $expired_pass = false; + + if (($nick_in_db != false) && ((!is_user_admin($nick) + || $config['enable_pass_policy_admin'])) + && (file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) + && ($config['enable_pass_policy']) + ) { + include_once ENTERPRISE_DIR.'/include/auth/mysql.php'; + + $blocked = login_check_blocked($nick); + + if ($blocked) { + include_once 'general/login_page.php'; + db_pandora_audit('Password expired', 'Password expired: '.$nick, $nick); + while (@ob_end_flush()) { + } + + exit(''); + } + + // Checks if password has expired + $check_status = check_pass_status($nick, $pass); + + switch ($check_status) { + case PASSSWORD_POLICIES_FIRST_CHANGE: + // first change + case PASSSWORD_POLICIES_EXPIRED: + // pass expired + $expired_pass = true; + login_change_password($nick, '', $check_status); + break; + } + } + } + + if (($nick_in_db !== false) && $expired_pass) { + // login ok and password has expired + include_once 'general/login_page.php'; + db_pandora_audit( + 'Password expired', + 'Password expired: '.$nick, + $nick + ); + while (@ob_end_flush()) { + } + + exit(''); + } else if (($nick_in_db !== false) && (!$expired_pass)) { + // login ok and password has not expired + // Double auth check + if ((!isset($double_auth_success) || !$double_auth_success) && is_double_auth_enabled($nick_in_db)) { + // Store this values in the session to know if the user login was correct + $_SESSION['prepared_login_da'] = [ + 'id_user' => $nick_in_db, + 'timestamp' => time(), + 'attempts' => 0, + ]; + + // Load the page to introduce the double auth code + $login_screen = 'double_auth'; + include_once 'general/login_page.php'; + while (@ob_end_flush()) { + } + + exit(''); + } + + // login ok and password has not expired + $process_login = true; + + if (is_user_admin($nick)) { + echo ""; + } else { + echo ""; + } + + if (!isset($_GET['sec2']) && !isset($_GET['sec'])) { + // Avoid the show homepage when the user go to + // a specific section of pandora + // for example when timeout the sesion + unset($_GET['sec2']); + $_GET['sec'] = 'general/logon_ok'; + $home_page = ''; + if (isset($nick)) { + $user_info = users_get_user_by_id($nick); + $home_page = io_safe_output($user_info['section']); + $home_url = $user_info['data_section']; + if ($home_page != '') { + switch ($home_page) { + case 'Event list': + $_GET['sec'] = 'eventos'; + $_GET['sec2'] = 'operation/events/events'; + break; + + case 'Group view': + $_GET['sec'] = 'estado'; + $_GET['sec2'] = 'operation/agentes/group_view'; + break; + + case 'Alert detail': + $_GET['sec'] = 'estado'; + $_GET['sec2'] = 'operation/agentes/alerts_status'; + break; + + case 'Tactical view': + $_GET['sec'] = 'estado'; + $_GET['sec2'] = 'operation/agentes/tactical'; + break; + + case 'Default': + $_GET['sec'] = 'general/logon_ok'; + break; + + case 'Dashboard': + $_GET['sec'] = 'reporting'; + $_GET['sec2'] = ENTERPRISE_DIR.'/dashboard/main_dashboard'; + $id_dashboard_select = db_get_value('id', 'tdashboard', 'name', $home_url); + $_GET['id_dashboard_select'] = $id_dashboard_select; + $_GET['d_from_main_page'] = 1; + break; + + case 'Visual console': + $_GET['sec'] = 'network'; + $_GET['sec2'] = 'operation/visual_console/index'; + break; + + case 'Other': + $home_url = io_safe_output($home_url); + $url_array = parse_url($home_url); + parse_str($url_array['query'], $res); + foreach ($res as $key => $param) { + $_GET[$key] = $param; + } + break; + } + } else { + $_GET['sec'] = 'general/logon_ok'; + } + } + } + + db_logon($nick_in_db, $_SERVER['REMOTE_ADDR']); + $_SESSION['id_usuario'] = $nick_in_db; + $config['id_user'] = $nick_in_db; + + // Check if connection goes through F5 balancer. If it does, then don't call config_prepare_session() or user will be back to login all the time + $prepare_session = true; + foreach ($_COOKIE as $key => $value) { + if (preg_match('/BIGipServer*/', $key)) { + $prepare_session = false; + } + } + + if ($prepare_session) { + config_prepare_session(); + } + + if (is_user_admin($config['id_user'])) { + // PHP configuration values + $PHPupload_max_filesize = config_return_in_bytes(ini_get('upload_max_filesize')); + $PHPmemory_limit = config_return_in_bytes(ini_get('memory_limit')); + $PHPmax_execution_time = ini_get('max_execution_time'); + + if ($PHPmax_execution_time !== '0') { + set_time_limit(0); + } + + $PHPupload_max_filesize_min = config_return_in_bytes('800M'); + + if ($PHPupload_max_filesize < $PHPupload_max_filesize_min) { + ini_set('upload_max_filesize', config_return_in_bytes('800M')); + } + + $PHPmemory_limit_min = config_return_in_bytes('500M'); + + if ($PHPmemory_limit < $PHPmemory_limit_min && $PHPmemory_limit !== '-1') { + ini_set('memory_limit', config_return_in_bytes('500M')); + } + + set_time_limit((int) $PHPmax_execution_time); + ini_set('upload_max_filesize', $PHPupload_max_filesize); + ini_set('memory_limit', $PHPmemory_limit); + } + + // ========================================================== + // -------- SET THE CUSTOM CONFIGS OF USER ------------------ + config_user_set_custom_config(); + // ========================================================== + // Remove everything that might have to do with people's passwords or logins + unset($pass, $login_good); + + $user_language = get_user_language($config['id_user']); + + $l10n = null; + if (file_exists('./include/languages/'.$user_language.'.mo')) { + $l10n = new gettext_reader(new CachedFileReader('./include/languages/'.$user_language.'.mo')); + $l10n->load_tables(); + } + } else { + // login wrong + $blocked = false; + + if ((!is_user_admin($nick) || $config['enable_pass_policy_admin']) && file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) { + $blocked = login_check_blocked($nick); + } + + if (!$blocked) { + if (file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) { + login_check_failed($nick); + // Checks failed attempts + } + + $login_failed = true; + include_once 'general/login_page.php'; + db_pandora_audit('Logon Failed', 'Invalid login: '.$nick, $nick); + while (@ob_end_flush()) { + } + + exit(''); + } else { + include_once 'general/login_page.php'; + db_pandora_audit('Logon Failed', 'Invalid login: '.$nick, $nick); + while (@ob_end_flush()) { + } + + exit(''); + } + } + + // Form the url + $query_params_redirect = $_GET; + // Visual console do not want sec2 + if ($home_page == 'Visual console') { + unset($query_params_redirect['sec2']); + } + + $redirect_url = '?logged=1'; + foreach ($query_params_redirect as $key => $value) { + if ($key == 'login') { + continue; + } + + $redirect_url .= '&'.safe_url_extraclean($key).'='.safe_url_extraclean($value); + } + + header('Location: '.$config['homeurl'].'index.php'.$redirect_url); + exit; + // Always exit after sending location headers + } + // Hash login process + else if (isset($_GET['loginhash'])) { + $loginhash_data = get_parameter('loginhash_data', ''); + $loginhash_user = str_rot13(get_parameter('loginhash_user', '')); + + if ($config['loginhash_pwd'] != '' && $loginhash_data == md5($loginhash_user.io_output_password($config['loginhash_pwd']))) { + db_logon($loginhash_user, $_SERVER['REMOTE_ADDR']); + $_SESSION['id_usuario'] = $loginhash_user; + $config['id_user'] = $loginhash_user; + } else { + include_once 'general/login_page.php'; + db_pandora_audit('Logon Failed (loginhash', '', 'system'); + while (@ob_end_flush()) { + } + + exit(''); + } + } + // There is no user connected + else { + if ($config['enterprise_installed']) { + enterprise_include_once('include/functions_reset_pass.php'); + } + + $correct_pass_change = (boolean) get_parameter('correct_pass_change', 0); + $reset = (boolean) get_parameter('reset', 0); + $first = (boolean) get_parameter('first', 0); + $reset_hash = get_parameter('reset_hash', ''); + + if ($correct_pass_change) { + $correct_reset_pass_process = ''; + $process_error_message = ''; + $pass1 = get_parameter('pass1'); + $pass2 = get_parameter('pass2'); + $id_user = get_parameter('id_user'); + + if ($pass1 == $pass2) { + $res = update_user_password($id_user, $pass1); + if ($res) { + db_process_sql_insert( + 'tsesion', + [ + 'id_sesion' => '', + 'id_usuario' => $id_user, + 'ip_origen' => $_SERVER['REMOTE_ADDR'], + 'accion' => 'Reset change', + 'descripcion' => 'Successful reset password process ', + 'fecha' => date('Y-m-d H:i:s'), + 'utimestamp' => time(), + ] + ); + + $correct_reset_pass_process = __('Password changed successfully'); + + register_pass_change_try($id_user, 1); + } else { + register_pass_change_try($id_user, 0); + + $process_error_message = __('Failed to change password'); + } + } else { + register_pass_change_try($id_user, 0); + + $process_error_message = __('Passwords must be the same'); + } + + include_once 'general/login_page.php'; + } else { + if ($reset_hash != '') { + $hash_data = explode(':::', $reset_hash); + $id_user = $hash_data[0]; + $codified_hash = $hash_data[1]; + + $db_reset_pass_entry = db_get_value_filter('reset_time', 'treset_pass', ['id_user' => $id_user, 'cod_hash' => $id_user.':::'.$codified_hash]); + $process_error_message = ''; + + if ($db_reset_pass_entry) { + if (($db_reset_pass_entry + SECONDS_2HOUR) < time()) { + register_pass_change_try($id_user, 0); + $process_error_message = __('Too much time since password change request'); + delete_reset_pass_entry($id_user); + include_once 'general/login_page.php'; + } else { + delete_reset_pass_entry($id_user); + include_once 'enterprise/include/process_reset_pass.php'; + } + } else { + register_pass_change_try($id_user, 0); + $process_error_message = __('This user has not requested a password change'); + include_once 'general/login_page.php'; + } + } else { + if (!$reset) { + include_once 'general/login_page.php'; + } else { + $user_reset_pass = get_parameter('user_reset_pass', ''); + $error = ''; + $mail = ''; + $show_error = false; + + if (!$first) { + if ($reset) { + if ($user_reset_pass == '') { + $reset = false; + $error = __('Id user cannot be empty'); + $show_error = true; + } else { + $check_user = check_user_id($user_reset_pass); + + if (!$check_user) { + $reset = false; + register_pass_change_try($user_reset_pass, 0); + $error = __('Error in reset password request'); + $show_error = true; + } else { + $check_mail = check_user_have_mail($user_reset_pass); + + if (!$check_mail) { + $reset = false; + register_pass_change_try($user_reset_pass, 0); + $error = __('This user doesn\'t have a valid email address'); + $show_error = true; + } else { + $mail = $check_mail; + } + } + } + } + + if (!$reset) { + if ($config['enterprise_installed']) { + include_once 'enterprise/include/reset_pass.php'; + } + } else { + $cod_hash = $user_reset_pass.'::::'.md5(rand(10, 1000000).rand(10, 1000000).rand(10, 1000000)); + + $subject = '['.get_product_name().'] '.__('Reset password'); + $body = __('This is an automatically sent message for user '); + $body .= ' "'.$user_reset_pass.'"'; + $body .= '

                      '; + $body .= __('Please click the link below to reset your password'); + $body .= '

                      '; + $body .= ''.__('Reset your password').''; + $body .= '

                      '; + $body .= get_product_name(); + $body .= '

                      '; + $body .= ''.__('Please do not reply to this email.').''; + + $result = send_email_to_user($mail, $body, $subject); + + $process_error_message = ''; + if (!$result) { + $process_error_message = __('Error at sending the email'); + } else { + send_token_to_db($user_reset_pass, $cod_hash); + } + + include_once 'general/login_page.php'; + } + } else { + include_once 'enterprise/include/reset_pass.php'; + } + } + } + } + + while (@ob_end_flush()) { + } + + exit(''); + } +} else { + if (isset($_GET['loginhash_data'])) { + $loginhash_data = get_parameter('loginhash_data', ''); + $loginhash_user = str_rot13(get_parameter('loginhash_user', '')); + $iduser = $_SESSION['id_usuario']; + // logoff_db ($iduser, $_SERVER["REMOTE_ADDR"]); check why is not available + unset($_SESSION['id_usuario']); unset($iduser); - if ($config["loginhash_pwd"] != "" && $loginhash_data == md5($loginhash_user.io_output_password($config["loginhash_pwd"]))) { - db_logon ($loginhash_user, $_SERVER['REMOTE_ADDR']); + if ($config['loginhash_pwd'] != '' && $loginhash_data == md5($loginhash_user.io_output_password($config['loginhash_pwd']))) { + db_logon($loginhash_user, $_SERVER['REMOTE_ADDR']); $_SESSION['id_usuario'] = $loginhash_user; - $config["id_user"] = $loginhash_user; - } - else { - require_once ('general/login_page.php'); - db_pandora_audit("Logon Failed (loginhash", "", "system"); - while (@ob_end_flush ()); - exit (""); + $config['id_user'] = $loginhash_user; + } else { + include_once 'general/login_page.php'; + db_pandora_audit('Logon Failed (loginhash', '', 'system'); + while (@ob_end_flush()) { + } + + exit(''); } } - $user_in_db = db_get_row_filter('tusuario', - array('id_user' => $config['id_user']), '*'); - if ($user_in_db == false) { - //logout - $_REQUEST = array (); - $_GET = array (); - $_POST = array (); - $config["auth_error"] = __("User doesn\'t exist."); - $iduser = $_SESSION["id_usuario"]; - logoff_db ($iduser, $_SERVER["REMOTE_ADDR"]); - unset($_SESSION["id_usuario"]); - unset($iduser); - require_once ('general/login_page.php'); - while (@ob_end_flush ()); - exit (""); - } - else { - if (((bool) $user_in_db['is_admin'] === false) && - ((bool) $user_in_db['not_login'] === true)) { - //logout - $_REQUEST = array (); - $_GET = array (); - $_POST = array (); - $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); - require_once ('general/login_page.php'); - while (@ob_end_flush ()); - exit (""); - } - } + $user_in_db = db_get_row_filter( + 'tusuario', + ['id_user' => $config['id_user']], + '*' + ); + if ($user_in_db == false) { + // logout + $_REQUEST = []; + $_GET = []; + $_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'; + while (@ob_end_flush()) { + } + + exit(''); + } else { + if (((bool) $user_in_db['is_admin'] === false) + && ((bool) $user_in_db['not_login'] === true) + ) { + // logout + $_REQUEST = []; + $_GET = []; + $_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'; + while (@ob_end_flush()) { + } + + exit(''); + } + } } -/* Enterprise support */ -if (file_exists (ENTERPRISE_DIR . "/load_enterprise.php")) { - include_once (ENTERPRISE_DIR . "/load_enterprise.php"); +// Enterprise support +if (file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) { + include_once ENTERPRISE_DIR.'/load_enterprise.php'; } // Log off -if (isset ($_GET["bye"])) { - include ("general/logoff.php"); - $iduser = $_SESSION["id_usuario"]; - db_logoff ($iduser, $_SERVER['REMOTE_ADDR']); +if (isset($_GET['bye'])) { + include 'general/logoff.php'; + $iduser = $_SESSION['id_usuario']; + db_logoff($iduser, $_SERVER['REMOTE_ADDR']); - $_SESSION = array(); - session_destroy(); - header_remove("Set-Cookie"); - setcookie(session_name(), $_COOKIE[session_name()], time() - 4800, "/"); + $_SESSION = []; + session_destroy(); + header_remove('Set-Cookie'); + setcookie(session_name(), $_COOKIE[session_name()], (time() - 4800), '/'); - if ($config['auth'] == 'saml') { - require_once($config['saml_path'] . 'simplesamlphp/lib/_autoload.php'); - $as = new SimpleSAML_Auth_Simple('PandoraFMS'); - $as->logout(); - } - while (@ob_end_flush ()); - exit (""); + if ($config['auth'] == 'saml') { + include_once $config['saml_path'].'simplesamlphp/lib/_autoload.php'; + $as = new SimpleSAML_Auth_Simple('PandoraFMS'); + $as->logout(); + } + + while (@ob_end_flush()) { + } + + exit(''); } clear_pandora_error_for_header(); -//---------------------------------------------------------------------- +// ---------------------------------------------------------------------- // EXTENSIONS -//---------------------------------------------------------------------- -/** +// ---------------------------------------------------------------------- +/* * Load the basic configurations of extension and add extensions into menu. * Load here, because if not, some extensions not load well, I don't why. */ $config['logged'] = false; -extensions_load_extensions ($process_login); +extensions_load_extensions($process_login); // Check for update manager messages -if (license_free() && is_user_admin ($config['id_user']) && - (($config['last_um_check'] < time()) || - (!isset($config['last_um_check'])))) { - - require_once("include/functions_update_manager.php"); - update_manager_download_messages (); +if (license_free() && is_user_admin($config['id_user']) + && (($config['last_um_check'] < time()) + || (!isset($config['last_um_check']))) +) { + include_once 'include/functions_update_manager.php'; + update_manager_download_messages(); } if ($process_login) { - /* Call all extensions login function */ - extensions_call_login_function (); - - unset($_SESSION['new_update']); - - require_once("include/functions_update_manager.php"); - enterprise_include_once("include/functions_update_manager.php"); - - if ($config["autoupdate"] == 1) { - if (enterprise_installed()) { - $result = update_manager_check_online_enterprise_packages_available(); - } - else { - $result = update_manager_check_online_free_packages_available(); - } - if ($result) - $_SESSION['new_update'] = 'new'; - - } - - //Set the initial global counter for chat. - users_get_last_global_counter('session'); - - $config['logged'] = true; -} -//---------------------------------------------------------------------- + // Call all extensions login function + extensions_call_login_function(); -//Get old parameters before navigation. + unset($_SESSION['new_update']); + + include_once 'include/functions_update_manager.php'; + enterprise_include_once('include/functions_update_manager.php'); + + if ($config['autoupdate'] == 1) { + if (enterprise_installed()) { + $result = update_manager_check_online_enterprise_packages_available(); + } else { + $result = update_manager_check_online_free_packages_available(); + } + + if ($result) { + $_SESSION['new_update'] = 'new'; + } + } + + // Set the initial global counter for chat. + users_get_last_global_counter('session'); + + $config['logged'] = true; +} + +// ---------------------------------------------------------------------- +// Get old parameters before navigation. $old_sec = ''; $old_sec2 = ''; $old_page = ''; -if (isset($_SERVER['HTTP_REFERER'])) - $old_page = $_SERVER['HTTP_REFERER']; +if (isset($_SERVER['HTTP_REFERER'])) { + $old_page = $_SERVER['HTTP_REFERER']; +} + $chunks = explode('?', $old_page); if (count($chunks) == 2) { - $chunks = explode('&', $chunks[1]); - - foreach ($chunks as $chunk) { - if (strstr($chunk, 'sec=') !== false) { - $old_sec = str_replace('sec=', '', $chunk); - } - if (strstr($chunk, 'sec2=') !== false) { - $old_sec = str_replace('sec2=', '', $chunk); - } - } + $chunks = explode('&', $chunks[1]); + + foreach ($chunks as $chunk) { + if (strstr($chunk, 'sec=') !== false) { + $old_sec = str_replace('sec=', '', $chunk); + } + + if (strstr($chunk, 'sec2=') !== false) { + $old_sec = str_replace('sec2=', '', $chunk); + } + } } $_SESSION['new_chat'] = false; if ($old_sec2 == 'operation/users/webchat') { - users_get_last_global_counter('session'); + users_get_last_global_counter('session'); } if ($page == 'operation/users/webchat') { - //Reload the global counter. - users_get_last_global_counter('session'); + // Reload the global counter. + users_get_last_global_counter('session'); +} + +if (isset($_SESSION['global_counter_chat'])) { + $old_global_counter_chat = $_SESSION['global_counter_chat']; +} else { + $old_global_counter_chat = users_get_last_global_counter('return'); } -if (isset($_SESSION['global_counter_chat'])) - $old_global_counter_chat = $_SESSION['global_counter_chat']; -else - $old_global_counter_chat = users_get_last_global_counter('return'); $now_global_counter_chat = users_get_last_global_counter('return'); if ($old_global_counter_chat != $now_global_counter_chat) { - if (!users_is_last_system_message()) - $_SESSION['new_chat'] = true; + if (!users_is_last_system_message()) { + $_SESSION['new_chat'] = true; + } } // Pop-ups display order: @@ -923,357 +987,380 @@ if ($old_global_counter_chat != $now_global_counter_chat) { // 2) identification (newsletter and register) // 3) last_message (update manager message popup // 4) login_help (online help, enterpirse version, forums, documentation) -if (is_user_admin ($config['id_user']) && - (!isset($config['initial_wizard']) || $config['initial_wizard'] != 1)) { - include_once ("general/login_required.php"); +if (is_user_admin($config['id_user']) + && (!isset($config['initial_wizard']) || $config['initial_wizard'] != 1) +) { + include_once 'general/login_required.php'; } -if (get_parameter ('login', 0) !== 0) { - // Display news dialog - include_once("general/news_dialog.php"); - - // Display login help info dialog - // If it's configured to not skip this - $display_previous_popup = false; - if (license_free() && is_user_admin ($config['id_user']) && $config['initial_wizard'] == 1) { - $display_previous_popup = include_once("general/login_identification_wizard.php"); - if ($display_previous_popup === false) { - $display_previous_popup = include_once("general/last_message.php"); - } - } - if ((!isset($config['skip_login_help_dialog']) || $config['skip_login_help_dialog'] == 0) && - $display_previous_popup === false && - $config['initial_wizard'] == 1) { - - include_once("general/login_help_dialog.php"); - } - $php_version = phpversion(); - $php_version_array = explode('.', $php_version); - if($php_version_array[0] < 7){ - include_once("general/php7_message.php"); - } +if (get_parameter('login', 0) !== 0) { + // Display news dialog + include_once 'general/news_dialog.php'; + + // Display login help info dialog + // If it's configured to not skip this + $display_previous_popup = false; + if (license_free() && is_user_admin($config['id_user']) && $config['initial_wizard'] == 1) { + $display_previous_popup = include_once 'general/login_identification_wizard.php'; + if ($display_previous_popup === false) { + $display_previous_popup = include_once 'general/last_message.php'; + } + } + + if ((!isset($config['skip_login_help_dialog']) || $config['skip_login_help_dialog'] == 0) + && $display_previous_popup === false + && $config['initial_wizard'] == 1 + ) { + include_once 'general/login_help_dialog.php'; + } + + $php_version = phpversion(); + $php_version_array = explode('.', $php_version); + if ($php_version_array[0] < 7) { + include_once 'general/php7_message.php'; + } } // Header -if ($config["pure"] == 0) { - if ($config['classic_menu']) { - echo '

                      '; - echo '
                      '; - } - else { - echo '
                      '; - } -} -else { - echo '
                      '; - // Require menu only to build structure to use it in ACLs - require ("operation/menu.php"); - require ("godmode/menu.php"); +if ($config['pure'] == 0) { + if ($config['classic_menu']) { + echo '
                      '; + echo '
                      '; + } else { + echo '
                      '; + } +} else { + echo '
                      '; + // Require menu only to build structure to use it in ACLs + include 'operation/menu.php'; + include 'godmode/menu.php'; } // http://es2.php.net/manual/en/ref.session.php#64525 // Session locking concurrency speedup! -session_write_close (); +session_write_close(); // Main block of content -if ($config["pure"] == 0) { - echo '
                      '; +if ($config['pure'] == 0) { + echo '
                      '; } // Page loader / selector if ($searchPage) { - require ('operation/search_results.php'); -} -else { - if ($page != "") { - - $main_sec = get_sec($sec); - if ($main_sec == false) { - if ($sec == 'extensions') - $main_sec = get_parameter('extension_in_menu'); - else - if ($sec == 'gextensions') - $main_sec = get_parameter('extension_in_menu'); - else - $main_sec = $sec; - $sec = $sec2; - $sec2 = ''; - } - $page .= '.php'; - - // Enterprise ACL check - if (enterprise_hook ('enterprise_acl', - array ($config['id_user'], $main_sec, $sec, true,$sec2)) == false) { - - require ("general/noaccess.php"); - - } - else { - $sec = $main_sec; - if (file_exists ($page)) { - if (! extensions_is_extension ($page)) { - - require_once($page); - } - else { - if ($sec[0] == 'g') - extensions_call_godmode_function (basename ($page)); - else - extensions_call_main_function (basename ($page)); - } - } - else { - ui_print_error_message(__('Sorry! I can\'t find the page!')); - } - } - } - else { - //home screen chosen by the user - $home_page =''; - if (isset($config['id_user'])) { - $user_info = users_get_user_by_id($config['id_user']); - $home_page = io_safe_output($user_info['section']); - $home_url = $user_info['data_section']; - } + include 'operation/search_results.php'; +} else { + if ($page != '') { + $main_sec = get_sec($sec); + if ($main_sec == false) { + if ($sec == 'extensions') { + $main_sec = get_parameter('extension_in_menu'); + } else if ($sec == 'gextensions') { + $main_sec = get_parameter('extension_in_menu'); + } else { + $main_sec = $sec; + } - if ($home_page != '') { - switch ($home_page) { - case 'Event list': - $_GET['sec'] = 'eventos'; - $_GET['sec2'] = 'operation/events/events'; - break; - case 'Group view': - $_GET['sec'] = 'view'; - $_GET['sec2'] = 'operation/agentes/group_view'; - break; - case 'Alert detail': - $_GET['sec'] = 'view'; - $_GET['sec2'] = 'operation/agentes/alerts_status'; - break; - case 'Tactical view': - $_GET['sec'] = 'view'; - $_GET['sec2'] = 'operation/agentes/tactical'; - break; - case 'Default': - $_GET['sec2'] = 'general/logon_ok'; - break; - case 'Dashboard': - $id_dashboard = db_get_value('id', 'tdashboard', 'name', $home_url); - $str = 'sec=reporting&sec2='.ENTERPRISE_DIR.'/dashboard/main_dashboard&id='.$id_dashboard.'&d_from_main_page=1'; - parse_str($str, $res); - foreach ($res as $key => $param) { - $_GET[$key] = $param; - } - break; - case 'Visual console': - $id_visualc = db_get_value('id', 'tlayout', 'name', $home_url); - if (($home_url == '') || ($id_visualc == false)) { - $str = 'sec=network&sec2=operation/visual_console/index&refr=60'; - } - else - $str = 'sec=network&sec2=operation/visual_console/render_view&id='.$id_visualc .'&refr=60'; - parse_str($str, $res); - foreach ($res as $key => $param) { - $_GET[$key] = $param; - } - break; - case 'Other': - $home_url = io_safe_output($home_url); - $url_array = parse_url($home_url); - parse_str ($url_array['query'], $res); - foreach ($res as $key => $param) { - $_GET[$key] = $param; - } - break; - } - if (isset($_GET['sec2'])) { - $file = $_GET['sec2'] . '.php'; - // Translate some secs - $main_sec = get_sec($_GET['sec']); - $_GET['sec'] = $main_sec == false ? $_GET['sec'] : $main_sec; - if ( - !file_exists ($file) || - ( - $_GET['sec2'] != 'general/logon_ok' && - enterprise_hook ('enterprise_acl', - array ($config['id_user'], $_GET['sec'], $_GET['sec2'], true, - isset($_GET['sec3']) ? $_GET['sec3'] : '') - ) == false - ) - ) { - unset($_GET['sec2']); - require ("general/noaccess.php"); - } - else { - require($file); - } - } else { - require ("general/noaccess.php"); - } - } - else { - require("general/logon_ok.php"); - } - } + $sec = $sec2; + $sec2 = ''; + } + + $page .= '.php'; + + // Enterprise ACL check + if (enterprise_hook( + 'enterprise_acl', + [ + $config['id_user'], + $main_sec, + $sec, + true, + $sec2, + ] + ) == false + ) { + include 'general/noaccess.php'; + } else { + $sec = $main_sec; + if (file_exists($page)) { + if (! extensions_is_extension($page)) { + include_once $page; + } else { + if ($sec[0] == 'g') { + extensions_call_godmode_function(basename($page)); + } else { + extensions_call_main_function(basename($page)); + } + } + } else { + ui_print_error_message(__('Sorry! I can\'t find the page!')); + } + } + } else { + // home screen chosen by the user + $home_page = ''; + if (isset($config['id_user'])) { + $user_info = users_get_user_by_id($config['id_user']); + $home_page = io_safe_output($user_info['section']); + $home_url = $user_info['data_section']; + } + + if ($home_page != '') { + switch ($home_page) { + case 'Event list': + $_GET['sec'] = 'eventos'; + $_GET['sec2'] = 'operation/events/events'; + break; + + case 'Group view': + $_GET['sec'] = 'view'; + $_GET['sec2'] = 'operation/agentes/group_view'; + break; + + case 'Alert detail': + $_GET['sec'] = 'view'; + $_GET['sec2'] = 'operation/agentes/alerts_status'; + break; + + case 'Tactical view': + $_GET['sec'] = 'view'; + $_GET['sec2'] = 'operation/agentes/tactical'; + break; + + case 'Default': + $_GET['sec2'] = 'general/logon_ok'; + break; + + case 'Dashboard': + $id_dashboard = db_get_value('id', 'tdashboard', 'name', $home_url); + $str = 'sec=reporting&sec2='.ENTERPRISE_DIR.'/dashboard/main_dashboard&id='.$id_dashboard.'&d_from_main_page=1'; + parse_str($str, $res); + foreach ($res as $key => $param) { + $_GET[$key] = $param; + } + break; + + case 'Visual console': + $id_visualc = db_get_value('id', 'tlayout', 'name', $home_url); + if (($home_url == '') || ($id_visualc == false)) { + $str = 'sec=network&sec2=operation/visual_console/index&refr=60'; + } else { + $str = 'sec=network&sec2=operation/visual_console/render_view&id='.$id_visualc.'&refr=60'; + } + + parse_str($str, $res); + foreach ($res as $key => $param) { + $_GET[$key] = $param; + } + break; + + case 'Other': + $home_url = io_safe_output($home_url); + $url_array = parse_url($home_url); + parse_str($url_array['query'], $res); + foreach ($res as $key => $param) { + $_GET[$key] = $param; + } + break; + } + + if (isset($_GET['sec2'])) { + $file = $_GET['sec2'].'.php'; + // Translate some secs + $main_sec = get_sec($_GET['sec']); + $_GET['sec'] = $main_sec == false ? $_GET['sec'] : $main_sec; + if (!file_exists($file) + || ( $_GET['sec2'] != 'general/logon_ok' + && enterprise_hook( + 'enterprise_acl', + [ + $config['id_user'], + $_GET['sec'], + $_GET['sec2'], + true, + isset($_GET['sec3']) ? $_GET['sec3'] : '', + ] + ) == false ) + ) { + unset($_GET['sec2']); + include 'general/noaccess.php'; + } else { + include $file; + } + } else { + include 'general/noaccess.php'; + } + } else { + include 'general/logon_ok.php'; + } + } } -if ($config["pure"] == 0) { - echo '
                      '; - echo '
                      '; // main - echo '
                       
                      '; - echo '
                      '; // page (id = page) -} -else { - echo "
                      "; // main_pure +if ($config['pure'] == 0) { + echo '
                      '; + echo '
                      '; + // main + echo '
                       
                      '; + echo '
                      '; + // page (id = page) +} else { + echo '
                      '; + // main_pure } -if ($config["pure"] == 0) { - echo '
                      '; //container div - echo '
                      '; - echo ''; +if ($config['pure'] == 0) { + echo '
                      '; + // container div + echo '
                      '; + echo ''; } -/// Clippy function -require_once('include/functions_clippy.php'); +// Clippy function +require_once 'include/functions_clippy.php'; clippy_start($sec2); -while (@ob_end_flush ()); +while (@ob_end_flush()) { +} -db_print_database_debug (); +db_print_database_debug(); echo ''; -$run_time = format_numeric (microtime (true) - $config['start_time'], 3); +$run_time = format_numeric((microtime(true) - $config['start_time']), 3); echo "\n\n"; // Values from PHP to be recovered from JAVASCRIPT -require('include/php_to_js_values.php'); +require 'include/php_to_js_values.php'; ?> + - - Pandora FMS - Installation Wizard - - - - - - - - - - - - - - - -
                      - -
                      - + + Pandora FMS - Installation Wizard + + + + + + + + + + + + + + + +
                      + +
                      +
                      "; +function check_extension($ext, $label) +{ + echo ''; } -function check_include ( $ext, $label ) { - echo ""; +function check_include($ext, $label) +{ + echo ''; } -function check_exists ( $file, $label ) { - echo ""; + +function check_exists($file, $label) +{ + echo ''; } -function check_generic ( $ok, $label ) { - echo ""; - echo ""; - return 1; - } - else { - echo " "; - echo ""; - echo ""; - return 0; - } + +function check_generic($ok, $label) +{ + echo "'; + echo ''; + return 1; + } else { + echo " "; + echo ''; + echo ''; + return 0; + } } -function check_writable ( $fullpath, $label ) { - echo ""; - echo ""; - return 0; - } - else { - echo " "; - echo ""; - echo ""; - return 1; - } - else { - echo " "; - echo ""; - echo ""; - return 1; - } + +function check_writable($fullpath, $label) +{ + echo "'; + echo ''; + return 0; + } else { + echo " "; + echo ''; + echo ''; + return 1; + } + } else { + echo " "; + echo ''; + echo ''; + return 1; + } } -function check_variable ( $var, $value, $label, $mode ) { - echo ""; + +function check_variable($var, $value, $label, $mode) +{ + echo ''; } -function parse_mysql_dump($url) { - if (file_exists($url)) { - $file_content = file($url); - $query = ""; - foreach($file_content as $sql_line) { - if (trim($sql_line) != "" && strpos($sql_line, "-- ") === false) { - $query .= $sql_line; - if(preg_match("/;[\040]*\$/", $sql_line)) { - if (!$result = mysql_query($query)) { - echo mysql_error(); //Uncomment for debug - echo "
                      $query
                      "; - return 0; - } - $query = ""; - } - } - } - return 1; - } - else - return 0; + +function parse_mysql_dump($url) +{ + if (file_exists($url)) { + $file_content = file($url); + $query = ''; + foreach ($file_content as $sql_line) { + if (trim($sql_line) != '' && strpos($sql_line, '-- ') === false) { + $query .= $sql_line; + if (preg_match("/;[\040]*\$/", $sql_line)) { + if (!$result = mysql_query($query)) { + echo mysql_error(); + // Uncomment for debug + echo "
                      $query
                      "; + return 0; + } + + $query = ''; + } + } + } + + return 1; + } else { + return 0; + } } -function parse_mysqli_dump($connection, $url) { - if (file_exists($url)) { - $file_content = file($url); - $query = ""; - foreach($file_content as $sql_line) { - if (trim($sql_line) != "" && strpos($sql_line, "-- ") === false) { - $query .= $sql_line; - if(preg_match("/;[\040]*\$/", $sql_line)) { - if (!$result = mysqli_query($connection, $query)) { - echo mysqli_error(); //Uncomment for debug - echo "
                      $query
                      "; - return 0; - } - $query = ""; - } - } - } - return 1; - } - else - return 0; + +function parse_mysqli_dump($connection, $url) +{ + if (file_exists($url)) { + $file_content = file($url); + $query = ''; + foreach ($file_content as $sql_line) { + if (trim($sql_line) != '' && strpos($sql_line, '-- ') === false) { + $query .= $sql_line; + if (preg_match("/;[\040]*\$/", $sql_line)) { + if (!$result = mysqli_query($connection, $query)) { + echo mysqli_error(); + // Uncomment for debug + echo "
                      $query
                      "; + return 0; + } + + $query = ''; + } + } + } + + return 1; + } else { + return 0; + } } -function random_name ($size) { - $temp = ""; - for ($a=0;$a< $size;$a++) - $temp = $temp. chr(rand(122,97)); - - return $temp; + +function random_name($size) +{ + $temp = ''; + for ($a = 0; $a < $size; $a++) { + $temp = $temp.chr(rand(122, 97)); + } + + return $temp; } -function print_logo_status ($step, $step_total) { - global $banner; - - $header = " + +function print_logo_status($step, $step_total) +{ + global $banner; + + $header = "

                      $banner
                      "; - $header .= " + $header .= "
                      Install step $step of $step_total
                      "; - return $header; + return $header; } + // // This function adjusts path settings in pandora db for FreeBSD. // // All packages and configuration files except operating system's base files // are installed under /usr/local in FreeBSD. So, path settings in pandora db -// for some programs should be changed from the Linux default. +// for some programs should be changed from the Linux default. // -function adjust_paths_for_freebsd($engine, $connection = false) { +function adjust_paths_for_freebsd($engine, $connection=false) +{ + $adjust_sql = [ + "update trecon_script set script = REPLACE(script,'/usr/share','/usr/local/share');", + "update tconfig set value = REPLACE(value,'/usr/bin','/usr/local/bin') where token='netflow_daemon' OR token='netflow_nfdump' OR token='netflow_nfexpire';", + "update talert_commands set command = REPLACE(command,'/usr/bin','/usr/local/bin');", + "update talert_commands set command = REPLACE(command,'/usr/share', '/usr/local/share');", + "update tplugin set execute = REPLACE(execute,'/usr/share','/usr/local/share');", + "update tevent_response set target = REPLACE(target,'/usr/share','/usr/local/share');", + "insert into tconfig (token, value) VALUES ('graphviz_bin_dir', '/usr/local/bin');", + ]; - $adjust_sql = array( - "update trecon_script set script = REPLACE(script,'/usr/share','/usr/local/share');", - "update tconfig set value = REPLACE(value,'/usr/bin','/usr/local/bin') where token='netflow_daemon' OR token='netflow_nfdump' OR token='netflow_nfexpire';", - "update talert_commands set command = REPLACE(command,'/usr/bin','/usr/local/bin');", - "update talert_commands set command = REPLACE(command,'/usr/share', '/usr/local/share');", - "update tplugin set execute = REPLACE(execute,'/usr/share','/usr/local/share');", - "update tevent_response set target = REPLACE(target,'/usr/share','/usr/local/share');", - "insert into tconfig (token, value) VALUES ('graphviz_bin_dir', '/usr/local/bin');" - ); + for ($i = 0; $i < count($adjust_sql); $i++) { + switch ($engine) { + case 'mysql': + $result = mysql_query($adjust_sql[$i]); + break; - for ($i = 0; $i < count ($adjust_sql); $i++) { - switch ($engine) { - case 'mysql': - $result = mysql_query($adjust_sql[$i]); - break; - case 'mysqli': - $result = mysqli_query($connection, $adjust_sql[$i]); - break; - case 'oracle': - //Delete the last semicolon from current query - $query = substr($adjust_sql[$i], 0, strlen($adjust_sql[$i]) - 1); - $sql = oci_parse($connection, $query); - $result = oci_execute($sql); - break; - case 'pgsql': - pg_send_query($connection, $adjust_sql[$i]); - $result = pg_get_result($connection); - break; - } - if (!$result) { - return 0; - } - } + case 'mysqli': + $result = mysqli_query($connection, $adjust_sql[$i]); + break; - return 1; + case 'oracle': + // Delete the last semicolon from current query + $query = substr($adjust_sql[$i], 0, (strlen($adjust_sql[$i]) - 1)); + $sql = oci_parse($connection, $query); + $result = oci_execute($sql); + break; + + case 'pgsql': + pg_send_query($connection, $adjust_sql[$i]); + $result = pg_get_result($connection); + break; + } + + if (!$result) { + return 0; + } + } + + return 1; } -function install_step1() { - global $banner; - echo " +function install_step1() +{ + global $banner; + + echo "
                      - " . print_logo_status (1,6) . " + ".print_logo_status(1, 6)."

                      Welcome to Pandora FMS installation Wizard

                      This wizard helps you to quick install Pandora FMS console and main database in your system.

                      @@ -384,40 +443,43 @@ function install_step1() {

                      For more information, please refer to documentation.
                      Pandora FMS Development Team

                      "; - if (file_exists("include/config.php")) { - echo "
                      Warning: You already have a config.php file. + if (file_exists('include/config.php')) { + echo "
                      Warning: You already have a config.php file. Configuration and database would be overwritten if you continued.
                      "; - } - echo "
                      "; - echo "
                      ') - .html(interface['name']) - ) - .append($('') - .html(interface['status']) - ) - .append($('') - .html(interf_graph) - ) - .append($('') - .html(interface['ip']) - ) - .append($('') - .html(interface['mac']) - ) - ); - }); - } - load_interfaces(selected_links); - } - }); + var params = []; + params.push("get_interface_info=1"); + params.push("id_agent=" + node_selected["id_agent"]); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data.length == 0) { + $("#interface_information") + .find("tbody") + .append( + $("
                      ").html(interface["name"])) + .append($("").html(interface["status"])) + .append($("").html(interf_graph)) + .append($("").html(interface["ip"])) + .append($("").html(interface["mac"])) + ); + }); + } + load_interfaces(selected_links); + } + }); } function load_interfaces(selected_links) { - //Clean - $("#relations_table .relation_link_row").remove(); - //Show the no relations - $("#relations_table-loading").css('display', 'none'); - $("#relations_table-no_relations").css('display', ''); + //Clean + $("#relations_table .relation_link_row").remove(); + //Show the no relations + $("#relations_table-loading").css("display", "none"); + $("#relations_table-no_relations").css("display", ""); - jQuery.each(selected_links, function (i, link_each) { - $("#relations_table-no_relations").css('display', 'none'); - $("#relations_table-loading").css('display', ''); + jQuery.each(selected_links, function(i, link_each) { + $("#relations_table-no_relations").css("display", "none"); + $("#relations_table-loading").css("display", ""); - var template_relation_row = $("#relations_table-template_row") - .clone(); + var template_relation_row = $("#relations_table-template_row").clone(); - $(template_relation_row).css('display', ''); - $(template_relation_row).attr('class', 'relation_link_row'); + $(template_relation_row).css("display", ""); + $(template_relation_row).attr("class", "relation_link_row"); - $("select[name='interface_source']", template_relation_row) - .attr('name', "interface_source_" + i) - .attr('id', "interface_source_" + i); - $("select[name='interface_target']", template_relation_row) - .attr('name', "interface_target_" + i) - .attr('id', "interface_target_" + i); - $(".edit_icon_progress", template_relation_row) - .attr('class', "edit_icon_progress_" + i); - $(".edit_icon", template_relation_row) - .attr('class', "edit_icon_" + i); - $(".edit_icon_correct", template_relation_row) - .attr('class', "edit_icon_correct_" + i); - $(".edit_icon_fail", template_relation_row) - .attr('class', "edit_icon_fail_" + i); - $(".edit_icon_link", template_relation_row) - .attr('class', "edit_icon_link_" + i) - .click(function () { - update_link(i, link_each.id_db); - } - ); + $("select[name='interface_source']", template_relation_row) + .attr("name", "interface_source_" + i) + .attr("id", "interface_source_" + i); + $("select[name='interface_target']", template_relation_row) + .attr("name", "interface_target_" + i) + .attr("id", "interface_target_" + i); + $(".edit_icon_progress", template_relation_row).attr( + "class", + "edit_icon_progress_" + i + ); + $(".edit_icon", template_relation_row).attr("class", "edit_icon_" + i); + $(".edit_icon_correct", template_relation_row).attr( + "class", + "edit_icon_correct_" + i + ); + $(".edit_icon_fail", template_relation_row).attr( + "class", + "edit_icon_fail_" + i + ); + $(".edit_icon_link", template_relation_row) + .attr("class", "edit_icon_link_" + i) + .click(function() { + update_link(i, link_each.id_db); + }); - var params3 = []; - params3.push("get_intefaces=1"); - params3.push("id_agent_target=" + link_each.target.id_agent); - params3.push("id_agent_source=" + link_each.source.id_agent); - params3.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params3 = []; + params3.push("get_intefaces=1"); + params3.push("id_agent_target=" + link_each.target.id_agent); + params3.push("id_agent_source=" + link_each.source.id_agent); + params3.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params3.join("&"), - dataType: 'json', - type: 'POST', - async: true, - cache: false, - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("select[name='interface_target_" + i + "']", template_relation_row).empty(); - $("select[name='interface_target_" + i + "']", template_relation_row).append(''); + jQuery.ajax({ + data: params3.join("&"), + dataType: "json", + type: "POST", + async: true, + cache: false, + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $( + "select[name='interface_target_" + i + "']", + template_relation_row + ).empty(); + $( + "select[name='interface_target_" + i + "']", + template_relation_row + ).append( + '' + ); - $("select[name='interface_source_" + i + "']", template_relation_row).empty(); - $("select[name='interface_source_" + i + "']", template_relation_row).append(''); - jQuery.each(data['target_interfaces'], function (j, interface) { - $("select[name='interface_target_" + i + "']", template_relation_row) - .append($("' + ); + jQuery.each(data["target_interfaces"], function(j, interface) { + $( + "select[name='interface_target_" + i + "']", + template_relation_row + ).append( + $("' + ); + jQuery.each(data.interfaces_parent, function(i, interface) { + $("#interface_target_select").append( + '" + ); + }); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - var parent_name = data_parent.text; - var child_name = child_data.text; - $('#label-node_source_interface').text(child_name); - $('#label-node_target_interface').text(parent_name); + $("#interface_source_select").empty(); + $("#interface_source_select").append( + '' + ); + jQuery.each(data.interfaces_child, function(i, interface) { + $("#interface_source_select").append( + '" + ); + }); - $("#interface_target_select").empty(); - $('#interface_target_select').append(''); - jQuery.each(data.interfaces_parent, function (i, interface) { - $('#interface_target_select').append(''); - }); - - $("#interface_source_select").empty(); - $('#interface_source_select').append(''); - jQuery.each(data.interfaces_child, function (i, interface) { - $('#interface_source_select').append(''); - }); - - $('#dialog_interface_link').dialog("open"); - } - }); - }); + $("#dialog_interface_link").dialog("open"); + } + }); + }); } function add_interface_link_js() { - cancel_set_parent_interface(); - $('#dialog_interface_link').dialog("close"); + cancel_set_parent_interface(); + $("#dialog_interface_link").dialog("close"); - source_value = $('#interface_source_select').val(); - source_text = $('#interface_source_select').find('option:selected').text(); - target_value = $('#interface_target_select').val(); - target_text = $('#interface_target_select').find('option:selected').text(); + source_value = $("#interface_source_select").val(); + source_text = $("#interface_source_select") + .find("option:selected") + .text(); + target_value = $("#interface_target_select").val(); + target_text = $("#interface_target_select") + .find("option:selected") + .text(); - var params = []; - params.push("add_interface_relation=1"); - params.push("id=" + networkmap_id); - params.push("source_value=" + source_value); - params.push("target_value=" + target_value); - params.push("source_text=" + source_text); - params.push("target_text=" + target_text); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + var params = []; + params.push("add_interface_relation=1"); + params.push("id=" + networkmap_id); + params.push("source_value=" + source_value); + params.push("target_value=" + target_value); + params.push("source_text=" + source_text); + params.push("target_text=" + target_text); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - var temp_link = {}; - temp_link['status_start'] = "0"; - temp_link['status_end'] = "0"; - - temp_link['id_db'] = data['id_db_link']; - - if (data['type_source'] == 1) { - temp_link['arrow_start'] = "module"; - temp_link['id_module_start'] = source_value; - temp_link["status_start"] = data['status']; - temp_link["link_color"] = (data['status'] == "1") ? "#FC4444" : "#999"; - } - else { - temp_link['arrow_start'] = ""; - temp_link['id_agent_start'] = source_value; - temp_link['id_module_start'] = 0; - } - if (data['type_target'] == 1) { - temp_link['arrow_end'] = "module"; - temp_link['id_module_end'] = target_value; - temp_link["status_end"] = data['status']; - temp_link["link_color"] = (data['status'] == "1") ? "#FC4444" : "#999"; - } - else { - temp_link['arrow_end'] = ""; - temp_link['id_agent_end'] = target_value; - temp_link['id_module_end'] = 0; - } + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + var temp_link = {}; + temp_link["status_start"] = "0"; + temp_link["status_end"] = "0"; - temp_link['text_start'] = data['text_start']; - temp_link['text_end'] = data['text_end']; + temp_link["id_db"] = data["id_db_link"]; - jQuery.each(graph.nodes, function (j, node) { - if (node['id_agent'] == data['id_db_target']) { - temp_link['target'] = graph.nodes[j]; - } - if (node['id_agent'] == data['id_db_source']) { - temp_link['source'] = graph.nodes[j]; - } - }); - - graph.links.push(temp_link); - - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } - } - }); + if (data["type_source"] == 1) { + temp_link["arrow_start"] = "module"; + temp_link["id_module_start"] = source_value; + temp_link["status_start"] = data["status"]; + temp_link["link_color"] = data["status"] == "1" ? "#FC4444" : "#999"; + } else { + temp_link["arrow_start"] = ""; + temp_link["id_agent_start"] = source_value; + temp_link["id_module_start"] = 0; + } + if (data["type_target"] == 1) { + temp_link["arrow_end"] = "module"; + temp_link["id_module_end"] = target_value; + temp_link["status_end"] = data["status"]; + temp_link["link_color"] = data["status"] == "1" ? "#FC4444" : "#999"; + } else { + temp_link["arrow_end"] = ""; + temp_link["id_agent_end"] = target_value; + temp_link["id_module_end"] = 0; + } + + temp_link["text_start"] = data["text_start"]; + temp_link["text_end"] = data["text_end"]; + + jQuery.each(graph.nodes, function(j, node) { + if (node["id_agent"] == data["id_db_target"]) { + temp_link["target"] = graph.nodes[j]; + } + if (node["id_agent"] == data["id_db_source"]) { + temp_link["source"] = graph.nodes[j]; + } + }); + + graph.links.push(temp_link); + + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } + } + }); } function refresh_holding_area() { - holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x"); - holding_pos_y = d3.select("#holding_area_" + networkmap_id).attr("y"); + holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x"); + holding_pos_y = d3.select("#holding_area_" + networkmap_id).attr("y"); - var pos_x = parseInt(holding_pos_x) + parseInt(node_radius); - var pos_y = parseInt(holding_pos_y) + parseInt(node_radius); - if (enterprise_installed) { - $('#holding_spinner_' + networkmap_id).css("display", ""); - var params = []; - params.push("refresh_holding_area=1"); - params.push("id=" + networkmap_id); - params.push("x=" + pos_x); - params.push("y=" + pos_y); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - window.holding_area = data['holding_area']; + var pos_x = parseInt(holding_pos_x) + parseInt(node_radius); + var pos_y = parseInt(holding_pos_y) + parseInt(node_radius); + if (enterprise_installed) { + $("#holding_spinner_" + networkmap_id).css("display", ""); + var params = []; + params.push("refresh_holding_area=1"); + params.push("id=" + networkmap_id); + params.push("x=" + pos_x); + params.push("y=" + pos_y); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + window.holding_area = data["holding_area"]; - jQuery.each(holding_area.nodes, function (i, node) { - var temp_node = {}; + jQuery.each(holding_area.nodes, function(i, node) { + var temp_node = {}; - temp_node['id'] = graph.nodes.length; - holding_area.nodes[i]['id'] = temp_node['id']; + temp_node["id"] = graph.nodes.length; + holding_area.nodes[i]["id"] = temp_node["id"]; - temp_node['id_db'] = node['id_db']; - temp_node['id_agent'] = node['id_agent']; - temp_node['id_module'] = 0; - temp_node['x'] = node['x']; - temp_node['y'] = node['y']; - temp_node['z'] = 0; - temp_node['fixed'] = true; - temp_node['state'] = 'holding_area'; - temp_node['type'] = 0; - temp_node['color'] = node['color']; - temp_node['shape'] = node['shape']; - temp_node['text'] = node['text']; - temp_node['image_url'] = node['image_url']; - temp_node['image_width'] = node['image_width']; - temp_node['image_height'] = node['image_width']; - temp_node['deleted'] = false; + temp_node["id_db"] = node["id_db"]; + temp_node["id_agent"] = node["id_agent"]; + temp_node["id_module"] = 0; + temp_node["x"] = node["x"]; + temp_node["y"] = node["y"]; + temp_node["z"] = 0; + temp_node["fixed"] = true; + temp_node["state"] = "holding_area"; + temp_node["type"] = 0; + temp_node["color"] = node["color"]; + temp_node["shape"] = node["shape"]; + temp_node["text"] = node["text"]; + temp_node["image_url"] = node["image_url"]; + temp_node["image_width"] = node["image_width"]; + temp_node["image_height"] = node["image_width"]; + temp_node["deleted"] = false; - graph.nodes.push(temp_node); - }); + graph.nodes.push(temp_node); + }); - jQuery.each(graph.links, function (j, g_link) { + jQuery.each(graph.links, function(j, g_link) { + for (var i = 0; i < holding_area.links.length; i++) { + if (g_link["id_db"] == holding_area.links[i]["id_db"]) { + holding_area.links.splice(i, 1); + } + } + }); - for (var i = 0; i < holding_area.links.length; i++) { - if (g_link['id_db'] == holding_area.links[i]['id_db']) { - holding_area.links.splice(i, 1); - } - } + jQuery.each(holding_area.links, function(i, link) { + var temp_link = {}; + temp_link["id_db"] = link["id_db"]; + temp_link["arrow_start"] = link["arrow_start"]; + temp_link["arrow_end"] = link["arrow_end"]; + temp_link["status_start"] = link["status_start"]; + temp_link["status_end"] = link["status_end"]; + temp_link["id_module_start"] = link["id_module_start"]; + temp_link["id_module_end"] = link["id_module_end"]; + temp_link["text_start"] = link["text_start"]; + temp_link["text_end"] = link["text_end"]; - }); + //Re-hook the links to nodes + jQuery.each(graph.nodes, function(j, node) { + if (node["id_agent"] == link["id_agent_end"]) { + temp_link["target"] = graph.nodes[j]; + } + if (node["id_agent"] == link["id_agent_start"]) { + temp_link["source"] = graph.nodes[j]; + } + }); - jQuery.each(holding_area.links, function (i, link) { - var temp_link = {}; - temp_link['id_db'] = link['id_db']; - temp_link['arrow_start'] = link['arrow_start']; - temp_link['arrow_end'] = link['arrow_end']; - temp_link['status_start'] = link['status_start']; - temp_link['status_end'] = link['status_end']; - temp_link['id_module_start'] = link['id_module_start']; - temp_link['id_module_end'] = link['id_module_end']; - temp_link['text_start'] = link['text_start']; - temp_link['text_end'] = link['text_end']; + graph.links.push(temp_link); + }); - //Re-hook the links to nodes - jQuery.each(graph.nodes, function (j, node) { - if (node['id_agent'] == link['id_agent_end']) { - temp_link['target'] = graph.nodes[j]; - } - if (node['id_agent'] == link['id_agent_start']) { - temp_link['source'] = graph.nodes[j]; - } - }); + $("#layer_graph_links_" + networkmap_id).remove(); + $("#layer_graph_nodes_" + networkmap_id).remove(); - graph.links.push(temp_link); - }); + window.layer_graph_links = window.layer_graph + .append("g") + .attr("id", "layer_graph_links_" + networkmap_id); + window.layer_graph_nodes = window.layer_graph + .append("g") + .attr("id", "layer_graph_nodes_" + networkmap_id); - $("#layer_graph_links_" + networkmap_id).remove(); - $("#layer_graph_nodes_" + networkmap_id).remove(); + force + .nodes(graph.nodes) + .links(graph.links) + .start(); - window.layer_graph_links = window.layer_graph - .append("g") - .attr("id", "layer_graph_links_" + networkmap_id); - window.layer_graph_nodes = window.layer_graph - .append("g") - .attr("id", "layer_graph_nodes_" + networkmap_id); + window.node = layer_graph_nodes.selectAll(".node"); + window.link = layer_graph_links.selectAll(".link"); - force.nodes(graph.nodes) - .links(graph.links) - .start(); + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); - window.node = layer_graph_nodes.selectAll(".node"); - window.link = layer_graph_links.selectAll(".link"); - - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - - $('#holding_spinner_' + networkmap_id).css("display", "none"); - } - }, - error: function () { - $('#holding_spinner_' + networkmap_id).css("display", "none"); - } - }); - } + $("#holding_spinner_" + networkmap_id).css("display", "none"); + } + }, + error: function() { + $("#holding_spinner_" + networkmap_id).css("display", "none"); + } + }); + } } -function restart_map () { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 250, - buttons: [ - { - text: ok_button, - click: function () { - $(this).dialog("close"); - proceed_to_restart_map(); - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); - } - } - ] - }); +function restart_map() { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 250, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + proceed_to_restart_map(); + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var dialog_confirm_text = "
                      "; - dialog_confirm_text = dialog_confirm_text + "
                      "; - dialog_confirm_text = dialog_confirm_text + "

                      " + warning_message + "

                      "; - dialog_confirm_text = dialog_confirm_text + "

                      " + message_to_confirm + "

                      "; - dialog_confirm_text = dialog_confirm_text + "
                      "; - - $('#restart_map_confirm').html(dialog_confirm_text); - $('#restart_map_confirm').dialog('open'); + var dialog_confirm_text = "
                      "; + dialog_confirm_text = + dialog_confirm_text + + "
                      "; + dialog_confirm_text = + dialog_confirm_text + + "

                      " + + warning_message + + "

                      "; + dialog_confirm_text = + dialog_confirm_text + + "

                      " + + message_to_confirm + + "

                      "; + dialog_confirm_text = dialog_confirm_text + "
                      "; + + $("#restart_map_confirm").html(dialog_confirm_text); + $("#restart_map_confirm").dialog("open"); } -function proceed_to_restart_map () { - $("
                      ").dialog ({ - resizable: true, - draggable: true, - modal: true, - overlay: { - opacity: 0.5, - background: 'black' - }, - width: 600, - height: 450, - buttons: [ - { - text: ok_button, - click: function () { - $(this).dialog("close"); - var new_elements = []; - new_elements[0] = $("#text-name").val(); - new_elements[1] = $("#id_group").val(); - new_elements[2] = $("#text-node_radius").val(); - new_elements[3] = $("#textarea_description").val(); - new_elements[4] = $("input[name=source]:checked").val(); - if (new_elements[4] == 'group') { - new_elements[5] = $("#checkbox-dont_show_subgroups").is(':checked'); - } - else if (new_elements[4] == 'recon_task') { - new_elements[5] = $("#recon_task_id").val(); - } - else { - new_elements[5] = $("#text-ip_mask").val(); - } - new_elements[6] = $("#method").val(); - new_elements[7] = $("#text-pos_x").val(); - new_elements[8] = $("#text-pos_y").val(); - new_elements[9] = $("#text-scale_z").val(); - new_elements[10] = $("#text-node_sep").val(); - new_elements[11] = $("#text-mindist").val(); - new_elements[12] = $("#text-rank_sep").val(); - new_elements[13] = $("#text-kval").val(); - reset_map_from_form(new_elements); - } - }, - { - text:cancel_button, - click: function () { - $(this).dialog("close"); - } - } - ] - }); +function proceed_to_restart_map() { + $( + "
                      " + ).dialog({ + resizable: true, + draggable: true, + modal: true, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 600, + height: 450, + buttons: [ + { + text: ok_button, + click: function() { + $(this).dialog("close"); + var new_elements = []; + new_elements[0] = $("#text-name").val(); + new_elements[1] = $("#id_group").val(); + new_elements[2] = $("#text-node_radius").val(); + new_elements[3] = $("#textarea_description").val(); + new_elements[4] = $("input[name=source]:checked").val(); + if (new_elements[4] == "group") { + new_elements[5] = $("#checkbox-dont_show_subgroups").is(":checked"); + } else if (new_elements[4] == "recon_task") { + new_elements[5] = $("#recon_task_id").val(); + } else { + new_elements[5] = $("#text-ip_mask").val(); + } + new_elements[6] = $("#method").val(); + new_elements[7] = $("#text-pos_x").val(); + new_elements[8] = $("#text-pos_y").val(); + new_elements[9] = $("#text-scale_z").val(); + new_elements[10] = $("#text-node_sep").val(); + new_elements[11] = $("#text-mindist").val(); + new_elements[12] = $("#text-rank_sep").val(); + new_elements[13] = $("#text-kval").val(); + reset_map_from_form(new_elements); + } + }, + { + text: cancel_button, + click: function() { + $(this).dialog("close"); + } + } + ] + }); - var params = []; - params.push("get_reset_map_form=1"); - params.push("map_id=" + networkmap_id); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'html', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - $('#restart_map_form').html(data); - $('#restart_map_form').dialog('open'); - } - }); + var params = []; + params.push("get_reset_map_form=1"); + params.push("map_id=" + networkmap_id); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "html", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + $("#restart_map_form").html(data); + $("#restart_map_form").dialog("open"); + } + }); } -function reset_map_from_form (new_elements) { - var params = []; - params.push("reset_map=1"); - params.push("map_id=" + networkmap_id); - params.push("elems[]=" + new_elements) - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (!data['error']) { - window.location = "index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=" + networkmap_id; - } - } - }); +function reset_map_from_form(new_elements) { + var params = []; + params.push("reset_map=1"); + params.push("map_id=" + networkmap_id); + params.push("elems[]=" + new_elements); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (!data["error"]) { + window.location = + "index.php?sec=network&sec2=operation/agentes/pandora_networkmap&tab=view&id_networkmap=" + + networkmap_id; + } + } + }); } function set_parent(parent_data) { - if (enterprise_installed) { - var selection = d3.selectAll('.node_children'); + if (enterprise_installed) { + var selection = d3.selectAll(".node_children"); - count = selection.size(); + count = selection.size(); - selection - .each(function (child_data) { - //Check if exist the link as - // repeat: - // old link: node1 (parent) - node2 (child) - // new link: node1 (parent) - node2 (child) - // - // swapped: - // old link: node1 (child) - node2 (parent) - // new link: node2 (child) - node1 (parent) + selection.each(function(child_data) { + //Check if exist the link as + // repeat: + // old link: node1 (parent) - node2 (child) + // new link: node1 (parent) - node2 (child) + // + // swapped: + // old link: node1 (child) - node2 (parent) + // new link: node2 (child) - node1 (parent) - var repeat = false; - jQuery.each(graph.links, function (i, link_item) { + var repeat = false; + jQuery.each(graph.links, function(i, link_item) { + if ( + link_item.source_id_db == child_data.id_db && + link_item.target_id_db == parent_data.id_db + ) { + repeat = true; + } - if ((link_item.source_id_db == child_data.id_db) && - (link_item.target_id_db == parent_data.id_db)) { + if ( + link_item.source_id_db == parent_data.id_db && + link_item.target_id_db == child_data.id_db + ) { + repeat = true; + } + }); - repeat = true; - } + if (repeat) { + count = count - 1; + if (count == 0) { + draw_elements_graph(); + set_positions_graph(); - if ((link_item.source_id_db == parent_data.id_db) && - (link_item.target_id_db == child_data.id_db)) { + cancel_set_parent(); + cancel_set_parent_interface(); + } - repeat = true; - } + return; //Break + } - }); + var params = []; + params.push("set_relationship=1"); + params.push("id=" + networkmap_id); + params.push("child=" + child_data.id_db); + params.push("parent=" + parent_data.id_db); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + //Add the relationship and paint + item = {}; + item["arrow_start"] = ""; + item["arrow_end"] = ""; + item["status_start"] = ""; + item["status_end"] = ""; + item["text_start"] = ""; + item["text_end"] = ""; + item["id_module_start"] = 0; + item["id_module_end"] = 0; + item["id_db"] = data["id"]; + item["source_id_db"] = child_data.id_db; + item["target_id_db"] = parent_data.id; + item["id_agent_start"] = graph.nodes[child_data.id]["id_agent"]; + item["id_agent_end"] = graph.nodes[parent_data.id]["id_agent"]; + item["target"] = graph.nodes[parent_data.id]; + item["source"] = graph.nodes[child_data.id]; - if (repeat) { - count = count - 1; - if (count == 0) { - draw_elements_graph(); - set_positions_graph(); + graph.links.push(item); + } + //update_networkmap(); + count = count - 1; + if (count == 0) { + draw_elements_graph(); + set_positions_graph(); - cancel_set_parent(); - cancel_set_parent_interface(); - } - - return; //Break - } - - var params = []; - params.push("set_relationship=1"); - params.push("id=" + networkmap_id); - params.push("child=" + child_data.id_db); - params.push("parent=" + parent_data.id_db); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - //Add the relationship and paint - item = {}; - item['arrow_start'] = ''; - item['arrow_end'] = ''; - item['status_start'] = ''; - item['status_end'] = ''; - item['text_start'] = ''; - item['text_end'] = ''; - item['id_module_start'] = 0; - item['id_module_end'] = 0; - item['id_db'] = data['id']; - item['source_id_db'] = child_data.id_db; - item['target_id_db'] = parent_data.id; - item['id_agent_start'] = graph.nodes[child_data.id]['id_agent']; - item['id_agent_end'] = graph.nodes[parent_data.id]['id_agent']; - item['target'] = graph.nodes[parent_data.id]; - item['source'] = graph.nodes[child_data.id]; - - graph.links.push(item); - } - //update_networkmap(); - count = count - 1; - if (count == 0) { - draw_elements_graph(); - set_positions_graph(); - - cancel_set_parent(); - cancel_set_parent_interface(); - } - } - }); - } - ); - } + cancel_set_parent(); + cancel_set_parent_interface(); + } + } + }); + }); + } } function cancel_set_parent_interface() { - var selection = d3.selectAll('.node_children'); + var selection = d3.selectAll(".node_children"); - selection - .each(function (d) { - d3.select("#id_node_" + d.id + networkmap_id) - .classed("node_selected", true) - .classed("node_children", false); - } - ); + selection.each(function(d) { + d3.select("#id_node_" + d.id + networkmap_id) + .classed("node_selected", true) + .classed("node_children", false); + }); - flag_setting_interface_link_running = false; + flag_setting_interface_link_running = false; } function cancel_set_parent() { - var selection = d3.selectAll('.node_children'); + var selection = d3.selectAll(".node_children"); - selection - .each(function (d) { - d3.select("#id_node_" + d.id + networkmap_id) - .classed("node_selected", true) - .classed("node_children", false); - } - ); + selection.each(function(d) { + d3.select("#id_node_" + d.id + networkmap_id) + .classed("node_selected", true) + .classed("node_children", false); + }); - flag_setting_relationship_running = false; + flag_setting_relationship_running = false; } //////////////////////////////////////////////////////////////////////// // OWN CODE FOR TO DRAG //////////////////////////////////////////////////////////////////////// function init_drag_and_drop() { - window.dragables = svg.selectAll(".dragable_node"); + window.dragables = svg.selectAll(".dragable_node"); - window.drag_start = [0, 0]; - window.drag_end = [0, 0]; - window.drag = d3.behavior.drag() - .on("dragstart", function () { - if (d3.event.sourceEvent.button == 2) - return; + window.drag_start = [0, 0]; + window.drag_end = [0, 0]; + window.drag = d3.behavior + .drag() + .on("dragstart", function() { + if (d3.event.sourceEvent.button == 2) return; - mouse_coords = d3.mouse(this); - drag_start[0] = drag_end[0] = mouse_coords[0]; - drag_start[1] = drag_end[1] = mouse_coords[1]; + mouse_coords = d3.mouse(this); + drag_start[0] = drag_end[0] = mouse_coords[0]; + drag_start[1] = drag_end[1] = mouse_coords[1]; - flag_drag_running = true; + flag_drag_running = true; - d3.event.sourceEvent.stopPropagation(); - }) - .on("dragend", function (d, i) { - if (d3.event.sourceEvent.button == 2) - return; + d3.event.sourceEvent.stopPropagation(); + }) + .on("dragend", function(d, i) { + if (d3.event.sourceEvent.button == 2) return; - flag_drag_running = false; + flag_drag_running = false; - var selection = d3.selectAll('.node_selected'); + var selection = d3.selectAll(".node_selected"); - if (enterprise_installed) { - holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x"); - holding_pos_y = d3.select("#holding_area_" + networkmap_id).attr("y"); - delete d.raw_text; - selection - .each(function (d) { - var params = []; - params.push("update_node=1"); - params.push("node=" + JSON.stringify(d)); - params.push("x=" + holding_pos_x); - params.push("y=" + holding_pos_y); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (d.state == 'holding_area') { - //It is out the holding area - if (data['state'] == "") { - //Remove the style of nodes and links - //in holding area - d3.select("#id_node_" + d.id + networkmap_id) - .classed("holding_area", false); - d3.select(".source_" + d.id + networkmap_id) - .classed("holding_area_link", false); - d3.select(".target_" + d.id + networkmap_id) - .classed("holding_area_link", false); - graph.nodes[d.id].state = ""; - } - } - } - }); - }); - } - else { - var params = []; - params.push("update_node_alert=1"); - params.push("map_id=" + networkmap_id); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#open_version_dialog").dialog(); - } - } - }); - } + if (enterprise_installed) { + holding_pos_x = d3.select("#holding_area_" + networkmap_id).attr("x"); + holding_pos_y = d3.select("#holding_area_" + networkmap_id).attr("y"); + delete d.raw_text; + selection.each(function(d) { + var params = []; + params.push("update_node=1"); + params.push("node=" + JSON.stringify(d)); + params.push("x=" + holding_pos_x); + params.push("y=" + holding_pos_y); + params.push( + "page=enterprise/operation/agentes/pandora_networkmap.view" + ); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (d.state == "holding_area") { + //It is out the holding area + if (data["state"] == "") { + //Remove the style of nodes and links + //in holding area + d3.select("#id_node_" + d.id + networkmap_id).classed( + "holding_area", + false + ); + d3.select(".source_" + d.id + networkmap_id).classed( + "holding_area_link", + false + ); + d3.select(".target_" + d.id + networkmap_id).classed( + "holding_area_link", + false + ); + graph.nodes[d.id].state = ""; + } + } + } + }); + }); + } else { + var params = []; + params.push("update_node_alert=1"); + params.push("map_id=" + networkmap_id); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#open_version_dialog").dialog(); + } + } + }); + } - d3.event.sourceEvent.stopPropagation(); - }) - .on("drag", function (d, i) { - if (d3.event.sourceEvent.button == 2) - return; + d3.event.sourceEvent.stopPropagation(); + }) + .on("drag", function(d, i) { + if (d3.event.sourceEvent.button == 2) return; - mouse_coords = d3.mouse(this); + mouse_coords = d3.mouse(this); - delta = [0, 0]; - delta[0] = mouse_coords[0] - drag_end[0]; - delta[1] = mouse_coords[1] - drag_end[1]; + delta = [0, 0]; + delta[0] = mouse_coords[0] - drag_end[0]; + delta[1] = mouse_coords[1] - drag_end[1]; - drag_end[0] = mouse_coords[0]; - drag_end[1] = mouse_coords[1]; + drag_end[0] = mouse_coords[0]; + drag_end[1] = mouse_coords[1]; - var selection = d3.selectAll('.node_selected'); + var selection = d3.selectAll(".node_selected"); - selection - .each(function (d) { - graph.nodes[d.id].x = d.x + delta[0]; - graph.nodes[d.id].y = d.y + delta[1]; - graph.nodes[d.id].px = d.px + delta[0]; - graph.nodes[d.id].py = d.py + delta[1]; - }); + selection.each(function(d) { + graph.nodes[d.id].x = d.x + delta[0]; + graph.nodes[d.id].y = d.y + delta[1]; + graph.nodes[d.id].px = d.px + delta[0]; + graph.nodes[d.id].py = d.py + delta[1]; + }); - draw_elements_graph(); - set_positions_graph(); + draw_elements_graph(); + set_positions_graph(); - d3.event.sourceEvent.stopPropagation(); - }); - dragables.call(drag); + d3.event.sourceEvent.stopPropagation(); + }); + dragables.call(drag); } function add_fictional_node() { - var name = $("input[name='name_fictional_node']").val(); - var networkmap_to_link = $("#networkmap_to_link").val(); + var name = $("input[name='name_fictional_node']").val(); + var networkmap_to_link = $("#networkmap_to_link").val(); - var x = (click_menu_position_svg[0] - translation[0]) / scale; - var y = (click_menu_position_svg[1] - translation[1]) / scale; + var x = (click_menu_position_svg[0] - translation[0]) / scale; + var y = (click_menu_position_svg[1] - translation[1]) / scale; - if (enterprise_installed) { - var params = []; - params.push("create_fictional_point=1"); - params.push("id=" + networkmap_id); - params.push("name=" + name); - params.push("networkmap=" + networkmap_to_link); - params.push("color=" + module_color_status[0]['color']); - params.push("radious=" + node_radius); - params.push("shape=circle"); - params.push("x=" + x); - params.push("y=" + y); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#dialog_node_add").dialog("close"); + if (enterprise_installed) { + var params = []; + params.push("create_fictional_point=1"); + params.push("id=" + networkmap_id); + params.push("name=" + name); + params.push("networkmap=" + networkmap_to_link); + params.push("color=" + module_color_status[0]["color"]); + params.push("radious=" + node_radius); + params.push("shape=circle"); + params.push("x=" + x); + params.push("y=" + y); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#dialog_node_add").dialog("close"); - var temp_node = {}; - temp_node['id'] = graph.nodes.length; - temp_node['id_db'] = data['id_node']; - temp_node['id_agent'] = data['id_agent']; - temp_node['id_module'] = 0; - temp_node['x'] = x; - temp_node['y'] = y; - temp_node['z'] = 0; - temp_node['fixed'] = true; - temp_node['type'] = 3; - temp_node['color'] = data['color']; - temp_node['shape'] = data['shape']; - temp_node['text'] = data['text']; - temp_node['image_url'] = ""; - temp_node['image_width'] = 0; - temp_node['image_height'] = 0; - temp_node['networkmap_id'] = networkmap_to_link; + var temp_node = {}; + temp_node["id"] = graph.nodes.length; + temp_node["id_db"] = data["id_node"]; + temp_node["id_agent"] = data["id_agent"]; + temp_node["id_module"] = 0; + temp_node["x"] = x; + temp_node["y"] = y; + temp_node["z"] = 0; + temp_node["fixed"] = true; + temp_node["type"] = 3; + temp_node["color"] = data["color"]; + temp_node["shape"] = data["shape"]; + temp_node["text"] = data["text"]; + temp_node["image_url"] = ""; + temp_node["image_width"] = 0; + temp_node["image_height"] = 0; + temp_node["networkmap_id"] = networkmap_to_link; - graph.nodes.push(temp_node); + graph.nodes.push(temp_node); - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } - } - }); - } - else { - $("#dialog_node_add").dialog("close"); + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } + } + }); + } else { + $("#dialog_node_add").dialog("close"); - var temp_node = {}; - temp_node['id'] = graph.nodes.length; - temp_node['id_db'] = data['id_node']; - temp_node['id_agent'] = data['id_agent']; - temp_node['id_module'] = 0; - temp_node['x'] = x; - temp_node['y'] = y; - temp_node['z'] = 0; - temp_node['fixed'] = true; - temp_node['type'] = 3; - temp_node['color'] = data['color']; - temp_node['shape'] = data['shape']; - temp_node['text'] = data['text']; - temp_node['image_url'] = ""; - temp_node['image_width'] = 0; - temp_node['image_height'] = 0; - temp_node['networkmap_id'] = networkmap_to_link; + var temp_node = {}; + temp_node["id"] = graph.nodes.length; + temp_node["id_db"] = data["id_node"]; + temp_node["id_agent"] = data["id_agent"]; + temp_node["id_module"] = 0; + temp_node["x"] = x; + temp_node["y"] = y; + temp_node["z"] = 0; + temp_node["fixed"] = true; + temp_node["type"] = 3; + temp_node["color"] = data["color"]; + temp_node["shape"] = data["shape"]; + temp_node["text"] = data["text"]; + temp_node["image_url"] = ""; + temp_node["image_width"] = 0; + temp_node["image_height"] = 0; + temp_node["networkmap_id"] = networkmap_to_link; - graph.nodes.push(temp_node); + graph.nodes.push(temp_node); - draw_elements_graph(); - init_drag_and_drop(); - set_positions_graph(); - } + draw_elements_graph(); + init_drag_and_drop(); + set_positions_graph(); + } } function init_graph(parameter_object) { - window.width_svg = $("#networkconsole_" + networkmap_id).width(); - if ($("#main").height()) { - window.height_svg = $("#main").height(); - } - else { - //Set the height in the pure view (fullscreen). - window.height_svg = $(window).height() - - $("#menu_tab_frame_view").height() - - 20; // 20 of margin - } + window.width_svg = $("#networkconsole_" + networkmap_id).width(); + if ($("#main").height()) { + window.height_svg = $("#main").height(); + } else { + //Set the height in the pure view (fullscreen). + window.height_svg = + $(window).height() - $("#menu_tab_frame_view").height() - 20; // 20 of margin + } - window.refresh_period = 5 * 1000; //milliseconds - if (typeof (parameter_object.refresh_period) != "undefined") { - window.refresh_period = parameter_object.refresh_period; - } - window.scale_minimap = 4.2; - window.translation = [0, 0]; - window.scale = z_dash || 0.5; - window.node_radius = 40; - if (typeof (parameter_object.node_radius) != "undefined") { - window.node_radius = parameter_object.node_radius; - } - window.interface_radius = 3; - window.disabled_drag_zoom = false; - window.key_multiple_selection = 17; //CTRL key - window.flag_multiple_selection = false; - window.flag_multiple_selection_running = false; - window.selection_rectangle = [0, 0, 0, 0]; - window.flag_drag_running = false; - window.in_a_node = false; - window.enterprise_installed = false; - window.flag_setting_relationship_running = false; - window.flag_setting_interface_link_running = false; + window.refresh_period = 5 * 1000; //milliseconds + if (typeof parameter_object.refresh_period != "undefined") { + window.refresh_period = parameter_object.refresh_period; + } + window.scale_minimap = 4.2; + window.translation = [0, 0]; + window.scale = z_dash || 0.5; + window.node_radius = 40; + if (typeof parameter_object.node_radius != "undefined") { + window.node_radius = parameter_object.node_radius; + } + window.interface_radius = 3; + window.disabled_drag_zoom = false; + window.key_multiple_selection = 17; //CTRL key + window.flag_multiple_selection = false; + window.flag_multiple_selection_running = false; + window.selection_rectangle = [0, 0, 0, 0]; + window.flag_drag_running = false; + window.in_a_node = false; + window.enterprise_installed = false; + window.flag_setting_relationship_running = false; + window.flag_setting_interface_link_running = false; - window.minimap_w = 0; - window.minimap_h = 0; - window.show_minimap = false; - window.show_labels = true; - window.context_minimap; + window.minimap_w = 0; + window.minimap_h = 0; + window.show_minimap = false; + window.show_labels = true; + window.context_minimap; - window.holding_area_dimensions = [200, 200]; - if (typeof (parameter_object.holding_area_dimensions) != "undefined") { - window.holding_area_dimensions = parameter_object.holding_area_dimensions; - } + window.holding_area_dimensions = [200, 200]; + if (typeof parameter_object.holding_area_dimensions != "undefined") { + window.holding_area_dimensions = parameter_object.holding_area_dimensions; + } - window.graph = null; - if (typeof (parameter_object.graph) != "undefined") { - window.graph = parameter_object.graph; - } + window.graph = null; + if (typeof parameter_object.graph != "undefined") { + window.graph = parameter_object.graph; + } - window.networkmap_center = []; - if (typeof (parameter_object.networkmap_center) != "undefined") { - window.networkmap_center = parameter_object.networkmap_center; - } + window.networkmap_center = []; + if (typeof parameter_object.networkmap_center != "undefined") { + window.networkmap_center = parameter_object.networkmap_center; + } - if (typeof (networkmap_center[0]) == "undefined") { - networkmap_center = [0, 0]; - } + if (typeof networkmap_center[0] == "undefined") { + networkmap_center = [0, 0]; + } - translation[0] = (width_svg / 2) - networkmap_center[0]; - translation[1] = (height_svg / 2) - networkmap_center[1]; + translation[0] = width_svg / 2 - networkmap_center[0]; + translation[1] = height_svg / 2 - networkmap_center[1]; - translation[0] = translation[0] * scale; - translation[1] = translation[1] * scale; + translation[0] = translation[0] * scale; + translation[1] = translation[1] * scale; - window.enterprise_installed = ''; - if (typeof (parameter_object.enterprise_installed) != "undefined") { - window.enterprise_installed = parameter_object.enterprise_installed; - } + window.enterprise_installed = ""; + if (typeof parameter_object.enterprise_installed != "undefined") { + window.enterprise_installed = parameter_object.enterprise_installed; + } - window.networkmap_dimensions = []; - if (typeof (parameter_object.networkmap_dimensions) != "undefined") { - window.networkmap_dimensions = parameter_object.networkmap_dimensions; - } - window.max = Math.max(networkmap_dimensions[0], networkmap_dimensions[1]); - window.min = Math.min(width_svg / scale_minimap, - height_svg / scale_minimap); + window.networkmap_dimensions = []; + if (typeof parameter_object.networkmap_dimensions != "undefined") { + window.networkmap_dimensions = parameter_object.networkmap_dimensions; + } + window.max = Math.max(networkmap_dimensions[0], networkmap_dimensions[1]); + window.min = Math.min(width_svg / scale_minimap, height_svg / scale_minimap); - window.minimap_relation = min / max; - minimap_w = networkmap_dimensions[0] * minimap_relation; - minimap_h = networkmap_dimensions[1] * minimap_relation; + window.minimap_relation = min / max; + minimap_w = networkmap_dimensions[0] * minimap_relation; + minimap_h = networkmap_dimensions[1] * minimap_relation; - $("#minimap_" + networkmap_id).attr('width', minimap_w); - $("#minimap_" + networkmap_id).attr('height', minimap_h); + $("#minimap_" + networkmap_id).attr("width", minimap_w); + $("#minimap_" + networkmap_id).attr("height", minimap_h); - window.canvas_minimap = $("#minimap_" + networkmap_id); - window.context_minimap = canvas_minimap[0].getContext('2d'); - window.minimap_drag = false; + window.canvas_minimap = $("#minimap_" + networkmap_id); + window.context_minimap = canvas_minimap[0].getContext("2d"); + window.minimap_drag = false; - window.url_background_grid = ''; - if (typeof (parameter_object.url_background_grid) != "undefined") { - // GRID - window.url_background_grid = ""; - } + window.url_background_grid = ""; + if (typeof parameter_object.url_background_grid != "undefined") { + // GRID + window.url_background_grid = ""; + } - var rect_center_x = graph.nodes[0].x; - var rect_center_y = graph.nodes[0].y; + var rect_center_x = graph.nodes[0].x; + var rect_center_y = graph.nodes[0].y; - //For to catch the keyevent for the ctrl key - d3.select(document) - .on("keydown", function () { - if (d3.event.keyCode == key_multiple_selection) { - flag_multiple_selection = true; - disabled_drag_zoom = true; - } - }) - .on("keyup", function () { - if (d3.event.keyCode == key_multiple_selection) { - flag_multiple_selection = false; - disabled_drag_zoom = false; - flag_multiple_selection_running = false; + //For to catch the keyevent for the ctrl key + d3.select(document) + .on("keydown", function() { + if (d3.event.keyCode == key_multiple_selection) { + flag_multiple_selection = true; + disabled_drag_zoom = true; + } + }) + .on("keyup", function() { + if (d3.event.keyCode == key_multiple_selection) { + flag_multiple_selection = false; + disabled_drag_zoom = false; + flag_multiple_selection_running = false; - d3.select("#selection_rectangle") - .style("display", "none"); - } - }); + d3.select("#selection_rectangle").style("display", "none"); + } + }); - window.force = d3.layout.force() - .charge(10) - .linkDistance(0) - .size([width_svg, height_svg]); + window.force = d3.layout + .force() + .charge(10) + .linkDistance(0) + .size([width_svg, height_svg]); - if (x_offs != null) { - translation[0] = translation[0] + x_offs; - } - if (y_offs != null) { - translation[1] = translation[1] + y_offs; - } - if (z_dash != null) { - scale = z_dash; - } + if (x_offs != null) { + translation[0] = translation[0] + x_offs; + } + if (y_offs != null) { + translation[1] = translation[1] + y_offs; + } + if (z_dash != null) { + scale = z_dash; + } - window.zoom_obj = d3.behavior.zoom(); - zoom_obj.scaleExtent([0.05, 1]) - .on("zoom", zoom) - .translate(translation) - .scale(scale); + window.zoom_obj = d3.behavior.zoom(); + zoom_obj + .scaleExtent([0.05, 1]) + .on("zoom", zoom) + .translate(translation) + .scale(scale); - window.svg = d3.select("#networkconsole_" + networkmap_id) - .append("svg") - .attr("id", "dinamic_networkmap_svg_" + networkmap_id) - .attr("width", width_svg) - .attr("height", height_svg) - .call(zoom_obj) - .on("mousedown", function () { - if (flag_multiple_selection) { - flag_multiple_selection_running = true; + window.svg = d3 + .select("#networkconsole_" + networkmap_id) + .append("svg") + .attr("id", "dinamic_networkmap_svg_" + networkmap_id) + .attr("width", width_svg) + .attr("height", height_svg) + .call(zoom_obj) + .on("mousedown", function() { + if (flag_multiple_selection) { + flag_multiple_selection_running = true; - mouse_coords = d3.mouse(this); + mouse_coords = d3.mouse(this); - selection_rectangle[0] = mouse_coords[0]; - selection_rectangle[1] = mouse_coords[1]; - selection_rectangle[2] = mouse_coords[0]; - selection_rectangle[3] = mouse_coords[1]; + selection_rectangle[0] = mouse_coords[0]; + selection_rectangle[1] = mouse_coords[1]; + selection_rectangle[2] = mouse_coords[0]; + selection_rectangle[3] = mouse_coords[1]; - d3.select("#selection_rectangle") - .style("display", "") - .attr("x", selection_rectangle[0]) - .attr("y", selection_rectangle[1]) - .attr("width", selection_rectangle[2] - selection_rectangle[0]) - .attr("height", selection_rectangle[3] - selection_rectangle[1]); - } - else { - clear_selection(); - } - }) - .on("mouseup", function () { - flag_multiple_selection_running = false; - d3.select("#selection_rectangle") - .style("display", "none"); - }) - .on("mousemove", function () { - if (flag_multiple_selection_running) { + d3.select("#selection_rectangle") + .style("display", "") + .attr("x", selection_rectangle[0]) + .attr("y", selection_rectangle[1]) + .attr("width", selection_rectangle[2] - selection_rectangle[0]) + .attr("height", selection_rectangle[3] - selection_rectangle[1]); + } else { + clear_selection(); + } + }) + .on("mouseup", function() { + flag_multiple_selection_running = false; + d3.select("#selection_rectangle").style("display", "none"); + }) + .on("mousemove", function() { + if (flag_multiple_selection_running) { + mouse_coords = d3.mouse(this); - mouse_coords = d3.mouse(this); + selection_rectangle[2] = mouse_coords[0]; + selection_rectangle[3] = mouse_coords[1]; - selection_rectangle[2] = mouse_coords[0]; - selection_rectangle[3] = mouse_coords[1]; + x = selection_rectangle[0]; + width = selection_rectangle[2] - selection_rectangle[0]; + if (width < 0) { + x = selection_rectangle[2]; + width = selection_rectangle[0] - selection_rectangle[2]; + } - x = selection_rectangle[0]; - width = selection_rectangle[2] - selection_rectangle[0]; - if (width < 0) { - x = selection_rectangle[2]; - width = selection_rectangle[0] - selection_rectangle[2]; - } + y = selection_rectangle[1]; + height = selection_rectangle[3] - selection_rectangle[1]; + if (height < 0) { + y = selection_rectangle[3]; + height = selection_rectangle[1] - selection_rectangle[3]; + } - y = selection_rectangle[1]; - height = selection_rectangle[3] - selection_rectangle[1]; - if (height < 0) { - y = selection_rectangle[3]; - height = selection_rectangle[1] - selection_rectangle[3]; - } + d3.select("#selection_rectangle") + .attr("x", x) + .attr("y", y) + .attr("width", width) + .attr("height", height); - d3.select("#selection_rectangle") - .attr("x", x) - .attr("y", y) - .attr("width", width) - .attr("height", height); + sel_rec_x1 = x; + sel_rec_x2 = x + width; + sel_rec_y1 = y; + sel_rec_y2 = y + height; - sel_rec_x1 = x; - sel_rec_x2 = x + width; - sel_rec_y1 = y; - sel_rec_y2 = y + height; + d3.selectAll(".node").each(function(data, i) { + item_x1 = (data.x - node_radius / 2) * scale + translation[0]; + item_x2 = (data.x + node_radius / 2) * scale + translation[0]; + item_y1 = (data.y - node_radius / 2) * scale + translation[1]; + item_y2 = (data.y + node_radius / 2) * scale + translation[1]; - d3.selectAll('.node').each(function (data, i) { + if ( + !d3.select(this).classed("node_selected") && + // inner circle inside selection frame + item_x1 >= sel_rec_x1 && + item_x2 <= sel_rec_x2 && + item_y1 >= sel_rec_y1 && + item_y1 <= sel_rec_y2 + ) { + d3.select("#id_node_" + data.id + networkmap_id).classed( + "node_selected", + true + ); + } + }); + } + }) + .on("contextmenu", function(d) { + show_menu("background", d); + }); - item_x1 = ((data.x - (node_radius / 2)) * scale + translation[0]); - item_x2 = ((data.x + (node_radius / 2)) * scale + translation[0]); - item_y1 = ((data.y - (node_radius / 2)) * scale + translation[1]); - item_y2 = ((data.y + (node_radius / 2)) * scale + translation[1]); + window.defs = svg.append("defs"); + defs + .selectAll("defs") + .data(module_color_status) + .enter() + .append("marker") + .attr("id", function(d) { + return "interface_start_" + d.status_code; + }) + .attr("refX", 0) + .attr("refY", interface_radius) + .attr("markerWidth", node_radius / 2 + interface_radius) + .attr("markerHeight", node_radius / 2 + interface_radius) + .attr("orient", "auto") + .append("circle") + .attr("cx", node_radius / 2.3 - interface_radius / 2.3) + .attr("cy", interface_radius) + .attr("r", interface_radius) + .attr("style", function(d) { + return "fill: " + d.color + ";"; + }); - if ( - !d3.select(this).classed("node_selected") && - // inner circle inside selection frame - item_x1 >= sel_rec_x1 && - item_x2 <= sel_rec_x2 && - item_y1 >= sel_rec_y1 && - item_y1 <= sel_rec_y2 - ) { + defs + .selectAll("defs") + .data(module_color_status) + .enter() + .append("marker") + .attr("id", function(d) { + return "interface_end_" + d.status_code; + }) + .attr("refX", node_radius / 2.3 + interface_radius / 2.3) + .attr("refY", interface_radius) + .attr("markerWidth", node_radius / 2 + interface_radius) + .attr("markerHeight", node_radius / 2 + interface_radius) + .attr("orient", "auto") + .append("circle") + .attr("cx", interface_radius) + .attr("cy", interface_radius) + .attr("r", interface_radius) + .attr("style", function(d) { + return "fill: " + d.color + ";"; + }); - d3.select("#id_node_" + data.id + networkmap_id) - .classed("node_selected", true); - } - }); - } - }) - .on("contextmenu", function (d) { show_menu("background", d); }); + defs + .append("marker") + .attr("id", "interface_start") + .attr("refX", 0) + .attr("refY", interface_radius) + .attr("markerWidth", node_radius / 2 + interface_radius) + .attr("markerHeight", node_radius / 2 + interface_radius) + .attr("orient", "auto") + .append("circle") + .attr("cx", node_radius / 2 - interface_radius / 2) + .attr("cy", interface_radius) + .attr("r", interface_radius) + .attr("style", "fill:" + module_color_status_unknown + ";"); + defs + .append("marker") + .attr("id", "interface_end") + .attr("refX", node_radius / 2 + interface_radius / 2) + .attr("refY", interface_radius) + .attr("markerWidth", node_radius / 2 + interface_radius) + .attr("markerHeight", node_radius / 2 + interface_radius) + .attr("orient", "auto") + .append("circle") + .attr("cx", interface_radius) + .attr("cy", interface_radius) + .attr("r", interface_radius) + .attr("style", "fill:" + module_color_status_unknown + ";"); - window.defs = svg.append("defs"); - defs.selectAll("defs") - .data(module_color_status) - .enter() - .append("marker") - .attr("id", function (d) { return "interface_start_" + d.status_code; }) - .attr("refX", 0) - .attr("refY", interface_radius) - .attr("markerWidth", (node_radius / 2) + interface_radius) - .attr("markerHeight", (node_radius / 2) + interface_radius) - .attr("orient", "auto") - .append("circle") - .attr("cx", (node_radius / 2.3) - (interface_radius / 2.3)) - .attr("cy", interface_radius) - .attr("r", interface_radius) - .attr("style", function (d) { - return "fill: " + d.color + ";"; - }); + //Added pattern for the background grid + svg + .append("pattern") + .attr("id", "background_grid") + .attr("height", 24) + .attr("width", 25) + .attr("patternUnits", "userSpaceOnUse") + .append("image") + .attr("y", 0) + .attr("x", 0) + .attr("xlink:href", url_background_grid) + .attr("height", 24) + .attr("width", 25); - defs.selectAll("defs") - .data(module_color_status) - .enter() - .append("marker") - .attr("id", function (d) { return "interface_end_" + d.status_code; }) - .attr("refX", (node_radius / 2.3) + (interface_radius / 2.3)) - .attr("refY", interface_radius) - .attr("markerWidth", (node_radius / 2) + interface_radius) - .attr("markerHeight", (node_radius / 2) + interface_radius) - .attr("orient", "auto") - .append("circle") - .attr("cx", interface_radius) - .attr("cy", interface_radius) - .attr("r", interface_radius) - .attr("style", function (d) { - return "fill: " + d.color + ";"; - }); + window.layer_graph = svg + .append("g") + .attr("id", "layer_graph_" + networkmap_id) + .attr("transform", "translate(" + translation + ")scale(" + scale + ")"); - defs.append("marker") - .attr("id", "interface_start") - .attr("refX", 0) - .attr("refY", interface_radius) - .attr("markerWidth", (node_radius / 2) + interface_radius) - .attr("markerHeight", (node_radius / 2) + interface_radius) - .attr("orient", "auto") - .append("circle") - .attr("cx", (node_radius / 2) - (interface_radius / 2)) - .attr("cy", interface_radius) - .attr("r", interface_radius) - .attr("style", "fill:" + module_color_status_unknown + ";"); + if (enterprise_installed) { + window.layer_graph + .append("rect") + .attr("id", "holding_area_" + networkmap_id) + .attr("width", holding_area_dimensions[0]) + .attr("height", holding_area_dimensions[1]) + .attr( + "x", + networkmap_dimensions[0] + node_radius - holding_area_dimensions[0] + ) + .attr( + "y", + networkmap_dimensions[1] + node_radius - holding_area_dimensions[1] + ) + .attr( + "style", + "fill: #e6e6e6; " + + "fill-opacity: 0.75; " + + "stroke: #dedede; " + + "stroke-width: 1; " + + "stroke-miterlimit: 4; " + + "stroke-opacity: 0.75; " + + "stroke-dasharray: none; " + + "stroke-dashoffset: 0" + ); - defs.append("marker") - .attr("id", "interface_end") - .attr("refX", (node_radius / 2) + (interface_radius / 2)) - .attr("refY", interface_radius) - .attr("markerWidth", (node_radius / 2) + interface_radius) - .attr("markerHeight", (node_radius / 2) + interface_radius) - .attr("orient", "auto") - .append("circle") - .attr("cx", interface_radius) - .attr("cy", interface_radius) - .attr("r", interface_radius) - .attr("style", "fill:" + module_color_status_unknown + ";"); + window.layer_graph + .append("text") + .append("tspan") + .attr("xml:space", "preserve") + .attr( + "style", + "font-size: 32px; " + + "font-style: normal; " + + "font-weight: normal; " + + "text-align: start; " + + "line-height: 125%; " + + "letter-spacing: 0px; " + + "word-spacing: 0px; " + + "text-anchor: start; " + + "fill: #000000; " + + "fill-opacity: 1; " + + "stroke: none; " + + "font-family: Verdana" + ) + .attr( + "x", + networkmap_dimensions[0] + node_radius - holding_area_dimensions[0] + ) + .attr( + "y", + networkmap_dimensions[1] + node_radius - holding_area_dimensions[1] - 10 + ) + .text(holding_area_title); + } - //Added pattern for the background grid - svg.append("pattern") - .attr("id", "background_grid") - .attr("height", 24) - .attr("width", 25) - .attr("patternUnits", "userSpaceOnUse") - .append("image") - .attr("y", 0) - .attr("x", 0) - .attr("xlink:href", url_background_grid) - .attr("height", 24) - .attr("width", 25); + window.layer_graph_links = window.layer_graph + .append("g") + .attr("id", "layer_graph_links_" + networkmap_id); + window.layer_graph_nodes = window.layer_graph + .append("g") + .attr("id", "layer_graph_nodes_" + networkmap_id); - window.layer_graph = svg - .append("g") - .attr("id", "layer_graph_" + networkmap_id) - .attr("transform", - "translate(" + translation + ")scale(" + scale + ")"); + window.layer_selection_rectangle = svg + .append("g") + .attr("id", "layer_selection_rectangle"); - if (enterprise_installed) { - window.layer_graph.append("rect") - .attr("id", "holding_area_" + networkmap_id) - .attr("width", holding_area_dimensions[0]) - .attr("height", holding_area_dimensions[1]) - .attr("x", - networkmap_dimensions[0] + node_radius - holding_area_dimensions[0]) - .attr("y", - networkmap_dimensions[1] + node_radius - holding_area_dimensions[1]) - .attr("style", "fill: #e6e6e6; " + - "fill-opacity: 0.75; " + - "stroke: #dedede; " + - "stroke-width: 1; " + - "stroke-miterlimit: 4; " + - "stroke-opacity: 0.75; " + - "stroke-dasharray: none; " + - "stroke-dashoffset: 0"); + force + .nodes(graph.nodes) + .links(graph.links) + .start(); - window.layer_graph.append("text") - .append("tspan") - .attr("xml:space", "preserve") - .attr("style", "font-size: 32px; " + - "font-style: normal; " + - "font-weight: normal; " + - "text-align: start; " + - "line-height: 125%; " + - "letter-spacing: 0px; " + - "word-spacing: 0px; " + - "text-anchor: start; " + - "fill: #000000; " + - "fill-opacity: 1; " + - "stroke: none; " + - "font-family: Verdana") - .attr("x", networkmap_dimensions[0] + node_radius - holding_area_dimensions[0]) - .attr("y", networkmap_dimensions[1] + node_radius - holding_area_dimensions[1] - 10) - .text(holding_area_title); - } + window.node = layer_graph_nodes.selectAll(".node"); + window.link = layer_graph_links.selectAll(".link"); - window.layer_graph_links = window.layer_graph - .append("g") - .attr("id", "layer_graph_links_" + networkmap_id); - window.layer_graph_nodes = window.layer_graph - .append("g") - .attr("id", "layer_graph_nodes_" + networkmap_id); + draw_elements_graph(); + set_positions_graph(); - window.layer_selection_rectangle = svg - .append("g") - .attr("id", "layer_selection_rectangle"); + layer_selection_rectangle + .append("rect") + .attr("width", 666) + .attr("height", 666) + .attr("x", 0) + .attr("y", 0) + .attr("id", "selection_rectangle") + .attr( + "style", + "display: none; fill:#e6e6e6; " + + "fill-opacity:0.46153846; " + + "stroke:#e6e6e6; " + + "stroke-width:1; " + + "stroke-miterlimit:4; " + + "stroke-opacity:1; " + + "stroke-dasharray:none;" + ); - force.nodes(graph.nodes) - .links(graph.links) - .start(); + $("#dialog_node_edit").dialog({ + autoOpen: false, + width: 650 + }); - window.node = layer_graph_nodes.selectAll(".node"); - window.link = layer_graph_links.selectAll(".link"); + $("#dialog_interface_link").dialog({ + autoOpen: false, + width: 650 + }); - draw_elements_graph(); - set_positions_graph(); - - layer_selection_rectangle - .append("rect") - .attr("width", 666) - .attr("height", 666) - .attr("x", 0) - .attr("y", 0) - .attr("id", "selection_rectangle") - .attr("style", "display: none; fill:#e6e6e6; " + - "fill-opacity:0.46153846; " + - "stroke:#e6e6e6; " + - "stroke-width:1; " + - "stroke-miterlimit:4; " + - "stroke-opacity:1; " + - "stroke-dasharray:none;"); - - $("#dialog_node_edit").dialog({ - autoOpen: false, - width: 650 - }); - - $("#dialog_interface_link").dialog({ - autoOpen: false, - width: 650 - }); - - $("#dialog_node_add").dialog({ - autoOpen: false, - width: 650 - }); + $("#dialog_node_add").dialog({ + autoOpen: false, + width: 650 + }); } function myMouseoverCircleFunction(node_id) { - var circle = d3.select("#id_node_" + node_id + networkmap_id + " circle"); + var circle = d3.select("#id_node_" + node_id + networkmap_id + " circle"); - over = circle.classed("node_over"); + over = circle.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - circle.classed("node_over", !over); + circle.classed("node_over", !over); - circle.transition().duration(400) - .attr("r", node_radius + 10); + circle + .transition() + .duration(400) + .attr("r", node_radius + 10); } function myMouseoutCircleFunction(node_id) { - var circle = d3.select("#id_node_" + node_id + networkmap_id + " circle"); + var circle = d3.select("#id_node_" + node_id + networkmap_id + " circle"); - over = circle.classed("node_over"); + over = circle.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - circle.classed("node_over", !over); + circle.classed("node_over", !over); - circle.transition().duration(400) - .attr("r", node_radius); + circle + .transition() + .duration(400) + .attr("r", node_radius); } function myMouseoverSquareFunction(node_id) { - var square = d3.select("#id_node_" + node_id + networkmap_id + " rect"); + var square = d3.select("#id_node_" + node_id + networkmap_id + " rect"); - over = square.classed("node_over"); + over = square.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - square.classed("node_over", !over); + square.classed("node_over", !over); - square.transition().duration(400) - .attr("width", (node_radius * 2) + 10) - .attr("height", (node_radius * 2) + 10) - .attr("transform", "translate(" + (-5) + "," + (-5) + ")"); + square + .transition() + .duration(400) + .attr("width", node_radius * 2 + 10) + .attr("height", node_radius * 2 + 10) + .attr("transform", "translate(" + -5 + "," + -5 + ")"); } function myMouseoutSquareFunction(node_id) { - var square = d3.select("#id_node_" + node_id + networkmap_id + " rect"); + var square = d3.select("#id_node_" + node_id + networkmap_id + " rect"); - over = square.classed("node_over"); + over = square.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - square.classed("node_over", !over); + square.classed("node_over", !over); - square.transition().duration(400) - .attr("width", (node_radius * 2)) - .attr("height", (node_radius * 2)) - .attr("transform", "translate(" + 0 + "," + 0 + ")"); + square + .transition() + .duration(400) + .attr("width", node_radius * 2) + .attr("height", node_radius * 2) + .attr("transform", "translate(" + 0 + "," + 0 + ")"); } function myMouseoverRhombusFunction(node_id) { - var rhombus = d3.select("#id_node_" + node_id + networkmap_id + " rect"); + var rhombus = d3.select("#id_node_" + node_id + networkmap_id + " rect"); - over = rhombus.classed("node_over"); + over = rhombus.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - rhombus.classed("node_over", !over); + rhombus.classed("node_over", !over); - rhombus.transition().duration(400) - .attr("width", (node_radius * 1.5) + 10) - .attr("height", (node_radius * 1.5) + 10); + rhombus + .transition() + .duration(400) + .attr("width", node_radius * 1.5 + 10) + .attr("height", node_radius * 1.5 + 10); } function myMouseoutRhombusFunction(node_id) { - var rhombus = d3.select("#id_node_" + node_id + networkmap_id + " rect"); + var rhombus = d3.select("#id_node_" + node_id + networkmap_id + " rect"); - over = rhombus.classed("node_over"); + over = rhombus.classed("node_over"); - in_a_node = !in_a_node; + in_a_node = !in_a_node; - rhombus.classed("node_over", !over); + rhombus.classed("node_over", !over); - rhombus.transition().duration(400) - .attr("width", (node_radius * 1.5)) - .attr("height", (node_radius * 1.5)); + rhombus + .transition() + .duration(400) + .attr("width", node_radius * 1.5) + .attr("height", node_radius * 1.5); } function draw_elements_graph() { - link = link.data(force.links().filter(function(d, i) { - if (d['deleted']) { - return false; - } - else { - return true; - } - }), - function (d) { - return d.source.id + networkmap_id + "-" + d.target.id + networkmap_id + Math.random(); - }); - + link = link.data( + force.links().filter(function(d, i) { + if (d["deleted"]) { + return false; + } else { + return true; + } + }), + function(d) { + return ( + d.source.id + + networkmap_id + + "-" + + d.target.id + + networkmap_id + + Math.random() + ); + } + ); - link_temp = link.enter() - .append("g") - .attr("id", function (d) { - return "link_id_" + d.id_db + networkmap_id; - }) - .attr("class", function (d) { - var holding_area_text = ""; - if ((d.source.state == 'holding_area') || - (d.target.state == 'holding_area')) { + link_temp = link + .enter() + .append("g") + .attr("id", function(d) { + return "link_id_" + d.id_db + networkmap_id; + }) + .attr("class", function(d) { + var holding_area_text = ""; + if ( + d.source.state == "holding_area" || + d.target.state == "holding_area" + ) { + holding_area_text = " holding_area_link "; + } - holding_area_text = " holding_area_link "; - } + return ( + "link " + + "source_" + + d.source.id + + networkmap_id + + " " + + "target_" + + d.target.id + + networkmap_id + + " " + + holding_area_text + + "id_module_start_" + + d.id_module_start + + " " + + "id_module_end_" + + d.id_module_end + ); + }); - return "link " + - "source_" + d.source.id + networkmap_id + " " + - "target_" + d.target.id + networkmap_id + " " + - holding_area_text + - "id_module_start_" + d.id_module_start + " " + - "id_module_end_" + d.id_module_end; - }); + link.exit().remove(); - link.exit().remove(); + link_temp + .append("path") + .attr("id", function(d) { + return "link_id_text_" + d.id_db + networkmap_id; + }) + .attr("class", function(d) { + var holding_area_text = ""; + if ( + d.source.state == "holding_area" || + d.target.state == "holding_area" + ) { + holding_area_text = " holding_area_link "; + } - link_temp.append("path") - .attr("id", function (d) { - return "link_id_text_" + d.id_db + networkmap_id; - }) - .attr("class", function (d) { - var holding_area_text = ""; - if ((d.source.state == 'holding_area') || - (d.target.state == 'holding_area')) { + return ( + "link " + + "source_" + + d.source.id + + networkmap_id + + " " + + "target_" + + d.target.id + + networkmap_id + + " " + + holding_area_text + + "id_module_start_" + + d.id_module_start + + " " + + "id_module_end_" + + d.id_module_end + ); + }) + .attr("stroke", function(d) { + if (d.link_color === undefined) { + return "#999"; + } else { + return d.link_color; + } + }) + .attr("stroke-width", 3) + .attr("d", null) + .attr("marker-start", function(d) { + if (d.arrow_start == "") { + return ""; + } else if (d.arrow_start == "module") { + if (typeof module_color_status[d.status_start] == "undefined") + return "url(#interface_start)"; + else return "url(#interface_start_" + d.status_start + ")"; + } + }) + .attr("marker-end", function(d) { + if (d.arrow_end == "") { + return ""; + } else if (d.arrow_end == "module") { + if (typeof module_color_status[d.status_end] == "undefined") + return "url(#interface_end)"; + else return "url(#interface_end_" + d.status_end + ")"; + } + }) + .on("mouseover", function(d) { + d3.select(this).classed("link_over", true); + }) + .on("mouseout", function(d) { + d3.select(this).classed("link_over", false); + }); - holding_area_text = " holding_area_link "; - } + //Add the reverse line for the end marker, it is invisible + link_temp + .append("path") + .attr("id", function(d) { + return "link_reverse_id_" + d.id_db + networkmap_id; + }) + .attr("stroke-width", 0) + .attr("d", null) + .attr("class", function(d) { + return "link_reverse"; + }); - return "link " + - "source_" + d.source.id + networkmap_id + " " + - "target_" + d.target.id + networkmap_id + " " + - holding_area_text + - "id_module_start_" + d.id_module_start + " " + - "id_module_end_" + d.id_module_end; - }) - .attr("stroke", function (d) { - if(d.link_color === undefined) { - return "#999"; - } else { - return d.link_color; - } - }) - .attr("stroke-width", 3) - .attr("d", null) - .attr('marker-start', function (d) { - if (d.arrow_start == "") { - return ""; - } - else if (d.arrow_start == "module") { - if (typeof (module_color_status[d.status_start]) == "undefined") - return "url(#interface_start)"; - else - return "url(#interface_start_" + d.status_start + ")"; - } - }) - .attr('marker-end', function (d) { - if (d.arrow_end == "") { - return ""; - } - else if (d.arrow_end == "module") { - if (typeof (module_color_status[d.status_end]) == "undefined") - return "url(#interface_end)"; - else - return "url(#interface_end_" + d.status_end + ")"; - } - }) - .on("mouseover", function (d) { - d3.select(this) - .classed("link_over", true); - }) - .on("mouseout", function (d) { - d3.select(this) - .classed("link_over", false); - }); + link_temp + .append("text") + .attr("xml:space", "preserve") + .append("textPath") + .attr("xlink:href", function(d) { + if (d.source.x < d.target.x) { + return "#link_id_text_" + d.id_db + networkmap_id; + } else { + return "#link_reverse_id_" + d.id_db + networkmap_id; + } + }) + .attr("startOffset", function(d) { + if (d.source.x < d.target.x) { + return "0%"; + } else { + return "85%"; + } + }) + .attr("text-anchor", function(d) { + if (d.source.x < d.target.x) { + return ""; + } else { + return "end"; + } + }) + .append("tspan") + .attr( + "style", + "font-size: 12px; " + + "font-style:normal; " + + "font-weight:normal; " + + "line-height: 100%; " + + "letter-spacing:0px; " + + "word-spacing:0px; " + + "fill:#000000; " + + "fill-opacity:1; " + + "stroke:none; " + + "text-align:start; " + ) + .text(function(d) { + var text_link = ""; + if (d.text_start) { + text_link = d.text_start; + } - //Add the reverse line for the end marker, it is invisible - link_temp.append("path") - .attr("id", function (d) { - return "link_reverse_id_" + d.id_db + networkmap_id; - }) - .attr("stroke-width", 0) - .attr("d", null) - .attr("class", function (d) { - return "link_reverse"; - }); + return Array(25).join(" ") + text_link; + }); - link_temp.append("text") - .attr("xml:space", "preserve") - .append("textPath") - .attr("xlink:href", function (d) { - if (d.source.x < d.target.x) { - return "#link_id_text_" + d.id_db + networkmap_id; - } - else { - return "#link_reverse_id_" + d.id_db + networkmap_id; - } - }) - .attr("startOffset", function (d) { - if (d.source.x < d.target.x) { - return "0%"; - } - else { - return "85%"; - } - }) - .attr("text-anchor", function (d) { - if (d.source.x < d.target.x) { - return ""; - } - else { - return "end"; - } - }) - .append("tspan") - .attr("style", "font-size: 12px; " + - "font-style:normal; " + - "font-weight:normal; " + - "line-height: 100%; " + - "letter-spacing:0px; " + - "word-spacing:0px; " + - "fill:#000000; " + - "fill-opacity:1; " + - "stroke:none; " + - "text-align:start; ") - .text(function (d) { - var text_link = ""; - if (d.text_start) { - text_link = d.text_start; - } + link_temp + .append("text") + .attr("xml:space", "preserve") + .append("textPath") + .attr("xlink:href", function(d) { + if (d.source.x < d.target.x) { + return "#link_id_text_" + d.id_db + networkmap_id; + } else { + return "#link_reverse_id_" + d.id_db + networkmap_id; + } + }) + .attr("startOffset", function(d) { + if (d.source.x < d.target.x) { + return "85%"; + } else { + return "0%"; + } + }) + .attr("text-anchor", function(d) { + if (d.source.x < d.target.x) { + return "end"; + } else { + return ""; + } + }) + .append("tspan") + .attr( + "style", + "font-size: 12px; " + + "font-style:normal; " + + "font-weight:normal; " + + "line-height: 100%; " + + "letter-spacing:0px; " + + "word-spacing:0px; " + + "fill:#000000; " + + "fill-opacity:1; " + + "stroke:none; " + + "text-align:end; " + ) + .text(function(d) { + var text_link = ""; + if (d.text_end) { + text_link = d.text_end; + } - return (Array(25).join(" ")) + text_link; - }); + return Array(25).join(" ") + text_link; + }); - link_temp.append("text") - .attr("xml:space", "preserve") - .append("textPath") - .attr("xlink:href", function (d) { - if (d.source.x < d.target.x) { - return "#link_id_text_" + d.id_db + networkmap_id; - } - else { - return "#link_reverse_id_" + d.id_db + networkmap_id; - } - }) - .attr("startOffset", function (d) { - if (d.source.x < d.target.x) { - return "85%"; - } - else { - return "0%"; - } - }) - .attr("text-anchor", function (d) { - if (d.source.x < d.target.x) { - return "end"; - } - else { - return ""; - } - }) - .append("tspan") - .attr("style", "font-size: 12px; " + - "font-style:normal; " + - "font-weight:normal; " + - "line-height: 100%; " + - "letter-spacing:0px; " + - "word-spacing:0px; " + - "fill:#000000; " + - "fill-opacity:1; " + - "stroke:none; " + - "text-align:end; ") - .text(function (d) { - var text_link = ""; - if (d.text_end) { - text_link = d.text_end; - } + node = node.data( + force.nodes().filter(function(d, i) { + if (d["deleted"]) { + return false; + } else { + return true; + } + }), + function(d) { + return d.id; + } + ); - return (Array(25).join(" ")) + text_link; - }); + node_temp = node + .enter() + .append("g") + .attr("id", function(d) { + return "id_node_" + d.id + networkmap_id; + }) + .attr("class", function(d) { + if (d.state == "holding_area") return "node holding_area"; + else return "node"; + }); - node = node.data(force.nodes().filter(function(d, i) { - if (d['deleted']) { - return false; - } - else { - return true; - } - }), function (d) { return d.id; }); + node.exit().remove(); - node_temp = node.enter() - .append("g") - .attr("id", function (d) { - return "id_node_" + d.id + networkmap_id; - }) - .attr("class", function (d) { - if (d.state == 'holding_area') - return "node holding_area"; - else - return "node"; - }); + //Shape circle + node_temp + .filter(function(d) { + if (d.shape == "circle") { + return true; + } else return false; + }) + .append("circle") + .attr("r", node_radius) + .attr("class", "node_shape node_shape_circle") + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverCircleFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutCircleFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - node.exit().remove(); + node_temp + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return is_central_node(d) ? $("#hidden-center_logo").val() : d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverCircleFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutCircleFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - //Shape circle - node_temp.filter(function (d) { - if (d.shape == 'circle') { return true; } - else return false; - }) - .append("circle") - .attr("r", node_radius) - .attr("class", "node_shape node_shape_circle") - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverCircleFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutCircleFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + //Shape square + node_temp + .filter(function(d) { + if (d.shape == "square") { + return true; + } else return false; + }) + .append("rect") + .attr("width", node_radius * 2) + .attr("height", node_radius * 2) + .attr("class", "node_shape node_shape_square") + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverSquareFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutSquareFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + node_temp + .filter(function(d) { + if (d.shape == "square") { + return true; + } else return false; + }) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverSquareFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutSquareFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - node_temp.append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return is_central_node(d) - ? $("#hidden-center_logo").val() - : d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverCircleFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutCircleFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + //Shape rhombus + node_temp + .filter(function(d) { + if (d.shape == "rhombus") { + return true; + } else return false; + }) + .append("rect") + .attr("transform", "") + .attr("width", node_radius * 1.5) + .attr("height", node_radius * 1.5) + .attr("class", "node_shape node_shape_rhombus") + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .style("fill", function(d) { + return d.color; + }) + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverRhombusFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutRhombusFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + node_temp + .filter(function(d) { + if (d.shape == "rhombus") { + return true; + } else return false; + }) + .append("image") + .attr("class", "node_image") + .attr("xlink:href", function(d) { + return d.image_url; + }) + .attr("x", function(d) { + return d.x - d.image_width / 2; + }) + .attr("y", function(d) { + return d.y - d.image_height / 2; + }) + .attr("width", function(d) { + return node_radius / 0.8; + }) + .attr("height", function(d) { + return node_radius / 0.8; + }) + .attr("node_id", function(d) { + return d.id + networkmap_id; + }) + .attr("id", "image2995") + .classed("dragable_node", true) //own dragable + .on("mouseover", function(d) { + myMouseoverRhombusFunction(d.id); + }) + .on("mouseout", function(d) { + myMouseoutRhombusFunction(d.id); + }) + .on("click", selected_node) + .on("dblclick", function(d) { + if (d.type == 3) { + move_to_networkmap(d); + } else { + edit_node(d, true); + } + }) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - //Shape square - node_temp.filter(function (d) { - if (d.shape == 'square') { return true; } - else return false; - }) - .append("rect") - .attr("width", node_radius * 2) - .attr("height", node_radius * 2) - .attr("class", "node_shape node_shape_square") - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverSquareFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutSquareFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + var font_size = node_radius / 1.5; - }) - .on("contextmenu", function (d) { show_menu("node", d); }); + node_temp + .append("text") + .attr("class", "node_text") + .attr("id", "node_text_" + networkmap_id) + .attr( + "style", + "font-style:normal; font-weight:normal; line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;" + ) + .attr("x", function(d) { + return d.x; + }) + .attr("y", function(d) { + return d.y + node_radius + 12; + }) + .append("tspan") + .attr( + "style", + "font-size: " + + font_size + + "px !important; font-family:Verdana; text-align:center; text-anchor:middle; fill:#000000" + ) + .text(function(d) { + return ellipsize(get_node_name_ov(d), 30); + }) + .classed("dragable_node", true) //own dragable + .on("click", selected_node) + .on("contextmenu", function(d) { + show_menu("node", d); + }); - node_temp.filter(function (d) { - if (d.shape == 'square') { return true; } - else return false; - }) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverSquareFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutSquareFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } + node_temp.append("title").text(function(d) { + return get_node_name_ov(d); + }); - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - //Shape rhombus - node_temp.filter(function (d) { - if (d.shape == 'rhombus') { return true; } - else return false; - }) - .append("rect") - .attr("transform", - "") - .attr("width", node_radius * 1.5) - .attr("height", node_radius * 1.5) - .attr("class", "node_shape node_shape_rhombus") - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .style("fill", function (d) { - return d.color; - }) - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverRhombusFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutRhombusFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - node_temp.filter(function (d) { - if (d.shape == 'rhombus') { return true; } - else return false; - }) - .append("image") - .attr("class", "node_image") - .attr("xlink:href", function (d) { - return d.image_url; - }) - .attr("x", function (d) { - return d.x - (d.image_width / 2); - }) - .attr("y", function (d) { - return d.y - (d.image_height / 2); - }) - .attr("width", function (d) { - return (node_radius / 0.8); - }) - .attr("height", function (d) { - return (node_radius / 0.8); - }) - .attr("node_id", function (d) { - return d.id + networkmap_id; - }) - .attr("id", "image2995") - .classed('dragable_node', true) //own dragable - .on("mouseover", function (d) { - myMouseoverRhombusFunction(d.id) - }) - .on("mouseout", function (d) { - myMouseoutRhombusFunction(d.id) - }) - .on("click", selected_node) - .on("dblclick", function (d) { - if (d.type == 3) { - move_to_networkmap(d); - } - else { - edit_node(d, true); - } - - }) - .on("contextmenu", function (d) { show_menu("node", d); }); - - var font_size = (node_radius / 1.5); - - node_temp.append("text") - .attr("class", "node_text") - .attr("id", "node_text_" + networkmap_id) - .attr("style", "font-style:normal; font-weight:normal; line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;") - .attr("x", function (d) { - return d.x; - }) - .attr("y", function (d) { - return d.y + node_radius + 12; - }) - .append("tspan") - .attr("style", "font-size: " + font_size + "px !important; font-family:Verdana; text-align:center; text-anchor:middle; fill:#000000") - .text(function (d) { - return ellipsize(get_node_name_ov(d), 30); - }) - .classed('dragable_node', true) //own dragable - .on("click", selected_node) - .on("contextmenu", function (d) { show_menu("node", d); }); - - node_temp.append("title") - .text(function (d) { return get_node_name_ov(d) }); - - node.exit().remove(); + node.exit().remove(); } -function is_central_node (data) { - return (data.type == 0 && data.id_agent == 0); +function is_central_node(data) { + return data.type == 0 && data.id_agent == 0; } -function get_node_name_ov (data) { - // Node central name should be the product name - return (is_central_node(data)) - ? $("#hidden-product_name").val() - : data.text; +function get_node_name_ov(data) { + // Node central name should be the product name + return is_central_node(data) ? $("#hidden-product_name").val() : data.text; } function choose_group_for_show_agents() { - if (enterprise_installed) { - group = $("#group_for_show_agents option:selected").val(); + if (enterprise_installed) { + group = $("#group_for_show_agents option:selected").val(); - $("#agents_filter_group").attr('disabled', true); - $("#spinner_group").css('display', ''); - if (group == -1) { - $("#agents_filter_group").html(''); - $("#spinner_group").css('display', 'none'); - } - else { - $("#group_for_show_agents").attr('disabled', true); + $("#agents_filter_group").attr("disabled", true); + $("#spinner_group").css("display", ""); + if (group == -1) { + $("#agents_filter_group").html( + '" + ); + $("#spinner_group").css("display", "none"); + } else { + $("#group_for_show_agents").attr("disabled", true); - var params = []; - params.push("get_agents_in_group=1"); - params.push("id=" + networkmap_id); - params.push("group=" + group); - params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "ajax.php", - success: function (data) { - if (data['correct']) { - $("#agents_filter_group").html(''); - jQuery.each(data['agents'], function (id, name) { - if (typeof (name) == 'undefined') return; + var params = []; + params.push("get_agents_in_group=1"); + params.push("id=" + networkmap_id); + params.push("group=" + group); + params.push("page=enterprise/operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#agents_filter_group").html(""); + jQuery.each(data["agents"], function(id, name) { + if (typeof name == "undefined") return; - $("#agents_filter_group").append(''); - }); + $("#agents_filter_group").append( + '" + ); + }); - $("#agents_filter_group").removeAttr('disabled'); - $("#group_for_show_agents").removeAttr('disabled'); - $("#spinner_group").css('display', 'none'); - $("input[name=add_agent_group_button]").removeAttr('disabled'); - } - else { - $("#group_for_show_agents").removeAttr('disabled'); - $("#agents_filter_group").html(''); - $("#spinner_group").css('display', 'none'); function show_networkmap_node(id_agent_param, refresh_state) { - id_agent = id_agent_param; + $("#agents_filter_group").removeAttr("disabled"); + $("#group_for_show_agents").removeAttr("disabled"); + $("#spinner_group").css("display", "none"); + $("input[name=add_agent_group_button]").removeAttr("disabled"); + } else { + $("#group_for_show_agents").removeAttr("disabled"); + $("#agents_filter_group").html( + '" + ); + $("#spinner_group").css("display", "none"); + function show_networkmap_node(id_agent_param, refresh_state) { + id_agent = id_agent_param; - canvas = $("#node_info"); - context_popup = canvas[0].getContext('2d'); + canvas = $("#node_info"); + context_popup = canvas[0].getContext("2d"); - dirty_popup = true; - self.setInterval("check_popup_modification()", 1000 / 30); + dirty_popup = true; + self.setInterval("check_popup_modification()", 1000 / 30); - $("#node_info").mousemove(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousemove(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - module_inner = inner_module(x, y); + module_inner = inner_module(x, y); - if (module_inner != null) { - document.body.style.cursor = "pointer"; - } - else { - document.body.style.cursor = "default"; - } - }); + if (module_inner != null) { + document.body.style.cursor = "pointer"; + } else { + document.body.style.cursor = "default"; + } + }); - $("#node_info").mousedown(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousedown(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - if (module_inner != null) { - show_tooltip(module_inner, x, y); - } + if (module_inner != null) { + show_tooltip(module_inner, x, y); + } - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseup(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseup(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseout(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseout(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $(window).resize(function () { - function show_networkmap_node(id_agent_param, refresh_state) { - id_agent = id_agent_param; + $(window).resize(function() { + function show_networkmap_node(id_agent_param, refresh_state) { + id_agent = id_agent_param; - canvas = $("#node_info"); - context_popup = canvas[0].getContext('2d'); + canvas = $("#node_info"); + context_popup = canvas[0].getContext("2d"); - dirty_popup = true; - self.setInterval("check_popup_modification()", 1000 / 30); + dirty_popup = true; + self.setInterval("check_popup_modification()", 1000 / 30); - $("#node_info").mousemove(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousemove(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - module_inner = inner_module(x, y); + module_inner = inner_module(x, y); - if (module_inner != null) { - document.body.style.cursor = "pointer"; - } - else { - document.body.style.cursor = "default"; - } - }); + if (module_inner != null) { + document.body.style.cursor = "pointer"; + } else { + document.body.style.cursor = "default"; + } + }); - $("#node_info").mousedown(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousedown(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - if (module_inner != null) { - show_tooltip(module_inner, x, y); - } + if (module_inner != null) { + show_tooltip(module_inner, x, y); + } - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseup(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseup(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseout(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseout(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $(window).resize(function () { + $(window).resize(function() { + pos_scroll = Math.floor( + $("#content_node_info").width() / 2 + ); - pos_scroll = Math.floor($("#content_node_info").width() / 2); + $("#content_node_info").scrollLeft(pos_scroll); - $("#content_node_info").scrollLeft(pos_scroll); + dirty_popup = true; + check_popup_modification(); + }); + } + pos_scroll = Math.floor($("#content_node_info").width() / 2); - dirty_popup = true; - check_popup_modification(); - }); - } - pos_scroll = Math.floor($("#content_node_info").width() / 2); + $("#content_node_info").scrollLeft(pos_scroll); - $("#content_node_info").scrollLeft(pos_scroll); - - dirty_popup = true; - check_popup_modification(); - }); - } - } - } - }); - } - } + dirty_popup = true; + check_popup_modification(); + }); + } + } + } + }); + } + } } //////////////////////////////////////////////////////////////////////// @@ -3915,372 +4205,391 @@ var offset_y = 0; var module_inner = null; function get_status_node() { - var params = []; - params.push("get_status_node=1"); - params.push("id=" + id_agent); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "../../../ajax.php", - success: function (data) { - if (data['correct']) { - color_status_node = data['status_agent']; - dirty_popup = true; - } - } - }); + var params = []; + params.push("get_status_node=1"); + params.push("id=" + id_agent); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "../../../ajax.php"), + success: function(data) { + if (data["correct"]) { + color_status_node = data["status_agent"]; + dirty_popup = true; + } + } + }); } function get_status_module() { - jQuery.each(modules, function (id, module) { - if (typeof (module) == 'undefined') return; + jQuery.each(modules, function(id, module) { + if (typeof module == "undefined") return; - - var params = []; - params.push("get_status_module=1"); - params.push("id=" + id); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "../../../ajax.php", - success: function (data) { - if (data['correct']) { - modules[data['id']].status_color = data['status_color']; - dirty_popup = true; - } - } - }); - - - }); + var params = []; + params.push("get_status_module=1"); + params.push("id=" + id); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "../../../ajax.php"), + success: function(data) { + if (data["correct"]) { + modules[data["id"]].status_color = data["status_color"]; + dirty_popup = true; + } + } + }); + }); } function show_networkmap_node(id_agent_param, refresh_state) { - id_agent = id_agent_param; + id_agent = id_agent_param; - canvas = $("#node_info"); - context_popup = canvas[0].getContext('2d'); + canvas = $("#node_info"); + context_popup = canvas[0].getContext("2d"); - dirty_popup = true; - self.setInterval("check_popup_modification()", 1000 / 30); + dirty_popup = true; + self.setInterval("check_popup_modification()", 1000 / 30); - $("#node_info").mousemove(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousemove(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - module_inner = inner_module(x, y); + module_inner = inner_module(x, y); - if (module_inner != null) { - document.body.style.cursor = "pointer"; - } - else { - document.body.style.cursor = "default"; - } - }); + if (module_inner != null) { + document.body.style.cursor = "pointer"; + } else { + document.body.style.cursor = "default"; + } + }); - $("#node_info").mousedown(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mousedown(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - if (module_inner != null) { - show_tooltip(module_inner, x, y); - } + if (module_inner != null) { + show_tooltip(module_inner, x, y); + } - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseup(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseup(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $("#node_info").mouseout(function (event) { - var x = event.pageX - $("#node_info").offset().left; - var y = event.pageY - $("#node_info").offset().top; + $("#node_info").mouseout(function(event) { + var x = event.pageX - $("#node_info").offset().left; + var y = event.pageY - $("#node_info").offset().top; - drag = false; - drag_x = 0; - drag_y = 0; - dirty_popup = true; + drag = false; + drag_x = 0; + drag_y = 0; + dirty_popup = true; - document.body.style.cursor = "default"; + document.body.style.cursor = "default"; - module_inner = null; + module_inner = null; - event.stopPropagation(); - return false; - }); + event.stopPropagation(); + return false; + }); - $(window).resize(function () { + $(window).resize(function() { + pos_scroll = Math.floor($("#content_node_info").width() / 2); - pos_scroll = Math.floor($("#content_node_info").width() / 2); + $("#content_node_info").scrollLeft(pos_scroll); - $("#content_node_info").scrollLeft(pos_scroll); - - dirty_popup = true; - check_popup_modification(); - }); + dirty_popup = true; + check_popup_modification(); + }); } function show_tooltip_content(id) { - var params = []; - params.push("get_tooltip_content=1"); - params.push("id=" + id); - params.push("page=operation/agentes/pandora_networkmap.view"); - jQuery.ajax({ - data: params.join("&"), - dataType: 'json', - type: 'POST', - url: action = "../../../ajax.php", - success: function (data) { - if (data['correct']) { - $("#tooltip").html(data['content']); - } - } - }); + var params = []; + params.push("get_tooltip_content=1"); + params.push("id=" + id); + params.push("page=operation/agentes/pandora_networkmap.view"); + jQuery.ajax({ + data: params.join("&"), + dataType: "json", + type: "POST", + url: (action = "../../../ajax.php"), + success: function(data) { + if (data["correct"]) { + $("#tooltip").html(data["content"]); + } + } + }); } function show_tooltip(id, x, y) { - $("#tooltip").css('top', y + 'px'); - $("#tooltip").css('left', x + 'px'); + $("#tooltip").css("top", y + "px"); + $("#tooltip").css("left", x + "px"); - var params1 = []; - params1.push("get_image_path=1"); - params1.push("img_src=" + "images/spinner.gif"); - params1.push("page=include/ajax/skins.ajax"); - jQuery.ajax({ - data: params1.join("&"), - type: 'POST', - url: action = "../../../ajax.php", - success: function (data) { - $("#tooltip").html(data); - $("#tooltip").css('display', ''); + var params1 = []; + params1.push("get_image_path=1"); + params1.push("img_src=" + "images/spinner.gif"); + params1.push("page=include/ajax/skins.ajax"); + jQuery.ajax({ + data: params1.join("&"), + type: "POST", + url: (action = "../../../ajax.php"), + success: function(data) { + $("#tooltip").html(data); + $("#tooltip").css("display", ""); - show_tooltip_content(id); - } - }); + show_tooltip_content(id); + } + }); } function hide_tooltip() { - $("#tooltip").css('display', 'none'); + $("#tooltip").css("display", "none"); } function inner_module(x, y) { - var return_var = null; + var return_var = null; - jQuery.each(modules, function (key, module) { - if (typeof (module) == 'undefined') return; + jQuery.each(modules, function(key, module) { + if (typeof module == "undefined") return; - if ((x >= module.pos_x) && (x < (module.pos_x + SIZE_MODULE)) && - (y >= module.pos_y) && (y < (module.pos_y + SIZE_MODULE))) { + if ( + x >= module.pos_x && + x < module.pos_x + SIZE_MODULE && + y >= module.pos_y && + y < module.pos_y + SIZE_MODULE + ) { + return_var = key; + } + }); - return_var = key; - } - }); - - return return_var; + return return_var; } function check_popup_modification() { - if (dirty_popup) { - draw_popup(); - dirty_popup = false; - } + if (dirty_popup) { + draw_popup(); + dirty_popup = false; + } } function draw_popup() { - //Calculate the size - count_no_snmp = module_count - count_snmp_modules; + //Calculate the size + count_no_snmp = module_count - count_snmp_modules; - if (count_no_snmp > count_snmp_modules) { - box_height = Math.ceil(count_no_snmp / 2) * VERTICAL_SPACE_MODULES - + VERTICAL_SPACING_BETWEEN_MODULES; - } - else { - box_height = Math.ceil(count_snmp_modules / 2) * VERTICAL_SPACE_MODULES - + VERTICAL_SPACING_BETWEEN_MODULES; - } + if (count_no_snmp > count_snmp_modules) { + box_height = + Math.ceil(count_no_snmp / 2) * VERTICAL_SPACE_MODULES + + VERTICAL_SPACING_BETWEEN_MODULES; + } else { + box_height = + Math.ceil(count_snmp_modules / 2) * VERTICAL_SPACE_MODULES + + VERTICAL_SPACING_BETWEEN_MODULES; + } - //Draw the agent box. - // 2 columns of HORIZONTAL_SPACE_MODULES px for each modules - // + 15 * 2 half each snmp module - box_width = HORIZONTAL_SPACE_MODULES * 2 + SIZE_MODULE; + //Draw the agent box. + // 2 columns of HORIZONTAL_SPACE_MODULES px for each modules + // + 15 * 2 half each snmp module + box_width = HORIZONTAL_SPACE_MODULES * 2 + SIZE_MODULE; + //Resize the canvas if the box is bigger before of paint. + if (box_height + 50 != $("#node_info").attr("height")) { + node_info_height = box_height + 50; + $("#node_info").attr("height", node_info_height); + //$("#node_info").attr("width", node_info_width); + } - //Resize the canvas if the box is bigger before of paint. - if ((box_height + 50) != $("#node_info").attr("height")) { - node_info_height = box_height + 50; - $("#node_info").attr("height", node_info_height); - //$("#node_info").attr("width", node_info_width); - } + if (box_width + 400 != $("#node_info").attr("width")) { + node_info_width = box_width + 400; + $("#node_info").attr("width", node_info_width); + } - if ((box_width + 400) != $("#node_info").attr("width")) { - node_info_width = box_width + 400; - $("#node_info").attr("width", node_info_width); - } + //Clean the canvas + context_popup.clearRect(0, 0, node_info_width, node_info_height); + context_popup.beginPath(); //Erase lines? - //Clean the canvas - context_popup.clearRect(0, 0, node_info_width, node_info_height); - context_popup.beginPath(); //Erase lines? + pos_x = (node_info_width - box_width) / 2 + offset_x; + context_popup.beginPath(); + context_popup.rect( + pos_x, + VERTICAL_SPACING_BETWEEN_MODULES + offset_y, + box_width, + box_height + ); + context_popup.fillStyle = "#ccc"; + context_popup.fill(); + //Draw the global status of agent into the box's border color. + context_popup.lineWidth = BORDER_SIZE_AGENT_BOX; + context_popup.strokeStyle = color_status_node; + context_popup.stroke(); - pos_x = (node_info_width - box_width) / 2 + offset_x; - - context_popup.beginPath(); - context_popup.rect(pos_x, VERTICAL_SPACING_BETWEEN_MODULES + offset_y, box_width, box_height); - context_popup.fillStyle = "#ccc"; - context_popup.fill(); - - //Draw the global status of agent into the box's border color. - context_popup.lineWidth = BORDER_SIZE_AGENT_BOX; - context_popup.strokeStyle = color_status_node; - context_popup.stroke(); - - if (mode_show == 'all') { - draw_snmp_modules(); - draw_modules(); - } - else if (mode_show == 'status_module') { - draw_snmp_modules(); - } + if (mode_show == "all") { + draw_snmp_modules(); + draw_modules(); + } else if (mode_show == "status_module") { + draw_snmp_modules(); + } } function draw_snmp_modules() { - module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; + module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; - count = 0; - reset_column = true; + count = 0; + reset_column = true; - jQuery.each(modules, function (key, module) { - if (typeof (module) == 'undefined') return; + jQuery.each(modules, function(key, module) { + if (typeof module == "undefined") return; - if (module.type != 18) return; + if (module.type != 18) return; - if (count < (count_snmp_modules / 2)) { - module_pos_x = pos_x - 15; - text_align = 'right'; - margin_text = 5; - } - else { - if (reset_column) { - module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; - reset_column = false; - } - module_pos_x = pos_x + box_width - 15; - text_align = 'left'; - margin_text = SIZE_MODULE - 5; - } - count++; + if (count < count_snmp_modules / 2) { + module_pos_x = pos_x - 15; + text_align = "right"; + margin_text = 5; + } else { + if (reset_column) { + module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; + reset_column = false; + } + module_pos_x = pos_x + box_width - 15; + text_align = "left"; + margin_text = SIZE_MODULE - 5; + } + count++; - context_popup.beginPath(); - context_popup.rect(module_pos_x, module_pos_y + offset_y, - SIZE_MODULE, SIZE_MODULE); - context_popup.fillStyle = module.status_color; - context_popup.fill(); - context_popup.lineWidth = 1; - context_popup.strokeStyle = "#000"; - context_popup.stroke(); + context_popup.beginPath(); + context_popup.rect( + module_pos_x, + module_pos_y + offset_y, + SIZE_MODULE, + SIZE_MODULE + ); + context_popup.fillStyle = module.status_color; + context_popup.fill(); + context_popup.lineWidth = 1; + context_popup.strokeStyle = "#000"; + context_popup.stroke(); - modules[key].pos_x = module_pos_x; - modules[key].pos_y = module_pos_y + offset_y; + modules[key].pos_x = module_pos_x; + modules[key].pos_y = module_pos_y + offset_y; - context_popup.fillStyle = "rgb(0,0,0)"; - context_popup.font = 'bold 10px sans-serif'; - context_popup.textBaseline = 'middle'; - context_popup.textAlign = text_align; - dimensions = context_popup.measureText(module.text); - text_pos_x = module_pos_x + margin_text; - text_pos_y = module_pos_y + 40 + offset_y; - context_popup.fillText(module.text, text_pos_x, text_pos_y); + context_popup.fillStyle = "rgb(0,0,0)"; + context_popup.font = "bold 10px sans-serif"; + context_popup.textBaseline = "middle"; + context_popup.textAlign = text_align; + dimensions = context_popup.measureText(module.text); + text_pos_x = module_pos_x + margin_text; + text_pos_y = module_pos_y + 40 + offset_y; + context_popup.fillText(module.text, text_pos_x, text_pos_y); - module_pos_y = module_pos_y + VERTICAL_SPACE_MODULES; - }); + module_pos_y = module_pos_y + VERTICAL_SPACE_MODULES; + }); } function draw_modules() { - module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; + module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; - count = 0; - reset_column = true; + count = 0; + reset_column = true; - jQuery.each(modules, function (key, module) { - if (typeof (module) == 'undefined') return; + jQuery.each(modules, function(key, module) { + if (typeof module == "undefined") return; - if (module.type == 18) return; + if (module.type == 18) return; - if (count < (count_no_snmp / 2)) { - module_pos_x = pos_x + (HORIZONTAL_SPACE_MODULES - SIZE_MODULE) / 2; - text_pos_x = pos_x + (HORIZONTAL_SPACE_MODULES / 2); - } - else { - if (reset_column) { - module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; - reset_column = false; - } - module_pos_x = pos_x + (box_width - HORIZONTAL_SPACE_MODULES) - + (HORIZONTAL_SPACE_MODULES - SIZE_MODULE) / 2; - text_pos_x = pos_x + (box_width - HORIZONTAL_SPACE_MODULES) + - (HORIZONTAL_SPACE_MODULES / 2) - } - count++; + if (count < count_no_snmp / 2) { + module_pos_x = pos_x + (HORIZONTAL_SPACE_MODULES - SIZE_MODULE) / 2; + text_pos_x = pos_x + HORIZONTAL_SPACE_MODULES / 2; + } else { + if (reset_column) { + module_pos_y = MARGIN_BETWEEN_AGENT_MODULE; + reset_column = false; + } + module_pos_x = + pos_x + + (box_width - HORIZONTAL_SPACE_MODULES) + + (HORIZONTAL_SPACE_MODULES - SIZE_MODULE) / 2; + text_pos_x = + pos_x + + (box_width - HORIZONTAL_SPACE_MODULES) + + HORIZONTAL_SPACE_MODULES / 2; + } + count++; - context_popup.beginPath(); - center_orig_x = module_pos_x + (SIZE_MODULE / 2); - center_orig_y = module_pos_y + offset_y + (SIZE_MODULE / 2); - radius = SIZE_MODULE / 2; - context_popup.arc(center_orig_x, center_orig_y, radius, 0, Math.PI * 2, false); - //context_popup.rect(module_pos_x, module_pos_y + offset_y, SIZE_MODULE, SIZE_MODULE); - context_popup.fillStyle = module.status_color; - context_popup.fill(); - context_popup.lineWidth = 1; - context_popup.strokeStyle = "#000"; - context_popup.stroke(); + context_popup.beginPath(); + center_orig_x = module_pos_x + SIZE_MODULE / 2; + center_orig_y = module_pos_y + offset_y + SIZE_MODULE / 2; + radius = SIZE_MODULE / 2; + context_popup.arc( + center_orig_x, + center_orig_y, + radius, + 0, + Math.PI * 2, + false + ); + //context_popup.rect(module_pos_x, module_pos_y + offset_y, SIZE_MODULE, SIZE_MODULE); + context_popup.fillStyle = module.status_color; + context_popup.fill(); + context_popup.lineWidth = 1; + context_popup.strokeStyle = "#000"; + context_popup.stroke(); + modules[key].pos_x = module_pos_x; + modules[key].pos_y = module_pos_y + offset_y; - modules[key].pos_x = module_pos_x; - modules[key].pos_y = module_pos_y + offset_y; + context_popup.fillStyle = "rgb(0,0,0)"; + context_popup.font = "bold 10px sans-serif"; + context_popup.textBaseline = "middle"; + context_popup.textAlign = "center"; + dimensions = context_popup.measureText(module.short_text); - context_popup.fillStyle = "rgb(0,0,0)"; - context_popup.font = 'bold 10px sans-serif'; - context_popup.textBaseline = 'middle'; - context_popup.textAlign = 'center'; - dimensions = context_popup.measureText(module.short_text); + text_pos_y = module_pos_y + 40 + offset_y; + context_popup.fillText(module.short_text, text_pos_x, text_pos_y); - text_pos_y = module_pos_y + 40 + offset_y; - context_popup.fillText(module.short_text, text_pos_x, text_pos_y); + module_pos_y = module_pos_y + VERTICAL_SPACE_MODULES; + }); - module_pos_y = module_pos_y + VERTICAL_SPACE_MODULES; - }); - - paint_tooltip_module_one_time = false; + paint_tooltip_module_one_time = false; } function update_fictional_node_popup(id) { - name = $("#text-fictional_name").val(); - shape = $("#fictional_shape option:selected").val(); - networmap = $("#networmaps_enterprise option:selected").val(); - radious = $("#fictional_radious").val(); - color = $("#fictional_color").val(); + name = $("#text-fictional_name").val(); + shape = $("#fictional_shape option:selected").val(); + networmap = $("#networmaps_enterprise option:selected").val(); + radious = $("#fictional_radious").val(); + color = $("#fictional_color").val(); - window.close(); + window.close(); - window.opener.update_fictional_node(id, name, shape, networmap, radious, color); + window.opener.update_fictional_node( + id, + name, + shape, + networmap, + radious, + color + ); } diff --git a/pandora_console/include/javascript/jquery.contextMenu.css b/pandora_console/include/javascript/jquery.contextMenu.css deleted file mode 100644 index b0b04223bf..0000000000 --- a/pandora_console/include/javascript/jquery.contextMenu.css +++ /dev/null @@ -1,167 +0,0 @@ -/*! - * jQuery contextMenu - Plugin for simple contextMenu handling - * - * Version: 1.6.5 - * - * Authors: Rodney Rehm, Addy Osmani (patches for FF) - * Web: http://medialize.github.com/jQuery-contextMenu/ - * - * Licensed under - * MIT License http://www.opensource.org/licenses/mit-license - * GPL v3 http://opensource.org/licenses/GPL-3.0 - * - */ - -.context-menu-list { - margin:0; - padding:0; - - min-width: 120px; - max-width: 250px; - display: inline-block; - position: absolute; - list-style-type: none; - border: 1px solid #DDD; - border-radius: 4px; - background: #EEE; - - -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - -moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - -ms-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - -o-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); - - font-family: Verdana, Arial, Helvetica, sans-serif; - font-size: 11px; - text-align: left; -} - -.context-menu-item { - padding: 0px 2px 0px 24px; - background-color: #EEE; - position: relative; - border-radius: 4px; - -webkit-user-select: none; - -moz-user-select: -moz-none; - -ms-user-select: none; - user-select: none; - padding-top: 8px; - padding-bottom: 8px; -} - -.context-menu-item span { - padding-top: 10px; - padding-bottom: 10px; - padding-right: 10px; - padding-left: 10px; -} - -.context-menu-separator { - padding-bottom:0; - border-bottom: 1px solid #DDD; -} - -.context-menu-item > label > input, -.context-menu-item > label > textarea { - -webkit-user-select: text; - -moz-user-select: text; - -ms-user-select: text; - user-select: text; -} - -.context-menu-item.hover { - cursor: pointer; - background-color: #82b92e; - border-radius: 4px; - color: #fff; -} - -.context-menu-item.disabled { - color: #666 !important; -} - -.context-menu-input.hover, -.context-menu-item.disabled.hover { - cursor: default; - background-color: #EEE; -} - -.context-menu-submenu:after { - content: ">"; - color: #666; - position: absolute; - top: 0; - right: 3px; - z-index: 1; -} - -/* icons - #protip: - In case you want to use sprites for icons (which I would suggest you do) have a look at - http://css-tricks.com/13224-pseudo-spriting/ to get an idea of how to implement - .context-menu-item.icon:before {} - */ -.context-menu-item.icon { min-height: 18px; background-repeat: no-repeat; background-position: 4px 2px; } -.context-menu-item.icon-edit { background-image: url(../../images/page_white_edit.png); } -.context-menu-item.icon-cut { background-image: url(../../images/cut.png); } -.context-menu-item.icon-copy { background-image: url(../../images/page_white_copy.png); } -.context-menu-item.icon-paste { background-image: url(../../images/page_white_paste.png); } -.context-menu-item.icon-delete { background-image: url(../../images/delete.png); } -.context-menu-item.icon-add { background-image: url(../../images/page_white_add.png); } -.context-menu-item.icon-quit { background-image: url(../../images/door.png); } -.context-menu-item.icon-refresh { background-image: url(../../images/refresh.png); } -.context-menu-item.icon-center { background-image: url(../../images/set_center.png); } -.context-menu-item.icon-details { background-image: url(../../images/show_details.png); } -.context-menu-item.icon-children { background-image: url(../../images/children.png); } -.context-menu-item.icon-cancel_set_parent { background-image: url(../../images/link_delete.png); } -.context-menu-item.icon-set_parent { background-image: url(../../images/father.png); } -.context-menu-item.icon-add_node { background-image: url(../../images/add.png); } -.context-menu-item.icon-refresh_holding_area { background-image: url(../../images/refresh_holding_area.png); } -.context-menu-item.icon-restart_map { background-image: url(../../images/reset.png); } -.context-menu-item.icon-interface_link_children { background-image: url(../../images/icono_link_hijo.png); } -.context-menu-item.icon-interface_link_parent { background-image: url(../../images/icono_link_padre.png); } -.context-menu-item.icon-interface_link_cancel { background-image: url(../../images/link_abortar.png); } - -/* vertically align inside labels */ -.context-menu-input > label > * { vertical-align: top; } - -/* position checkboxes and radios as icons */ -.context-menu-input > label > input[type="checkbox"], -.context-menu-input > label > input[type="radio"] { - margin-left: -17px; -} -.context-menu-input > label > span { - margin-left: 5px; -} - -.context-menu-input > label, -.context-menu-input > label > input[type="text"], -.context-menu-input > label > textarea, -.context-menu-input > label > select { - display: block; - width: 100%; - - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - -ms-box-sizing: border-box; - -o-box-sizing: border-box; - box-sizing: border-box; -} - -.context-menu-input > label > textarea { - height: 100px; -} -.context-menu-item > .context-menu-list { - display: none; - /* re-positioned by js */ - right: -5px; - top: 5px; -} - -.context-menu-item.hover > .context-menu-list { - display: block; -} - -.context-menu-accesskey { - text-decoration: underline; -} diff --git a/pandora_console/include/javascript/jquery.pandora.js b/pandora_console/include/javascript/jquery.pandora.js index 7cc18ec790..bd0da308c4 100644 --- a/pandora_console/include/javascript/jquery.pandora.js +++ b/pandora_console/include/javascript/jquery.pandora.js @@ -26,7 +26,8 @@ $.fn.showMessage = function (msg) { return $(this).hide ().empty () - .text (msg) + // here, previously .text (msg) + .html (msg) .slideDown (); }; }) (jQuery); diff --git a/pandora_console/include/javascript/openlayers.pandora.js b/pandora_console/include/javascript/openlayers.pandora.js index 32b7282440..ae06463d95 100755 --- a/pandora_console/include/javascript/openlayers.pandora.js +++ b/pandora_console/include/javascript/openlayers.pandora.js @@ -13,508 +13,570 @@ // GNU General Public License for more details. var map; // Map global var object is use in multiple places. -var statusShow = 'all'; +var statusShow = "all"; //The name of layer hierachy because in PHP change the text name into language of user. -var storeLayerNameHierachy = ''; +var storeLayerNameHierachy = ""; function js_refreshParentLines(layerName) { - if (typeof(layerName) == 'undefined') { - layerName = storeLayerNameHierachy; - } - else { - storeLayerNameHierachy = layerName; - } - - listFeaturesWithParents = Array(); - - jQuery.each(map.getLayersByClass("OpenLayers.Layer.Vector"), function (i, layer) { - visible = layer.visibility; - - jQuery.each(layer.features, function (i, feature) { - if (feature.data.type == "point_agent_info") { - id_parent = feature.data.id_parent; - long_lat = feature.data.long_lat; - id = feature.data.id; - status = feature.data.status; - - listFeaturesWithParents[id] = { - 'id': id, - 'id_parent': id_parent, - 'long_lat': long_lat, - 'status': status, - 'visible': visible}; - } - }); - }); - - var layer = map.getLayersByName(layerName); - layer = layer[0]; - - layer.destroyFeatures(); - - jQuery.each(listFeaturesWithParents, function (i, feature) { - //INI "break" of foreach posibilites - if (typeof(feature) == 'undefined') return; - if (feature.id_parent == 0) return; - if (typeof(listFeaturesWithParents[feature.id_parent]) == 'undefined') return; //The agent have parent but this parent is not in the map. - if ((!feature.visible) - || (!listFeaturesWithParents[feature.id_parent].visible)) return; - if ((isHideFeatureByStatus(feature.status)) - || (isHideFeatureByStatus(listFeaturesWithParents[feature.id_parent].status))) return; - //END "break" of foreach posibilites - - points = new Array(); - - points[0] = new OpenLayers.Geometry.Point(feature.long_lat.lon, feature.long_lat.lat); - points[1] = new OpenLayers.Geometry.Point(listFeaturesWithParents[feature.id_parent].long_lat.lon, listFeaturesWithParents[feature.id_parent].long_lat.lat); - - var line = new OpenLayers.Feature.Vector( - new OpenLayers.Geometry.LineString(points), - null, - { strokeWidth: 2, fillOpacity: 0.2, fillColor: 'red', strokeDashstyle: "dash", strokeColor: 'red'}); - - layer.addFeatures(line); - }); + if (typeof layerName == "undefined") { + layerName = storeLayerNameHierachy; + } else { + storeLayerNameHierachy = layerName; + } + + listFeaturesWithParents = Array(); + + jQuery.each(map.getLayersByClass("OpenLayers.Layer.Vector"), function( + i, + layer + ) { + visible = layer.visibility; + + jQuery.each(layer.features, function(i, feature) { + if (feature.data.type == "point_agent_info") { + id_parent = feature.data.id_parent; + long_lat = feature.data.long_lat; + id = feature.data.id; + status = feature.data.status; + + listFeaturesWithParents[id] = { + id: id, + id_parent: id_parent, + long_lat: long_lat, + status: status, + visible: visible + }; + } + }); + }); + + var layer = map.getLayersByName(layerName); + layer = layer[0]; + + layer.destroyFeatures(); + + jQuery.each(listFeaturesWithParents, function(i, feature) { + //INI "break" of foreach posibilites + if (typeof feature == "undefined") return; + if (feature.id_parent == 0) return; + if (typeof listFeaturesWithParents[feature.id_parent] == "undefined") + return; //The agent have parent but this parent is not in the map. + if (!feature.visible || !listFeaturesWithParents[feature.id_parent].visible) + return; + if ( + isHideFeatureByStatus(feature.status) || + isHideFeatureByStatus(listFeaturesWithParents[feature.id_parent].status) + ) + return; + //END "break" of foreach posibilites + + points = new Array(); + + points[0] = new OpenLayers.Geometry.Point( + feature.long_lat.lon, + feature.long_lat.lat + ); + points[1] = new OpenLayers.Geometry.Point( + listFeaturesWithParents[feature.id_parent].long_lat.lon, + listFeaturesWithParents[feature.id_parent].long_lat.lat + ); + + var line = new OpenLayers.Feature.Vector( + new OpenLayers.Geometry.LineString(points), + null, + { + strokeWidth: 2, + fillOpacity: 0.2, + fillColor: "red", + strokeDashstyle: "dash", + strokeColor: "red" + } + ); + + layer.addFeatures(line); + }); } /** * Inicialize the map in the browser and the object map. - * + * * @param string id_div The id of div to draw the map. * @param integer initial_zoom The initial zoom to show the map. * @param float center_latitude The coord of latitude for center. * @param float center_longitude The coord of longitude for center. * @param array objBaseLayers The array of baselayers with number index, and the baselayer is another asociative array that content 'type', 'name' and 'url'. * @param array arrayControls The array of enabled controls, the controls is: 'Navigation', 'MousePosition', 'OverviewMap', 'PanZoom', 'PanZoomBar', 'ScaleLine', 'Scale' - * + * * @return None */ -function js_printMap(id_div, initial_zoom, center_latitude, center_longitude, objBaseLayers, arrayControls) { - controlsList = []; - - for (var controlIndex in arrayControls) { - if (isInt(controlIndex)) { - switch (arrayControls[controlIndex]) { - case 'Navigation': - controlsList.push(new OpenLayers.Control.Navigation()); - break; - case 'MousePosition': - controlsList.push(new OpenLayers.Control.MousePosition()); - break; - case 'OverviewMap': - controlsList.push(new OpenLayers.Control.OverviewMap()); - break; - case 'PanZoom': - controlsList.push(new OpenLayers.Control.PanZoom()); - break; - case 'PanZoomBar': - controlsList.push(new OpenLayers.Control.PanZoomBar()); - break; - case 'ScaleLine': - controlsList.push(new OpenLayers.Control.ScaleLine()); - break; - case 'Scale': - controlsList.push(new OpenLayers.Control.Scale()); - break; - case 'layerSwitcher': - controlsList.push(new OpenLayers.Control.LayerSwitcher()); - break; - } - } - } - - - var option = { - controls: controlsList, - projection: new OpenLayers.Projection("EPSG:900913"), - displayProjection: new OpenLayers.Projection("EPSG:4326"), - units: "m", - numZoomLevels: 18, - maxResolution: 156543.0339, - maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)}; - - map = new OpenLayers.Map(id_div, option); - map.events.Event - var baseLayer = null; - - map.events.on({"zoomend": EventZoomEnd}); - map.events.on({"mouseup": EventZoomEnd}); +function js_printMap( + id_div, + initial_zoom, + center_latitude, + center_longitude, + objBaseLayers, + arrayControls +) { + controlsList = []; - //Define the maps layer - for (var baselayerIndex in objBaseLayers) { - if (isInt(baselayerIndex)) { - switch (objBaseLayers[baselayerIndex]['type']) { - case 'OSM': - baseLayer = null; - baseLayer = new OpenLayers.Layer.OSM( - objBaseLayers[baselayerIndex]['name'], - objBaseLayers[baselayerIndex]['url'], - { - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - case 'Gmap': - switch (objBaseLayers[baselayerIndex]['gmap_type']) { - case 'G_PHYSICAL_MAP': - baseLayer = new OpenLayers.Layer.Google( - objBaseLayers[baselayerIndex]['name'], - {type: G_PHYSICAL_MAP, - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - case 'G_HYBRID_MAP': - baseLayer = new OpenLayers.Layer.Google( - objBaseLayers[baselayerIndex]['name'], - {type: G_HYBRID_MAP, - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - case 'G_SATELLITE_MAP': - baseLayer = new OpenLayers.Layer.Google( - objBaseLayers[baselayerIndex]['name'], - {type: G_SATELLITE_MAP, - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - default: - baseLayer = new OpenLayers.Layer.Google( - objBaseLayers[baselayerIndex]['name'], - {numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'], - 'sphericalMercator': true - } - ); - map.addLayer(baseLayer); - break; - } - break; - case 'Static_Image': - baseLayer = null; - baseLayer = new OpenLayers.Layer.Image( - objBaseLayers[baselayerIndex]['name'], - objBaseLayers[baselayerIndex]['url'], - new OpenLayers.Bounds(objBaseLayers[baselayerIndex]['bb_left'], - objBaseLayers[baselayerIndex]['bb_bottom'], - objBaseLayers[baselayerIndex]['bb_right'], - objBaseLayers[baselayerIndex]['bb_top'] - ), - new OpenLayers.Size(objBaseLayers[baselayerIndex]['image_width'], objBaseLayers[baselayerIndex]['image_height']), - { - projection: new OpenLayers.Projection("EPSG:4326"), - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'] - } - ); - map.addLayer(baseLayer); - break; - case 'WMS': - // http:///geoserver/wms - // ?bbox=-130,24,-66,50 - // &styles=population - // &Format=application/openlayers - // &request=GetMap - // &layers=topp:states - // &width=550 - // &height=250 - // &srs=EPSG:4326 - var layer = new OpenLayers.Layer.WMS( - objBaseLayers[baselayerIndex]['name'], - objBaseLayers[baselayerIndex]['url'], - { - layers: objBaseLayers[baselayerIndex]['layers'], - format: "image/png" - }, - { - numZoomLevels: objBaseLayers[baselayerIndex]['num_zoom_levels'] - } - ); - map.addLayer(layer); - break; - } - } - } - - var lonLat = new OpenLayers.LonLat(center_longitude, center_latitude) - .transform(map.displayProjection, map.getProjectionObject()); - - map.setCenter (lonLat, initial_zoom); - + for (var controlIndex in arrayControls) { + if (isInt(controlIndex)) { + switch (arrayControls[controlIndex]) { + case "Navigation": + controlsList.push(new OpenLayers.Control.Navigation()); + break; + case "MousePosition": + controlsList.push(new OpenLayers.Control.MousePosition()); + break; + case "OverviewMap": + controlsList.push(new OpenLayers.Control.OverviewMap()); + break; + case "PanZoom": + controlsList.push(new OpenLayers.Control.PanZoom()); + break; + case "PanZoomBar": + controlsList.push(new OpenLayers.Control.PanZoomBar()); + break; + case "ScaleLine": + controlsList.push(new OpenLayers.Control.ScaleLine()); + break; + case "Scale": + controlsList.push(new OpenLayers.Control.Scale()); + break; + case "layerSwitcher": + controlsList.push(new OpenLayers.Control.LayerSwitcher()); + break; + } + } + } + + var option = { + controls: controlsList, + projection: new OpenLayers.Projection("EPSG:900913"), + displayProjection: new OpenLayers.Projection("EPSG:4326"), + units: "m", + numZoomLevels: 18, + maxResolution: 156543.0339, + maxExtent: new OpenLayers.Bounds( + -20037508, + -20037508, + 20037508, + 20037508.34 + ) + }; + + map = new OpenLayers.Map(id_div, option); + map.events.Event; + var baseLayer = null; + + map.events.on({ zoomend: EventZoomEnd }); + map.events.on({ mouseup: EventZoomEnd }); + + //Define the maps layer + for (var baselayerIndex in objBaseLayers) { + if (isInt(baselayerIndex)) { + switch (objBaseLayers[baselayerIndex]["type"]) { + case "OSM": + baseLayer = null; + baseLayer = new OpenLayers.Layer.OSM( + objBaseLayers[baselayerIndex]["name"], + objBaseLayers[baselayerIndex]["url"], + { + numZoomLevels: objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + case "Gmap": + switch (objBaseLayers[baselayerIndex]["gmap_type"]) { + case "G_PHYSICAL_MAP": + baseLayer = new OpenLayers.Layer.Google( + objBaseLayers[baselayerIndex]["name"], + { + type: G_PHYSICAL_MAP, + numZoomLevels: + objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + case "G_HYBRID_MAP": + baseLayer = new OpenLayers.Layer.Google( + objBaseLayers[baselayerIndex]["name"], + { + type: G_HYBRID_MAP, + numZoomLevels: + objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + case "G_SATELLITE_MAP": + baseLayer = new OpenLayers.Layer.Google( + objBaseLayers[baselayerIndex]["name"], + { + type: G_SATELLITE_MAP, + numZoomLevels: + objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + default: + baseLayer = new OpenLayers.Layer.Google( + objBaseLayers[baselayerIndex]["name"], + { + numZoomLevels: + objBaseLayers[baselayerIndex]["num_zoom_levels"], + sphericalMercator: true + } + ); + map.addLayer(baseLayer); + break; + } + break; + case "Static_Image": + baseLayer = null; + baseLayer = new OpenLayers.Layer.Image( + objBaseLayers[baselayerIndex]["name"], + objBaseLayers[baselayerIndex]["url"], + new OpenLayers.Bounds( + objBaseLayers[baselayerIndex]["bb_left"], + objBaseLayers[baselayerIndex]["bb_bottom"], + objBaseLayers[baselayerIndex]["bb_right"], + objBaseLayers[baselayerIndex]["bb_top"] + ), + new OpenLayers.Size( + objBaseLayers[baselayerIndex]["image_width"], + objBaseLayers[baselayerIndex]["image_height"] + ), + { + projection: new OpenLayers.Projection("EPSG:4326"), + numZoomLevels: objBaseLayers[baselayerIndex]["num_zoom_levels"] + } + ); + map.addLayer(baseLayer); + break; + case "WMS": + // http:///geoserver/wms + // ?bbox=-130,24,-66,50 + // &styles=population + // &Format=application/openlayers + // &request=GetMap + // &layers=topp:states + // &width=550 + // &height=250 + // &srs=EPSG:4326 + var layer = new OpenLayers.Layer.WMS( + objBaseLayers[baselayerIndex]["name"], + objBaseLayers[baselayerIndex]["url"], + { + layers: objBaseLayers[baselayerIndex]["layers"], + format: "image/png" + }, + { + numZoomLevels: objBaseLayers[baselayerIndex]["num_zoom_levels"] + } + ); + map.addLayer(layer); + break; + } + } + } + + var lonLat = new OpenLayers.LonLat( + center_longitude, + center_latitude + ).transform(map.displayProjection, map.getProjectionObject()); + + map.setCenter(lonLat, initial_zoom); } -function EventZoomEnd (evt,zoom = map.zoom) { - if(evt == null){ - var actual_zoom = (zoom < 6) ? 6 : zoom; - } - else{ - var actual_zoom = (evt.object.zoom < 6) ? 6 : evt.object.zoom; - } - - - var max_width_marker = 38; - var max_zoom_map = map.numZoomLevels; - var max_font_size = 15; - - var actual_font_size = (actual_zoom * max_font_size) / max_zoom_map; - - jQuery.each($("tspan"), function (i, tspan) { - if (actual_zoom <= 18 && actual_zoom > 13) - actual_font_size = (max_font_size - 3); - else if (actual_zoom <= 13 && actual_zoom >= 8) - actual_font_size = (max_font_size - 6); - else if (actual_zoom <= 8) - actual_font_size = (max_font_size - 6); - $(tspan).css('font-size', actual_font_size); - }); - - var layers = map.getLayersByClass("OpenLayers.Layer.Vector"); - - - jQuery.each(layers, function (i, layer) { - var features = layer.features; - - jQuery.each(features, function (j, feature) { - var graphicHeight = feature.style.graphicHeight || -1; - var graphicWidth = feature.style.graphicWidth || -1; - - if (graphicHeight > 0 && graphicWidth > 0) { - var new_width_marker = (actual_zoom * max_width_marker) / max_zoom_map; - var new_height_marker = (actual_zoom * max_width_marker) / max_zoom_map; - - feature.style.fontSize = '' + actual_font_size + ' !important'; - feature.style.graphicHeight = new_height_marker; - feature.style.graphicWidth = new_width_marker; - feature.style.labelYOffset = (new_width_marker * -1); - } - - }); - layer.redraw(); - }); +function EventZoomEnd(evt, zoom = map.zoom) { + if (evt == null) { + var actual_zoom = zoom < 6 ? 6 : zoom; + } else { + var actual_zoom = evt.object.zoom < 6 ? 6 : evt.object.zoom; + } + + var max_width_marker = 38; + var max_zoom_map = map.numZoomLevels; + var max_font_size = 15; + + var actual_font_size = (actual_zoom * max_font_size) / max_zoom_map; + + jQuery.each($("tspan"), function(i, tspan) { + if (actual_zoom <= 18 && actual_zoom > 13) + actual_font_size = max_font_size - 3; + else if (actual_zoom <= 13 && actual_zoom >= 8) + actual_font_size = max_font_size - 6; + else if (actual_zoom <= 8) actual_font_size = max_font_size - 6; + $(tspan).css("font-size", actual_font_size); + }); + + var layers = map.getLayersByClass("OpenLayers.Layer.Vector"); + + jQuery.each(layers, function(i, layer) { + var features = layer.features; + + jQuery.each(features, function(j, feature) { + var graphicHeight = feature.style.graphicHeight || -1; + var graphicWidth = feature.style.graphicWidth || -1; + + if (graphicHeight > 0 && graphicWidth > 0) { + var new_width_marker = (actual_zoom * max_width_marker) / max_zoom_map; + var new_height_marker = (actual_zoom * max_width_marker) / max_zoom_map; + + feature.style.fontSize = "" + actual_font_size + " !important"; + feature.style.graphicHeight = new_height_marker; + feature.style.graphicWidth = new_width_marker; + feature.style.labelYOffset = new_width_marker * -1; + } + }); + layer.redraw(); + }); } /** * Change the style of state button, and call the function "hideAgentsStatus" * whith new state for agents icons to show. - * + * * @param string newShowStatus State to show. * @return none */ function changeShowStatus(newShowStatus) { - statusShow = newShowStatus; - hideAgentsStatus(); - EventZoomEnd(null,map.zoom); - js_refreshParentLines(); + statusShow = newShowStatus; + hideAgentsStatus(); + EventZoomEnd(null, map.zoom); + js_refreshParentLines(); } /** * Function that change the visibility of feature by status and state var * statusShow - * + * * @param object feature The feature to change the visibility * @param int status The status code, it can be (1,4) for bad, (2) for warning, (0) for ok and the rest * @return */ function hideFeatureByStatus(feature, status) { - feature.style.display = 'none'; - - switch (statusShow) { - case 'bad': - if ((status == 1) || (status == 4) || (status == 100)) - feature.style.display = ''; - break; - case 'warning': - if ((status == 2) || (status == 200)) - feature.style.display = ''; - break; - case 'ok': - if ((status == 0) || (status == 300)) - feature.style.display = ''; - break; - case 'default': - if ((status != 1) && (status != 4) && (status != 2) && (status != 0) && (status != 100) && (status != 200) && (status != 300)) - feature.style.display = ''; - break; - case 'all': - feature.style.display = ''; - break; - } + feature.style.display = "none"; + + switch (statusShow) { + case "bad": + if (status == 1 || status == 4 || status == 100) + feature.style.display = ""; + break; + case "warning": + if (status == 2 || status == 200) feature.style.display = ""; + break; + case "ok": + if (status == 0 || status == 300) feature.style.display = ""; + break; + case "default": + if ( + status != 1 && + status != 4 && + status != 2 && + status != 0 && + status != 100 && + status != 200 && + status != 300 + ) + feature.style.display = ""; + break; + case "all": + feature.style.display = ""; + break; + } } /** * Test if the feature is hidden. - * - * @param integer status The integer status. + * + * @param integer status The integer status. * @return boolean The true or false. */ function isHideFeatureByStatus(status) { - returnVar = true; - - switch (statusShow) { - case 'bad': - if ((status == 1) || (status == 4) || (status == 100)) - returnVar = false; - break; - case 'warning': - if ((status == 2) || (status == 200)) - returnVar = false; - break; - case 'ok': - if ((status == 0) || (status == 300)) - returnVar = false; - break; - case 'default': - if ((status != 1) && (status != 4) && (status != 2) && (status != 0) && (status != 100) && (status != 200) && (status != 300)) - returnVar = false; - break; - case 'all': - returnVar = false; - break; - } - - return returnVar; + returnVar = true; + + switch (statusShow) { + case "bad": + if (status == 1 || status == 4 || status == 100) returnVar = false; + break; + case "warning": + if (status == 2 || status == 200) returnVar = false; + break; + case "ok": + if (status == 0 || status == 300) returnVar = false; + break; + case "default": + if ( + status != 1 && + status != 4 && + status != 2 && + status != 0 && + status != 100 && + status != 200 && + status != 300 + ) + returnVar = false; + break; + case "all": + returnVar = false; + break; + } + + return returnVar; } /** * Hide the agents icons that not is of current state var statusShow. - * + * * @return none */ function hideAgentsStatus() { - layers = map.getLayersByClass("OpenLayers.Layer.Vector"); - - jQuery.each(layers, function (i, layer) { - features = layer.features; - - jQuery.each(features, function (j, feature) { - status = feature.data.status; - - hideFeatureByStatus(feature, status); - }); - - layer.redraw(); - }); + layers = map.getLayersByClass("OpenLayers.Layer.Vector"); + + jQuery.each(layers, function(i, layer) { + features = layer.features; + + jQuery.each(features, function(j, feature) { + status = feature.data.status; + + hideFeatureByStatus(feature, status); + }); + + layer.redraw(); + }); } /** * Change the refresh time for the map. - * + * * @param int time seconds * @return none */ function changeRefreshTime(time) { - refreshAjaxIntervalSeconds = time * 1000; - - clearInterval(idIntervalAjax); - idIntervalAjax = setInterval("clock_ajax_refresh()", refreshAjaxIntervalSeconds); - oldRefreshAjaxIntervalSeconds = refreshAjaxIntervalSeconds; + refreshAjaxIntervalSeconds = time * 1000; + + clearInterval(idIntervalAjax); + idIntervalAjax = setInterval( + "clock_ajax_refresh()", + refreshAjaxIntervalSeconds + ); + oldRefreshAjaxIntervalSeconds = refreshAjaxIntervalSeconds; } /** * Make the layer in the map. - * + * * @param string name The name of layer, it's show in the toolbar of layer. * @param boolean visible Set visible the layer. - * @param array dot It's a asociative array that have 'url' of icon image, 'width' in pixeles and 'height' in pixeles. - * + * @param array dot It's a asociative array that have 'url' of icon image, 'width' in pixeles and 'height' in pixeles. + * * @return object The layer created. */ function js_makeLayer(name, visible, dot) { - if (dot == null) { - dot = Array(); - dot['url'] = 'images/dot_green.png'; - dot['width'] = 20; //11; - dot['height'] = 20; //11; - } - - //Set the style in layer - var style = new OpenLayers.StyleMap( - {fontColor: "#ff0000", - labelYOffset: - dot['height'], - graphicHeight: dot['height'], - graphicWidth: dot['width'], - externalGraphic: dot['url'], - label:"${nombre}" - } - ); - - //Make the layer as type vector - var layer = new OpenLayers.Layer.Vector(name, {styleMap: style}); - - layer.setVisibility(visible); - map.addLayer(layer); - - return layer; + if (dot == null) { + dot = Array(); + dot["url"] = "images/dot_green.png"; + dot["width"] = 20; //11; + dot["height"] = 20; //11; + } + + //Set the style in layer + var style = new OpenLayers.StyleMap({ + fontColor: "#ff0000", + labelYOffset: -dot["height"], + graphicHeight: dot["height"], + graphicWidth: dot["width"], + externalGraphic: dot["url"], + label: "${nombre}" + }); + + //Make the layer as type vector + var layer = new OpenLayers.Layer.Vector(name, { styleMap: style }); + + layer.setVisibility(visible); + map.addLayer(layer); + + return layer; } /** * Active and set callbacks of events. - * - * @param callbackFunClick Function to call when the user make single click in the map. - * + * + * @param callbackFunClick Function to call when the user make single click in the map. + * * @return None */ function js_activateEvents(callbackFunClick) { - /** - * Pandora click openlayers object. - */ - OpenLayers.Control.PandoraClick = OpenLayers.Class(OpenLayers.Control, { - defaultHandlerOptions: { - 'single': true, - 'double': false, - 'pixelTolerance': 0, - 'stopSingle': false, - 'stopDouble': false - }, - initialize: function(options) { - this.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions); - OpenLayers.Control.prototype.initialize.apply(this, arguments); - this.handler = new OpenLayers.Handler.Click(this, {'click': options.callbackFunctionClick}, this.handlerOptions); - } - }); - - var click = new OpenLayers.Control.PandoraClick({callbackFunctionClick: callbackFunClick}); - - map.addControl(click); - click.activate(); + /** + * Pandora click openlayers object. + */ + OpenLayers.Control.PandoraClick = OpenLayers.Class(OpenLayers.Control, { + defaultHandlerOptions: { + single: true, + double: false, + pixelTolerance: 0, + stopSingle: false, + stopDouble: false + }, + initialize: function(options) { + this.handlerOptions = OpenLayers.Util.extend( + {}, + this.defaultHandlerOptions + ); + OpenLayers.Control.prototype.initialize.apply(this, arguments); + this.handler = new OpenLayers.Handler.Click( + this, + { click: options.callbackFunctionClick }, + this.handlerOptions + ); + } + }); + + var click = new OpenLayers.Control.PandoraClick({ + callbackFunctionClick: callbackFunClick + }); + + map.addControl(click); + click.activate(); } /** * Test the value is a int. - * + * * @param mixed X The val that test to if is int. - * + * * @return Boolean True if it's int. */ function isInt(x) { - var y=parseInt(x); - if (isNaN(y)) return false; - return x==y && x.toString()==y.toString(); + var y = parseInt(x); + if (isNaN(y)) return false; + return x == y && x.toString() == y.toString(); } /** * Set the visibility of a layer - * + * * @param string name The name of layer. * @param boolean action True or false */ function showHideLayer(name, action) { - var layer = map.getLayersByName(name); + var layer = map.getLayersByName(name); - layer[0].setVisibility(action); + layer[0].setVisibility(action); } /** * Add a point with the default icon in the map. - * + * * @param string layerName The name of layer to put the point. * @param string pointName The name to show in the point. * @param float lon The coord of latitude for point. @@ -523,38 +585,51 @@ function showHideLayer(name, action) { * @param string type_string The type of point, it's use for ajax request. * @param integer statusAgent The status of point. * @param integer idParent Id Parent of agent. - * + * * @return Object The point. */ -function js_addAgentPoint(layerName, pointName, lon, lat, id, type_string, statusAgent, idParent) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); - - var layer = map.getLayersByName(layerName); - layer = layer[0]; - - feature = new OpenLayers.Feature.Vector(point, - { - id_parent: idParent, - status: statusAgent, - nombre: pointName, - id: id, - type: type_string, - long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject()) - }); +function js_addAgentPoint( + layerName, + pointName, + lon, + lat, + id, + type_string, + statusAgent, + idParent +) { + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); - if (isHideFeatureByStatus(statusAgent)) { - feature.style.display = 'none'; - } - - layer.addFeatures(feature); - - return feature; + var layer = map.getLayersByName(layerName); + layer = layer[0]; + + feature = new OpenLayers.Feature.Vector(point, { + id_parent: idParent, + status: statusAgent, + nombre: pointName, + id: id, + type: type_string, + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }); + + if (isHideFeatureByStatus(statusAgent)) { + feature.style.display = "none"; + } + + layer.addFeatures(feature); + + return feature; } /** * Add a point with the default icon in the map. - * + * * @param string layerName The name of layer to put the point. * @param string pointName The name to show in the point. * @param float lon The coord of latitude for point. @@ -562,207 +637,307 @@ function js_addAgentPoint(layerName, pointName, lon, lat, id, type_string, statu * @param string id The id of point. * @param string type_string The type of point, it's use for ajax request. * @param integer statusAgent The status of point. - * + * * @return Object The point. */ -function js_addPoint(layerName, pointName, lon, lat, id, type_string, statusAgent) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); +function js_addPoint( + layerName, + pointName, + lon, + lat, + id, + type_string, + statusAgent +) { + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); - var layer = map.getLayersByName(layerName); - layer = layer[0]; + var layer = map.getLayersByName(layerName); + layer = layer[0]; - feature = new OpenLayers.Feature.Vector(point,{status: statusAgent, nombre: pointName, id: id, type: type_string, long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject()) }); - - if (isHideFeatureByStatus(statusAgent)) { - feature.style.display = 'none'; - } - - layer.addFeatures(feature); - - return feature; + feature = new OpenLayers.Feature.Vector(point, { + status: statusAgent, + nombre: pointName, + id: id, + type: type_string, + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }); + + if (isHideFeatureByStatus(statusAgent)) { + feature.style.display = "none"; + } + + layer.addFeatures(feature); + + return feature; } /** * Add a agent point and set the icon in the map. - * + * * @param string layerName The name of layer to put the point. * @param string pointName The name to show in the point. * @param float lon The coord of latitude for point. * @param float lat The coord of longitude for point. - * @param string icon Url of icon image. + * @param string icon Url of icon image. * @param integer width The width of icon. * @param integer height The height of icon. * @param string id The id of point. * @param string type_string The type of point, it's use for ajax request. * @param integer statusAgent The status of point. * @param integer idParent Id Parent of agent. - * + * * @return Object The point. */ -function js_addAgentPointExtent(layerName, pointName, lon, lat, icon, width, height, id, type_string, statusAgent, idParent) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); - - var layer = map.getLayersByName(layerName); - layer = layer[0]; - - if (typeof(statusAgent) == 'string') - statusA = parseInt(statusAgent); - else - statusA = statusAgent; - - feature = new OpenLayers.Feature.Vector(point, - { - id_parent: idParent.toString(), - status: statusA, - id: id.toString(), - type: type_string, - long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject()) - }, - { - fontWeight: "bolder", - fontColor: "#00014F", - labelYOffset: -height, - graphicHeight: width, - graphicWidth: height, - externalGraphic: icon, - label: pointName - }); - - if (isHideFeatureByStatus(statusAgent)) { - feature.style.display = 'none'; - } - - layer.addFeatures(feature); - - return feature; +function js_addAgentPointExtent( + layerName, + pointName, + lon, + lat, + icon, + width, + height, + id, + type_string, + statusAgent, + idParent +) { + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); + + var layer = map.getLayersByName(layerName); + layer = layer[0]; + + if (typeof statusAgent == "string") statusA = parseInt(statusAgent); + else statusA = statusAgent; + + feature = new OpenLayers.Feature.Vector( + point, + { + id_parent: idParent.toString(), + status: statusA, + id: id.toString(), + type: type_string, + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }, + { + fontWeight: "bolder", + fontColor: "#00014F", + labelYOffset: -height, + graphicHeight: width, + graphicWidth: height, + externalGraphic: icon, + label: pointName + } + ); + + if (isHideFeatureByStatus(statusAgent)) { + feature.style.display = "none"; + } + + layer.addFeatures(feature); + + return feature; } /** * Add a point and set the icon in the map. - * + * * @param string layerName The name of layer to put the point. * @param string pointName The name to show in the point. * @param float lon The coord of latitude for point. * @param float lat The coord of longitude for point. - * @param string icon Url of icon image. + * @param string icon Url of icon image. * @param integer width The width of icon. * @param integer height The height of icon. * @param string id The id of point. * @param string type_string The type of point, it's use for ajax request. * @param integer statusAgent The status of point. - * + * * @return Object The point. */ -function js_addPointExtent(layerName, pointName, lon, lat, icon, width, height, id, type_string, statusAgent) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); +function js_addPointExtent( + layerName, + pointName, + lon, + lat, + icon, + width, + height, + id, + type_string, + statusAgent +) { + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); - var layer = map.getLayersByName(layerName); - layer = layer[0]; - - if (typeof(statusAgent) == 'string') - statusA = parseInt(statusAgent); - else - statusA = statusAgent; - - feature = new OpenLayers.Feature.Vector(point,{status: statusA, id: id, type: type_string, long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject()) }, {fontWeight: "bolder", fontColor: "#00014F", labelYOffset: -height, graphicHeight: width, graphicWidth: height, externalGraphic: icon, label: pointName}); - - if (isHideFeatureByStatus(statusAgent)) { - feature.style.display = 'none'; - } - - layer.addFeatures(feature); - - return feature; + var layer = map.getLayersByName(layerName); + layer = layer[0]; + + if (typeof statusAgent == "string") statusA = parseInt(statusAgent); + else statusA = statusAgent; + + feature = new OpenLayers.Feature.Vector( + point, + { + status: statusA, + id: id, + type: type_string, + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }, + { + fontWeight: "bolder", + fontColor: "#00014F", + labelYOffset: -height, + graphicHeight: width, + graphicWidth: height, + externalGraphic: icon, + label: pointName + } + ); + + if (isHideFeatureByStatus(statusAgent)) { + feature.style.display = "none"; + } + + layer.addFeatures(feature); + + return feature; } /** - * + * * @param string layerName The name of layer to put the point path. * @param float lon The coord of latitude for point path. * @param float lat The coord of longitude for point path. * @param string color The color of point path in rrggbb format. * @param boolean manual The type of point path, if it's manual, the point is same a donut. * @param string id The id of point path. - * + * * @return None */ function js_addPointPath(layerName, lon, lat, color, manual, id) { - var point = new OpenLayers.Geometry.Point(lon, lat) - .transform(map.displayProjection, map.getProjectionObject()); - - var layer = map.getLayersByName(layerName); - layer = layer[0]; + var point = new OpenLayers.Geometry.Point(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ); - var pointRadiusNormal = 4; - var strokeWidth = 2; - var pointRadiusManual = pointRadiusNormal - (strokeWidth / 2); - - if (manual) { - point = new OpenLayers.Feature.Vector(point,{estado: "ok", id: id, type: "point_path_info", - long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject())}, - {fillColor: "#ffffff", pointRadius: pointRadiusManual, stroke: 1, strokeColor: color, strokeWidth: strokeWidth, cursor: "pointer"} - ); - } - else { - point = new OpenLayers.Feature.Vector(point,{estado: "ok", id: id, type: "point_path_info", - long_lat: new OpenLayers.LonLat(lon, lat).transform(map.displayProjection, map.getProjectionObject())}, - {fillColor: color, pointRadius: pointRadiusNormal, cursor: "pointer"} - ); - } + var layer = map.getLayersByName(layerName); + layer = layer[0]; - layer.addFeatures(point); + var pointRadiusNormal = 4; + var strokeWidth = 2; + var pointRadiusManual = pointRadiusNormal - strokeWidth / 2; + + if (manual) { + point = new OpenLayers.Feature.Vector( + point, + { + estado: "ok", + id: id, + type: "point_path_info", + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }, + { + fillColor: "#ffffff", + pointRadius: pointRadiusManual, + stroke: 1, + strokeColor: color, + strokeWidth: strokeWidth, + cursor: "pointer" + } + ); + } else { + point = new OpenLayers.Feature.Vector( + point, + { + estado: "ok", + id: id, + type: "point_path_info", + long_lat: new OpenLayers.LonLat(lon, lat).transform( + map.displayProjection, + map.getProjectionObject() + ) + }, + { fillColor: color, pointRadius: pointRadiusNormal, cursor: "pointer" } + ); + } + + layer.addFeatures(point); } /** * Draw the lineString. - * + * * @param string layerName The name of layer to put the point path. * @param Array points The array have content the points, but the point as lonlat openlayers object without transformation. * @param string color The color of point path in rrggbb format. - * + * * @return None */ function js_addLineString(layerName, points, color) { - var mapPoints = new Array(points.length); - var layer = map.getLayersByName(layerName); + var mapPoints = new Array(points.length); + var layer = map.getLayersByName(layerName); - layer = layer[0]; - - for (var i = 0; i < points.length; i++) { - mapPoints[i] = points[i].transform(map.displayProjection, map.getProjectionObject()); - } - - var lineString = new OpenLayers.Feature.Vector( - new OpenLayers.Geometry.LineString(mapPoints), - null, - { strokeWidth: 2, fillOpacity: 0.2, fillColor: color, strokeColor: color} - ); + layer = layer[0]; - layer.addFeatures(lineString); + for (var i = 0; i < points.length; i++) { + mapPoints[i] = points[i].transform( + map.displayProjection, + map.getProjectionObject() + ); + } + + var lineString = new OpenLayers.Feature.Vector( + new OpenLayers.Geometry.LineString(mapPoints), + null, + { strokeWidth: 2, fillOpacity: 0.2, fillColor: color, strokeColor: color } + ); + + layer.addFeatures(lineString); } /** * Return feature object for a id agent passed. - * + * * @param interger id The agent id. * @return mixed Return the feature object, if it didn't found then return null. */ function searchPointAgentById(id) { - for (layerIndex = 0; layerIndex < map.getNumLayers(); layerIndex++) { - layer = map.layers[layerIndex]; + for (layerIndex = 0; layerIndex < map.getNumLayers(); layerIndex++) { + layer = map.layers[layerIndex]; - if (layer.features != undefined) { - for (featureIndex = 0; featureIndex < layer.features.length; featureIndex++) { - feature = layer.features[featureIndex]; - if (feature.data.id == id) { - return feature; - } - } - } - } + if (layer.features != undefined) { + for ( + featureIndex = 0; + featureIndex < layer.features.length; + featureIndex++ + ) { + feature = layer.features[featureIndex]; + if (feature.data.id == id) { + return feature; + } + } + } + } - return null; + return null; } diff --git a/pandora_console/include/javascript/pandora.base64.js b/pandora_console/include/javascript/pandora.base64.js index 174872b0e6..53c6e996ae 100644 --- a/pandora_console/include/javascript/pandora.base64.js +++ b/pandora_console/include/javascript/pandora.base64.js @@ -2,8 +2,7 @@ // Exports the strToBase64 and base64ToStr functions -(function () { - +(function() { "use strict"; /*\ @@ -16,38 +15,40 @@ /* Array of bytes to base64 string decoding */ - function b64ToUint6 (nChr) { - - return nChr > 64 && nChr < 91 ? - nChr - 65 - : nChr > 96 && nChr < 123 ? - nChr - 71 - : nChr > 47 && nChr < 58 ? - nChr + 4 - : nChr === 43 ? - 62 - : nChr === 47 ? - 63 - : - 0; - + function b64ToUint6(nChr) { + return nChr > 64 && nChr < 91 + ? nChr - 65 + : nChr > 96 && nChr < 123 + ? nChr - 71 + : nChr > 47 && nChr < 58 + ? nChr + 4 + : nChr === 43 + ? 62 + : nChr === 47 + ? 63 + : 0; } - function base64DecToArr (sBase64, nBlocksSize) { + function base64DecToArr(sBase64, nBlocksSize) { + var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), + nInLen = sB64Enc.length, + nOutLen = nBlocksSize + ? Math.ceil(((nInLen * 3 + 1) >> 2) / nBlocksSize) * nBlocksSize + : (nInLen * 3 + 1) >> 2, + taBytes = new Uint8Array(nOutLen); - var - sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length, - nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen); - - for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) { + for ( + var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; + nInIdx < nInLen; + nInIdx++ + ) { nMod4 = nInIdx & 3; - nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4; + nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << (18 - 6 * nMod4); if (nMod4 === 3 || nInLen - nInIdx === 1) { for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) { - taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255; + taBytes[nOutIdx] = (nUint24 >>> ((16 >>> nMod3) & 24)) & 255; } nUint24 = 0; - } } @@ -56,79 +57,114 @@ /* Base64 string to array encoding */ - function uint6ToB64 (nUint6) { - - return nUint6 < 26 ? - nUint6 + 65 - : nUint6 < 52 ? - nUint6 + 71 - : nUint6 < 62 ? - nUint6 - 4 - : nUint6 === 62 ? - 43 - : nUint6 === 63 ? - 47 - : - 65; - + function uint6ToB64(nUint6) { + return nUint6 < 26 + ? nUint6 + 65 + : nUint6 < 52 + ? nUint6 + 71 + : nUint6 < 62 + ? nUint6 - 4 + : nUint6 === 62 + ? 43 + : nUint6 === 63 + ? 47 + : 65; } - function base64EncArr (aBytes) { - - var nMod3 = 2, sB64Enc = ""; + function base64EncArr(aBytes) { + var nMod3 = 2, + sB64Enc = ""; for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { nMod3 = nIdx % 3; - if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; } - nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); + if (nIdx > 0 && ((nIdx * 4) / 3) % 76 === 0) { + sB64Enc += "\r\n"; + } + nUint24 |= aBytes[nIdx] << ((16 >>> nMod3) & 24); if (nMod3 === 2 || aBytes.length - nIdx === 1) { - sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63)); + sB64Enc += String.fromCharCode( + uint6ToB64((nUint24 >>> 18) & 63), + uint6ToB64((nUint24 >>> 12) & 63), + uint6ToB64((nUint24 >>> 6) & 63), + uint6ToB64(nUint24 & 63) + ); nUint24 = 0; } } - return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '=='); - + return ( + sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + + (nMod3 === 2 ? "" : nMod3 === 1 ? "=" : "==") + ); } /* UTF-8 array to DOMString and vice versa */ - function UTF8ArrToStr (aBytes) { - + function UTF8ArrToStr(aBytes) { var sView = ""; for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) { nPart = aBytes[nIdx]; sView += String.fromCharCode( - nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */ - /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */ - (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 - : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */ - (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 - : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */ - (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 - : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */ - (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 - : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */ - (nPart - 192 << 6) + aBytes[++nIdx] - 128 - : /* nPart < 127 ? */ /* one byte */ - nPart + nPart > 251 && nPart < 254 && nIdx + 5 < nLen /* six bytes */ + ? /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */ + (nPart - 252) * 1073741824 + + ((aBytes[++nIdx] - 128) << 24) + + ((aBytes[++nIdx] - 128) << 18) + + ((aBytes[++nIdx] - 128) << 12) + + ((aBytes[++nIdx] - 128) << 6) + + aBytes[++nIdx] - + 128 + : nPart > 247 && nPart < 252 && nIdx + 4 < nLen /* five bytes */ + ? ((nPart - 248) << 24) + + ((aBytes[++nIdx] - 128) << 18) + + ((aBytes[++nIdx] - 128) << 12) + + ((aBytes[++nIdx] - 128) << 6) + + aBytes[++nIdx] - + 128 + : nPart > 239 && nPart < 248 && nIdx + 3 < nLen /* four bytes */ + ? ((nPart - 240) << 18) + + ((aBytes[++nIdx] - 128) << 12) + + ((aBytes[++nIdx] - 128) << 6) + + aBytes[++nIdx] - + 128 + : nPart > 223 && nPart < 240 && nIdx + 2 < nLen /* three bytes */ + ? ((nPart - 224) << 12) + + ((aBytes[++nIdx] - 128) << 6) + + aBytes[++nIdx] - + 128 + : nPart > 191 && nPart < 224 && nIdx + 1 < nLen /* two bytes */ + ? ((nPart - 192) << 6) + aBytes[++nIdx] - 128 /* nPart < 127 ? */ + : /* one byte */ + nPart ); } return sView; - } - function strToUTF8Arr (sDOMStr) { - - var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0; + function strToUTF8Arr(sDOMStr) { + var aBytes, + nChr, + nStrLen = sDOMStr.length, + nArrLen = 0; /* mapping... */ for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) { nChr = sDOMStr.charCodeAt(nMapIdx); - nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6; + nArrLen += + nChr < 0x80 + ? 1 + : nChr < 0x800 + ? 2 + : nChr < 0x10000 + ? 3 + : nChr < 0x200000 + ? 4 + : nChr < 0x4000000 + ? 5 + : 6; } aBytes = new Uint8Array(nArrLen); @@ -147,55 +183,52 @@ } else if (nChr < 0x10000) { /* three bytes */ aBytes[nIdx++] = 224 + (nChr >>> 12); - aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 6) & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x200000) { /* four bytes */ aBytes[nIdx++] = 240 + (nChr >>> 18); - aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 12) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 6) & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x4000000) { /* five bytes */ aBytes[nIdx++] = 248 + (nChr >>> 24); - aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 18) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 12) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 6) & 63); aBytes[nIdx++] = 128 + (nChr & 63); - } else /* if (nChr <= 0x7fffffff) */ { + } /* if (nChr <= 0x7fffffff) */ else { /* six bytes */ aBytes[nIdx++] = 252 + (nChr >>> 30); - aBytes[nIdx++] = 128 + (nChr >>> 24 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); - aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 24) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 18) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 12) & 63); + aBytes[nIdx++] = 128 + ((nChr >>> 6) & 63); aBytes[nIdx++] = 128 + (nChr & 63); } } return aBytes; - } - function strToBase64 (strInput) { - if (typeof strInput !== 'string') - throw new TypeError('The input should be a string') + function strToBase64(strInput) { + if (typeof strInput !== "string") + throw new TypeError("The input should be a string"); - return base64EncArr(strToUTF8Arr(strInput)) + return base64EncArr(strToUTF8Arr(strInput)); } - function base64ToStr (base64Input) { - if (typeof base64Input !== 'string') - throw new TypeError('The input should be a string') + function base64ToStr(base64Input) { + if (typeof base64Input !== "string") + throw new TypeError("The input should be a string"); - return UTF8ArrToStr(base64DecToArr(base64Input)) + return UTF8ArrToStr(base64DecToArr(base64Input)); } // Export the functions to the global scope if (window) { - if (!window.strToBase64) - window.strToBase64 = strToBase64 - if (!window.base64ToStr) - window.base64ToStr = base64ToStr + if (!window.strToBase64) window.strToBase64 = strToBase64; + if (!window.base64ToStr) window.base64ToStr = base64ToStr; } -}) () +})(); diff --git a/pandora_console/include/javascript/pandora.js b/pandora_console/include/javascript/pandora.js index 2b323a55f1..37a9987812 100644 --- a/pandora_console/include/javascript/pandora.js +++ b/pandora_console/include/javascript/pandora.js @@ -1,29 +1,44 @@ -var ENTERPRISE_DIR = 'enterprise'; +var ENTERPRISE_DIR = "enterprise"; /* Function to hide/unhide a specific Div id */ -function toggleDiv (divid){ - if (document.getElementById(divid).style.display == 'none') { - document.getElementById(divid).style.display = 'block'; - } - else { - document.getElementById(divid).style.display = 'none'; - } +function toggleDiv(divid) { + if (document.getElementById(divid).style.display == "none") { + document.getElementById(divid).style.display = "block"; + } else { + document.getElementById(divid).style.display = "none"; + } } -function winopeng (url, wid) { - open (url, wid,"width=1000,height=550,status=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes"); - // WARNING !! Internet Explorer DOESNT SUPPORT "-" CARACTERS IN WINDOW HANDLE VARIABLE - status = wid; +function winopeng(url, wid) { + open( + url, + wid, + "width=1000,height=550,status=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes" + ); + // WARNING !! Internet Explorer DOESNT SUPPORT "-" CARACTERS IN WINDOW HANDLE VARIABLE + status = wid; } -function winopeng_var (url, wid, width, height) { - open (url, wid,"width="+width+",height="+height+",status=no,toolbar=no,menubar=no,scrollbar=yes"); - // WARNING !! Internet Explorer DOESNT SUPPORT "-" CARACTERS IN WINDOW HANDLE VARIABLE - status = wid; +function winopeng_var(url, wid, width, height) { + open( + url, + wid, + "width=" + + width + + ",height=" + + height + + ",status=no,toolbar=no,menubar=no,scrollbar=yes" + ); + // WARNING !! Internet Explorer DOESNT SUPPORT "-" CARACTERS IN WINDOW HANDLE VARIABLE + status = wid; } -function open_help (help_id, home_url, id_user) { - open (home_url+"general/pandora_help.php?id="+help_id+"&id_user="+id_user, "pandorahelp", "width=650,height=500,status=0,toolbar=0,menubar=0,scrollbars=1,location=0"); +function open_help(help_id, home_url, id_user) { + open( + home_url + "general/pandora_help.php?id=" + help_id + "&id_user=" + id_user, + "pandorahelp", + "width=650,height=500,status=0,toolbar=0,menubar=0,scrollbars=1,location=0" + ); } /** @@ -33,18 +48,23 @@ function open_help (help_id, home_url, id_user) { * * @retval str with entities decoded */ -function js_html_entity_decode (str) { - if (! str) - return ""; - - str2 = str.replace (//g,">").replace(/</g,'<') - .replace(/>/g,'>').replace(/\/g,'\\') - .replace(/"/g,'\"').replace(/'/g,'\'') - .replace(/&/g,'&').replace(/ /g,' ') - .replace(/ /g, '\r').replace(/ /g, '\n'); - - return str2; +function js_html_entity_decode(str) { + if (!str) return ""; + + str2 = str + .replace(//g, ">") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/\/g, "\\") + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, "&") + .replace(/ /g, " ") + .replace(/ /g, "\r") + .replace(/ /g, "\n"); + + return str2; } /** @@ -56,30 +76,27 @@ function js_html_entity_decode (str) { alert (a.in_array (4)); // true alert (a.in_array (5)); // false */ -Array.prototype.in_array = function () { - for (var j in this) { - if (this[j] == arguments[0]) - return true; - } - - return false; +Array.prototype.in_array = function() { + for (var j in this) { + if (this[j] == arguments[0]) return true; + } + + return false; }; /** * Util for check is empty object - * + * * @param obj the object to check * @returns {Boolean} True it is empty */ function isEmptyObject(obj) { - for(var prop in obj) { - if(obj.hasOwnProperty(prop)) - return false; - } - - return true; -} + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) return false; + } + return true; +} /** * Fill up select box with id "module" with modules after agent has been selected, but this not empty the select box.s @@ -88,177 +105,179 @@ function isEmptyObject(obj) { * @param id_agent Agent ID that has been selected * @param selected Which module(s) have to be selected */ -function agent_changed_by_multiple_agents (event, id_agent, selected) { - // Hack to avoid certain module types - var module_types_excluded = []; - if (typeof $("input.module_types_excluded") !== 'undefined') { - try { - $("input.module_types_excluded").each(function(index, el) { - var module_type = parseInt($(el).val()); - - if (module_type !== NaN) - module_types_excluded.push(module_type); - }); - } - catch (error) { - - } - } - - var module_status = -1; - if (typeof $("#status_module") !== 'undefined') { - try { - module_status = $("#status_module").val(); - } - catch (error) { - } - } - - // Module name - var module_name = $("#text-module_filter").val(); - - var idAgents = Array(); - - jQuery.each ($("#id_agents option:selected"), function (i, val) { - //val() because the var is same - idAgents.push($(val).val()); - }); +function agent_changed_by_multiple_agents(event, id_agent, selected) { + // Hack to avoid certain module types + var module_types_excluded = []; + if (typeof $("input.module_types_excluded") !== "undefined") { + try { + $("input.module_types_excluded").each(function(index, el) { + var module_type = parseInt($(el).val()); - var tags_to_search = $('#tags1').val(); + if (module_type !== NaN) module_types_excluded.push(module_type); + }); + } catch (error) {} + } - //Hack to find only enabled modules - //Pass a flag as global var - find_modules = 'all'; - if (typeof show_only_enabled_modules !== 'undefined' - && show_only_enabled_modules) { - find_modules = 'enabled'; - } - - var selection_mode = $('#modules_selection_mode').val(); - if (typeof selection_mode === 'undefined') { - selection_mode = 'common'; - } - - var serialized = $('#hidden-serialized').val(); - if (typeof serialized === 'undefined') { - serialized = ''; - } - - $('#module') - .prop('disabled', true) - .empty() - .append($('') - .html("Loading...") - .attr("value", 0)); - - // Check if homedir was received like a JSON - var homedir = '.'; - var id_server = 0; - if (typeof event !== 'undefined' && typeof event.data !== 'undefined') { - - - if (event.data != null) { - if (typeof event.data !== 'undefined') { - if (typeof event.data.homedir !== 'undefined') { - homedir = event.data.homedir; - } - - if (typeof event.data.metaconsole !== 'undefined' - && event.data.metaconsole) { - id_server = $("#" + event.data.id_server).val(); - } - } - } - } - - jQuery.post (homedir + '/ajax.php', - { - "page": "operation/agentes/ver_agente", - "get_agent_modules_json_for_multiple_agents": 1, - "id_agent[]": idAgents, - "tags[]": tags_to_search, - "all": find_modules, - "module_types_excluded[]": module_types_excluded, - "name": module_name, - "selection_mode": selection_mode, - "serialized": serialized, - "id_server": id_server, - "status_module": module_status - }, - function (data) { - $('#module').empty (); - - if (isEmptyObject(data)) { - //Trick for catch the translate text. - var noneText = $("#id_agents").val() === null - ? $("#select_agent_first_text").html() - : $("#none_text").html(); - if (noneText == null) { - noneText = 'None'; - } - - $('#module') - .append ($('') - .html(noneText) - .attr ("None", "") - .prop('selected', true)); - - return; - } - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#module') - .append ($('') - .html ($(document) - .data('text_for_module')) - .attr("value", 0) - .prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#module') - .append ($('') - .html (data['any_text']) - .attr ("value", 0) - .prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#module') - .append ($('') - .html (anyText) - .attr ("value", 0) - .prop('selected', true)); - } - } - jQuery.each (data, function (i, val) { - var s = js_html_entity_decode(val); - - $('#module') - .append ($('') - .html (s) - .attr ("value", i) - .attr("title", s)); - - $('#module').fadeIn ('normal'); - }); - if (typeof selected !== 'undefined') - $('#module').attr ('value', selected); - - $('#module') - .css ("max-width", "") - .prop('disabled', false); - - if (typeof(function_hook_loaded_module_list) == 'function') { - function_hook_loaded_module_list(); - } - }, - "json"); + var module_status = -1; + if (typeof $("#status_module") !== "undefined") { + try { + module_status = $("#status_module").val(); + } catch (error) {} + } + + // Module name + var module_name = $("#text-module_filter").val(); + + var idAgents = Array(); + + jQuery.each($("#id_agents option:selected"), function(i, val) { + //val() because the var is same + idAgents.push($(val).val()); + }); + + var tags_to_search = $("#tags1").val(); + + //Hack to find only enabled modules + //Pass a flag as global var + find_modules = "all"; + if ( + typeof show_only_enabled_modules !== "undefined" && + show_only_enabled_modules + ) { + find_modules = "enabled"; + } + + var selection_mode = $("#modules_selection_mode").val(); + if (typeof selection_mode === "undefined") { + selection_mode = "common"; + } + + var serialized = $("#hidden-serialized").val(); + if (typeof serialized === "undefined") { + serialized = ""; + } + + $("#module") + .prop("disabled", true) + .empty() + .append( + $("") + .html("Loading...") + .attr("value", 0) + ); + + // Check if homedir was received like a JSON + var homedir = "."; + var id_server = 0; + if (typeof event !== "undefined" && typeof event.data !== "undefined") { + if (event.data != null) { + if (typeof event.data !== "undefined") { + if (typeof event.data.homedir !== "undefined") { + homedir = event.data.homedir; + } + + if ( + typeof event.data.metaconsole !== "undefined" && + event.data.metaconsole + ) { + id_server = $("#" + event.data.id_server).val(); + } + } + } + } + + jQuery.post( + homedir + "/ajax.php", + { + page: "operation/agentes/ver_agente", + get_agent_modules_json_for_multiple_agents: 1, + "id_agent[]": idAgents, + "tags[]": tags_to_search, + all: find_modules, + "module_types_excluded[]": module_types_excluded, + name: module_name, + selection_mode: selection_mode, + serialized: serialized, + id_server: id_server, + status_module: module_status + }, + function(data) { + $("#module").empty(); + + if (isEmptyObject(data)) { + //Trick for catch the translate text. + var noneText = + $("#id_agents").val() === null + ? $("#select_agent_first_text").html() + : $("#none_text").html(); + if (noneText == null) { + noneText = "None"; + } + + $("#module").append( + $("") + .html(noneText) + .attr("None", "") + .prop("selected", true) + ); + + return; + } + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#module").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#module").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#module").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + jQuery.each(data, function(i, val) { + var s = js_html_entity_decode(val); + + $("#module").append( + $("") + .html(s) + .attr("value", i) + .attr("title", s) + ); + + $("#module").fadeIn("normal"); + }); + if (typeof selected !== "undefined") $("#module").attr("value", selected); + + $("#module") + .css("max-width", "") + .prop("disabled", false); + + if (typeof function_hook_loaded_module_list == "function") { + function_hook_loaded_module_list(); + } + }, + "json" + ); } /** @@ -269,62 +288,88 @@ function agent_changed_by_multiple_agents (event, id_agent, selected) { * @param id_agent Agent ID that has been selected * @param selected Which module(s) have to be selected */ -function agent_changed_by_multiple_agents_with_alerts (event, id_agent, selected) { - var idAgents = Array(); - - jQuery.each ($("#id_agents option:selected"), function (i, val) { - //val() because the var is same - idAgents.push($(val).val()); - }); - - var selection_mode = $('#modules_selection_mode').val(); - if(selection_mode == undefined) { - selection_mode = 'common'; - } - - template = $('#id_alert_template option:selected').val(); - - $('#module').attr ('disabled', 1); - $('#module').empty (); - $('#module').append ($('').html ("Loading...").attr ("value", 0)); - jQuery.post ('ajax.php', - {"page": "operation/agentes/ver_agente", - "get_agent_modules_multiple_alerts_json_for_multiple_agents": 1, - "template": template, - "id_agent[]": idAgents, - "selection_mode": selection_mode - }, - function (data) { - $('#module').empty (); - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#module').append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#module').append ($('').html (data['any_text']).attr ("value", 0).prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#module').append ($('').html (anyText).attr ("value", 0).prop('selected', true)); - } - } - jQuery.each (data, function (i, val) { - s = js_html_entity_decode(val); - $('#module').append ($('').html (s).attr ("value", val)); - $('#module').fadeIn ('normal'); - }); - if (selected != undefined) - $('#module').attr ('value', selected); - $('#module').removeAttr('disabled'); - }, - "json" - ); +function agent_changed_by_multiple_agents_with_alerts( + event, + id_agent, + selected +) { + var idAgents = Array(); + + jQuery.each($("#id_agents option:selected"), function(i, val) { + //val() because the var is same + idAgents.push($(val).val()); + }); + + var selection_mode = $("#modules_selection_mode").val(); + if (selection_mode == undefined) { + selection_mode = "common"; + } + + template = $("#id_alert_template option:selected").val(); + + $("#module").attr("disabled", 1); + $("#module").empty(); + $("#module").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + jQuery.post( + "ajax.php", + { + page: "operation/agentes/ver_agente", + get_agent_modules_multiple_alerts_json_for_multiple_agents: 1, + template: template, + "id_agent[]": idAgents, + selection_mode: selection_mode + }, + function(data) { + $("#module").empty(); + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#module").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#module").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#module").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + jQuery.each(data, function(i, val) { + s = js_html_entity_decode(val); + $("#module").append( + $("") + .html(s) + .attr("value", val) + ); + $("#module").fadeIn("normal"); + }); + if (selected != undefined) $("#module").attr("value", selected); + $("#module").removeAttr("disabled"); + }, + "json" + ); } /** @@ -335,66 +380,92 @@ function agent_changed_by_multiple_agents_with_alerts (event, id_agent, selected * @param id_agent Agent ID that has been selected * @param selected Which module(s) have to be selected */ -function alert_templates_changed_by_multiple_agents_with_alerts (event, id_agent, selected) { - var idAgents = Array(); - - jQuery.each ($("#id_agents option:selected"), function (i, val) { - //val() because the var is same - idAgents.push($(val).val()); - }); - - var selection_mode = $('#modules_selection_mode').val(); - if(selection_mode == undefined) { - selection_mode = 'common'; - } - - templates = Array(); - jQuery.each ($("#id_alert_templates option:selected"), function (i, val) { - //val() because the var is same - templates.push($(val).val()); - }); - - $('#module').attr ('disabled', 1); - $('#module').empty (); - $('#module').append ($('').html ("Loading...").attr ("value", 0)); - jQuery.post ('ajax.php', - {"page": "operation/agentes/ver_agente", - "get_agent_modules_alerts_json_for_multiple_agents": 1, - "templates[]": templates, - "id_agent[]": idAgents, - "selection_mode": selection_mode - }, - function (data) { - $('#module').empty (); - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#module').append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#module').append ($('').html (data['any_text']).attr ("value", 0).prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#module').append ($('').html (anyText).attr ("value", 0).prop('selected', true)); - } - } - jQuery.each (data, function (i, val) { - s = js_html_entity_decode(val); - $('#module').append ($('').html (s).attr ("value", val)); - $('#module').fadeIn ('normal'); - }); - if (selected != undefined) - $('#module').attr ('value', selected); - $('#module').removeAttr('disabled'); - }, - "json" - ); +function alert_templates_changed_by_multiple_agents_with_alerts( + event, + id_agent, + selected +) { + var idAgents = Array(); + + jQuery.each($("#id_agents option:selected"), function(i, val) { + //val() because the var is same + idAgents.push($(val).val()); + }); + + var selection_mode = $("#modules_selection_mode").val(); + if (selection_mode == undefined) { + selection_mode = "common"; + } + + templates = Array(); + jQuery.each($("#id_alert_templates option:selected"), function(i, val) { + //val() because the var is same + templates.push($(val).val()); + }); + + $("#module").attr("disabled", 1); + $("#module").empty(); + $("#module").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + jQuery.post( + "ajax.php", + { + page: "operation/agentes/ver_agente", + get_agent_modules_alerts_json_for_multiple_agents: 1, + "templates[]": templates, + "id_agent[]": idAgents, + selection_mode: selection_mode + }, + function(data) { + $("#module").empty(); + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#module").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#module").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#module").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + jQuery.each(data, function(i, val) { + s = js_html_entity_decode(val); + $("#module").append( + $("") + .html(s) + .attr("value", val) + ); + $("#module").fadeIn("normal"); + }); + if (selected != undefined) $("#module").attr("value", selected); + $("#module").removeAttr("disabled"); + }, + "json" + ); } /** @@ -404,91 +475,114 @@ function alert_templates_changed_by_multiple_agents_with_alerts (event, id_agent * @param id_module Module ID that has been selected * @param selected Which agent(s) have to be selected */ -function module_changed_by_multiple_modules (event, id_module, selected) { - var idModules = Array(); - - jQuery.each ($("#module_name option:selected"), function (i, val) { - //val() because the var is same - idModules.push($(val).val()); - }); - - $('#agents').attr ('disabled', 1); - $('#agents').empty (); - $('#agents').append ($('').html ("Loading...").attr ("value", 0)); - - var status_module = -1; - if (typeof $("#status_module") !== 'undefined') { - try { - status_module = $("#status_module").val(); - } - catch (error) { - } - } - - var selection_mode = $('#agents_selection_mode').val(); - if(selection_mode == undefined) { - selection_mode = 'common'; - } - - jQuery.post('ajax.php', - {"page": "operation/agentes/ver_agente", - "get_agents_json_for_multiple_modules": 1, - "status_module": status_module, - "module_name[]": idModules, - "selection_mode": selection_mode - }, - function (data) { - $('#agents') - .append ($('').html ("Loading...").attr ("value", 0)); - - $('#agents').empty (); - - if (isEmptyObject(data)) { - var noneText = $("#none_text").html(); //Trick for catch the translate text. - - if (noneText == null) { - noneText = 'None'; - } - - $('#agents') - .append($('').html (noneText).attr ("None", "").prop('selected', true)); - - return; - } - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#agents') - .append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#agents') - .append ($('').html (data['any_text']).attr ("value", 0).prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#agents') - .append($('').html (anyText).attr ("value", 0).prop('selected', true)); - } - } - jQuery.each (data, function (i, val) { - s = js_html_entity_decode(val); - $('#agents') - .append ($('').html (s).attr ("value", i)); - $('#agents').fadeIn ('normal'); - }); - - if (selected != undefined) - $('#agents').attr ('value', selected); - $('#agents').removeAttr('disabled'); - }, - "json" - ); +function module_changed_by_multiple_modules(event, id_module, selected) { + var idModules = Array(); + + jQuery.each($("#module_name option:selected"), function(i, val) { + //val() because the var is same + idModules.push($(val).val()); + }); + + $("#agents").attr("disabled", 1); + $("#agents").empty(); + $("#agents").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + + var status_module = -1; + if (typeof $("#status_module") !== "undefined") { + try { + status_module = $("#status_module").val(); + } catch (error) {} + } + + var selection_mode = $("#agents_selection_mode").val(); + if (selection_mode == undefined) { + selection_mode = "common"; + } + + jQuery.post( + "ajax.php", + { + page: "operation/agentes/ver_agente", + get_agents_json_for_multiple_modules: 1, + status_module: status_module, + "module_name[]": idModules, + selection_mode: selection_mode + }, + function(data) { + $("#agents").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + + $("#agents").empty(); + + if (isEmptyObject(data)) { + var noneText = $("#none_text").html(); //Trick for catch the translate text. + + if (noneText == null) { + noneText = "None"; + } + + $("#agents").append( + $("") + .html(noneText) + .attr("None", "") + .prop("selected", true) + ); + + return; + } + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#agents").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#agents").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#agents").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + jQuery.each(data, function(i, val) { + s = js_html_entity_decode(val); + $("#agents").append( + $("") + .html(s) + .attr("value", i) + ); + $("#agents").fadeIn("normal"); + }); + + if (selected != undefined) $("#agents").attr("value", selected); + $("#agents").removeAttr("disabled"); + }, + "json" + ); } /** @@ -498,354 +592,403 @@ function module_changed_by_multiple_modules (event, id_module, selected) { * @param id_agent Agent ID that has been selected * @param selected Which module(s) have to be selected */ -function agent_changed_by_multiple_agents_id (event, id_agent, selected) { - var idAgents = Array(); - - jQuery.each ($("#id_agents option:selected"), function (i, val) { - //val() because the var is same - idAgents.push($(val).val()); - }); - - $('#module').attr ('disabled', 1); - $('#module').empty (); - $('#module').append ($('').html ("Loading...").attr ("value", 0)); - jQuery.post ('ajax.php', - {"page": "operation/agentes/ver_agente", - "get_agent_modules_json_for_multiple_agents_id": 1, - "id_agent[]": idAgents - }, - function (data) { - $('#module').empty (); - - if (typeof($(document).data('text_for_module')) != 'undefined') { - $('#module').append ($('').html ($(document).data('text_for_module')).attr("value", 0).prop('selected', true)); - } - else { - if (typeof(data['any_text']) != 'undefined') { - $('#module').append ($('').html (data['any_text']).attr ("value", 0).prop('selected', true)); - } - else { - var anyText = $("#any_text").html(); //Trick for catch the translate text. - - if (anyText == null) { - anyText = 'Any'; - } - - $('#module').append ($('').html (anyText).attr ("value", 0).prop('selected', true)); - } - } - - jQuery.each (data, function (i, val) { - s = js_html_entity_decode(val['nombre']); - //$('#module').append ($('').html (s).attr ("value", val)); - $('#module').append ($('').html (s).attr ("value", val['id_agente_modulo'])); - $('#module').fadeIn ('normal'); - }); - if (selected != undefined) - $('#module').attr ('value', selected); - $('#module').removeAttr('disabled'); - }, - "json" - ); -} +function agent_changed_by_multiple_agents_id(event, id_agent, selected) { + var idAgents = Array(); + jQuery.each($("#id_agents option:selected"), function(i, val) { + //val() because the var is same + idAgents.push($(val).val()); + }); + + $("#module").attr("disabled", 1); + $("#module").empty(); + $("#module").append( + $("") + .html("Loading...") + .attr("value", 0) + ); + jQuery.post( + "ajax.php", + { + page: "operation/agentes/ver_agente", + get_agent_modules_json_for_multiple_agents_id: 1, + "id_agent[]": idAgents + }, + function(data) { + $("#module").empty(); + + if (typeof $(document).data("text_for_module") != "undefined") { + $("#module").append( + $("") + .html($(document).data("text_for_module")) + .attr("value", 0) + .prop("selected", true) + ); + } else { + if (typeof data["any_text"] != "undefined") { + $("#module").append( + $("") + .html(data["any_text"]) + .attr("value", 0) + .prop("selected", true) + ); + } else { + var anyText = $("#any_text").html(); //Trick for catch the translate text. + + if (anyText == null) { + anyText = "Any"; + } + + $("#module").append( + $("") + .html(anyText) + .attr("value", 0) + .prop("selected", true) + ); + } + } + + jQuery.each(data, function(i, val) { + s = js_html_entity_decode(val["nombre"]); + //$('#module').append ($('').html (s).attr ("value", val)); + $("#module").append( + $("") + .html(s) + .attr("value", val["id_agente_modulo"]) + ); + $("#module").fadeIn("normal"); + }); + if (selected != undefined) $("#module").attr("value", selected); + $("#module").removeAttr("disabled"); + }, + "json" + ); +} function post_process_select_init(name) { - // Manual mode is hidden by default - - $('#' + name + '_manual').hide(); - $('#' + name + '_default').show(); + // Manual mode is hidden by default + + $("#" + name + "_manual").hide(); + $("#" + name + "_default").show(); } -function post_process_select_init_unit(name,selected) { - // Manual mode is hidden by default - - $('#' + name + '_manual').hide(); - $('#' + name + '_default').show(); - - if(selected != "") { - var select_or_text = false; - $('#' + name + '_select option').each(function(i,item) { - if ($(item).val() == selected) { - select_or_text = true; - return false; - } - }); - - if(select_or_text) { - $('#' + name + '_select option[value='+ selected +']').attr("selected",true); - $('#text-' + name + '_text').val(""); - } else { - $('#' + name + '_select option[value=none]').attr("selected",true); - $('#' + name + '_default').hide(); - $('#' + name + '_manual').show(); - } - } else { - $('#' + name + '_select option[value=none]').attr("selected",true); - } - - $('#' + name + '_select').change(function() { - var value = $('#' + name + '_select').val(); - $('#' + name + '_select option[value='+ value +']').attr("selected",true); - }); - +function post_process_select_init_unit(name, selected) { + // Manual mode is hidden by default + + $("#" + name + "_manual").hide(); + $("#" + name + "_default").show(); + + if (selected != "") { + var select_or_text = false; + $("#" + name + "_select option").each(function(i, item) { + if ($(item).val() == selected) { + select_or_text = true; + return false; + } + }); + + if (select_or_text) { + $("#" + name + "_select option[value=" + selected + "]").attr( + "selected", + true + ); + $("#text-" + name + "_text").val(""); + } else { + $("#" + name + "_select option[value=none]").attr("selected", true); + $("#" + name + "_default").hide(); + $("#" + name + "_manual").show(); + } + } else { + $("#" + name + "_select option[value=none]").attr("selected", true); + } + + $("#" + name + "_select").change(function() { + var value = $("#" + name + "_select").val(); + $("#" + name + "_select option[value=" + value + "]").attr( + "selected", + true + ); + }); } -function post_process_select_events_unit(name,selected) { - - $('.' + name + '_toggler').click(function() { - $('#' + name + '_select option[value=none]').attr("selected",true); - $('#text-' + name + '_text').val(""); - toggleBoth(name); - }); +function post_process_select_events_unit(name, selected) { + $("." + name + "_toggler").click(function() { + var value = $("#text-" + name + "_text").val(); + + var count = $("#" + name + "_select option").filter(function(i, item) { + if ($(item).val() == value) return true; + else return false; + }).length; + + if (count != 1) { + $("#" + name + "_select").append( + $("
                      '+param+'
                      ' + + param + + '
                      Name
                      NameValue' + delete_icon + '
                      ' + + delete_icon + + "
                      "; - echo " $label "; - echo ""; - if (!extension_loaded($ext)) { - echo ""; - return 1; - } - else { - echo ""; - return 0; - } - echo "
                      '; + echo " $label "; + echo ''; + if (!extension_loaded($ext)) { + echo ""; + return 1; + } else { + echo ""; + return 0; + } + + echo '
                      "; - echo " $label "; - echo ""; - if (!include($ext)) { - echo ""; - return 1; - } - else { - echo ""; - return 0; - } - echo "
                      '; + echo " $label "; + echo ''; + if (!include $ext) { + echo ""; + return 1; + } else { + echo ""; + return 0; + } + + echo '
                      "; - echo " $label "; - echo ""; - if (!file_exists ($file)) { - echo " "; - return 1; - } - else { - echo " "; - return 0; - } - echo "
                      '; + echo " $label "; + echo ''; + if (!file_exists($file)) { + echo " "; + return 1; + } else { + echo " "; + return 0; + } + + echo '
                      "; - if ($ok == 0 ) { - echo " "; - echo ""; - echo " $label "; - echo "
                      "; - echo " $label "; - echo "
                      "; + if ($ok == 0) { + echo " "; + echo ''; + echo " $label "; + echo '
                      '; + echo " $label "; + echo '
                      "; - if (file_exists($fullpath)) - if (is_writable($fullpath)) { - echo " "; - echo ""; - echo " $label "; - echo "
                      "; - echo " $label "; - echo "
                      "; - echo " $label "; - echo "
                      "; + if (file_exists($fullpath)) { + if (is_writable($fullpath)) { + echo " "; + echo ''; + echo " $label "; + echo '
                      '; + echo " $label "; + echo '
                      '; + echo " $label "; + echo '
                      "; - echo " $label "; - echo ""; - if ($mode == 1) { - if ($var >= $value) { - echo " "; - return 0; - } - else { - echo " "; - return 1; - } - } - elseif ($var == $value) { - echo " "; - return 0; - } - else { - echo " "; - return 1; - } - echo "
                      '; + echo " $label "; + echo ''; + if ($mode == 1) { + if ($var >= $value) { + echo " "; + return 0; + } else { + echo " "; + return 1; + } + } else if ($var == $value) { + echo " "; + return 0; + } else { + echo " "; + return 1; + } + + echo '
                      "; - $writable = check_writable ( "include", "Checking if ./include is writable"); - if (file_exists("include/config.php")) - $writable += check_writable ( "include/config.php", "Checking if include/config.php is writable"); - echo "
                      "; - - echo "
                      Warning: This installer will overwrite and destroy + } + + echo '
                      '; + echo ''; + $writable = check_writable('include', 'Checking if ./include is writable'); + if (file_exists('include/config.php')) { + $writable += check_writable('include/config.php', 'Checking if include/config.php is writable'); + } + + echo '
                      '; + + echo "
                      Warning: This installer will overwrite and destroy your existing Pandora FMS configuration and Database. Before continue, please be sure that you have no valuable Pandora FMS data in your Database.
                      "; - - echo "
                      Upgrade: + + echo "
                      Upgrade: If you want to upgrade from Pandora FMS 4.x to 5.0 version, please use the migration tool inside /extras directory in this setup.
                      "; - echo "
                      "; + echo '
                      '; - if ($writable == 0) { - echo "
                      "; - echo ""; - echo "
                      "; - } - else { - echo "
                      ERROR:You need to setup permissions to be able to write in ./include directory
                      "; - } - echo "
                      "; - - echo "
                      "; - echo " + if ($writable == 0) { + echo "
                      "; + echo ""; + echo '
                      '; + } else { + echo "
                      ERROR:You need to setup permissions to be able to write in ./include directory
                      "; + } + + echo '
                      '; + + echo "
                      "; + echo "
                Pandora FMS is an OpenSource Software project registered at @@ -426,33 +488,35 @@ function install_step1() {
                "; } -function install_step1_licence() { - echo " + +function install_step1_licence() +{ + echo "
                - " . print_logo_status (2,6) . " + ".print_logo_status(2, 6)."

                GPL2 Licence terms agreement

                Pandora FMS is an OpenSource software project licensed under the GPL2 licence. Pandora FMS includes, as well, another software also licensed under LGPL and BSD licenses. Before continue, you must accept the licence terms..

                For more information, please refer to our website at http://pandorafms.org and contact us if you have any kind of question about the usage of Pandora FMS

                If you dont accept the licence terms, please, close your browser and delete Pandora FMS files.

                "; - - if (!file_exists("COPYING")) { - echo "
                Licence file 'COPYING' is not present in your distribution. This means you have some 'partial' Pandora FMS distribution. We cannot continue without accepting the licence file."; - echo "
                "; - } - else { - echo "
                "; - echo ""; - echo "

                "; - echo "

                "; - } - echo "
                "; - - echo "
                + + if (!file_exists('COPYING')) { + echo "
                Licence file 'COPYING' is not present in your distribution. This means you have some 'partial' Pandora FMS distribution. We cannot continue without accepting the licence file."; + echo '
                '; + } else { + echo ""; + echo "'; + echo '

                '; + echo "

                "; + } + + echo '
                '; + + echo "
                Pandora FMS is an OpenSource Software project registered at @@ -461,53 +525,51 @@ function install_step1_licence() {
                "; } -function install_step2() { - - echo " + +function install_step2() +{ + echo "
                - " . print_logo_status (3,6) . " + ".print_logo_status(3, 6)."
                "; - echo "

                Checking software dependencies

                "; - echo ""; - $res = 0; - $res += check_variable(phpversion(),"5.2","PHP version >= 5.2",1); - $res += check_extension("gd","PHP GD extension"); - $res += check_extension("ldap","PHP LDAP extension"); - $res += check_extension("snmp","PHP SNMP extension"); - $res += check_extension("session","PHP session extension"); - $res += check_extension("gettext","PHP gettext extension"); - $res += check_extension("mbstring","PHP Multibyte String"); - $res += check_extension("zip","PHP Zip"); - $res += check_extension("zlib","PHP Zlib extension"); - $res += check_extension("json","PHP json extension"); - $res += check_extension("curl","CURL (Client URL Library)"); - $res += check_extension("filter","PHP filter extension"); - $res += check_extension("calendar","PHP calendar extension"); - if (PHP_OS == "FreeBSD") { - $res += check_exists ("/usr/local/bin/twopi","Graphviz Binary"); - } - else if (PHP_OS == "NetBSD") { - $res += check_exists ("/usr/pkg/bin/twopi","Graphviz Binary"); - } - else if ( substr(PHP_OS, 0, 3) == 'WIN' ) { - $res += check_exists ("..\\..\\..\\Graphviz\\bin\\twopi.exe", "Graphviz Binary"); - } - else { - $res += check_exists ("/usr/bin/twopi","Graphviz Binary"); - } - - echo "'; + check_extension('mysql', 'PHP MySQL extension'); + check_extension('mysqli', 'PHP MySQL(mysqli) extension'); + echo '
                "; - echo "Checking software dependencies'; + echo ''; + $res = 0; + $res += check_variable(phpversion(), '5.2', 'PHP version >= 5.2', 1); + $res += check_extension('gd', 'PHP GD extension'); + $res += check_extension('ldap', 'PHP LDAP extension'); + $res += check_extension('snmp', 'PHP SNMP extension'); + $res += check_extension('session', 'PHP session extension'); + $res += check_extension('gettext', 'PHP gettext extension'); + $res += check_extension('mbstring', 'PHP Multibyte String'); + $res += check_extension('zip', 'PHP Zip'); + $res += check_extension('zlib', 'PHP Zlib extension'); + $res += check_extension('json', 'PHP json extension'); + $res += check_extension('curl', 'CURL (Client URL Library)'); + $res += check_extension('filter', 'PHP filter extension'); + $res += check_extension('calendar', 'PHP calendar extension'); + if (PHP_OS == 'FreeBSD') { + $res += check_exists('/usr/local/bin/twopi', 'Graphviz Binary'); + } else if (PHP_OS == 'NetBSD') { + $res += check_exists('/usr/pkg/bin/twopi', 'Graphviz Binary'); + } else if (substr(PHP_OS, 0, 3) == 'WIN') { + $res += check_exists("..\\..\\..\\Graphviz\\bin\\twopi.exe", 'Graphviz Binary'); + } else { + $res += check_exists('/usr/bin/twopi', 'Graphviz Binary'); + } + + echo '"; - check_extension("mysql", "PHP MySQL extension"); - check_extension("mysqli", "PHP MySQL(mysqli) extension"); - echo "
                '; + echo "DB Engines"; - echo ""; - echo "
                "; - - if ($res > 0) { - echo " + echo '
                '; + echo '
                '; + + if ($res > 0) { + echo "
                You have some incomplete dependencies. Please correct them or this installer will not be able to finish your installation. @@ -521,16 +583,16 @@ function install_step2() { "; - } - else { - echo "
                "; - echo " + } else { + echo "
                "; + echo " "; - echo "
                "; - } - echo "
                "; - echo "
                "; - echo " + echo '
                '; + } + + echo '
                '; + echo "
                "; + echo "
                @@ -542,24 +604,26 @@ function install_step2() { } -function install_step3() { - $options = ''; - if (extension_loaded("mysql")) { - $options .= ""; - } - if (extension_loaded("mysqli")) { - $options .= ""; - } - - $error = false; - if (empty($options)) { - $error = true; - } - - echo " +function install_step3() +{ + $options = ''; + if (extension_loaded('mysql')) { + $options .= ""; + } + + if (extension_loaded('mysqli')) { + $options .= ""; + } + + $error = false; + if (empty($options)) { + $error = true; + } + + echo "
                - " . print_logo_status (4,6) . " + ".print_logo_status(4, 6)."

                Environment and database setup

                @@ -583,38 +647,38 @@ function install_step3() { please be sure that you have no valuable Pandora FMS data in your Database.

                "; - - if (extension_loaded("oci8")) { - echo "
                For Oracle installation an existing Database with a privileged user is needed.
                "; - } - if (!$error) { - echo ""; - } - - echo ""; - echo "
                "; - echo "DB Engine
                "; - - - if ($error) { - echo " + + if (extension_loaded('oci8')) { + echo "
                For Oracle installation an existing Database with a privileged user is needed.
                "; + } + + if (!$error) { + echo ""; + } + + echo ""; + echo '"; - // the field dbgrant is only shown when the DB host is different from 127.0.0.1 or localhost - echo " + // the field dbgrant is only shown when the DB host is different from 127.0.0.1 or localhost + echo ""; - - echo " "; - - echo ""; - if ($_SERVER['SERVER_ADDR'] == 'localhost' || $_SERVER['SERVER_ADDR'] == '127.0.0.1') { - echo "
                '; + echo 'DB Engine
                '; + + if ($error) { + echo "
                Warning: You haven't a any DB engine with PHP. Please check the previous step to DB engine dependencies.
                "; - } - else { - echo ""; - - echo "
                "; - echo " Installation in
                "; - echo ""; - } - echo "
                DB User with privileges
                + } else { + echo "'; + + echo '
                '; + echo ' Installation in
                '; + echo "'; + } + + echo "
                DB User with privileges
                DB Password for this user
                @@ -628,69 +692,52 @@ function install_step3() {
                Drop Database if exists
                + echo "
                Drop Database if exists
                Full path to HTTP publication directory
                + + echo "
                Full path to HTTP publication directory
                For example /var/www/pandora_console/
                + value='".dirname(__FILE__)."'>
                - Drop Database if exists
                - - "; - } else { - echo "
                "; - } - echo "URL path to Pandora FMS Console
                + echo '
                '; + echo "URL path to Pandora FMS Console
                For example '/pandora_console'
                + value='".dirname($_SERVER['SCRIPT_NAME'])."'>
                "; - - if (!$error) { - echo "
                "; - echo " - "; - echo "
                "; - ?> - - "; - - echo ""; - - echo "
                "; - echo " + if (!$error) { + echo "
                "; + echo " + "; + echo '
                '; + ?> + + '; + + echo ''; + + echo "
                "; + echo "
                Pandora FMS is an OpenSource Software project registered at SourceForge @@ -698,113 +745,130 @@ function install_step3() {
                "; } -function install_step4() { - $pandora_config = "include/config.php"; - - if ( (! isset($_POST["user"])) || (! isset($_POST["dbname"])) || (! isset($_POST["host"])) || - (! isset($_POST["pass"])) || (!isset($_POST['engine'])) || (! isset($_POST["db_action"])) ) { - $dbpassword = ""; - $dbuser = ""; - $dbhost = ""; - $dbname = ""; - $engine = ""; - $dbaction = ""; - $dbgrant = ""; - } - else { - $engine = $_POST['engine']; - $dbpassword = $_POST["pass"]; - $dbuser = $_POST["user"]; - $dbhost = $_POST["host"]; - $dbaction = $_POST["db_action"]; - if (isset($_POST["dbgrant"]) && $_POST["dbgrant"] != "") - $dbgrant = $_POST["dbgrant"]; - else - $dbgrant = $_SERVER["SERVER_ADDR"]; - if (isset($_POST["drop"])) - $dbdrop = $_POST["drop"]; - else - $dbdrop = 0; - - $dbname = $_POST["dbname"]; - if (isset($_POST["url"])) - $url = $_POST["url"]; - else - $url = "http://localhost"; - if (isset($_POST["path"])) { - $path = $_POST["path"]; - $path = str_replace("\\", "/", $path); // Windows compatibility - } - else - $path = "/var/www"; - } - $everything_ok = 0; - $step1=0; - $step2=0; - $step3=0; - $step4=0; $step5=0; $step6=0; $step7=0; - - echo " + +function install_step4() +{ + $pandora_config = 'include/config.php'; + + if ((! isset($_POST['user'])) || (! isset($_POST['dbname'])) || (! isset($_POST['host'])) + || (! isset($_POST['pass'])) || (!isset($_POST['engine'])) || (! isset($_POST['db_action'])) + ) { + $dbpassword = ''; + $dbuser = ''; + $dbhost = ''; + $dbname = ''; + $engine = ''; + $dbaction = ''; + $dbgrant = ''; + } else { + $engine = $_POST['engine']; + $dbpassword = $_POST['pass']; + $dbuser = $_POST['user']; + $dbhost = $_POST['host']; + $dbaction = $_POST['db_action']; + if (isset($_POST['dbgrant']) && $_POST['dbgrant'] != '') { + $dbgrant = $_POST['dbgrant']; + } else { + $dbgrant = $_SERVER['SERVER_ADDR']; + } + + if (isset($_POST['drop'])) { + $dbdrop = $_POST['drop']; + } else { + $dbdrop = 0; + } + + $dbname = $_POST['dbname']; + if (isset($_POST['url'])) { + $url = $_POST['url']; + } else { + $url = 'http://localhost'; + } + + if (isset($_POST['path'])) { + $path = $_POST['path']; + $path = str_replace('\\', '/', $path); + // Windows compatibility + } else { + $path = '/var/www'; + } + } + + $everything_ok = 0; + $step1 = 0; + $step2 = 0; + $step3 = 0; + $step4 = 0; + $step5 = 0; + $step6 = 0; + $step7 = 0; + + echo "
                - " . print_logo_status(5,6) . " + ".print_logo_status(5, 6)."

                Creating database and default configuration file

                "; - switch ($engine) { - case 'mysql': - if (! mysql_connect ($dbhost, $dbuser, $dbpassword)) { - check_generic ( 0, "Connection with Database"); - } - else { - check_generic ( 1, "Connection with Database"); - - // Drop database if needed and don't want to install over an existing DB - if ($dbdrop == 1) { - mysql_query ("DROP DATABASE IF EXISTS `$dbname`"); - } - - // Create schema - if ($dbaction == 'db_new' || $dbdrop == 1) { - $step1 = mysql_query ("CREATE DATABASE `$dbname`"); - check_generic ($step1, "Creating database '$dbname'"); - } - else { - $step1 = 1; - } - if ($step1 == 1) { - $step2 = mysql_select_db($dbname); - check_generic ($step2, "Opening database '$dbname'"); - - $step3 = parse_mysql_dump("pandoradb.sql"); - check_generic ($step3, "Creating schema"); - - $step4 = parse_mysql_dump("pandoradb_data.sql"); - check_generic ($step4, "Populating database"); - if (PHP_OS == "FreeBSD") { - $step_freebsd = adjust_paths_for_freebsd ($engine); - check_generic ($step_freebsd, "Adjusting paths in database for FreeBSD"); - } - - $random_password = random_name (8); - $host = $dbhost; // set default granted origin to the origin of the queries - if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) - $host = $dbgrant; // if the granted origin is different from local machine, set the valid origin - $step5 = mysql_query ("GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host - IDENTIFIED BY '".$random_password."'"); - mysql_query ("FLUSH PRIVILEGES"); - check_generic ($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
                Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
                "); - - $step6 = is_writable("include"); - check_generic ($step6, "Write permissions to save config file in './include'"); - - $cfgin = fopen ("include/config.inc.php","r"); - $cfgout = fopen ($pandora_config,"w"); - $config_contents = fread ($cfgin, filesize("include/config.inc.php")); - $dbtype = 'mysql'; - $config_new = '$random_password
                Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
                "); + + $step6 = is_writable('include'); + check_generic($step6, "Write permissions to save config file in './include'"); + + $cfgin = fopen('include/config.inc.php', 'r'); + $cfgout = fopen($pandora_config, 'w'); + $config_contents = fread($cfgin, filesize('include/config.inc.php')); + $dbtype = 'mysql'; + $config_new = ''; - $step7 = fputs ($cfgout, $config_new); - $step7 = $step7 + fputs ($cfgout, $config_contents); - if ($step7 > 0) - $step7 = 1; - fclose ($cfgin); - fclose ($cfgout); - chmod ($pandora_config, 0600); - check_generic ($step7, "Created new config file at '".$pandora_config."'"); - } - } - - if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { - $everything_ok = 1; - } - break; - case 'mysqli': - $connection = mysqli_connect ($dbhost, $dbuser, $dbpassword); - if (mysqli_connect_error() > 0) { - check_generic ( 0, "Connection with Database"); - } - else { - check_generic ( 1, "Connection with Database"); - - // Drop database if needed and don't want to install over an existing DB - if ($dbdrop == 1) { - mysqli_query ($connection, "DROP DATABASE IF EXISTS `$dbname`"); - } - - // Create schema - if ($dbaction == 'db_new' || $dbdrop == 1) { - $step1 = mysqli_query ($connection, "CREATE DATABASE `$dbname`"); - check_generic ($step1, "Creating database '$dbname'"); - } - else { - $step1 = 1; - } - if ($step1 == 1) { - $step2 = mysqli_select_db($connection, $dbname); - check_generic ($step2, "Opening database '$dbname'"); - - $step3 = parse_mysqli_dump($connection, "pandoradb.sql"); - check_generic ($step3, "Creating schema"); - - $step4 = parse_mysqli_dump($connection, "pandoradb_data.sql"); - check_generic ($step4, "Populating database"); - if (PHP_OS == "FreeBSD") { - $step_freebsd = adjust_paths_for_freebsd ($engine, $connection); - check_generic ($step_freebsd, "Adjusting paths in database for FreeBSD"); - } - - $random_password = random_name (8); - $host = $dbhost; // set default granted origin to the origin of the queries - if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) - $host = $dbgrant; // if the granted origin is different from local machine, set the valid origin - $step5 = mysqli_query ($connection, "GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host - IDENTIFIED BY '".$random_password."'"); - mysqli_query ($connection, "FLUSH PRIVILEGES"); - check_generic ($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
                Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
                "); - - $step6 = is_writable("include"); - check_generic ($step6, "Write permissions to save config file in './include'"); - - $cfgin = fopen ("include/config.inc.php","r"); - $cfgout = fopen ($pandora_config,"w"); - $config_contents = fread ($cfgin, filesize("include/config.inc.php")); - $dbtype = 'mysql'; - $config_new = ' 0) { + $step7 = 1; + } + + fclose($cfgin); + fclose($cfgout); + chmod($pandora_config, 0600); + check_generic($step7, "Created new config file at '".$pandora_config."'"); + } + } + + if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { + $everything_ok = 1; + } + break; + + case 'mysqli': + $connection = mysqli_connect($dbhost, $dbuser, $dbpassword); + if (mysqli_connect_error() > 0) { + check_generic(0, 'Connection with Database'); + } else { + check_generic(1, 'Connection with Database'); + + // Drop database if needed and don't want to install over an existing DB + if ($dbdrop == 1) { + mysqli_query($connection, "DROP DATABASE IF EXISTS `$dbname`"); + } + + // Create schema + if ($dbaction == 'db_new' || $dbdrop == 1) { + $step1 = mysqli_query($connection, "CREATE DATABASE `$dbname`"); + check_generic($step1, "Creating database '$dbname'"); + } else { + $step1 = 1; + } + + if ($step1 == 1) { + $step2 = mysqli_select_db($connection, $dbname); + check_generic($step2, "Opening database '$dbname'"); + + $step3 = parse_mysqli_dump($connection, 'pandoradb.sql'); + check_generic($step3, 'Creating schema'); + + $step4 = parse_mysqli_dump($connection, 'pandoradb_data.sql'); + check_generic($step4, 'Populating database'); + if (PHP_OS == 'FreeBSD') { + $step_freebsd = adjust_paths_for_freebsd($engine, $connection); + check_generic($step_freebsd, 'Adjusting paths in database for FreeBSD'); + } + + $random_password = random_name(8); + $host = $dbhost; + // set default granted origin to the origin of the queries + if (($dbhost != 'localhost') && ($dbhost != '127.0.0.1')) { + $host = $dbgrant; + // if the granted origin is different from local machine, set the valid origin + } + + $step5 = mysqli_query( + $connection, + "GRANT ALL PRIVILEGES ON `$dbname`.* to pandora@$host + IDENTIFIED BY '".$random_password."'" + ); + mysqli_query($connection, 'FLUSH PRIVILEGES'); + check_generic($step5, "Established privileges for user pandora. A new random password has been generated: $random_password
                Please write it down, you will need to setup your Pandora FMS server, editing the /etc/pandora/pandora_server.conf file
                "); + + $step6 = is_writable('include'); + check_generic($step6, "Write permissions to save config file in './include'"); + + $cfgin = fopen('include/config.inc.php', 'r'); + $cfgout = fopen($pandora_config, 'w'); + $config_contents = fread($cfgin, filesize('include/config.inc.php')); + $dbtype = 'mysql'; + $config_new = ''; - $step7 = fputs ($cfgout, $config_new); - $step7 = $step7 + fputs ($cfgout, $config_contents); - if ($step7 > 0) - $step7 = 1; - fclose ($cfgin); - fclose ($cfgout); - chmod ($pandora_config, 0600); - check_generic ($step7, "Created new config file at '".$pandora_config."'"); - } - } - - if (($step7 + $step6 + $step5 + $step4 + $step3 + $step2 + $step1) == 7) { - $everything_ok = 1; - } - break; - } - echo "
                "; - - if ($everything_ok == 1) { - echo "
                '; + + if ($everything_ok == 1) { + echo "
                "; + echo " "; - echo "
                "; - } - else { - $info = "
                There were some problems. + echo '
                '; + } else { + $info = "
                There were some problems. Installation was not completed.

                Please correct failures before trying again. All database "; - if ($engine == 'oracle') - $info .= "objects "; - else - $info .= "schemes "; - - $info .= "created in this step have been dropped.

                -
                "; - echo $info; - - switch ($engine) { - case 'mysql': - if (mysql_error() != "") { - echo "
                ERROR: ". mysql_error().".
                "; - } - - if ($step1 == 1) { - mysql_query ("DROP DATABASE $dbname"); - } - break; - case 'mysqli': - if (mysqli_error($connection) != "") { - echo "
                ERROR: ". mysqli_error($connection).".
                "; - } - - if ($step1 == 1) { - mysqli_query ($connection, "DROP DATABASE $dbname"); - } - break; - } - echo "
                "; - } - echo "
                "; - echo "
                "; - echo " + if ($engine == 'oracle') { + $info .= 'objects '; + } else { + $info .= 'schemes '; + } + + $info .= 'created in this step have been dropped.

                +
                '; + echo $info; + + switch ($engine) { + case 'mysql': + if (mysql_error() != '') { + echo "
                ERROR: ".mysql_error().'.
                '; + } + + if ($step1 == 1) { + mysql_query("DROP DATABASE $dbname"); + } + break; + + case 'mysqli': + if (mysqli_error($connection) != '') { + echo "
                ERROR: ".mysqli_error($connection).'.
                '; + } + + if ($step1 == 1) { + mysqli_query($connection, "DROP DATABASE $dbname"); + } + break; + } + + echo ''; + } + + echo ''; + echo "
                "; + echo "
                Pandora FMS is an Open Source Software project registered at @@ -993,11 +1072,12 @@ function install_step4() { } -function install_step5() { - echo " +function install_step5() +{ + echo "
                - " . print_logo_status (6,6) . " + ".print_logo_status(6, 6)."

                Installation complete

                For security, you now must manually delete this installer @@ -1017,11 +1097,10 @@ function install_step5() {

                "; - echo "
                + echo "
                Pandora FMS is an OpenSource Software project registered at SourceForge
                "; } -?> diff --git a/pandora_console/mobile/include/db.class.php b/pandora_console/mobile/include/db.class.php index 7db3b2b944..e46ae6ea88 100644 --- a/pandora_console/mobile/include/db.class.php +++ b/pandora_console/mobile/include/db.class.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,31 +10,38 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +// Singleton +class DB +{ + + private static $instance; + + private $system; + + private $engine; + + + public function __construct($engine='mysql') + { + $this->system = &$system; + $this->engine = $engine; + + switch ($engine) { + case 'mysql': + // NONE + break; + } + } + + + public static function getInstance($engine='mysql') + { + if (!(self::$instance instanceof self)) { + self::$instance = new self($engine); + } + + return self::$instance; + } + -//Singleton -class DB { - private static $instance; - - private $system; - private $engine; - - public function __construct($engine = 'mysql') { - $this->system = &$system; - $this->engine = $engine; - - switch ($engine) { - case 'mysql': - //NONE - break; - } - } - - public static function getInstance($engine = 'mysql') { - if (!(self::$instance instanceof self)) { - self::$instance = new self($engine); - } - - return self::$instance; - } } -?> \ No newline at end of file diff --git a/pandora_console/mobile/include/functions_web.php b/pandora_console/mobile/include/functions_web.php index 48239f1feb..8b43b33a58 100644 --- a/pandora_console/mobile/include/functions_web.php +++ b/pandora_console/mobile/include/functions_web.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,77 +10,78 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +function menu() +{ + $enterpriseHook = enterprise_include('mobile/include/functions_web.php'); -function menu() { - $enterpriseHook = enterprise_include('mobile/include/functions_web.php'); - - ?> -
                - -
                - -
                -
                - - + - - + + \ No newline at end of file + diff --git a/pandora_console/mobile/include/style/main.css b/pandora_console/mobile/include/style/main.css index 6bb416c74a..b3e066c893 100755 --- a/pandora_console/mobile/include/style/main.css +++ b/pandora_console/mobile/include/style/main.css @@ -1,351 +1,391 @@ * { - text-decoration: none !important; - font-size: 12px; + text-decoration: none !important; + font-size: 12px; } body { - background-color: white; - border-style: none; - direction: ltr; - display: block; - font-family: Arial,Helvetica,sans-serif; - margin: 0; - text-align: left; - vertical-align: top; + background-color: white; + border-style: none; + direction: ltr; + display: block; + font-family: Arial, Helvetica, sans-serif; + margin: 0; + text-align: left; + vertical-align: top; } .small { - font-size: 10px !important; + font-size: 10px !important; } .ui-header .ui-title { - font-size: 14px !important; + font-size: 14px !important; } .ui-btn-inner { - font-weight: bold; + font-weight: bold; } /*INIT----------Tactical styles-----------------------------------------*/ /* Common */ -#tactical1, #tactical2, #agent_graphs, #agent_details { - border-radius: 6px; - +#tactical1, +#tactical2, +#agent_graphs, +#agent_details { + border-radius: 6px; } -.agent_graphs, .events_bar { - padding-top: 10px; +.agent_graphs, +.events_bar { + padding-top: 10px; } -#tactical1 *, #tactical2 * { - font-weight: bold; +#tactical1 *, +#tactical2 * { + font-weight: bold; } -#tactical1 a, #tactical2 a { - font-weight: bold; - color: #222; +#tactical1 a, +#tactical2 a { + font-weight: bold; + color: #222; } legend { - margin-bottom: 5px; + margin-bottom: 5px; } .ui-btn-up-c { - font-weight: normal !important; - text-shadow: none !important; + font-weight: normal !important; + text-shadow: none !important; } /* For mobiles */ -@media screen and (max-width: 750px) -{ - #tactical1 *, #tactical2 * { - font-size: 12px; - } - #tactical1 a, #tactical2 a { - font-size: 18px; - } +@media screen and (max-width: 750px) { + #tactical1 *, + #tactical2 * { + font-size: 12px; + } + #tactical1 a, + #tactical2 a { + font-size: 18px; + } } /* For tablets */ -@media screen and (min-width: 750px) -{ - #tactical1 a, #tactical2 a { - font-size: 25px !important; - } +@media screen and (min-width: 750px) { + #tactical1 a, + #tactical2 a { + font-size: 25px !important; + } } /*END-----------Tactical styles-----------------------------------------*/ #status_pie { - position: relative; - width: 100%; + position: relative; + width: 100%; } #outter_status_pie { - position: relative; - text-align: center; + position: relative; + text-align: center; } /*INIT----------Groups styles-----------------------------------------*/ .group_view tr { - border-bottom: 3px solid white !important; + border-bottom: 3px solid white !important; } - - -tr.group_view_crit, .group_view_crit { - background-color: #FA3030; - color: #000000 !important; +tr.group_view_crit, +.group_view_crit { + background-color: #fa3030; + color: #000000 !important; } .group_view_crit * { - color: #000000 !important; + color: #000000 !important; } -.ui-btn-up-group_view_crit, .ui-btn-hover-group_view_crit { - background-color: #f85858; - color: #fff; - border: 1px solid #111111; - font-weight: bold; - text-shadow: none; +.ui-btn-up-group_view_crit, +.ui-btn-hover-group_view_crit { + background-color: #f85858; + color: #fff; + border: 1px solid #111111; + font-weight: bold; + text-shadow: none; } - -.group_view_normal, .group_view_normal *, -.group_view_norm, .group_view_norm * { - background-color: #FFFFFF; - color: #000000 !important; +.group_view_normal, +.group_view_normal *, +.group_view_norm, +.group_view_norm * { + background-color: #ffffff; + color: #000000 !important; } .group_view_norm * { - color: #000000 !important; + color: #000000 !important; } - -.group_view_not_init, .group_view_not_init * { - background-color: #5AB7E5; - color: #fff !important; +.group_view_not_init, +.group_view_not_init * { + background-color: #5ab7e5; + color: #fff !important; } -.ui-btn-up-group_view_normal, .ui-btn-hover-group_view_normal, -.ui-btn-up-group_view_norm, .ui-btn-hover-group_view_norm { - background-color: #6EB432; - color: #fff; - border: 1px solid #111111; - font-weight: bold; - text-shadow: none; +.ui-btn-up-group_view_normal, +.ui-btn-hover-group_view_normal, +.ui-btn-up-group_view_norm, +.ui-btn-hover-group_view_norm { + background-color: #6eb432; + color: #fff; + border: 1px solid #111111; + font-weight: bold; + text-shadow: none; } -.group_view_ok, .group_view_ok * { - background-color: #00C000; - color: #000000 !important; +.group_view_ok, +.group_view_ok * { + background-color: #00c000; + color: #000000 !important; } .group_view_ok * { - color: #000000 !important; + color: #000000 !important; } -.ui-btn-up-group_view_ok, .ui-btn-hover-group_view_ok { - background-color: #6EB432; - color: #fff; - border: 1px solid #111111; - font-weight: bold; - text-shadow: none; +.ui-btn-up-group_view_ok, +.ui-btn-hover-group_view_ok { + background-color: #6eb432; + color: #fff; + border: 1px solid #111111; + font-weight: bold; + text-shadow: none; } - -tr.group_view_warn, .group_view_warn, tr.group_view_warn.a, a.group_view_warn, tr.a.group_view_warn { - background-color: #F5E535; +tr.group_view_warn, +.group_view_warn, +tr.group_view_warn.a, +a.group_view_warn, +tr.a.group_view_warn { + background-color: #f5e535; } a.group_view_warn { - color: #000000 !important; + color: #000000 !important; } -.ui-btn-up-group_view_warn, .ui-btn-hover-group_view_warn { - background-color: #ffea59; - color: #111; - border: 1px solid #111111; - font-weight: bold; - text-shadow: none; +.ui-btn-up-group_view_warn, +.ui-btn-hover-group_view_warn { + background-color: #ffea59; + color: #111; + border: 1px solid #111111; + font-weight: bold; + text-shadow: none; } - -tr.group_view_alrm, .group_view_alrm { - background-color: #ED8701; +tr.group_view_alrm, +.group_view_alrm { + background-color: #ed8701; } .group_view_alrm * { - color: #000000 !important; + color: #000000 !important; } -.ui-btn-up-group_view_alrm, .ui-btn-hover-group_view_alrm { - background-color: #F7931E; - color: #FFF; - border: 1px solid #111111; - font-weight: bold; - text-shadow: none; +.ui-btn-up-group_view_alrm, +.ui-btn-hover-group_view_alrm { + background-color: #f7931e; + color: #fff; + border: 1px solid #111111; + font-weight: bold; + text-shadow: none; } - -tr.group_view_unk, .group_view_unk { - background-color: #C4C4C4; +tr.group_view_unk, +.group_view_unk { + background-color: #c4c4c4; } .group_view_unk * { - color: #000000 !important; + color: #000000 !important; } -.ui-btn-up-group_view_unk, .ui-btn-hover-group_view_unk { - background-color: #999999; - color: #fff; - border: 1px solid #111111; - font-weight: bold; - text-shadow: none; +.ui-btn-up-group_view_unk, +.ui-btn-hover-group_view_unk { + background-color: #999999; + color: #fff; + border: 1px solid #111111; + font-weight: bold; + text-shadow: none; } -.ui-btn-active:visited, .ui-btn-active:hover, .ui-btn-active a.ui-link-inherit { - color: #888 !important; - text-shadow: none !important; +.ui-btn-active:visited, +.ui-btn-active:hover, +.ui-btn-active a.ui-link-inherit { + color: #888 !important; + text-shadow: none !important; } -tr.group_view_data, .group_view_data { - color: #000000 !important; +tr.group_view_data, +.group_view_data { + color: #000000 !important; } .group_view_data_unk * { - color: #303030 !important; + color: #303030 !important; } .group_view_data_ok * { - color: #00C000 !important; + color: #00c000 !important; } .group_view_data_crit * { - color: #5C0000 !important; + color: #5c0000 !important; } .group_view_data_alrm * { - color: #5C1D00 !important; + color: #5c1d00 !important; } .group_view_data_warn * { - color: #5C5900 !important; + color: #5c5900 !important; } .group_view * { - text-shadow: none !important; - font-size: 12px !important; + text-shadow: none !important; + font-size: 12px !important; } .list_groups .link_count { - display: inline !important; + display: inline !important; } - -.list_groups .number_count, .list_groups .name_count { - position: absolute; - top: 0; +.list_groups .number_count, +.list_groups .name_count { + position: absolute; + top: 0; } .list_groups .number_count { - right: 10px; + right: 10px; } .list_groups .name_count { - left: 10px; + left: 10px; } .list_groups .name_count img { - float: left; - margin-right: 10px; + float: left; + margin-right: 10px; } /* For mobiles */ -@media screen and (max-width: 750px) -{ - .list_groups .name_count img { - margin-top: -7px; - } +@media screen and (max-width: 750px) { + .list_groups .name_count img { + margin-top: -7px; + } } /* For tablets */ -@media screen and (min-width: 750px) -{ - .list_groups .name_count img { - margin-top: -3px; - } +@media screen and (min-width: 750px) { + .list_groups .name_count img { + margin-top: -3px; + } } /*END-----------Groups styles-----------------------------------------*/ - - /*INIT----------Events styles-----------------------------------------*/ -.datos_green, .datos_greenf9, .datos_green a, .datos_greenf9 a { - background-color: #52A000; - color: #FFFFFF !important; - text-shadow: none !important; +.datos_green, +.datos_greenf9, +.datos_green a, +.datos_greenf9 a { + background-color: #52a000; + color: #ffffff !important; + text-shadow: none !important; } -.datos_red, .datos_redf9, .datos_red a, .datos_redf9 a { - background-color: #FF3E41; - color: #FFFFFF !important; - text-shadow: none !important; +.datos_red, +.datos_redf9, +.datos_red a, +.datos_redf9 a { + background-color: #ff3e41; + color: #ffffff !important; + text-shadow: none !important; } -.datos_yellow, .datos_yellowf9, .datos_yellow a, .datos_yellowf9 a { - background-color: #F5E535; - color: #000000 !important; - text-shadow: none !important; +.datos_yellow, +.datos_yellowf9, +.datos_yellow a, +.datos_yellowf9 a { + background-color: #f5e535; + color: #000000 !important; + text-shadow: none !important; } -.datos_blue, .datos_bluef9, .datos_blue a, .datos_bluef9 a { - background-color: #77E2F2; - color: #000000 !important; - text-shadow: none !important; +.datos_blue, +.datos_bluef9, +.datos_blue a, +.datos_bluef9 a { + background-color: #77e2f2; + color: #000000 !important; + text-shadow: none !important; } -.datos_grey, .datos_greyf9, .datos_grey a, .datos_greyf9 a { - background-color: #E4E4E4; - color: #000000 !important; - text-shadow: none !important; +.datos_grey, +.datos_greyf9, +.datos_grey a, +.datos_greyf9 a { + background-color: #e4e4e4; + color: #000000 !important; + text-shadow: none !important; } -.datos_pink, .datos_pinkf9, .datos_pink a, .datos_pinkf9 a { - background-color: #FF92E9; - color: #000000 !important; - text-shadow: none !important; +.datos_pink, +.datos_pinkf9, +.datos_pink a, +.datos_pinkf9 a { + background-color: #ff92e9; + color: #000000 !important; + text-shadow: none !important; } -.datos_brown, .datos_brownf9, .datos_brown a, .datos_brownf9 a { - background-color: #C97A4A; - color: #000000 !important; - text-shadow: none !important; +.datos_brown, +.datos_brownf9, +.datos_brown a, +.datos_brownf9 a { + background-color: #c97a4a; + color: #000000 !important; + text-shadow: none !important; } tr.events { - border-bottom: 6px solid #f7f7f7 !important; - font-size: 12px !important; + border-bottom: 6px solid #f7f7f7 !important; + font-size: 12px !important; } table#list_events th { - font-size: 12px !important; - font-weight: bolder !important; - border: 0px; + font-size: 12px !important; + font-weight: bolder !important; + border: 0px; } div.graph { - margin: 0 auto; + margin: 0 auto; } -table.alternate tr:nth-child(odd) td, table.alternate tr:nth-child(odd) th{ - background-color: #ffffff; +table.alternate tr:nth-child(odd) td, +table.alternate tr:nth-child(odd) th { + background-color: #ffffff; } -table.alternate tr:nth-child(even) td, table.alternate tr:nth-child(eveny) th{ - background-color: #e4e5e4; +table.alternate tr:nth-child(even) td, +table.alternate tr:nth-child(eveny) th { + background-color: #e4e5e4; } table.pandora_responsive { - width: 100%; + width: 100%; } -table.pandora_responsive td, table.pandora_responsive th{ - padding: 4px; +table.pandora_responsive td, +table.pandora_responsive th { + padding: 4px; } -table.event_details img{ - margin-left: 4px; +table.event_details img { + margin-left: 4px; } -table.event_details td{ - height: 14px; +table.event_details td { + height: 14px; } table.event_details td.cell_event_name { - font-size: 14px; + font-size: 14px; } #validate_button { - margin: 10px auto; - display: block; + margin: 10px auto; + display: block; } /* @@ -474,221 +514,225 @@ table.event_details td.cell_event_name { */ @media screen and (max-width: 35em) { - /* Hide the title of event name */ - #list_events tbody tr.events td.cell_0 b.ui-table-cell-label { - display: none; - } + /* Hide the title of event name */ + #list_events tbody tr.events td.cell_0 b.ui-table-cell-label { + display: none; + } } /*END-----------Events styles-----------------------------------------*/ - - - - /*INIT-----------Agents styles----------------------------------------*/ -.red, .redb, .redi, .error { - background: #f85858 !important; +.red, +.redb, +.redi, +.error { + background: #f85858 !important; } .green { - background: #6EB432 !important; + background: #6eb432 !important; } .orange { - background: #FF8800 !important; + background: #ff8800 !important; } .yellow { - background: #ffea59 !important; + background: #ffea59 !important; } .grey { - background: #AAAAAA !important; - font-weight: bold; + background: #aaaaaa !important; + font-weight: bold; } -.green, .orange, .yellow, .red, .grey, .agents_tiny_stats span { - text-shadow: none; - color: white !important; - padding: 1px 3px; - border-radius: 2px; +.green, +.orange, +.yellow, +.red, +.grey, +.agents_tiny_stats span { + text-shadow: none; + color: white !important; + padding: 1px 3px; + border-radius: 2px; } .agents_tiny_stats span { - background: #222; + background: #222; } .agent_details { - padding: 10px 0px 10px 0px; + padding: 10px 0px 10px 0px; } .agent_details > img { - vertical-align: middle; - width: 20px; + vertical-align: middle; + width: 20px; } -.agent_os{ - float: right; - position: absolute; - top: 0px; - right: 0px; - padding: 10px; +.agent_os { + float: right; + position: absolute; + top: 0px; + right: 0px; + padding: 10px; } .agent_list_ips { - padding: 10px 0px 10px 0px; + padding: 10px 0px 10px 0px; } .agent_list_ips > img { - vertical-align: middle; - width: 20px; + vertical-align: middle; + width: 20px; } .agent_last_contact { - padding: 10px 0px 10px 0px; + padding: 10px 0px 10px 0px; } .agent_description { - padding: 10px 0px 10px 0px; + padding: 10px 0px 10px 0px; } .agent_name { - font-weight: bold; - font-size: 14px; -} - -#list_agents .cell_0 img { - float: left; - margin-right: 3px; + font-weight: bold; + font-size: 14px; } -#list_agents td:hover, #list_networkmaps td:hover, -#list_events td:hover, #list_Modules td:hover, #list_agent_Modules td:hover, -#list_visualmaps td:hover, #last_agent_events td:hover { - cursor: pointer; +#list_agents .cell_0 img { + float: left; + margin-right: 3px; +} + +#list_agents td:hover, +#list_networkmaps td:hover, +#list_events td:hover, +#list_Modules td:hover, +#list_agent_Modules td:hover, +#list_visualmaps td:hover, +#last_agent_events td:hover { + cursor: pointer; } #list_agents td { - height: 25px; - padding-top: 10px; + height: 25px; + padding-top: 10px; } .agents_tiny_stats_tactical { - display: block; - text-align: center; - width: 100%; + display: block; + text-align: center; + width: 100%; } @media screen and (max-width: 34.99em) { - #list_agents td { - height: 35px; - padding-top: 7px; - display: table-cell; - clear: none; - float: none; - padding-left: 0px !important; - padding-right: 0px !important; - width: auto !important; - } - - #list_agents td.cell_0 { - border-top: 0px none; - } - #list_agents td.cell_0>span.tiny>img { - width: 5px; - height: 30px; - margin-top: -6px; - margin-left: 0px; - } + #list_agents td { + height: 35px; + padding-top: 7px; + display: table-cell; + clear: none; + float: none; + padding-left: 0px !important; + padding-right: 0px !important; + width: auto !important; + } - #list_agents .cell_2 .ui-table-cell-label, - #list_agents .cell_3 .ui-table-cell-label, - #list_agents .cell_6 .ui-table-cell-label, - #list_agents .cell_4 .ui-table-cell-label, - #list_agents .cell_5 .ui-table-cell-label, - #list_agents .cell_8 .ui-table-cell-label { - min-width: auto !important; - } - - #list_agents .cell_3 .ui-table-cell-label, - #list_agents .cell_6 .ui-table-cell-label, - #list_agents .cell_7 .ui-table-cell-label { - padding-left: 10px; - } - - #list_agents .cell_2, - #list_agents .cell_3, - #list_agents .cell_7 { - display: inline !important; - float: none !important; - } - - #list_agents .cell_4, - #list_agents .cell_8 { - display: inline !important; - float: none !important; - } - - #list_agents .cell_8 { - display: inline !important; - float: none !important; - } - - #list_agents b.ui-table-cell-label { - display: none; - } - - #list_agents .show_collapside { - display: none !important; - } - - #list_agents .cell_1, - #list_agents .cell_2, - #list_agents .cell_3, - #list_agents .cell_4 { - display: none !important; - } - - #list_agents .cell_0 .ui-link { - font-size: 12px; - } - - #list_agents .cell_6 .show_collapside { - display: none !important; - } - - .agents_tiny_stats * { - font-size: 12px !important; - } - - #list_agent_Modules td { - padding-top: 7px !important; - } - - .agents_tiny_stats { - float: right; - } + #list_agents td.cell_0 { + border-top: 0px none; + } + #list_agents td.cell_0 > span.tiny > img { + width: 5px; + height: 30px; + margin-top: -6px; + margin-left: 0px; + } + + #list_agents .cell_2 .ui-table-cell-label, + #list_agents .cell_3 .ui-table-cell-label, + #list_agents .cell_6 .ui-table-cell-label, + #list_agents .cell_4 .ui-table-cell-label, + #list_agents .cell_5 .ui-table-cell-label, + #list_agents .cell_8 .ui-table-cell-label { + min-width: auto !important; + } + + #list_agents .cell_3 .ui-table-cell-label, + #list_agents .cell_6 .ui-table-cell-label, + #list_agents .cell_7 .ui-table-cell-label { + padding-left: 10px; + } + + #list_agents .cell_2, + #list_agents .cell_3, + #list_agents .cell_7 { + display: inline !important; + float: none !important; + } + + #list_agents .cell_4, + #list_agents .cell_8 { + display: inline !important; + float: none !important; + } + + #list_agents .cell_8 { + display: inline !important; + float: none !important; + } + + #list_agents b.ui-table-cell-label { + display: none; + } + + #list_agents .show_collapside { + display: none !important; + } + + #list_agents .cell_1, + #list_agents .cell_2, + #list_agents .cell_3, + #list_agents .cell_4 { + display: none !important; + } + + #list_agents .cell_0 .ui-link { + font-size: 12px; + } + + #list_agents .cell_6 .show_collapside { + display: none !important; + } + + .agents_tiny_stats * { + font-size: 12px !important; + } + + #list_agent_Modules td { + padding-top: 7px !important; + } + + .agents_tiny_stats { + float: right; + } } /* For mobiles */ -@media screen and (max-width: 750px) -{ - .agents_tiny_stats * { - font-size: 12px !important; - } +@media screen and (max-width: 750px) { + .agents_tiny_stats * { + font-size: 12px !important; + } } /* For tablets */ -@media screen and (min-width: 750px) -{ - .agents_tiny_stats * { - font-size: 17px !important; - } +@media screen and (min-width: 750px) { + .agents_tiny_stats * { + font-size: 17px !important; + } } /*END-----------Agents styles-----------------------------------------*/ - - /*INIT-----------Alerts styles---------------------------------------*/ #list_alerts td { - height: 35px; - padding-top: 20px; + height: 35px; + padding-top: 20px; } /*END-----------Alerts styles---------------------------------------*/ @@ -696,8 +740,8 @@ table.event_details td.cell_event_name { /*INIT-----------Network maps styles---------------------------------------*/ #list_networkmaps td { - height: 35px; - padding-top: 20px; + height: 35px; + padding-top: 20px; } /*END-----------Network maps styles---------------------------------------*/ @@ -705,672 +749,674 @@ table.event_details td.cell_event_name { /*INIT-----------Visual maps styles---------------------------------------*/ #list_visualmaps td { - height: 35px; - padding-top: 20px; + height: 35px; + padding-top: 20px; } #rendered_visual_map div { - color: #003a3a; - text-shadow: none !important; + color: #003a3a; + text-shadow: none !important; } #rendered_visual_map { - text-align: center; + text-align: center; } /* For mobiles */ -@media screen and (max-width: 750px) -{ - #rendered_visual_map div { - font-size: 6pt !important; - } +@media screen and (max-width: 750px) { + #rendered_visual_map div { + font-size: 6pt !important; + } } /* For tablets */ -@media screen and (min-width: 750px) -{ - #rendered_visual_map div { - font-size: 8pt !important; - } +@media screen and (min-width: 750px) { + #rendered_visual_map div { + font-size: 8pt !important; + } } /* For mobiles */ -@media screen and (max-width: 750px) -{ - .resize_visual_font_size_4pt * { - font-size: 2pt !important; - } - .resize_visual_font_size_6pt * { - font-size: 3pt !important; - } - .resize_visual_font_size_8pt * { - font-size: 4pt !important; - } - .resize_visual_font_size_14pt * { - font-size: 6pt !important; - } - .resize_visual_font_size_24pt * { - font-size: 10pt !important; - } - .resize_visual_font_size_36pt * { - font-size: 14pt !important; - } - .resize_visual_font_size_72pt * { - font-size: 27pt !important; - } +@media screen and (max-width: 750px) { + .resize_visual_font_size_4pt * { + font-size: 2pt !important; + } + .resize_visual_font_size_6pt * { + font-size: 3pt !important; + } + .resize_visual_font_size_8pt * { + font-size: 4pt !important; + } + .resize_visual_font_size_14pt * { + font-size: 6pt !important; + } + .resize_visual_font_size_24pt * { + font-size: 10pt !important; + } + .resize_visual_font_size_36pt * { + font-size: 14pt !important; + } + .resize_visual_font_size_72pt * { + font-size: 27pt !important; + } } /* For tablets */ -@media screen and (min-width: 750px) -{ - .resize_visual_font_size_4pt * { - font-size: 2pt !important; - } - .resize_visual_font_size_6pt * { - font-size: 3pt !important; - } - .resize_visual_font_size_8pt * { - font-size: 4pt !important; - } - .resize_visual_font_size_14pt * { - font-size: 7pt !important; - } - .resize_visual_font_size_24pt * { - font-size: 12pt !important; - } - .resize_visual_font_size_36pt * { - font-size: 18pt !important; - } - .resize_visual_font_size_72pt * { - font-size: 36pt !important; - } +@media screen and (min-width: 750px) { + .resize_visual_font_size_4pt * { + font-size: 2pt !important; + } + .resize_visual_font_size_6pt * { + font-size: 3pt !important; + } + .resize_visual_font_size_8pt * { + font-size: 4pt !important; + } + .resize_visual_font_size_14pt * { + font-size: 7pt !important; + } + .resize_visual_font_size_24pt * { + font-size: 12pt !important; + } + .resize_visual_font_size_36pt * { + font-size: 18pt !important; + } + .resize_visual_font_size_72pt * { + font-size: 36pt !important; + } } /*END-----------Visual maps styles---------------------------------------*/ /*INIT-----------Modules styles---------------------------------------*/ @media screen and (max-width: 34.99em) { - #list_Modules .cell_1 .ui-table-cell-label, - #list_Modules .cell_5 .ui-table-cell-label, - #list_Modules .cell_6 .ui-table-cell-label { - min-width: auto !important; - } - - #list_Modules .cell_5 .ui-table-cell-label, - #list_Modules .cell_6 .ui-table-cell-label { - padding-left: 10px; - } - - #list_Modules .cell_0 .ui-table-cell-label, - #list_Modules .cell_1 .ui-table-cell-label, - #list_Modules .cell_3 .ui-table-cell-label, - #list_Modules .cell_4 .ui-table-cell-label, - #list_Modules .cell_5 .ui-table-cell-label { - display: none !important; - } - - #list_Modules td { - height: 35px; - padding-top: 7px; - display: table-cell; - clear: none; - float: none; - padding-left: 0px !important; - padding-right: 0px !important; - } - - #list_Modules .show_collapside { - display: inline !important; - } - - #list_Modules .data { - white-space: nowrap; - } - - #list_Modules .cell_1, - #list_Modules .cell_2, - #list_Modules .cell_3 { - display: none !important; - } - - #list_Modules .cell_0 .show_collapside, - #list_Modules .cell_1 .show_collapside, - #list_Modules .cell_4 .show_collapside, - #list_Modules .cell_5 .show_collapside { - display: none !important; - } - - #list_Modules .cell_0 .ui-link { - font-size: 12px; - } - - #list_Modules .cell_0{ - width: 50%; - border-top: 0px none; - } - #list_Modules .cell_4{ - width: 25%; - } - #list_Modules .cell_5{ - width: 25%; - } -} - #list_Modules td.cell_0>span.tiny>img { - width: 5px; - height: 30px; - margin-top: -5px; - margin-left: 0px; - float: left; - } - #list_Modules .module_name { - font-size: 12px !important; - } + #list_Modules .cell_1 .ui-table-cell-label, + #list_Modules .cell_5 .ui-table-cell-label, + #list_Modules .cell_6 .ui-table-cell-label { + min-width: auto !important; + } + + #list_Modules .cell_5 .ui-table-cell-label, + #list_Modules .cell_6 .ui-table-cell-label { + padding-left: 10px; + } + + #list_Modules .cell_0 .ui-table-cell-label, + #list_Modules .cell_1 .ui-table-cell-label, + #list_Modules .cell_3 .ui-table-cell-label, + #list_Modules .cell_4 .ui-table-cell-label, + #list_Modules .cell_5 .ui-table-cell-label { + display: none !important; + } + + #list_Modules td { + height: 35px; + padding-top: 7px; + display: table-cell; + clear: none; + float: none; + padding-left: 0px !important; + padding-right: 0px !important; + } + + #list_Modules .show_collapside { + display: inline !important; + } + + #list_Modules .data { + white-space: nowrap; + } + + #list_Modules .cell_1, + #list_Modules .cell_2, + #list_Modules .cell_3 { + display: none !important; + } + + #list_Modules .cell_0 .show_collapside, + #list_Modules .cell_1 .show_collapside, + #list_Modules .cell_4 .show_collapside, + #list_Modules .cell_5 .show_collapside { + display: none !important; + } + + #list_Modules .cell_0 .ui-link { + font-size: 12px; + } + + #list_Modules .cell_0 { + width: 50%; + border-top: 0px none; + } + #list_Modules .cell_4 { + width: 25%; + } + #list_Modules .cell_5 { + width: 25%; + } + + #list_Modules td.cell_0 > span.tiny > img { + width: 5px; + height: 30px; + margin-top: -5px; + margin-left: 0px; + float: left; + } + #list_Modules .module_name { + font-size: 12px !important; + } } #list_Modules .cell_5 a { - color: #000000 !important; + color: #000000 !important; } #list_Modules .module_name { - font-size: 15px; - font-weight: bold; + font-size: 15px; + font-weight: bold; } -#list_Modules td, #list_agent_Modules td { - height: 35px; - padding-top: 20px; +#list_Modules td, +#list_agent_Modules td { + height: 35px; + padding-top: 20px; } #list_agent_Modules td.cell_0 > span.tiny { - display: none; + display: none; } #list_Modules .cell_5 img { - float: left; + float: left; } #user_logged { - position: absolute; - font-size: 11px !important; - right: 10px; - top: 8px; - background: url(../../../images/header_user.png) no-repeat right; - padding-right: 20px; - line-height: 20px; + position: absolute; + font-size: 11px !important; + right: 10px; + top: 8px; + background: url(../../../images/header_user.png) no-repeat right; + padding-right: 20px; + line-height: 20px; } @media screen and (max-width: 34.99em) { - #list_agent_Modules .ui-table-cell-label, - #list_agent_Modules .cell_2, - #list_agent_Modules .cell_3 { - display: none; - } + #list_agent_Modules .ui-table-cell-label, + #list_agent_Modules .cell_2, + #list_agent_Modules .cell_3 { + display: none; + } } /*END------------Modules styles---------------------------------------*/ - - /*INIT---------Fix the square border in search input------------------*/ .ui-input-search { - border-radius: 0.6em 0.6em 0.6em 0.6em !important; + border-radius: 0.6em 0.6em 0.6em 0.6em !important; } .ui-select { - width: 100% !important; + width: 100% !important; } /*END----------Fix the square border in search input------------------*/ - - - ul.ui-listview li.ui-btn div.ui-btn-inner div.ui-btn-text a { - padding-top: 5px; - padding-left: 5px; + padding-top: 5px; + padding-left: 5px; } .ui-btn-inner { - border: 0px solid #000!important; + border: 0px solid #000 !important; } li.ui-btn { - margin-bottom: 4px !important; - margin-top: 4px !important; + margin-bottom: 4px !important; + margin-top: 4px !important; } - /*INIT---------Fix the tons of air between the rows in small table----*/ .head_vertical { - margin-top: 0px !important; - border-top: 1px solid grey; + margin-top: 0px !important; + border-top: 1px solid grey; } .head_horizontal { - border-bottom: 1px solid grey !important; + border-bottom: 1px solid grey !important; } #list_events .head_horizontal { - border-bottom: 0px solid white !important; + border-bottom: 0px solid white !important; } .cell_0 { - border-top: solid 1px #666; - margin-top: 0px; + border-top: solid 1px #666; + margin-top: 0px; } #list_events .cell_0 { - border: 0px; + border: 0px; } /* Hack to align table titles in mobile mode */ .ui-table-cell-label { - float: left; + float: left; } @media screen and (max-width: 34.99em) { - .ui-table th, .ui-table td { - padding: 8px !important; - padding-left: 3px; - } - - .head_vertical { - display: none !important; - } + .ui-table th, + .ui-table td { + padding: 8px !important; + padding-left: 3px; + } + + .head_vertical { + display: none !important; + } } /*END----------Fix the tons of air between the rows in small table----*/ - - - - - /*INIT---------Fix to avoid clicks under loading message--------------*/ .ui-loader-background { - width:100% !important; - height:100% !important; - top:0 !important; - margin: 0 !important; - background: rgba(0, 0, 0, 0.3) !important; - display:none !important; - position: fixed !important; - z-index:100 !important; + width: 100% !important; + height: 100% !important; + top: 0 !important; + margin: 0 !important; + background: rgba(0, 0, 0, 0.3) !important; + display: none !important; + position: fixed !important; + z-index: 100 !important; } .ui-loading .ui-loader-background { - display:block !important; + display: block !important; } /*END----------Fix to avoid clicks under loading message--------------*/ - .button_layer { - position: relative; - float: right; - padding-right: 60px; - height: 30px; + position: relative; + float: right; + padding-right: 60px; + height: 30px; } .ui-icon-big { - width: 28px !important; - height: 28px !important; + width: 28px !important; + height: 28px !important; } -@media screen and (max-width: 35em) -{ - .events .status_row { - display: none; - } - - .events .cell_0 a.event_name { - width: 87%; - float: left; - } - - .events_agent { - min-width: 50%; - } - - .agents_last_contact { - float: right; - } +@media screen and (max-width: 35em) { + .events .status_row { + display: none; + } + + .events .cell_0 a.event_name { + width: 87%; + float: left; + } + + .events_agent { + min-width: 50%; + } + + .agents_last_contact { + float: right; + } } -@media screen and (min-width: 35em) -{ - .events .cell_0 .event_link{ - display: none; - } - - .events td { - height: 35px; - } - - .events_agent { - float: left; - margin-right: 15px; - } +@media screen and (min-width: 35em) { + .events .cell_0 .event_link { + display: none; + } + + .events td { + height: 35px; + } + + .events_agent { + float: left; + margin-right: 15px; + } } /* Common */ -.ui-li>.ui-btn-inner { - background: white; +.ui-li > .ui-btn-inner { + background: white; } .groups_sublist li { - border-radius: 0px; + border-radius: 0px; } /* For mobiles */ -@media screen and (max-width: 750px) -{ - .ui-content>.ui-btn { - margin: 10px 7px; - height: 30px; - padding-top: 3px; - } - - label, input, .ui-btn-inner { - font-size: 12px !important; - } - - .list_groups .ui-btn-inner { - padding-top: 15px !important; - height: 20px !important; - } - - .login_logo img { - width: 220px; - margin-bottom: 10px; - padding-top: 5%; - } - - .untiny { - display: none; - } +@media screen and (max-width: 750px) { + .ui-content > .ui-btn { + margin: 10px 7px; + height: 30px; + padding-top: 3px; + } + + label, + input, + .ui-btn-inner { + font-size: 12px !important; + } + + .list_groups .ui-btn-inner { + padding-top: 15px !important; + height: 20px !important; + } + + .login_logo img { + width: 220px; + margin-bottom: 10px; + padding-top: 5%; + } + + .untiny { + display: none; + } } /* For tablets */ -@media screen and (min-width: 750px) -{ - .ui-content>.ui-btn { - width: 31%; - display: inline-block; - margin: 8px 5px; - height: 40px; - padding-top: 8px; - } - - label, input, .ui-btn-inner { - font-size: 16px !important; - padding-top: 6px !important; - } - - .list_groups .ui-btn-inner { - padding-top: 20px !important; - height: 35px !important; - } - - .ui-header .ui-title { - font-size: 18px !important; - } - - * { - font-size: 18px !important; - } +@media screen and (min-width: 750px) { + .ui-content > .ui-btn { + width: 31%; + display: inline-block; + margin: 8px 5px; + height: 40px; + padding-top: 8px; + } - .event_name { - font-size: 15px !important; - } - - .login_logo img { - width: 300px; - margin-bottom: 20px; - padding-top: 5%; - } - - .tiny { - display: none; - } + label, + input, + .ui-btn-inner { + font-size: 16px !important; + padding-top: 6px !important; + } + + .list_groups .ui-btn-inner { + padding-top: 20px !important; + height: 35px !important; + } + + .ui-header .ui-title { + font-size: 18px !important; + } + + * { + font-size: 18px !important; + } + + .event_name { + font-size: 15px !important; + } + + .login_logo img { + width: 300px; + margin-bottom: 20px; + padding-top: 5%; + } + + .tiny { + display: none; + } } #login_container { - width: 60%; - margin: 0 auto; - max-width: 300px; - padding-top: 5%; + width: 60%; + margin: 0 auto; + max-width: 300px; + padding-top: 5%; } .event_name { - font-size: 12px; - font-weight: bold; + font-size: 12px; + font-weight: bold; } #login_container #login_btn-container { - margin-top: 30px; + margin-top: 30px; } -#login_container input, #login_container .ui-btn-text{ - font-size: 16px !important; +#login_container input, +#login_container .ui-btn-text { + font-size: 16px !important; } - table.tactical_bars { - width: 100%; + width: 100%; } .tactical_bar { - text-align: center; - margin-bottom: 4px; + text-align: center; + margin-bottom: 4px; } -.ui-bar, .ui-body { - margin: 5px; +.ui-bar, +.ui-body { + margin: 5px; } .events .cell_0 img { - margin-right: 5px; + margin-right: 5px; } .cell_0 { - max-width: 500px; + max-width: 500px; } .cell_event_name { - padding-bottom: 10px; - font-weight: bold; + padding-bottom: 10px; + font-weight: bold; } /*INIT-----------Icons styles---------------------------------------*/ .ui-icon-tactical_view { - background-image: url(../../../images/op_monitoring.menu.png) !important; + background-image: url(../../../images/op_monitoring.menu.png) !important; } .ui-icon-events { - background-image: url(../../../images/op_events.menu.png) !important; + background-image: url(../../../images/op_events.menu.png) !important; } .ui-icon-groups { - background-image: url(../../../images/group.menu.png) !important; + background-image: url(../../../images/group.menu.png) !important; } .ui-icon-alerts { - background-image: url(../../../images/op_alerts.menu.png) !important; + background-image: url(../../../images/op_alerts.menu.png) !important; } .ui-icon-agents { - background-image: url(../../../images/agent_mc.menu.png) !important; + background-image: url(../../../images/agent_mc.menu.png) !important; } .ui-icon-modules { - background-image: url(../../../images/brick.menu.png) !important; + background-image: url(../../../images/brick.menu.png) !important; } .ui-icon-network_maps { - background-image: url(../../../images/op_network.menu.png) !important; + background-image: url(../../../images/op_network.menu.png) !important; } .ui-icon-visual_console { - background-image: url(../../../images/visual_console.menu.png) !important; + background-image: url(../../../images/visual_console.menu.png) !important; } .ui-icon-dashboard { - background-image: url(../../../images/dashboard.menu.png) !important; + background-image: url(../../../images/dashboard.menu.png) !important; } -.ui-icon-tactical_view, .ui-icon-events, -.ui-icon-groups, .ui-icon-alerts, -.ui-icon-agents, .ui-icon-modules, -.ui-icon-network_maps, .ui-icon-visual_console, +.ui-icon-tactical_view, +.ui-icon-events, +.ui-icon-groups, +.ui-icon-alerts, +.ui-icon-agents, +.ui-icon-modules, +.ui-icon-network_maps, +.ui-icon-visual_console, .ui-icon-dashboard { - background-color: #333 !important; - background-position: center; - border-radius: 15px !important; - -webkit-border-radius: 15px !important; + background-color: #333 !important; + background-position: center; + border-radius: 15px !important; + -webkit-border-radius: 15px !important; } #login_btn-container .ui-icon { - background-color: #333 !important; - border-radius: 15px !important; - -webkit-border-radius: 15px !important; + background-color: #333 !important; + border-radius: 15px !important; + -webkit-border-radius: 15px !important; } /* For mobiles */ -@media screen and (max-width: 750px) -{ - .ui-icon-tactical_view, .ui-icon-events, - .ui-icon-groups, .ui-icon-alerts, - .ui-icon-agents, .ui-icon-modules, - .ui-icon-network_maps, .ui-icon-visual_console, - .ui-icon-dashboard { - width: 22px !important; - height: 22px !important; - margin-top: -13px !important; - background-size: 16px 16px; - } +@media screen and (max-width: 750px) { + .ui-icon-tactical_view, + .ui-icon-events, + .ui-icon-groups, + .ui-icon-alerts, + .ui-icon-agents, + .ui-icon-modules, + .ui-icon-network_maps, + .ui-icon-visual_console, + .ui-icon-dashboard { + width: 22px !important; + height: 22px !important; + margin-top: -13px !important; + background-size: 16px 16px; + } } /* For tablets */ -@media screen and (min-width: 750px) -{ - .ui-icon-tactical_view, .ui-icon-events, - .ui-icon-groups, .ui-icon-alerts, - .ui-icon-agents, .ui-icon-modules, - .ui-icon-network_maps, .ui-icon-visual_console, - .ui-icon-dashboard { - width: 32px !important; - height: 32px !important; - margin-top: -17px !important; - } +@media screen and (min-width: 750px) { + .ui-icon-tactical_view, + .ui-icon-events, + .ui-icon-groups, + .ui-icon-alerts, + .ui-icon-agents, + .ui-icon-modules, + .ui-icon-network_maps, + .ui-icon-visual_console, + .ui-icon-dashboard { + width: 32px !important; + height: 32px !important; + margin-top: -17px !important; + } } /*END-----------Network maps styles---------------------------------------*/ #logout_dialog-button_close { - display: block; - margin: 0 auto; - margin-top: 20px; + display: block; + margin: 0 auto; + margin-top: 20px; } .ui-btn-active * { - color: #FFF !important; + color: #fff !important; } .ui-btn-active { - background: #82b92e !important; + background: #82b92e !important; } span.nobold * { - font-weight: normal; + font-weight: normal; } .events_timestamp { - font-size: 10px; - float: right; - text-align: right; - line-height: 1.1em; + font-size: 10px; + float: right; + text-align: right; + line-height: 1.1em; } .events_timestamp > img { - vertical-align: middle; - margin-left: 10px; + vertical-align: middle; + margin-left: 10px; } .events_agent { - float: left; + float: left; } .events_agent b.ui-table-cell-label { - display: block !important; + display: block !important; } -#list_Modules *, #list_agent_Modules *, #list_agents *, #list_alerts *, #list_networkmaps *, #list_visualmaps * { - color: #222; +#list_Modules *, +#list_agent_Modules *, +#list_agents *, +#list_alerts *, +#list_networkmaps *, +#list_visualmaps * { + color: #222; } -DIV.legend>DIV { - width: 100% !important; - opacity: 0.65 !important; +div.legend > div { + width: 100% !important; + opacity: 0.65 !important; } -DIV.nodata_text { - padding: 5px 12px 0px 68px; - font-weight: bold; - color: #C1C1C1; - text-transform: uppercase; - display: table-cell; - vertical-align: middle; - text-align: left; - font-size: 14px !important; +div.nodata_text { + padding: 5px 12px 0px 68px; + font-weight: bold; + color: #c1c1c1; + text-transform: uppercase; + display: table-cell; + vertical-align: middle; + text-align: left; + font-size: 14px !important; } -DIV.nodata_container { - width:150px; - height:100px; - background-repeat:no-repeat; - background-position: center; - margin: 15px auto; - display: table; +div.nodata_container { + width: 150px; + height: 100px; + background-repeat: no-repeat; + background-position: center; + margin: 15px auto; + display: table; } #free_search-container a { - margin-right: 2px; - margin-top: -12px; + margin-right: 2px; + margin-top: -12px; } #free_search-container span.ui-btn-inner { - height: 7px; + height: 7px; } .ui-icon-delete { - margin-top: -3px !important; + margin-top: -3px !important; } .empty_advice { - color: #ff0000; - margin-top: 5px !important; + color: #ff0000; + margin-top: 5px !important; } /* JQuery Mobile responsive hack to tables with */ .ui-table-reflow.ui-responsive { - display: table !important; + display: table !important; } .widget_agent_module > th { - background-color: #373737; + background-color: #373737; } #list_agent_Modules > tbody > tr > td { - clear: none; - vertical-align: middle; - padding: 0px; + clear: none; + vertical-align: middle; + padding: 0px; } -#list_agent_Modules > tbody > tr > td.cell_0 { - border-top: 0px none; +#list_agent_Modules > tbody > tr > td.cell_0 { + border-top: 0px none; } .legend_graph td.legendLabel > div { - font-size: 12px !important; + font-size: 12px !important; } .legend_graph td.legendLabel { - font-size: 12px !important; + font-size: 12px !important; } .ui-popup-hidden { - display: none; + display: none; } diff --git a/pandora_console/mobile/include/system.class.php b/pandora_console/mobile/include/system.class.php index cb365f95f1..8b79ef0139 100644 --- a/pandora_console/mobile/include/system.class.php +++ b/pandora_console/mobile/include/system.class.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,113 +10,151 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +// Singleton +class System +{ -//Singleton -class System { - private static $instance; - - private $session; - private $config; - - function __construct() { - $this->loadConfig(); - $session_id = session_id(); - DB::getInstance($this->getConfig('db_engine', 'mysql')); - if (session_status() === PHP_SESSION_NONE) session_start(); - $this->session = $_SESSION; - session_write_close(); + private static $instance; + + private $session; + + private $config; + + + function __construct() + { + $this->loadConfig(); + $session_id = session_id(); + DB::getInstance($this->getConfig('db_engine', 'mysql')); + if (session_status() === PHP_SESSION_NONE) { + session_start(); + } + + $this->session = $_SESSION; + session_write_close(); + + include_once $this->getConfig('homedir').'/include/functions.php'; + include_once $this->getConfig('homedir').'/include/functions_io.php'; + } + + + public static function getInstance() + { + if (!(self::$instance instanceof self)) { + self::$instance = new self; + } + + return self::$instance; + } + + + private function loadConfig() + { + global $config; + + $config['mobile'] = true; + + $this->config = &$config; + } + + + public function getRequest($name, $default=null) + { + return get_parameter($name, $default); + } + + + public function safeOutput($value) + { + return io_safe_output($value); + } + + + public function safeInput($value) + { + return io_safe_input($value); + } + + + public function getConfig($name, $default=null) + { + if (!isset($this->config[$name])) { + return $default; + } else { + return $this->config[$name]; + } + } + + + public function setSessionBase($name, $value) + { + if (session_status() === PHP_SESSION_NONE) { + session_start(); + } + + $_SESSION[$name] = $value; + session_write_close(); + } + + + public function setSession($name, $value) + { + $this->session[$name] = $value; + + if (session_status() === PHP_SESSION_NONE) { + session_start(); + } + + $_SESSION = $this->session; + session_write_close(); + } + + + public function getSession($name, $default=null) + { + if (!isset($this->session[$name])) { + return $default; + } else { + return $this->session[$name]; + } + } + + + public function sessionDestroy() + { + if (session_status() === PHP_SESSION_NONE) { + session_start(); + } + + session_destroy(); + } + + + public function getPageSize() + { + return 10; + } + + + public function checkACL($access='AR', $group_id=0) + { + if (check_acl($this->getConfig('id_user'), $group_id, $access)) { + return true; + } else { + db_pandora_audit( + 'ACL Violation', + 'Trying to access to Mobile Page' + ); + + return false; + } + } + + + public function getDefaultACLFailText() + { + return __('Access to this page is restricted to authorized users only, please contact your system administrator if you should need help.').'

                '.__('Please remember that any attempts to access this page will be recorded on the %s System Database.', get_product_name()); + } - require_once($this->getConfig('homedir') . '/include/functions.php'); - require_once($this->getConfig('homedir') . '/include/functions_io.php'); - } - - public static function getInstance() { - if (!(self::$instance instanceof self)) { - self::$instance = new self; - } - - return self::$instance; - } - - private function loadConfig() { - global $config; - - $config['mobile'] = true; - - $this->config = &$config; - } - - public function getRequest($name, $default = null) { - return get_parameter($name, $default); - } - - public function safeOutput($value) { - return io_safe_output($value); - } - - public function safeInput($value) { - return io_safe_input($value); - } - - public function getConfig($name, $default = null) { - if (!isset($this->config[$name])) { - return $default; - } - else { - return $this->config[$name]; - } - } - - public function setSessionBase($name, $value) { - if (session_status() === PHP_SESSION_NONE) session_start(); - $_SESSION[$name] = $value; - session_write_close(); - } - - public function setSession($name, $value) { - $this->session[$name] = $value; - - if (session_status() === PHP_SESSION_NONE) session_start(); - $_SESSION = $this->session; - session_write_close(); - } - - public function getSession($name, $default = null) { - if (!isset($this->session[$name])) { - return $default; - } - else { - return $this->session[$name]; - } - } - - public function sessionDestroy() { - if (session_status() === PHP_SESSION_NONE) session_start(); - session_destroy(); - } - - public function getPageSize() { - return 10; - } - - public function checkACL($access = "AR", $group_id = 0) { - if (check_acl($this->getConfig('id_user'), $group_id, $access)) { - return true; - } - else { - db_pandora_audit("ACL Violation", - "Trying to access to Mobile Page"); - - return false; - } - } - public function getDefaultACLFailText() { - return - __("Access to this page is restricted to authorized users only, please contact your system administrator if you should need help.") . - "

                " . - __("Please remember that any attempts to access this page will be recorded on the %s System Database.", get_product_name()) - ; - } } -?> \ No newline at end of file diff --git a/pandora_console/mobile/include/ui.class.php b/pandora_console/mobile/include/ui.class.php index 29505c8956..ff411a86e0 100755 --- a/pandora_console/mobile/include/ui.class.php +++ b/pandora_console/mobile/include/ui.class.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,694 +10,815 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +// Singleton +class Ui +{ -//Singleton -class Ui { - private static $instance; - - private $title; - private $page_name; - - private $endHeader = false; - private $header = array(); - private $endContent = false; - private $content = array(); - private $endFooter = false; - private $footer = array(); - private $form = array(); - private $grid = array(); - private $collapsible = true; - private $endForm = true; - private $endGrid = true; - private $endCollapsible = true; - private $dialogs = array(); - private $dialog = ''; - - public function __construct() { - } - - public static function getInstance() { - if (!(self::$instance instanceof self)) { - self::$instance = new self; - } - - return self::$instance; - } - - public function debug($var, $file = false) { - $more_info = ''; - if (is_string($var)) { - $more_info = 'size: ' . strlen($var); - } - elseif (is_bool($var)) { - $more_info = 'val: ' . - ($var ? 'true' : 'false'); - } - elseif (is_null($var)) { - $more_info = 'is null'; - } - elseif (is_array($var)) { - $more_info = count($var); - } - - if ($file === true) - $file = '/tmp/logDebug'; - - if (strlen($file) > 0) { - $f = fopen($file, "a"); - ob_start(); - echo date("Y/m/d H:i:s") . " (" . gettype($var) . ") " . $more_info . "\n"; - print_r($var); - echo "\n\n"; - $output = ob_get_clean(); - fprintf($f,"%s",$output); - fclose($f); - } - else { - echo "
                " .
                -				date("Y/m/d H:i:s") . " (" . gettype($var) . ") " . $more_info .
                -				"
                "; - echo "
                ";print_r($var);echo "
                "; - } - } - - public function createPage($title = null, $page_name = null) { - if (!isset($title)) { - $this->title = __('%s mobile', get_product_name()); - } - else { - $this->title = $title; - } - - if (!isset($page_name)) { - $this->page_name = 'main_page'; - } - else { - $this->page_name = $page_name; - } - - $this->html = ''; - $this->endHeader = false; - $this->header = array(); - $this->endContent = false; - $this->content = array(); - $this->noFooter = false; - $this->endFooter = false; - $this->footer = array(); - $this->form = array(); - $this->grid = array(); - $this->collapsible = array(); - $this->endForm = true; - $this->endGrid = true; - $this->endCollapsible = true; - $this->dialog = ''; - $this->dialogs = array(); - } - - public function showFooter($show = true) { - $this->noFooter = !$show; - } - - public function beginHeader() { - $this->header = array(); - $this->header['button_left'] = ''; - $this->header['button_right'] = ''; - $this->header['title'] = ''; - $this->endHeader = false; - } - - public function endHeader() { - $this->endHeader = true; - } - - public function createHeader($title = null, $buttonLeft = null, $buttonRight = null) { - $this->beginHeader(); - - $this->headerTitle($title); - $this->headerAddButtonLeft($buttonLeft); - $this->headerAddButtonRight($buttonRight); - - $this->endHeader(); - } - - public function headerTitle($title = null) { - if (isset($title)) { - $this->header['title'] = $title; - } - } - - public function headerAddButtonLeft($button = null) { - if (isset($button)) { - $this->header['button_left'] = $button; - } - } - - public function headerAddButtonRight($button = null) { - if (isset($button)) { - $this->header['button_right'] = $button; - } - } - - public function createHeaderButton($options) { - return $this->createButton($options); - } - - public function createDefaultHeader($title = false, $left_button = false) { - if ($title === false) { - $title = __('%s : Mobile', get_product_name()); - } - - if ($left_button === false) { - $left_button = $this->createHeaderButton( - array('icon' => 'back', - 'pos' => 'left', - 'text' => __('Logout'), - 'href' => 'index.php?action=logout')); - } - - $this->createHeader( - $title, - $left_button, - $this->createHeaderButton( - array('icon' => 'home', - 'pos' => 'right', - 'text' => __('Home'), - 'href' => 'index.php?page=home'))); - } - - public function createButton($options) { - $return = 'footer = array(); - $this->endFooter = false; - } - - public function endFooter() { - $this->endFooter = true; - } - - public function createFooter($text = "") { - $this->footerText($text); - } - - public function footerText($text = null) { - if (!isset($text)) { - $this->footer['text'] = ''; - } - else { - $this->footer['text'] = $text; - } - - $this->endFooter(); - } - - public function defaultFooter() { - global $pandora_version, $build_version; - - if (isset($_SERVER['REQUEST_TIME'])) { - $time = $_SERVER['REQUEST_TIME']; - } - else { - $time = get_system_time (); - } - - return ""; - } - - public function beginContent() { - $this->content = array(); - $this->endContent = false; - } - - public function endContent() { - $this->endContent = true; - } - - public function contentAddHtml($html) { - $this->content[] = $html; - } - - public function contentBeginGrid($mode = 'responsive') { - $this->endGrid = false; - - $this->grid = array(); - $this->grid['mode'] = $mode; - $this->grid['cells'] = array(); - } - - public function contentGridAddCell($html, $key = false) { - $k = uniqid('cell_'); - if ($key !== false) { - $k = $key; - } - - $this->grid['cells'][$k] = $html; - } - - public function contentEndGrid() { - $this->endGrid = true; - - //TODO Make others modes, only responsible mode - $convert_columns_jquery_grid = array( - 2 => 'a', 3 => 'b', 4 => 'c', 5 => 'd'); - $convert_cells_jquery_grid = array('a', 'b', 'c', 'd', 'e'); - - $html = "
                \n"; - - reset($convert_cells_jquery_grid); - foreach ($this->grid['cells'] as $key => $cell) { - switch ($this->grid['mode']) { - default: - case 'responsive': - $html .= "
                \n"; - break; - } - next($convert_cells_jquery_grid); - $html .= "
                \n"; - $html .= $cell; - $html .= "
                \n"; - - $html .= "
                \n"; - } - - $html .= "
                \n"; - - $this->contentAddHtml($html); - $this->grid = array(); - } - - public function contentBeginCollapsible($title = " ") { - $this->endCollapsible = false; - $this->collapsible = array(); - $this->collapsible['items'] = array(); - $this->collapsible['title'] = $title; - } - - public function contentCollapsibleAddItem($html) { - $this->collapsible['items'][] = $html; - } - - public function contentEndCollapsible() { - $this->endCollapsible = true; - - $html = "
                \n"; - $html .= "

                " . $this->collapsible['title'] . "

                \n"; - - $html .= "
                  \n"; - foreach ($this->collapsible['items'] as $item) { - $html .= "
                • " . $item . "
                • "; - } - $html .= "
                \n"; - - $html .= "
                \n"; - - - $this->contentAddHtml($html); - $this->collapsible = array(); - } - - public function beginForm($action = "index.php", $method = "post") { - $this->form = array(); - $this->endForm = false; - - $this->form['action'] = $action; - $this->form['method'] = $method; - } - - public function endForm() { - $this->contentAddHtml($this->getEndForm()); - - } - - public function getEndForm() { - $this->endForm = true; - - $html = "
                \n"; - foreach ($this->form['fields'] as $field) { - $html .= $field . "\n"; - } - $html .= "
                \n"; - - $this->form = array(); - - return $html; - } - - public function formAddHtml($html) { - $this->form['fields'][] = $html; - } - - public function formAddInput($options) { - $this->formAddHtml($this->getInput($options)); - } - - public function getInput($options) { - if (empty($options['name'])) { - $options['name'] = uniqid('input'); - } - - if (empty($options['id'])) { - $options['id'] = 'text-' . $options['name']; - } - - $html = "
                \n"; - $html .= "
                \n"; - if (!empty($options['label'])) { - $html .= "\n"; - } - - //Erase other options and only for the input - unset($options['label']); - - $html .= " $value) { - $html .= " " . $option . "='" . $value . "' "; - } - $html .= ">\n"; - - $html .= "
                \n"; - $html .= "
                \n"; - - return $html; - } - - public function formAddInputPassword($options) { - $options['type'] = 'password'; - - $this->formAddInput($options); - } - - public function formAddInputText($options) { - $options['type'] = 'text'; - - $this->formAddInput($options); - } - - public function formAddInputSearch($options) { - $options['type'] = 'search'; - - $this->formAddInput($options); - } - - public function formAddInpuDate($options) { - $options['type'] = 'date'; - $options['data-clear-btn'] = "false"; - - $this->formAddInput($options); - } - - public function formAddCheckbox($options) { - $options['type'] = 'checkbox'; - - if (isset($options['checked'])) { - if ($options['checked']) { - $options['checked'] = 'checked'; - } - else { - unset($options['checked']); - } - } - $this->formAddInput($options); - } - - public function formAddSubmitButton($options) { - $options['type'] = 'submit'; - - if (isset($options['icon'])) { - $options['data-icon'] = $options['icon']; - unset($options['icon']); - } - - if (isset($options['icon_pos'])) { - $options['data-iconpos'] = $options['icon_pos']; - unset($options['icon_pos']); - } - - if (isset($options['text'])) { - $options['value'] = $options['text']; - unset($options['text']); - } - - $this->formAddInput($options); - } - - public function formAddSelectBox($options) { - $html = ''; - - if (empty($options['name'])) { - $options['name'] = uniqid('input'); - } - - if (empty($options['id'])) { - $options['id'] = 'select-' . $options['name']; - } - - $html = "
                \n"; - $html .= "
                \n"; - if (!empty($options['label'])) { - $html .= "\n"; - } - - $html .= "\n"; - - $html .= "
                \n"; - $html .= "
                \n"; - - $this->formAddHtml($html); - } - - public function formAddSlider($options) { - $options['type'] = 'range'; - - $this->formAddInput($options); - // - } - - public function addDialog($options) { - - $type = 'hidden'; - - $dialog_id = uniqid('dialog_'); - $dialog_class = ''; - - $title_close_button = false; - $title_text = ''; - - $content_id = uniqid('content_'); - $content_class = ''; - $content_text = ''; - - $button_close = true; - $button_text = __('Close'); - - if (is_array($options)) { - if (isset($options['type'])) - $type = $options['type']; - if (isset($options['dialog_id'])) - $dialog_id = $options['dialog_id']; - if (isset($options['dialog_class'])) - $dialog_class = $options['dialog_class']; - if (isset($options['title_close_button'])) - $title_close_button = $options['title_close_button']; - if (isset($options['title_text'])) - $title_text = $options['title_text']; - if (isset($options['content_id'])) - $content_id = $options['content_id']; - if (isset($options['content_class'])) - $content_class = $options['content_class']; - if (isset($options['content_text'])) - $content_text = $options['content_text']; - if (isset($options['button_close'])) - $button_close = $options['button_close']; - if (isset($options['button_text'])) - $button_text = $options['button_text']; - } - - $html_title_close_button = ""; - if ($title_close_button) { - $html_title_close_button = "data-close-btn='yes'"; - } - - $dialogHtml = "
                \n"; - - $this->dialogs[$type][] = $dialogHtml; - } - - public function showError($msg) { - echo $msg; - } - - - public function showPage() { - if (!$this->endHeader) { - $this->showError(__('Not found header.')); - } - else if (!$this->endContent) { - $this->showError(__('Not found content.')); - } - else if ((!$this->endFooter) && (!$this->noFooter)) { - $this->showError(__('Not found footer.')); - } - else if (!$this->endForm) { - $this->showError(__('Incorrect form.')); - } - else if (!$this->endGrid) { - $this->showError(__('Incorrect grid.')); - } - else if (!$this->endCollapsible) { - $this->showError(__('Incorrect collapsible.')); - } - - ob_start (); - echo "\n"; - echo "\n"; - echo " \n"; - echo " " . $this->title . "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo " \n"; - echo " \n"; - echo "
                "; - if (!empty($this->dialogs)) { - if (!empty($this->dialogs['onStart'])) { - foreach ($this->dialogs['onStart'] as $dialog) { - echo " " . $dialog . "\n"; - } - } - } - echo "
                \n"; - echo "
                \n"; - echo "

                " . $this->header['title'] . "

                \n"; - echo " " . $this->header['button_left'] . "\n"; - echo " " . $this->header['button_right'] . "\n"; - echo "
                \n"; - echo "
                \n"; - foreach ($this->content as $content) { - echo " " . $content . "\n"; - } - echo "
                \n"; - if (!$this->noFooter) { - echo "
                \n"; - if (!empty($this->footer['text'])) { - echo " " . $this->footer['text'] . "\n"; - } - else { - echo " " . $this->defaultFooter() . "\n"; - } - } - echo "
                \n"; - echo "
                \n"; - if (!empty($this->dialogs)) { - if (!empty($this->dialogs['hidden'])) { - foreach ($this->dialogs['hidden'] as $dialog) { - echo " " . $dialog . "\n"; - } - } - } - echo "\n"; + echo " \n"; + echo " \n"; + + echo " \n"; + echo " \n"; + echo "
                "; + if (!empty($this->dialogs)) { + if (!empty($this->dialogs['onStart'])) { + foreach ($this->dialogs['onStart'] as $dialog) { + echo ' '.$dialog."\n"; + } + } + } + + echo "
                \n"; + echo "
                \n"; + echo '

                '.$this->header['title']."

                \n"; + echo ' '.$this->header['button_left']."\n"; + echo ' '.$this->header['button_right']."\n"; + echo "
                \n"; + echo "
                \n"; + foreach ($this->content as $content) { + echo ' '.$content."\n"; + } + + echo "
                \n"; + if (!$this->noFooter) { + echo "
                \n"; + if (!empty($this->footer['text'])) { + echo ' '.$this->footer['text']."\n"; + } else { + echo ' '.$this->defaultFooter()."\n"; + } + } + + echo "
                \n"; + echo "
                \n"; + if (!empty($this->dialogs)) { + if (!empty($this->dialogs['hidden'])) { + foreach ($this->dialogs['hidden'] as $dialog) { + echo ' '.$dialog."\n"; + } + } + } + + echo ""; - echo " \n"; - echo ""; - ob_end_flush(); - } - - // Add a listener to set a link when a row of a table is clicked. - // The target link will be the first tag found into the row - public function contentAddLinkListener ($table_name) { - $this->contentAddHtml(""); - } - - // - // + ' + ); + } + + } +class Table +{ + + private $head = []; + + private $rows = []; + + public $id = ''; + + private $rowClass = []; + + private $class_table = ''; + + private $row_heads = []; + + public $row_keys_as_head_row = false; + + + public function __construct() + { + $this->init(); + } + + + public function init() + { + $this->id = uniqid(); + $this->head = []; + $this->rows = []; + $this->rowClass = []; + $this->class_table = ''; + $this->row_heads = []; + $this->row_keys_as_head_row = false; + } + + + public function addHeader($head) + { + $this->head = $head; + } + + + public function addRowHead($key, $head_text) + { + $this->row_heads[$key] = $head_text; + } + + + public function addRow($row=[], $key=false) + { + if ($key !== false) { + $this->rows[$key] = $row; + } else { + $this->rows[] = $row; + } + } + + + public function importFromHash($data) + { + foreach ($data as $id => $row) { + $table_row = []; + foreach ($row as $key => $value) { + if (!in_array($key, $this->head)) { + $this->head[] = $key; + } + + $cell_key = array_search($key, $this->head); + + $table_row[$cell_key] = $value; + } + + $this->rows[$id] = $table_row; + } + } + + + public function importFromHashEvents($data) + { + foreach ($data as $id => $row) { + $table_row = []; + + foreach ($row as $key => $value) { + if (!in_array($key, $this->head)) { + // $this->head[] = $key; + } + + // $cell_key = array_search($key, $this->head); + // $table_row[$cell_key] = $value; + $table_row[$key] = $value; + } + + $this->rows[$id] = $table_row; + } + } + + + public function setClass($class='') + { + $this->class_table = $class; + } + + + public function setId($id=false) + { + if (empty($id)) { + $this->id = uniqid(); + } else { + $this->id = $id; + } + } + + + public function setRowClass($class='', $pos=false) + { + if (is_array($class)) { + $this->rowClass = $class; + } else { + if ($pos !== false) { + $this->rowClass[$pos] = $class; + } else { + $this->rowClass = array_fill(0, count($this->rows), $class); + } + } + } + + + public function getHTML() + { + $html = ''; + + $html = ""; + + if ($this->head) { + $html .= ''; + $html .= ''; + // Empty head for white space between rows in the responsive vertical layout + // ~ $html .= ""; + foreach ($this->head as $head) { + $html .= "'; + } + + $html .= ''; + $html .= ''; + } + + $html .= ''; + foreach ($this->rows as $key => $row) { + $class = ''; + if (isset($this->rowClass[$key])) { + $class = $this->rowClass[$key]; + } + + $html .= ""; + // Empty head for white space between rows in the responsive vertical layout + foreach ($row as $key_cell => $cell) { + $html .= "'; + } + + $html .= ''; + } + + $html .= ''; + $html .= '
                ".$head.'
                ".$cell.'
                '; + + return $html; + } + -class Table { - private $head = array(); - private $rows = array(); - public $id = ''; - private $rowClass = array(); - private $class_table = ''; - private $row_heads = array(); - public $row_keys_as_head_row = false; - - public function __construct() { - $this->init(); - } - - public function init() { - $this->id = uniqid(); - $this->head = array(); - $this->rows = array(); - $this->rowClass = array(); - $this->class_table = ''; - $this->row_heads = array(); - $this->row_keys_as_head_row = false; - } - - public function addHeader($head) { - $this->head = $head; - } - - public function addRowHead($key, $head_text) { - $this->row_heads[$key] = $head_text; - } - - public function addRow($row = array(), $key = false) { - if ($key !== false) { - $this->rows[$key] = $row; - } - else { - $this->rows[] = $row; - } - } - - public function importFromHash($data) { - foreach ($data as $id => $row) { - $table_row = array(); - foreach ($row as $key => $value) { - - if (!in_array($key, $this->head)) { - $this->head[] = $key; - } - - $cell_key = array_search($key, $this->head); - - $table_row[$cell_key] = $value; - } - - $this->rows[$id] = $table_row; - } - } - - public function importFromHashEvents($data) { - foreach ($data as $id => $row) { - $table_row = array(); - - foreach ($row as $key => $value) { - if (!in_array($key, $this->head)) { - //$this->head[] = $key; - } - - //$cell_key = array_search($key, $this->head); - - //$table_row[$cell_key] = $value; - $table_row[$key] = $value; - } - - $this->rows[$id] = $table_row; - } - } - - public function setClass($class = '') { - $this->class_table = $class; - } - - public function setId($id = false) { - if (empty($id)) { - $this->id = uniqid(); - } - else { - $this->id = $id; - } - } - - public function setRowClass($class = '', $pos = false) { - if (is_array($class)) { - $this->rowClass = $class; - } - else { - if ($pos !== false) { - $this->rowClass[$pos] = $class; - } - else { - $this->rowClass = array_fill(0, count($this->rows), $class); - } - } - } - - public function getHTML() { - $html = ''; - - $html = ""; - - - if ($this->head) { - $html .= ""; - $html .= ""; - //Empty head for white space between rows in the responsive vertical layout - //~ $html .= ""; - foreach ($this->head as $head) { - $html .= ""; - } - $html .= ""; - $html .= ""; - } - - $html .= ""; - foreach ($this->rows as $key => $row) { - $class = ''; - if (isset($this->rowClass[$key])) { - $class = $this->rowClass[$key]; - } - - $html .= ""; - //Empty head for white space between rows in the responsive vertical layout - - foreach ($row as $key_cell => $cell) { - $html .= ""; - } - - $html .= ""; - } - - $html .= ""; - $html .= "
                " . $head . "
                " . $cell . "
                "; - - return $html; - } } - -?> diff --git a/pandora_console/mobile/include/user.class.php b/pandora_console/mobile/include/user.class.php index d3793beff0..61267f2023 100644 --- a/pandora_console/mobile/include/user.class.php +++ b/pandora_console/mobile/include/user.class.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,323 +10,380 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +// Singleton +class User +{ -//Singleton -class User { - private static $instance; - - private $user; - private $logged = false; - private $errorLogin = false; - private $loginTime = false; - private $logout_action = false; - private $needDoubleAuth = false; - private $errorDoubleAuth = false; - - public static function getInstance () { - if (!(self::$instance instanceof self)) { - //Check if in the session - $system = System::getInstance(); - $user = $system->getSession('user', null); - - if (!empty($user)) { - self::$instance = $user; - } - else { - self::$instance = new self(); - } - } - return self::$instance; - } - - public function saveLogin () { - - if ($this->logged) { - $system = System::getInstance(); - - //hack to compatibility with pandora - global $config; - $config['id_user'] = $this->user; - - $system->setSessionBase('id_usuario', $this->user); - $system->setSession('user', $this); + private static $instance; - config_user_set_custom_config(); - } - } - - public function isLogged () { - $system = System::getInstance(); - - $autologin = $system->getRequest('autologin', false); - if ($autologin) { - $user = $system->getRequest('user', null); - $password = $system->getRequest('password', null); - - $this->login($user, $password); - } - - return $this->logged; - } + private $user; - public function login ($user = null, $password = null) { - $system = System::getInstance(); - - if (($user == null) && ($password == null)) { - $user = $system->getRequest('user', null); - $password = $system->getRequest('password', null); - } - - if (!empty($user) && !empty($password)) { - $user_in_db = process_user_login($user, $password); - if ($user_in_db !== false) { - - $this->logged = true; - $this->user = $user_in_db; - $this->loginTime = time(); - $this->errorLogin = false; + private $logged = false; - // The user login was successful, but the second step is not completed - if ($this->isDobleAuthRequired()) { - $this->needDoubleAuth = true; - } - } - else { - - $this->logged = false; - $this->loginTime = false; - $this->errorLogin = true; - $this->needDoubleAuth = false; - $this->errorDoubleAuth = false; - } - } - - $this->saveLogin(); - - return $this->logged; - } + private $errorLogin = false; - public function getLoginTime () { - return $this->loginTime; - } - - public function isWaitingDoubleAuth () { - return $this->needDoubleAuth; - } - - public function isDobleAuthRequired ($user = false) { - if (empty($user) && !empty($this->user)) - $user = $this->user; + private $loginTime = false; - if (!empty($user)) - return (bool) db_get_value('id', 'tuser_double_auth', 'id_user', $user); - else - return false; - } + private $logout_action = false; - public function validateDoubleAuthCode ($user = null, $code = null) { + private $needDoubleAuth = false; - if (!$this->needDoubleAuth) { - return true; - } + private $errorDoubleAuth = false; - $system = System::getInstance(); - require_once ($system->getConfig('homedir').'/include/auth/GAuth/Auth.php'); - $result = false; + public static function getInstance() + { + if (!(self::$instance instanceof self)) { + // Check if in the session + $system = System::getInstance(); + $user = $system->getSession('user', null); - if (empty($user)) { - $user = $this->user; - } - if (empty($code)) { - $code = $system->getRequest('auth_code', null); - $code = $system->safeOutput($code); - } + if (!empty($user)) { + self::$instance = $user; + } else { + self::$instance = new self(); + } + } - if (!empty($user) && !empty($code)) { - $secret = db_get_value('secret', 'tuser_double_auth', 'id_user', $user); + return self::$instance; + } - if ($secret === false) { - $result = false; - $this->errorDoubleAuth = array( - 'title_text' => __('Double authentication failed'), - 'content_text' => __('Secret code not found') .". " - .__('Please contact the administrator to reset your double authentication') - ); - } - else if (!empty($secret)) { - try { - $gAuth = new \GAuth\Auth($secret); - $result = $gAuth->validateCode($code); - // Double auth success - if ($result) { - $this->needDoubleAuth = false; - $this->saveLogin(); - } - else { - $result = false; - $this->errorDoubleAuth = array( - 'title_text' => __('Double authentication failed'), - 'content_text' => __('Invalid code') - ); - } - } catch (Exception $e) { - $result = false; - $this->errorDoubleAuth = array( - 'title_text' => __('Double authentication failed'), - 'content_text' => __('There was an error checking the code') - ); - } - } - } - - return $result; - } - - public function logout () { - $this->user = null; - $this->logged = false; - $this->loginTime = false; - $this->errorLogin = false; - $this->logout_action = true; - $this->needDoubleAuth = false; - $this->errorDoubleAuth = false; + public function saveLogin() + { + if ($this->logged) { + $system = System::getInstance(); - $system = System::getInstance(); - $system->setSession('user', null); - $system->sessionDestroy(); - } - - public function showLoginPage () { - global $pandora_version; - - $ui = Ui::getInstance(); - $system = System::getInstance(); - - $ui->createPage(); - if ($this->errorLogin) { - - $options['type'] = 'onStart'; - $options['title_text'] = __('Login Failed'); - $options['content_text'] = __('User not found in database or incorrect password.'); - $ui->addDialog($options); - - } - if ($this->logout_action) { - - $options['dialog_id'] = 'logout_dialog'; - $options['type'] = 'onStart'; - $options['title_text'] = __('Login out'); - $options['content_text'] = __('Your session has ended. Please close your browser window to close this %s session.', get_product_name()); - $ui->addDialog($options); - - } - $ui->createHeader(); - $ui->showFooter(false); - $ui->beginContent(); - - $logo_image = html_print_image (ui_get_mobile_login_icon(), - true, array ("alt" => "logo", "border" => 0), false, false, false, true); - - $ui->contentAddHtml(''); - $ui->contentAddHtml('
                '); - $ui->beginForm(''); - $ui->formAddHtml(html_print_input_hidden('action', 'login', true)); - $options = array( - 'name' => 'user', - 'value' => $this->user, - 'placeholder' => __('user'), - 'label' => __('User') - ); - $ui->formAddInputText($options); - $options = array( - 'name' => 'password', - 'value' => '', - 'placeholder' => __('password'), - 'label' => __('Password') - ); - $ui->formAddInputPassword($options); - $options = array( - 'value' => __('Login'), - 'icon' => 'arrow-r', - 'icon_pos' => 'right', - 'name' => 'login_btn' - ); - $ui->formAddSubmitButton($options); - $ui->endForm(); - $ui->contentAddHtml('
                '); - $ui->endContent(); - $ui->showPage(); - - $this->errorLogin = false; - $this->logout_action = false; - } + // hack to compatibility with pandora + global $config; + $config['id_user'] = $this->user; + + $system->setSessionBase('id_usuario', $this->user); + $system->setSession('user', $this); + + config_user_set_custom_config(); + } + } + + + public function isLogged() + { + $system = System::getInstance(); + + $autologin = $system->getRequest('autologin', false); + if ($autologin) { + $user = $system->getRequest('user', null); + $password = $system->getRequest('password', null); + + $this->login($user, $password); + } + + return $this->logged; + } + + + public function login($user=null, $password=null) + { + $system = System::getInstance(); + + if (($user == null) && ($password == null)) { + $user = $system->getRequest('user', null); + $password = $system->getRequest('password', null); + } + + if (!empty($user) && !empty($password)) { + $user_in_db = process_user_login($user, $password); + if ($user_in_db !== false) { + $this->logged = true; + $this->user = $user_in_db; + $this->loginTime = time(); + $this->errorLogin = false; + + // The user login was successful, but the second step is not completed + if ($this->isDobleAuthRequired()) { + $this->needDoubleAuth = true; + } + } else { + $this->logged = false; + $this->loginTime = false; + $this->errorLogin = true; + $this->needDoubleAuth = false; + $this->errorDoubleAuth = false; + } + } + + $this->saveLogin(); + + return $this->logged; + } + + + public function getLoginTime() + { + return $this->loginTime; + } + + + public function isWaitingDoubleAuth() + { + return $this->needDoubleAuth; + } + + + public function isDobleAuthRequired($user=false) + { + if (empty($user) && !empty($this->user)) { + $user = $this->user; + } + + if (!empty($user)) { + return (bool) db_get_value('id', 'tuser_double_auth', 'id_user', $user); + } else { + return false; + } + } + + + public function validateDoubleAuthCode($user=null, $code=null) + { + if (!$this->needDoubleAuth) { + return true; + } + + $system = System::getInstance(); + include_once $system->getConfig('homedir').'/include/auth/GAuth/Auth.php'; + + $result = false; + + if (empty($user)) { + $user = $this->user; + } + + if (empty($code)) { + $code = $system->getRequest('auth_code', null); + $code = $system->safeOutput($code); + } + + if (!empty($user) && !empty($code)) { + $secret = db_get_value('secret', 'tuser_double_auth', 'id_user', $user); + + if ($secret === false) { + $result = false; + $this->errorDoubleAuth = [ + 'title_text' => __('Double authentication failed'), + 'content_text' => __('Secret code not found').'. '.__('Please contact the administrator to reset your double authentication'), + ]; + } else if (!empty($secret)) { + try { + $gAuth = new \GAuth\Auth($secret); + $result = $gAuth->validateCode($code); + + // Double auth success + if ($result) { + $this->needDoubleAuth = false; + $this->saveLogin(); + } else { + $result = false; + $this->errorDoubleAuth = [ + 'title_text' => __('Double authentication failed'), + 'content_text' => __('Invalid code'), + ]; + } + } catch (Exception $e) { + $result = false; + $this->errorDoubleAuth = [ + 'title_text' => __('Double authentication failed'), + 'content_text' => __('There was an error checking the code'), + ]; + } + } + } + + return $result; + } + + + public function logout() + { + $this->user = null; + $this->logged = false; + $this->loginTime = false; + $this->errorLogin = false; + $this->logout_action = true; + $this->needDoubleAuth = false; + $this->errorDoubleAuth = false; + + $system = System::getInstance(); + $system->setSession('user', null); + $system->sessionDestroy(); + } + + + public function showLoginPage() + { + global $pandora_version; + + $ui = Ui::getInstance(); + $system = System::getInstance(); + + $ui->createPage(); + if ($this->errorLogin) { + $options['type'] = 'onStart'; + $options['title_text'] = __('Login Failed'); + $options['content_text'] = __('User not found in database or incorrect password.'); + $ui->addDialog($options); + } + + if ($this->logout_action) { + $options['dialog_id'] = 'logout_dialog'; + $options['type'] = 'onStart'; + $options['title_text'] = __('Login out'); + $options['content_text'] = __('Your session has ended. Please close your browser window to close this %s session.', get_product_name()); + $ui->addDialog($options); + } + + $ui->createHeader(); + $ui->showFooter(false); + $ui->beginContent(); + + $logo_image = html_print_image( + ui_get_mobile_login_icon(), + true, + [ + 'alt' => 'logo', + 'border' => 0, + ], + false, + false, + false, + true + ); + + $ui->contentAddHtml( + '' + ); + $ui->contentAddHtml('
                '); + $ui->beginForm(''); + $ui->formAddHtml(html_print_input_hidden('action', 'login', true)); + $options = [ + 'name' => 'user', + 'value' => $this->user, + 'placeholder' => __('user'), + 'label' => __('User'), + ]; + $ui->formAddInputText($options); + $options = [ + 'name' => 'password', + 'value' => '', + 'placeholder' => __('password'), + 'label' => __('Password'), + ]; + $ui->formAddInputPassword($options); + $options = [ + 'value' => __('Login'), + 'icon' => 'arrow-r', + 'icon_pos' => 'right', + 'name' => 'login_btn', + ]; + $ui->formAddSubmitButton($options); + $ui->endForm(); + $ui->contentAddHtml('
                '); + $ui->endContent(); + $ui->showPage(); + + $this->errorLogin = false; + $this->logout_action = false; + } + + + public function showDoubleAuthPage() + { + global $pandora_version; + + $ui = Ui::getInstance(); + + $ui->createPage(); + if (!empty($this->errorDoubleAuth)) { + $options['type'] = 'onStart'; + $options['title_text'] = $this->errorDoubleAuth['title_text']; + $options['content_text'] = $this->errorDoubleAuth['content_text'].'
                '; + $ui->addDialog($options); + } + + $left_button = $ui->createHeaderButton( + [ + 'icon' => 'back', + 'pos' => 'left', + 'text' => __('Logout'), + 'href' => 'index.php?action=logout', + ] + ); + $ui->createHeader('', $left_button); + $ui->showFooter(false); + $ui->beginContent(); + $ui->contentAddHtml( + '' + ); + $ui->contentAddHtml('
                '); + $ui->beginForm(); + $ui->formAddHtml(html_print_input_hidden('action', 'double_auth', true)); + $options = [ + 'name' => 'auth_code', + 'value' => '', + 'placeholder' => __('Authenticator code'), + 'label' => __('Authenticator code'), + ]; + $ui->formAddInputPassword($options); + $options = [ + 'value' => __('Check code'), + 'icon' => 'arrow-r', + 'icon_pos' => 'right', + 'name' => 'auth_code_btn', + ]; + $ui->formAddSubmitButton($options); + $ui->endForm(); + $ui->contentAddHtml('
                '); + $ui->endContent(); + $ui->showPage(); + + $this->errorDoubleAuth = false; + } + + + public function getIdUser() + { + return $this->user; + // Oldies methods + } + + + public function isInGroup($access='AR', $id_group=0, $name_group=false) + { + return (bool) check_acl($this->user, $id_group, $access); + } + + + public function getIdGroups($access='AR', $all=false) + { + return array_keys(users_get_groups($this->user, $access, $all)); + } + + + public function getInfo() + { + return users_get_user_by_id($this->user); + } - public function showDoubleAuthPage () { - global $pandora_version; - - $ui = Ui::getInstance(); - - $ui->createPage(); - if (!empty($this->errorDoubleAuth)) { - $options['type'] = 'onStart'; - $options['title_text'] = $this->errorDoubleAuth['title_text']; - $options['content_text'] = $this->errorDoubleAuth['content_text'] . "
                "; - $ui->addDialog($options); - } - $left_button = $ui->createHeaderButton( - array('icon' => 'back', - 'pos' => 'left', - 'text' => __('Logout'), - 'href' => 'index.php?action=logout')); - $ui->createHeader('', $left_button); - $ui->showFooter(false); - $ui->beginContent(); - $ui->contentAddHtml(''); - $ui->contentAddHtml('
                '); - $ui->beginForm(); - $ui->formAddHtml(html_print_input_hidden('action', 'double_auth', true)); - $options = array( - 'name' => 'auth_code', - 'value' => '', - 'placeholder' => __('Authenticator code'), - 'label' => __('Authenticator code') - ); - $ui->formAddInputPassword($options); - $options = array( - 'value' => __('Check code'), - 'icon' => 'arrow-r', - 'icon_pos' => 'right', - 'name' => 'auth_code_btn' - ); - $ui->formAddSubmitButton($options); - $ui->endForm(); - $ui->contentAddHtml('
                '); - $ui->endContent(); - $ui->showPage(); - - $this->errorDoubleAuth = false; - } - public function getIdUser () { - return $this->user; //Oldies methods - } - - public function isInGroup ($access = "AR", $id_group = 0, $name_group = false) { - return (bool)check_acl($this->user, $id_group, $access); - } - - public function getIdGroups ($access = "AR", $all = false) { - return array_keys(users_get_groups($this->user, $access, $all)); - } - - public function getInfo () { - return users_get_user_by_id($this->user); - } } -?> diff --git a/pandora_console/mobile/index.php b/pandora_console/mobile/index.php index 8b0a4f28a2..e80b744823 100644 --- a/pandora_console/mobile/index.php +++ b/pandora_console/mobile/index.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,21 +10,21 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -//Set character encoding to UTF-8 - fixes a lot of multibyte character -//headaches -if (function_exists ('mb_internal_encoding')) { - mb_internal_encoding ("UTF-8"); +// Set character encoding to UTF-8 - fixes a lot of multibyte character +// headaches +if (function_exists('mb_internal_encoding')) { + mb_internal_encoding('UTF-8'); } $develop_bypass = 0; -require_once("include/ui.class.php"); -require_once("include/system.class.php"); -require_once("include/db.class.php"); -require_once("include/user.class.php"); +require_once 'include/ui.class.php'; +require_once 'include/system.class.php'; +require_once 'include/db.class.php'; +require_once 'include/user.class.php'; -/* Info: +/* + Info: * The classes above doesn't start any session before it's properly * configured into the file below, but it's important the classes * exist at the time the session is started for things like @@ -33,56 +32,60 @@ require_once("include/user.class.php"); */ require_once '../include/config.php'; -require_once('operation/home.php'); -require_once('operation/tactical.php'); -require_once('operation/groups.php'); -require_once('operation/events.php'); -require_once('operation/alerts.php'); -require_once('operation/agents.php'); -require_once('operation/modules.php'); -require_once('operation/module_graph.php'); -require_once('operation/agent.php'); -require_once('operation/visualmaps.php'); -require_once('operation/visualmap.php'); +require_once 'operation/home.php'; +require_once 'operation/tactical.php'; +require_once 'operation/groups.php'; +require_once 'operation/events.php'; +require_once 'operation/alerts.php'; +require_once 'operation/agents.php'; +require_once 'operation/modules.php'; +require_once 'operation/module_graph.php'; +require_once 'operation/agent.php'; +require_once 'operation/visualmaps.php'; +require_once 'operation/visualmap.php'; $enterpriseHook = enterprise_include('mobile/include/enterprise.class.php'); $enterpriseHook = enterprise_include('mobile/operation/dashboard.php'); $enterpriseHook = enterprise_include('mobile/operation/home.php'); -$is_mobile=true; +$is_mobile = true; -if (!empty ($config["https"]) && empty ($_SERVER['HTTPS'])) { - $query = ''; - if (sizeof ($_REQUEST)) - //Some (old) browsers don't like the ?&key=var - $query .= 'mobile/index.php?1=1'; - - //We don't clean these variables up as they're only being passed along - foreach ($_GET as $key => $value) { - if ($key == 1) - continue; - $query .= '&'.$key.'='.$value; - } - foreach ($_POST as $key => $value) { - $query .= '&'.$key.'='.$value; - } - $url = ui_get_full_url($query); - - // Prevent HTTP response splitting attacks - // http://en.wikipedia.org/wiki/HTTP_response_splitting - $url = str_replace ("\n", "", $url); - header ('Location: '.$url); - exit; //Always exit after sending location headers +if (!empty($config['https']) && empty($_SERVER['HTTPS'])) { + $query = ''; + if (sizeof($_REQUEST)) { + // Some (old) browsers don't like the ?&key=var + $query .= 'mobile/index.php?1=1'; + } + + // We don't clean these variables up as they're only being passed along + foreach ($_GET as $key => $value) { + if ($key == 1) { + continue; + } + + $query .= '&'.$key.'='.$value; + } + + foreach ($_POST as $key => $value) { + $query .= '&'.$key.'='.$value; + } + + $url = ui_get_full_url($query); + + // Prevent HTTP response splitting attacks + // http://en.wikipedia.org/wiki/HTTP_response_splitting + $url = str_replace("\n", '', $url); + header('Location: '.$url); + exit; + // Always exit after sending location headers } $system = System::getInstance(); -//~ In this moment doesn't work the version mobile when have metaconsole version. -//~ In the future versions of pandora maybe is added a mobile version of PandoraFMS Metaconsole version. -//~ if ($system->getConfig('metaconsole')) - //~ header ("Location: " . $system->getConfig('homeurl') . "enterprise/meta"); - - -require_once($system->getConfig('homedir').'/include/constants.php'); +// ~ In this moment doesn't work the version mobile when have metaconsole version. +// ~ In the future versions of pandora maybe is added a mobile version of PandoraFMS Metaconsole version. +// ~ if ($system->getConfig('metaconsole')) + // ~ header ("Location: " . $system->getConfig('homeurl') . "enterprise/meta"); +require_once $system->getConfig('homedir').'/include/constants.php'; $user = User::getInstance(); $user->saveLogin(); @@ -93,286 +96,306 @@ $action = $system->getRequest('action'); // The logout action has priority if ($action != 'logout') { - if (!$user->isLogged()) { - $action = 'login'; - } - else if ($user->isWaitingDoubleAuth()) { - $dauth_period = SECONDS_2MINUTES; - $now = time(); - $dauth_time = $user->getLoginTime(); + if (!$user->isLogged()) { + $action = 'login'; + } else if ($user->isWaitingDoubleAuth()) { + $dauth_period = SECONDS_2MINUTES; + $now = time(); + $dauth_time = $user->getLoginTime(); - if ($now - $dauth_period < $dauth_time) { - $action = 'double_auth'; - } - // Expired login - else { - $action = 'logout'; - } - } + if (($now - $dauth_period) < $dauth_time) { + $action = 'double_auth'; + } + // Expired login + else { + $action = 'logout'; + } + } } -if ($action != "ajax") { - $user_language = get_user_language ($system->getConfig('id_user')); - if (file_exists ('../include/languages/'.$user_language.'.mo')) { - $l10n = new gettext_reader (new CachedFileReader('../include/languages/'.$user_language.'.mo')); - $l10n->load_tables(); - } +if ($action != 'ajax') { + $user_language = get_user_language($system->getConfig('id_user')); + if (file_exists('../include/languages/'.$user_language.'.mo')) { + $l10n = new gettext_reader(new CachedFileReader('../include/languages/'.$user_language.'.mo')); + $l10n->load_tables(); + } } if ($user->isLogged()) { - - if (file_exists ("../enterprise/load_enterprise.php")) { - include_once ("../enterprise/load_enterprise.php"); - } + if (file_exists('../enterprise/load_enterprise.php')) { + include_once '../enterprise/load_enterprise.php'; + } } switch ($action) { - case 'ajax': - $parameter1 = $system->getRequest('parameter1', false); - $parameter2 = $system->getRequest('parameter2', false); + case 'ajax': + $parameter1 = $system->getRequest('parameter1', false); + $parameter2 = $system->getRequest('parameter2', false); - if (class_exists("Enterprise")) { - $enterprise = Enterprise::getInstance(); + if (class_exists('Enterprise')) { + $enterprise = Enterprise::getInstance(); - $permission = $enterprise->checkEnterpriseACL($parameter1); + $permission = $enterprise->checkEnterpriseACL($parameter1); - if (!$permission) { - return false; - } - } - - switch ($parameter1) { - case 'events': - $events = new Events(); - $events->ajax($parameter2); - break; - case 'agents': - $agents = new Agents(); - $agents->ajax($parameter2); - break; - case 'agent': - $agent = new Agent(); - $agent->ajax($parameter2); - break; - case 'modules': - $modules = new Modules(); - $modules->ajax($parameter2); - break; - case 'module_graph': - $module_graph = new ModuleGraph(); - $module_graph->ajax($parameter2); - break; - case 'visualmap': - $visualmap = new Visualmap(); - $visualmap->ajax($parameter2); - case 'tactical': - $tactical = new Tactical(); - $tactical->ajax($parameter2); - break; - default: - if (class_exists("Enterprise")) { - $enterprise->enterpriseAjax($parameter1, $parameter2); - } - break; - } - return; - break; - case 'login': - if ($user->login() && $user->isLogged()) { + if (!$permission) { + return false; + } + } - if (file_exists ("../enterprise/load_enterprise.php")) { - include_once ("../enterprise/load_enterprise.php"); - } - - if ($user->isWaitingDoubleAuth()) { - if ($user->validateDoubleAuthCode()) { - // Logged. Refresh the page - header('Location: .'); - return; - } - else { - $user->showDoubleAuthPage(); - } - } - else { - // Logged. Refresh the page - header('Location: .'); - return; - } + switch ($parameter1) { + case 'events': + $events = new Events(); + $events->ajax($parameter2); + break; - } - else { - $user->showLoginPage(); - } - break; - case 'double_auth': - if ($user->isLogged()) { + case 'agents': + $agents = new Agents(); + $agents->ajax($parameter2); + break; - if (file_exists ("../enterprise/load_enterprise.php")) { - include_once ("../enterprise/load_enterprise.php"); - } + case 'agent': + $agent = new Agent(); + $agent->ajax($parameter2); + break; + + case 'modules': + $modules = new Modules(); + $modules->ajax($parameter2); + break; + + case 'module_graph': + $module_graph = new ModuleGraph(); + $module_graph->ajax($parameter2); + break; + + case 'visualmap': + $visualmap = new Visualmap(); + $visualmap->ajax($parameter2); + case 'tactical': + $tactical = new Tactical(); + $tactical->ajax($parameter2); + break; + + default: + if (class_exists('Enterprise')) { + $enterprise->enterpriseAjax($parameter1, $parameter2); + } + break; + } + return; + + break; + case 'login': + if ($user->login() && $user->isLogged()) { + if (file_exists('../enterprise/load_enterprise.php')) { + include_once '../enterprise/load_enterprise.php'; + } + + if ($user->isWaitingDoubleAuth()) { + if ($user->validateDoubleAuthCode()) { + // Logged. Refresh the page + header('Location: .'); + return; + } else { + $user->showDoubleAuthPage(); + } + } else { + // Logged. Refresh the page + header('Location: .'); + return; + } + } else { + $user->showLoginPage(); + } + break; + + case 'double_auth': + if ($user->isLogged()) { + if (file_exists('../enterprise/load_enterprise.php')) { + include_once '../enterprise/load_enterprise.php'; + } - if ($user->validateDoubleAuthCode()) { - $user_language = get_user_language ($system->getConfig('id_user')); - if (file_exists ('../include/languages/'.$user_language.'.mo')) { - $l10n = new gettext_reader (new CachedFileReader('../include/languages/'.$user_language.'.mo')); - $l10n->load_tables(); - } - - if($_GET['page'] != ''){ - header('refresh:0; url=http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); - } - - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show(); - } - else { - $user->showDoubleAuthPage(); - } - } - else { - $user->showLoginPage(); - } - break; - case 'logout': - $user->logout(); - $user->showLoginPage(); - break; - default: - if (class_exists("Enterprise")) { - $enterprise = Enterprise::getInstance(); - if (!empty($page) && $page != $default_page) { - $permission = $enterprise->checkEnterpriseACL($page); + if ($user->validateDoubleAuthCode()) { + $user_language = get_user_language($system->getConfig('id_user')); + if (file_exists('../include/languages/'.$user_language.'.mo')) { + $l10n = new gettext_reader(new CachedFileReader('../include/languages/'.$user_language.'.mo')); + $l10n->load_tables(); + } - if (!$permission) { - $error['type'] = 'onStart'; - $error['title_text'] = __('You don\'t have access to this page'); - $error['content_text'] = System::getDefaultACLFailText(); - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show($error); + if ($_GET['page'] != '') { + header('refresh:0; url=http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); + } - return; - } - } - } - - if (empty($page)) { - $user_info = $user->getInfo(); - $home_page = $system->safeOutput($user_info['section']); - $section_data = $user_info['data_section']; + if (class_exists('HomeEnterprise')) { + $home = new HomeEnterprise(); + } else { + $home = new Home(); + } - switch ($home_page) { - case 'Event list': - $page = 'events'; - break; - case 'Group view': - break; - case 'Alert detail': - $page = 'alerts'; - break; - case 'Tactical view': - $page = 'tactical'; - break; - case 'Dashboard': - $page = 'dashboard'; - $id_dashboard = (int) db_get_value('id', 'tdashboard', 'name', $section_data); - $_GET['id_dashboard'] = $id_dashboard; - break; - case 'Visual console': - $page = 'visualmap'; - $id_map = (int) db_get_value('id', 'tlayout', 'name', $section_data); - $_GET['id'] = $id_map; - break; - } - } + $home->show(); + } else { + $user->showDoubleAuthPage(); + } + } else { + $user->showLoginPage(); + } + break; - switch ($page) { - case 'home': - default: - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show(); - break; - case 'tactical': - $tactical = new Tactical(); - $tactical->show(); - break; - case 'groups': - $groups = new Groups(); - $groups->show(); - break; - case 'events': - $events = new Events(); - $events->show(); - break; - case 'alerts': - $alerts = new Alerts(); - $alerts->show(); - break; - case 'agents': - $agents = new Agents(); - $agents->show(); - break; - case 'modules': - $modules = new Modules(); - $modules->show(); - break; - case 'module_graph': - $module_graph = new ModuleGraph(); - $module_graph->show(); - break; - case 'agent': - $agent = new Agent(); - $agent->show(); - break; - case 'visualmaps': - $visualmaps = new Visualmaps(); - $visualmaps->show(); - break; - case 'visualmap': - $visualmap = new Visualmap(); - $visualmap->show(); - break; - case 'dashboard_list': - if (class_exists("Dashboards")) { - $dashboard = new Dashboards(); - $dashboard->showDashboards(); - } - else { - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show(); - } - break; - case 'dashboard': - if (class_exists("Dashboards")) { - $dashboard = new Dashboards(); - $dashboard->show(); - } - else { - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show(); - } - break; - } - break; + case 'logout': + $user->logout(); + $user->showLoginPage(); + break; + + default: + if (class_exists('Enterprise')) { + $enterprise = Enterprise::getInstance(); + if (!empty($page) && $page != $default_page) { + $permission = $enterprise->checkEnterpriseACL($page); + + if (!$permission) { + $error['type'] = 'onStart'; + $error['title_text'] = __('You don\'t have access to this page'); + $error['content_text'] = System::getDefaultACLFailText(); + if (class_exists('HomeEnterprise')) { + $home = new HomeEnterprise(); + } else { + $home = new Home(); + } + + $home->show($error); + + return; + } + } + } + + if (empty($page)) { + $user_info = $user->getInfo(); + $home_page = $system->safeOutput($user_info['section']); + $section_data = $user_info['data_section']; + + switch ($home_page) { + case 'Event list': + $page = 'events'; + break; + + case 'Group view': + break; + + case 'Alert detail': + $page = 'alerts'; + break; + + case 'Tactical view': + $page = 'tactical'; + break; + + case 'Dashboard': + $page = 'dashboard'; + $id_dashboard = (int) db_get_value('id', 'tdashboard', 'name', $section_data); + $_GET['id_dashboard'] = $id_dashboard; + break; + + case 'Visual console': + $page = 'visualmap'; + $id_map = (int) db_get_value('id', 'tlayout', 'name', $section_data); + $_GET['id'] = $id_map; + break; + } + } + + switch ($page) { + case 'home': + default: + if (class_exists('HomeEnterprise')) { + $home = new HomeEnterprise(); + } else { + $home = new Home(); + } + + $home->show(); + break; + + case 'tactical': + $tactical = new Tactical(); + $tactical->show(); + break; + + case 'groups': + $groups = new Groups(); + $groups->show(); + break; + + case 'events': + $events = new Events(); + $events->show(); + break; + + case 'alerts': + $alerts = new Alerts(); + $alerts->show(); + break; + + case 'agents': + $agents = new Agents(); + $agents->show(); + break; + + case 'modules': + $modules = new Modules(); + $modules->show(); + break; + + case 'module_graph': + $module_graph = new ModuleGraph(); + $module_graph->show(); + break; + + case 'agent': + $agent = new Agent(); + $agent->show(); + break; + + case 'visualmaps': + $visualmaps = new Visualmaps(); + $visualmaps->show(); + break; + + case 'visualmap': + $visualmap = new Visualmap(); + $visualmap->show(); + break; + + case 'dashboard_list': + if (class_exists('Dashboards')) { + $dashboard = new Dashboards(); + $dashboard->showDashboards(); + } else { + if (class_exists('HomeEnterprise')) { + $home = new HomeEnterprise(); + } else { + $home = new Home(); + } + + $home->show(); + } + break; + + case 'dashboard': + if (class_exists('Dashboards')) { + $dashboard = new Dashboards(); + $dashboard->show(); + } else { + if (class_exists('HomeEnterprise')) { + $home = new HomeEnterprise(); + } else { + $home = new Home(); + } + + $home->show(); + } + break; + } + break; } - - - - -?> diff --git a/pandora_console/mobile/operation/agent.php b/pandora_console/mobile/operation/agent.php index 954c8bd130..6337b75e93 100644 --- a/pandora_console/mobile/operation/agent.php +++ b/pandora_console/mobile/operation/agent.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,21 +10,27 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -include_once("../include/functions_users.php"); +require_once '../include/functions_users.php'; -class Agent { - private $correct_acl = false; - private $id = 0; - private $agent = null; - - function __construct() { - $system = System::getInstance(); - - $this->id = $system->getRequest('id', 0); - - global $config; +class Agent +{ - echo ""; - - if (!$system->getConfig('metaconsole')) { - $this->agent = agents_get_agents(array( - 'disabled' => 0, - 'id_agente' => $this->id), array('*')); - } - else { - $this->agent = agents_get_meta_agents(array( - 'disabled' => 0, - 'id_agente' => $this->id), array('*')); - } - - if (!empty($this->agent)) { - $this->agent = $this->agent[0]; - - - if ($system->checkACL('AR', $this->agent['id_grupo'])) { - $this->correct_acl = true; - } - else { - $this->correct_acl = false; - } - } - else { - $this->agent = null; - $this->correct_acl = true; - } - } - - public function show() { - if (!$this->correct_acl) { - $this->show_fail_acl(); - } - else { - $this->show_agent(); - } - } - - private function show_fail_acl() { - $error['type'] = 'onStart'; - $error['title_text'] = __('You don\'t have access to this page'); - $error['content_text'] = System::getDefaultACLFailText(); - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show($error); - } - - - public function ajax($parameter2 = false) { - $system = System::getInstance(); + '; - if (!$this->correct_acl) { - return; - } - else { - switch ($parameter2) { - case 'render_events_bar': - $agent_id = $system->getRequest('agent_id', '0'); - $width = $system->getRequest('width', '400'); - graph_graphic_agentevents( - $agent_id, $width, 30, SECONDS_1DAY, ui_get_full_url(false)); - exit; - } - } - } - - private function show_agent() { - $ui = Ui::getInstance(); - $system = System::getInstance(); - - - - - $ui->createPage(); - - if ($this->id != 0) { - $agent_alias = (string) $this->agent['alias']; - - $agents_filter = (string) $system->getRequest('agents_filter'); - $agents_filter_q_param = empty($agents_filter) ? '' : '&agents_filter=' . $agents_filter; - - $ui->createDefaultHeader( - sprintf('%s', $agent_alias), - $ui->createHeaderButton( - array('icon' => 'back', - 'pos' => 'left', - 'text' => __('Back'), - 'href' => 'index.php?page=agents' . $agents_filter_q_param))); - } - else { - $ui->createDefaultHeader(__("Agents")); - } - $ui->showFooter(false); - $ui->beginContent(); - if (empty($this->agent)) { - $ui->contentAddHtml('' . - __('No agent found') . ''); - } - else { - $ui->contentBeginGrid(); - if ($this->agent['disabled']) { - $agent_alias = "" . $agent_alias . "" . - ui_print_help_tip(__('Disabled'), true); - } - else if ($this->agent['quiet']) { - $agent_alias = "" . $agent_alias . " " . - html_print_image("images/dot_blue.png", - true, array("border" => '0', "title" => __('Quiet'), "alt" => "")) . ""; - } - - - if ($system->getConfig('metaconsole')) { - metaconsole_connect(null, $this->agent['id_tmetaconsole_setup']); - //~ $addresses = agents_get_addresses($this->agent['id_tagente']); - } - else - $addresses = agents_get_addresses($this->id); - - if ($system->getConfig('metaconsole')) - metaconsole_restore_db(); - - $address = $this->agent['direccion']; - //~ foreach ($addresses as $k => $add) { - //~ if ($add == $address) { - //~ unset($addresses[$k]); - //~ } - //~ } - - //~ $ip = html_print_image('images/world.png', - //~ true, array('title' => __('IP address'))) . - //~ '  '; - $ip .= empty($address) ? '' . __('N/A') . - '' : $address; - - //~ if (!empty($addresses)) { - //~ $ip .= ui_print_help_tip(__('Other IP addresses') . - //~ ': ' . implode(', ',$addresses), true); - //~ } - - $last_contact = '' . __('Last contact') . - ': ' . - ui_print_timestamp ($this->agent["ultimo_contacto"], true); - - //~ $description = '' . __('Description') . ': '; - if (empty($agent["comentarios"])) { - $description .= '' . __('N/A') . ''; - } - else { - $description .= $this->agent["comentarios"]; - } - - $html = '
                '; - $html .= '' . $agent_alias . - ''; - $html .= '
                '; - $html .= '
                ' . ui_print_os_icon ($this->agent["id_os"], false, true, - true, false, false, false, false, true) . '
                '; - $html .= '
                '; - $html .= $ip . ' - ' . - groups_get_name ($this->agent["id_grupo"], true); - $html .= '
                + if (!$system->getConfig('metaconsole')) { + $this->agent = agents_get_agents( + [ + 'disabled' => 0, + 'id_agente' => $this->id, + ], + ['*'] + ); + } else { + $this->agent = agents_get_meta_agents( + [ + 'disabled' => 0, + 'id_agente' => $this->id, + ], + ['*'] + ); + } + + if (!empty($this->agent)) { + $this->agent = $this->agent[0]; + + if ($system->checkACL('AR', $this->agent['id_grupo'])) { + $this->correct_acl = true; + } else { + $this->correct_acl = false; + } + } else { + $this->agent = null; + $this->correct_acl = true; + } + } + + + public function show() + { + if (!$this->correct_acl) { + $this->show_fail_acl(); + } else { + $this->show_agent(); + } + } + + + private function show_fail_acl() + { + $error['type'] = 'onStart'; + $error['title_text'] = __('You don\'t have access to this page'); + $error['content_text'] = System::getDefaultACLFailText(); + if (class_exists('HomeEnterprise')) { + $home = new HomeEnterprise(); + } else { + $home = new Home(); + } + + $home->show($error); + } + + + public function ajax($parameter2=false) + { + $system = System::getInstance(); + + if (!$this->correct_acl) { + return; + } else { + switch ($parameter2) { + case 'render_events_bar': + $agent_id = $system->getRequest('agent_id', '0'); + $width = $system->getRequest('width', '400'); + graph_graphic_agentevents( + $agent_id, + $width, + 30, + SECONDS_1DAY, + ui_get_full_url(false) + ); + exit; + } + } + } + + + private function show_agent() + { + $ui = Ui::getInstance(); + $system = System::getInstance(); + + $ui->createPage(); + + if ($this->id != 0) { + $agent_alias = (string) $this->agent['alias']; + + $agents_filter = (string) $system->getRequest('agents_filter'); + $agents_filter_q_param = empty($agents_filter) ? '' : '&agents_filter='.$agents_filter; + + $ui->createDefaultHeader( + sprintf('%s', $agent_alias), + $ui->createHeaderButton( + [ + 'icon' => 'back', + 'pos' => 'left', + 'text' => __('Back'), + 'href' => 'index.php?page=agents'.$agents_filter_q_param, + ] + ) + ); + } else { + $ui->createDefaultHeader(__('Agents')); + } + + $ui->showFooter(false); + $ui->beginContent(); + if (empty($this->agent)) { + $ui->contentAddHtml( + ''.__('No agent found').'' + ); + } else { + $ui->contentBeginGrid(); + if ($this->agent['disabled']) { + $agent_alias = ''.$agent_alias.''.ui_print_help_tip(__('Disabled'), true); + } else if ($this->agent['quiet']) { + $agent_alias = ''.$agent_alias.' '.html_print_image( + 'images/dot_blue.png', + true, + [ + 'border' => '0', + 'title' => __('Quiet'), + 'alt' => '', + ] + ).''; + } + + if ($system->getConfig('metaconsole')) { + metaconsole_connect(null, $this->agent['id_tmetaconsole_setup']); + // ~ $addresses = agents_get_addresses($this->agent['id_tagente']); + } else { + $addresses = agents_get_addresses($this->id); + } + + if ($system->getConfig('metaconsole')) { + metaconsole_restore_db(); + } + + $address = $this->agent['direccion']; + // ~ foreach ($addresses as $k => $add) { + // ~ if ($add == $address) { + // ~ unset($addresses[$k]); + // ~ } + // ~ } + // ~ $ip = html_print_image('images/world.png', + // ~ true, array('title' => __('IP address'))) . + // ~ '  '; + $ip .= empty($address) ? ''.__('N/A').'' : $address; + + // ~ if (!empty($addresses)) { + // ~ $ip .= ui_print_help_tip(__('Other IP addresses') . + // ~ ': ' . implode(', ',$addresses), true); + // ~ } + $last_contact = ''.__('Last contact').': '.ui_print_timestamp($this->agent['ultimo_contacto'], true); + + // ~ $description = '' . __('Description') . ': '; + if (empty($agent['comentarios'])) { + $description .= ''.__('N/A').''; + } else { + $description .= $this->agent['comentarios']; + } + + $html = '
                '; + $html .= ''.$agent_alias.''; + $html .= '
                '; + $html .= '
                '.ui_print_os_icon( + $this->agent['id_os'], + false, + true, + true, + false, + false, + false, + false, + true + ).'
                '; + $html .= '
                '; + $html .= $ip.' - '.groups_get_name($this->agent['id_grupo'], true); + $html .= '
                '; - $html .= $last_contact; - $html .= '
                + $html .= $last_contact; + $html .= '
                '; - $html .= $description; - $html .= '
                '; - - if ($system->getConfig('metaconsole')) { - metaconsole_connect(null, - $this->agent['id_tmetaconsole_setup']); - } - - $ui->contentGridAddCell($html, 'agent_details'); - - ob_start(); + $html .= $description; + $html .= ''; - // Fixed width non interactive charts - $status_chart_width = 160; - $graph_width = 160; - - $html = '
                '; - $html .= "" . __('Modules by status') . ""; - $html .= '
                '; - $html .= graph_agent_status ($this->id, $graph_width, 160, true); - $html .= '
                '; - $graph_js = ob_get_clean(); - $html = $graph_js . $html; - - unset($this->agent['fired_count']); - - if ($this->agent['total_count'] > 0) { - $html .= '
                ' . - reporting_tiny_stats($this->agent, true, 'agent', ' ') . '
                '; - } - - $html .= '
                '; - $html .= '
                '; - $html .= "" . __('Events (24h)') . ""; - $html .= '
                '; - $html .= '
                '; - - $ui->contentGridAddCell($html, 'agent_graphs'); - $ui->contentEndGrid(); - - if ($system->getConfig('metaconsole')) - metaconsole_restore_db(); - - $modules = new Modules(); - - if ($system->getConfig('metaconsole')) - $filters = array('id_agent' => $this->agent['id_tagente'], 'all_modules' => true, 'status' => -1); - else - $filters = array('id_agent' => $this->id, 'all_modules' => true, 'status' => -1); - - $modules->setFilters($filters); - $modules->disabledColumns(array('agent')); - $ui->contentBeginCollapsible(__('Modules')); - $ui->contentCollapsibleAddItem($modules->listModulesHtml(0, true)); - $ui->contentEndCollapsible(); - - if ($system->getConfig('metaconsole')) { - metaconsole_connect(null, $this->agent['id_tmetaconsole_setup']); - } - - $alerts = new Alerts(); - - if ($system->getConfig('metaconsole')) - $filters = array('id_agent' => $this->agent['id_tagente'], 'all_alerts' => true); - else - $filters = array('id_agent' => $this->id, 'all_alerts' => true); - - $alerts->setFilters($filters); - $alerts->disabledColumns(array('agent')); - $ui->contentBeginCollapsible(__('Alerts')); - $ui->contentCollapsibleAddItem($alerts->listAlertsHtml(true)); - $ui->contentEndCollapsible(); - - if ($system->getConfig('metaconsole')) - metaconsole_restore_db(); - - $events = new Events(); - $events->addJavascriptDialog(); - - $options = $events->get_event_dialog_options(); - $ui->addDialog($options); - - $options = $events->get_event_dialog_error_options($options); - $ui->addDialog($options); - - $ui->contentAddHtml("
                "); - $ui->contentAddHtml(""); - - $ui->contentBeginCollapsible(sprintf(__('Last %s Events'), $system->getPageSize())); - $tabledata = $events->listEventsHtml(0, true, 'last_agent_events'); - $ui->contentCollapsibleAddItem($tabledata['table']); - $ui->contentCollapsibleAddItem($events->putEventsTableJS($this->id)); - $ui->contentEndCollapsible(); - } - - $ui->contentAddLinkListener('last_agent_events'); - $ui->contentAddLinkListener('list_events'); - $ui->contentAddLinkListener('list_agent_Modules'); + if ($system->getConfig('metaconsole')) { + metaconsole_connect( + null, + $this->agent['id_tmetaconsole_setup'] + ); + } - $ui->contentAddHtml(""); - - $ui->endContent(); - $ui->showPage(); - } - + " + ); + + $ui->endContent(); + $ui->showPage(); + } + + } - - - -?> \ No newline at end of file diff --git a/pandora_console/mobile/operation/agents.php b/pandora_console/mobile/operation/agents.php index 2a45208132..0700edfede 100644 --- a/pandora_console/mobile/operation/agents.php +++ b/pandora_console/mobile/operation/agents.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,409 +10,463 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +class Agents +{ -class Agents { - private $correct_acl = false; - private $acl = "AR"; - - private $default = true; - private $default_filters = array(); - - private $group = 0; - private $status = -1; - private $free_search = ''; - - private $list_status = null; - - function __construct() { - $system = System::getInstance(); - - $this->list_status = array( - -1 => __('All'), - AGENT_MODULE_STATUS_CRITICAL_BAD => __('Critical'), - AGENT_MODULE_STATUS_NORMAL => __('Normal'), - AGENT_MODULE_STATUS_WARNING => __('Warning'), - AGENT_MODULE_STATUS_UNKNOWN => __('Unknown')); - - if ($system->checkACL($this->acl)) { - $this->correct_acl = true; - } - else { - $this->correct_acl = false; - } - } - - public function ajax($parameter2 = false) { - $system = System::getInstance(); - - if (!$this->correct_acl) { - return; - } - else { - switch ($parameter2) { - case 'get_agents': - $this->getFilters(); - $page = $system->getRequest('page', 0); - - $agents = array(); - $end = 1; - - $listAgents = $this->getListAgents($page, true); - - if (!empty($listAgents['agents'])) { - $end = 0; - - $agents = array(); - foreach ($listAgents['agents'] as $key => $agent) { - $agent[0] = '' . - __('Agent') . '' . $agent[0]; - //~ $agent[1] = '' . - //~ __('Description') . '' . $agent[1]; - $agent[2] = '' . - __('OS') . '' . $agent[2]; - $agent[3] = '' . - __('Group') . '' . $agent[3]; - //~ $agent[4] = '' . - //~ __('Interval') . '' . $agent[4]; - $agent[5] = '' . - __('Modules') . '' . $agent[5]; - $agent[6] = '' . - __('Status') . '' . $agent[6]; - $agent[7] = '' . - __('Alerts') . '' . $agent[7]; - $agent[8] = '' . - __('Last contact') . '' . $agent[8]; - - $agents[$key] = $agent; - } - } - - echo json_encode(array('end' => $end, 'agents' => $agents)); - break; - } - } - } - - private function getFilters() { - $system = System::getInstance(); - $user = User::getInstance(); - - // Default - $filters = array( - 'free_search' => '', - 'status' => -1, - 'group' => 0 - ); - - $serialized_filters = (string) $system->getRequest('agents_filter'); - if (!empty($serialized_filters)) { - $filters_unsafe = json_decode(base64_decode($serialized_filters, true), true); - if ($filters_unsafe) $filters = $system->safeInput($filters_unsafe); - } - - $this->default_filters['group'] = true; - $this->default_filters['status'] = true; - $this->default_filters['free_search'] = true; - - $this->free_search = $system->getRequest('free_search', $filters['free_search']); - if ($this->free_search != '') { - $this->default = false; - $this->default_filters['free_search'] = false; - $filters['free_search'] = $this->free_search; - } - - $this->status = $system->getRequest('status', $filters['status']); - if (($this->status === __("Status")) || ($this->status == -1)) { - $this->status = -1; - } - else { - $this->default = false; - $this->default_filters['status'] = false; - $filters['status'] = (int) $this->status; - } - - $this->group = (int)$system->getRequest('group', $filters['group']); - if (!$user->isInGroup($this->acl, $this->group)) { - $this->group = 0; - } - if (($this->group === __("Group")) || ($this->group == 0)) { - $this->group = 0; - } - else { - $this->default = false; - $this->default_filters['group'] = false; - $filters['group'] = $this->group; - } - - if (!empty($filters)) { - // Store the filter - $this->serializedFilters = base64_encode(json_encode($system->safeOutput($filters))); - } - } - - public function show() { - if (!$this->correct_acl) { - $this->show_fail_acl(); - } - else { - $this->getFilters(); - $this->show_agents(); - } - } - - private function show_fail_acl() { - $error['type'] = 'onStart'; - $error['title_text'] = __('You don\'t have access to this page'); - $error['content_text'] = System::getDefaultACLFailText(); - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show($error); - } - - private function show_agents() { - $ui = Ui::getInstance(); - - $ui->createPage(); - $ui->createDefaultHeader(__("Agents"), - $ui->createHeaderButton( - array('icon' => 'back', - 'pos' => 'left', - 'text' => __('Back'), - 'href' => 'index.php?page=home'))); - $ui->showFooter(false); - $ui->beginContent(); - $filter_title = sprintf(__('Filter Agents by %s'), - $this->filterEventsGetString()); - $ui->contentBeginCollapsible($filter_title); - $ui->beginForm("index.php?page=agents"); - $system = System::getInstance(); - $groups = users_get_groups_for_select( - $system->getConfig('id_user'), "AR", true, true, false, 'id_grupo'); - $options = array( - 'name' => 'group', - 'title' => __('Group'), - 'label' => __('Group'), - 'items' => $groups, - 'selected' => $this->group - ); - $ui->formAddSelectBox($options); - - $options = array( - 'name' => 'status', - 'title' => __('Status'), - 'label' => __('Status'), - 'items' => $this->list_status, - 'selected' => $this->status - ); - $ui->formAddSelectBox($options); - - $options = array( - 'name' => 'free_search', - 'value' => $this->free_search, - 'placeholder' => __('Free search') - ); - $ui->formAddInputSearch($options); - - $options = array( - 'icon' => 'refresh', - 'icon_pos' => 'right', - 'text' => __('Apply Filter') - ); - $ui->formAddSubmitButton($options); - $html = $ui->getEndForm(); - $ui->contentCollapsibleAddItem($html); - $ui->contentEndCollapsible(); - $this->listAgentsHtml(); - $ui->endContent(); - $ui->showPage(); - } - - private function getListAgents($page = 0, $ajax = false) { - $system = System::getInstance(); + private $correct_acl = false; - $total = 0; - $agents = array(); - - $search_sql = ''; - - if (!empty($this->free_search)) { - $search_sql = " AND ( - alias COLLATE utf8_general_ci LIKE '%" . $this->free_search . "%' - OR nombre COLLATE utf8_general_ci LIKE '%" . $this->free_search . "%' - OR direccion LIKE '%" . $this->free_search . "%' - OR comentarios LIKE '%" . $this->free_search . "%') "; - } - - if (!$system->getConfig('metaconsole')) { - $total = agents_get_agents(array( - 'disabled' => 0, - 'id_grupo' => $this->group, - 'search' => $search_sql, - 'status' => $this->status), - array ('COUNT(*) AS total'), 'AR', false); - } - else { - $total = agents_get_meta_agents(array( - 'disabled' => 0, - 'id_grupo' => $this->group, - 'search' => $search_sql, - 'status' => $this->status), - array ('COUNT(*) AS total'), 'AR', false); - } - $total = isset($total[0]['total']) ? $total[0]['total'] : 0; - - $order = array('field' => 'alias COLLATE utf8_general_ci', - 'field2' => 'nombre COLLATE utf8_general_ci', 'order' => 'ASC'); - if (!$system->getConfig('metaconsole')) { - $agents_db = agents_get_agents(array( - 'disabled' => 0, - 'id_grupo' => $this->group, - 'search' => $search_sql, - 'status' => $this->status, - 'offset' => (int) $page * $system->getPageSize(), - 'limit' => (int) $system->getPageSize()), - array ('id_agente', - 'id_grupo', - 'id_os', - 'alias', - 'ultimo_contacto', - 'intervalo', - 'comentarios description', - 'quiet', - 'normal_count', - 'warning_count', - 'critical_count', - 'unknown_count', - 'notinit_count', - 'total_count', - 'fired_count'), - 'AR', $order); - } - else { - $agents_db = agents_get_meta_agents(array( - 'disabled' => 0, - 'id_grupo' => $this->group, - 'search' => $search_sql, - 'status' => $this->status, - 'offset' => (int) $page * $system->getPageSize(), - 'limit' => (int) $system->getPageSize()), - array ('id_agente', - 'id_grupo', - 'id_os', - 'alias', - 'ultimo_contacto', - 'intervalo', - 'comentarios description', - 'quiet', - 'normal_count', - 'warning_count', - 'critical_count', - 'unknown_count', - 'notinit_count', - 'total_count', - 'fired_count'), - 'AR', $order); - } - if (empty($agents_db)) - $agents_db = array(); - - foreach ($agents_db as $agent) { - $row = array(); - - - $img_status = agents_tree_view_status_img ($agent["critical_count"], - $agent["warning_count"], $agent["unknown_count"], $agent['total_count'], $agent['notinit_count']); - - $img_alert = agents_tree_view_alert_img ($agent["fired_count"]); - - $serialized_filters_q_param = empty($this->serializedFilters) ? '' : '&agents_filter=' . $this->serializedFilters; - - $row[0] = $row[__('Agent')] = '' . $img_status . '' . - '' . ui_print_truncate_text($agent['alias'], 30, false) . ''; - //~ $row[1] = $row[__('Description')] = '' . - //~ ui_print_truncate_text($agent["description"], 'description', false, true) . - //~ ''; - - $row[2] = $row[__('OS')] = ui_print_os_icon ($agent["id_os"], false, true); - $row[3] = $row[__('Group')] = ui_print_group_icon ($agent["id_grupo"], true, "groups_small", '', false); - //~ $row[4] = $row[__('Interval')] = '' . - //~ '' . human_time_description_raw($agent["intervalo"]) . ''; - - - $row[5] = $row[__('Status')] = '' . - $img_status; - $row[6] = $row[__('Alerts')] = '' . - $img_alert; - - $row[7] = $row[__('Modules')] = - '' . - '' . reporting_tiny_stats($agent, true, 'agent', ' ') . ' '; - - $last_time = time_w_fixed_tz($agent["ultimo_contacto"]); - $now = get_system_time(); - $diferencia = $now - $last_time; - $time = ui_print_timestamp ($last_time, true, array('style' => 'font-size: 12px; margin-left: 20px;', 'units' => 'tiny')); - $style = ''; - if ($diferencia > ($agent["intervalo"] * 2)) - $row[8] = $row[__('Last contact')] = ''.$time.''; - else - $row[8] = $row[__('Last contact')] = $time; - - $row[8] = $row[__('Last contact')] = '' . - '' . $row[__('Last contact')] . ''; - - if (!$ajax) { - unset($row[0]); - unset($row[1]); - unset($row[2]); - unset($row[3]); - unset($row[4]); - unset($row[5]); - unset($row[6]); - unset($row[7]); - unset($row[8]); - } - - $agents[$agent['id_agente']] = $row; - - } - - return array('agents' => $agents, 'total' => $total); - } - - private function listAgentsHtml($page = 0) { - $system = System::getInstance(); - $ui = Ui::getInstance(); - - $listAgents = $this->getListAgents($page); - - if ($listAgents['total'] == 0) { - $ui->contentAddHtml('

                ' . __('No agents') . '

                '); - } - else { - $table = new Table(); - $table->id = 'list_agents'; - $table->importFromHash($listAgents['agents']); - $ui->contentAddHtml($table->getHTML()); - - if ($system->getPageSize() < $listAgents['total']) { - $ui->contentAddHtml('
                ' . - html_print_image('images/spinner.gif', true, false, false, false, false, true) . - ' ' . __('Loading...') . - '
                '); - - $this->addJavascriptAddBottom(); - } - } - $ui->contentAddLinkListener('list_agents'); - } - - private function addJavascriptAddBottom() { - $ui = Ui::getInstance(); - - $ui->contentAddHtml(""); - } - - private function filterEventsGetString() { - if ($this->default) { - return __("(Default)"); - } - else { - $filters_to_serialize = array(); - - if (!$this->default_filters['group']) { - $filters_to_serialize[] = sprintf(__("Group: %s"), - groups_get_name($this->group, true)); - } - if (!$this->default_filters['status']) { - $filters_to_serialize[] = sprintf(__("Status: %s"), - $this->list_status[$this->status]); - } - if (!$this->default_filters['free_search']) { - $filters_to_serialize[] = sprintf(__("Free Search: %s"), - $this->free_search); - } - - $string = '(' . implode(' - ', $filters_to_serialize) . ')'; - - //~ $status = $this->list_status[$this->status]; - //~ $group = groups_get_name($this->group, true); - //~ - //~ - //~ $string = sprintf( - //~ __("(Status: %s - Group: %s - Free Search: %s)"), - //~ $status, $group, $this->free_search); - - return $string; - } - } -} + " + ); + } -?> + + private function filterEventsGetString() + { + if ($this->default) { + return __('(Default)'); + } else { + $filters_to_serialize = []; + + if (!$this->default_filters['group']) { + $filters_to_serialize[] = sprintf( + __('Group: %s'), + groups_get_name($this->group, true) + ); + } + + if (!$this->default_filters['status']) { + $filters_to_serialize[] = sprintf( + __('Status: %s'), + $this->list_status[$this->status] + ); + } + + if (!$this->default_filters['free_search']) { + $filters_to_serialize[] = sprintf( + __('Free Search: %s'), + $this->free_search + ); + } + + $string = '('.implode(' - ', $filters_to_serialize).')'; + + // ~ $status = $this->list_status[$this->status]; + // ~ $group = groups_get_name($this->group, true); + // ~ + // ~ + // ~ $string = sprintf( + // ~ __("(Status: %s - Group: %s - Free Search: %s)"), + // ~ $status, $group, $this->free_search); + return $string; + } + } + + +} diff --git a/pandora_console/mobile/operation/alerts.php b/pandora_console/mobile/operation/alerts.php index cf9c89272f..b95ba9492d 100644 --- a/pandora_console/mobile/operation/alerts.php +++ b/pandora_console/mobile/operation/alerts.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,332 +10,396 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +class Alerts +{ + + private $correct_acl = false; + + private $acl = 'LM'; + + private $default = true; + + private $default_filters = []; + + private $free_search = ''; + + private $group = 0; + + private $status = 'all'; + + private $standby = -1; + + private $id_agent = 0; + + private $all_alerts = false; + + private $alert_status_items = null; + + private $alert_standby_items = null; + + private $columns = null; + + + function __construct() + { + $this->alert_status_items = [ + 'all_enabled' => __('All (Enabled)'), + 'all' => __('All'), + 'fired' => __('Fired'), + 'notfired' => __('Not fired'), + 'disabled' => __('Disabled'), + ]; + + $this->alert_standby_items = [ + '-1' => __('All'), + '1' => __('Standby on'), + '0' => __('Standby off'), + ]; + + $this->columns = ['agent' => 1]; + + $system = System::getInstance(); + + if ($system->checkACL($this->acl)) { + $this->correct_acl = true; + } else { + $this->correct_acl = false; + } + } + + + private function alertsGetFilters() + { + $system = System::getInstance(); + $user = User::getInstance(); + + $this->default_filters['standby'] = true; + $this->default_filters['group'] = true; + $this->default_filters['status'] = true; + $this->default_filters['free_search'] = true; + + $this->free_search = $system->getRequest('free_search', ''); + if ($this->free_search != '') { + $this->default = false; + $this->default_filters['free_search'] = false; + } + + $this->status = $system->getRequest('status', __('Status')); + if (($this->status === __('Status')) || ($this->status == 'all')) { + $this->status = 'all'; + } else { + $this->default = false; + $this->default_filters['status'] = false; + } + + $this->group = $system->getRequest('group', __('Group')); + if (!$user->isInGroup($this->acl, $this->group)) { + $this->group = 0; + } + + if (($this->group === __('Group')) || ($this->group == 0)) { + $this->group = 0; + } else { + $this->default = false; + $this->default_filters['group'] = false; + } + + $this->standby = $system->getRequest('standby', __('Stand by')); + if (($this->standby === __('Stand by')) || ($this->standby == -1)) { + $this->standby = -1; + } else { + $this->default = false; + $this->default_filters['standby'] = false; + } + } + + + public function setFilters($filters) + { + if (isset($filters['id_agent'])) { + $this->id_agent = $filters['id_agent']; + } + + if (isset($filters['all_alerts'])) { + $this->all_alerts = $filters['all_alerts']; + } + } + + + public function ajax($parameter2=false) + { + $system = System::getInstance(); + + if (!$this->correct_acl) { + return; + } else { + switch ($parameter2) { + case 'xxxx': + break; + } + } + } + + + public function show() + { + if (!$this->correct_acl) { + $this->show_fail_acl(); + } else { + $this->alertsGetFilters(); + $this->show_alerts(); + } + } + + + private function show_fail_acl() + { + $error['type'] = 'onStart'; + $error['title_text'] = __('You don\'t have access to this page'); + $error['content_text'] = System::getDefaultACLFailText(); + if (class_exists('HomeEnterprise')) { + $home = new HomeEnterprise(); + } else { + $home = new Home(); + } + + $home->show($error); + } + + + private function show_alerts() + { + $ui = Ui::getInstance(); + + $ui->createPage(); + $ui->createDefaultHeader( + __('Alerts'), + $ui->createHeaderButton( + [ + 'icon' => 'back', + 'pos' => 'left', + 'text' => __('Back'), + 'href' => 'index.php?page=home', + ] + ) + ); + $ui->showFooter(false); + $ui->beginContent(); + $filter_title = sprintf( + __('Filter Alerts by %s'), + $this->filterAlertsGetString() + ); + $ui->contentBeginCollapsible($filter_title); + $ui->beginForm(); + $options = [ + 'name' => 'page', + 'type' => 'hidden', + 'value' => 'alerts', + ]; + $ui->formAddInput($options); + + $system = System::getInstance(); + $groups = users_get_groups_for_select( + $system->getConfig('id_user'), + 'ER', + true, + true, + false, + 'id_grupo' + ); + $options = [ + 'name' => 'group', + 'title' => __('Group'), + 'label' => __('Group'), + 'items' => $groups, + 'selected' => $this->group, + ]; + $ui->formAddSelectBox($options); + + $options = [ + 'name' => 'free_search', + 'value' => $this->free_search, + 'placeholder' => __('Free search'), + ]; + $ui->formAddInputSearch($options); + + $options = [ + 'name' => 'status', + 'title' => __('Status'), + 'label' => __('Status'), + 'items' => $this->alert_status_items, + 'selected' => $this->status, + ]; + $ui->formAddSelectBox($options); + + $options = [ + 'name' => 'standby', + 'title' => __('Stand by'), + 'label' => __('Stand by'), + 'items' => $this->alert_standby_items, + 'selected' => $this->standby, + ]; + $ui->formAddSelectBox($options); + + $options = [ + 'icon' => 'refresh', + 'icon_pos' => 'right', + 'text' => __('Apply Filter'), + ]; + $ui->formAddSubmitButton($options); + + $html = $ui->getEndForm(); + $ui->contentCollapsibleAddItem($html); + $ui->contentEndCollapsible(); + $this->listAlertsHtml(); + $ui->endContent(); + $ui->showPage(); + } + + + public function disabledColumns($columns=null) + { + if (!empty($columns)) { + foreach ($columns as $column) { + unset($this->columns[$column]); + } + } + } + + + public function listAlertsHtml($return=false) + { + $countAlerts = alerts_get_alerts( + $this->group, + $this->free_search, + $this->status, + $this->standby, + 'AR', + true, + $this->id_agent + ); + + $alerts = alerts_get_alerts( + $this->group, + $this->free_search, + $this->status, + $this->standby, + 'AR', + false, + $this->id_agent + ); + if (empty($alerts)) { + $alerts = []; + } + + $table = []; + foreach ($alerts as $alert) { + if ($alert['alert_disabled']) { + $disabled_style = "%s"; + } else { + $disabled_style = '%s'; + } + + if ($alert['times_fired'] > 0) { + $status = STATUS_ALERT_FIRED; + $title = __('Alert fired').' '.$alert['internal_counter'].' '.__('time(s)'); + } else if ($alert['disabled'] > 0) { + $status = STATUS_ALERT_DISABLED; + $title = __('Alert disabled'); + } else { + $status = STATUS_ALERT_NOT_FIRED; + $title = __('Alert not fired'); + } + + $row = []; + if (isset($this->columns['agent']) && $this->columns['agent']) { + $row[__('Agent')] = sprintf($disabled_style, io_safe_output($alert['agent_name'])); + } + + $row[__('Module')] = sprintf( + $disabled_style, + io_safe_output($alert['module_name']) + ); + $row[__('Template')] = sprintf( + $disabled_style, + io_safe_output($alert['template_name']) + ); + $row[__('Last Fired')] = sprintf( + $disabled_style, + ui_print_timestamp($alert['last_fired'], true) + ); + $row[__('Status')] = ui_print_status_image($status, $title, true); + + $table[] = $row; + } + + $ui = UI::getInstance(); + if (empty($table)) { + $html = '

                '.__('No alerts').'

                '; + if (!$return) { + $ui->contentAddHtml($html); + } else { + return $html; + } + } else { + $tableHTML = new Table(); + $tableHTML->id = 'list_alerts'; + $tableHTML->importFromHash($table); + if (!$return) { + $ui->contentAddHtml($tableHTML->getHTML()); + } else { + return $tableHTML->getHTML(); + } + } + } + + + private function filterAlertsGetString() + { + if ($this->default) { + return __('(Default)'); + } else { + $filters_to_serialize = []; + + if (!$this->default_filters['standby']) { + $filters_to_serialize[] = sprintf( + __('Standby: %s'), + $this->alert_standby_items[$this->standby] + ); + } + + if (!$this->default_filters['group']) { + $filters_to_serialize[] = sprintf( + __('Group: %s'), + groups_get_name($this->group, true) + ); + } + + if (!$this->default_filters['status']) { + $filters_to_serialize[] = sprintf( + __('Status: %s'), + $this->alert_status_items[$this->status] + ); + } + + if (!$this->default_filters['free_search']) { + $filters_to_serialize[] = sprintf( + __('Free Search: %s'), + $this->free_search + ); + } + + $string = '('.implode(' - ', $filters_to_serialize).')'; + + return $string; + + // ~ $status_text = $this->alert_status_items[$this->status]; + // ~ $standby_text = $this->alert_standby_items[$this->standby]; + // ~ $group_text = groups_get_name($this->group, true); + // ~ return sprintf(__('(Status: %s - Standby: %s - Group: %s - Free Search: %s)'), + // ~ $status_text, $standby_text, $group_text, $this->free_search); + } + } + -class Alerts { - private $correct_acl = false; - private $acl = "LM"; - - private $default = true; - private $default_filters = array(); - - private $free_search = ''; - private $group = 0; - private $status = 'all'; - private $standby = -1; - private $id_agent = 0; - private $all_alerts = false; - - private $alert_status_items = null; - private $alert_standby_items = null; - - private $columns = null; - - function __construct() { - $this->alert_status_items = array( - 'all_enabled' => __('All (Enabled)'), - 'all' => __('All'), - 'fired' => __('Fired'), - 'notfired' => __('Not fired'), - 'disabled' => __('Disabled')); - - $this->alert_standby_items = array( - '-1' => __('All'), - '1' => __('Standby on'), - '0' => __('Standby off')); - - $this->columns = array('agent' => 1); - - $system = System::getInstance(); - - if ($system->checkACL($this->acl)) { - $this->correct_acl = true; - } - else { - $this->correct_acl = false; - } - } - - private function alertsGetFilters() { - $system = System::getInstance(); - $user = User::getInstance(); - - - $this->default_filters['standby'] = true; - $this->default_filters['group'] = true; - $this->default_filters['status'] = true; - $this->default_filters['free_search'] = true; - - $this->free_search = $system->getRequest('free_search', ''); - if ($this->free_search != '') { - $this->default = false; - $this->default_filters['free_search'] = false; - } - - $this->status = $system->getRequest('status', __("Status")); - if (($this->status === __("Status")) || ($this->status == 'all')) { - $this->status = 'all'; - } - else { - $this->default = false; - $this->default_filters['status'] = false; - } - - $this->group = $system->getRequest('group', __("Group")); - if (!$user->isInGroup($this->acl, $this->group)) { - $this->group = 0; - } - if (($this->group === __("Group")) || ($this->group == 0)) { - $this->group = 0; - } - else { - $this->default = false; - $this->default_filters['group'] = false; - } - - $this->standby = $system->getRequest('standby', __('Stand by')); - if (($this->standby === __('Stand by')) || ($this->standby == -1)) { - $this->standby = -1; - } - else { - $this->default = false; - $this->default_filters['standby'] = false; - } - } - - public function setFilters($filters) { - if (isset($filters['id_agent'])) { - $this->id_agent = $filters['id_agent']; - } - if (isset($filters['all_alerts'])) { - $this->all_alerts = $filters['all_alerts']; - } - } - - public function ajax($parameter2 = false) { - $system = System::getInstance(); - - if (!$this->correct_acl) { - return; - } - else { - switch ($parameter2) { - case 'xxxx': - break; - } - } - } - - public function show() { - if (!$this->correct_acl) { - $this->show_fail_acl(); - } - else { - $this->alertsGetFilters(); - $this->show_alerts(); - } - } - - private function show_fail_acl() { - $error['type'] = 'onStart'; - $error['title_text'] = __('You don\'t have access to this page'); - $error['content_text'] = System::getDefaultACLFailText(); - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show($error); - } - - private function show_alerts() { - $ui = Ui::getInstance(); - - $ui->createPage(); - $ui->createDefaultHeader(__("Alerts"), - $ui->createHeaderButton( - array('icon' => 'back', - 'pos' => 'left', - 'text' => __('Back'), - 'href' => 'index.php?page=home'))); - $ui->showFooter(false); - $ui->beginContent(); - $filter_title = sprintf(__('Filter Alerts by %s'), - $this->filterAlertsGetString()); - $ui->contentBeginCollapsible($filter_title); - $ui->beginForm(); - $options = array( - 'name' => 'page', - 'type' => 'hidden', - 'value' => 'alerts' - ); - $ui->formAddInput($options); - - $system = System::getInstance(); - $groups = users_get_groups_for_select( - $system->getConfig('id_user'), "ER", true, true, false, 'id_grupo'); - $options = array( - 'name' => 'group', - 'title' => __('Group'), - 'label' => __('Group'), - 'items' => $groups, - 'selected' => $this->group - ); - $ui->formAddSelectBox($options); - - $options = array( - 'name' => 'free_search', - 'value' => $this->free_search, - 'placeholder' => __('Free search') - ); - $ui->formAddInputSearch($options); - - $options = array( - 'name' => 'status', - 'title' => __('Status'), - 'label' => __('Status'), - 'items' => $this->alert_status_items, - 'selected' => $this->status - ); - $ui->formAddSelectBox($options); - - $options = array( - 'name' => 'standby', - 'title' => __('Stand by'), - 'label' => __('Stand by'), - 'items' => $this->alert_standby_items, - 'selected' => $this->standby - ); - $ui->formAddSelectBox($options); - - $options = array( - 'icon' => 'refresh', - 'icon_pos' => 'right', - 'text' => __('Apply Filter') - ); - $ui->formAddSubmitButton($options); - - $html = $ui->getEndForm(); - $ui->contentCollapsibleAddItem($html); - $ui->contentEndCollapsible(); - $this->listAlertsHtml(); - $ui->endContent(); - $ui->showPage(); - } - - public function disabledColumns($columns = null) { - if (!empty($columns)) { - foreach ($columns as $column) { - unset($this->columns[$column]); - } - } - } - - public function listAlertsHtml ($return = false) { - $countAlerts = alerts_get_alerts($this->group, - $this->free_search, $this->status, $this->standby, "AR", true, $this->id_agent); - - $alerts = alerts_get_alerts($this->group, - $this->free_search, $this->status, $this->standby, "AR", false, $this->id_agent); - if (empty($alerts)) - $alerts = array(); - - $table = array(); - foreach ($alerts as $alert) { - if ($alert['alert_disabled']) { - $disabled_style = "%s"; - } - else { - $disabled_style = "%s"; - } - - if ($alert["times_fired"] > 0) { - $status = STATUS_ALERT_FIRED; - $title = __('Alert fired').' '.$alert["internal_counter"].' '.__('time(s)'); - } - elseif ($alert["disabled"] > 0) { - $status = STATUS_ALERT_DISABLED; - $title = __('Alert disabled'); - } - else { - $status = STATUS_ALERT_NOT_FIRED; - $title = __('Alert not fired'); - } - - $row = array(); - if (isset($this->columns['agent']) && $this->columns['agent']) { - $row[__('Agent')] = sprintf($disabled_style, io_safe_output($alert['agent_name'])); - } - $row[__('Module')] = sprintf($disabled_style, - io_safe_output($alert['module_name'])); - $row[__('Template')] = sprintf($disabled_style, - io_safe_output($alert['template_name'])); - $row[__('Last Fired')] = sprintf($disabled_style, - ui_print_timestamp ($alert["last_fired"], true)); - $row[__('Status')] = ui_print_status_image($status, $title, true); - - - $table[] = $row; - } - - $ui = UI::getInstance(); - if (empty($table)) { - $html = '

                ' . __('No alerts') . '

                '; - if (!$return) { - $ui->contentAddHtml($html); - } - else { - return $html; - } - } - else { - $tableHTML = new Table(); - $tableHTML->id = 'list_alerts'; - $tableHTML->importFromHash($table); - if (!$return) { - $ui->contentAddHtml($tableHTML->getHTML()); - } - else { - return $tableHTML->getHTML(); - } - } - } - - private function filterAlertsGetString() { - - if ($this->default) { - return __("(Default)"); - } - else { - $filters_to_serialize = array(); - - if (!$this->default_filters['standby']) { - $filters_to_serialize[] = sprintf(__("Standby: %s"), - $this->alert_standby_items[$this->standby]); - } - if (!$this->default_filters['group']) { - $filters_to_serialize[] = sprintf(__("Group: %s"), - groups_get_name($this->group, true)); - } - if (!$this->default_filters['status']) { - $filters_to_serialize[] = sprintf(__("Status: %s"), - $this->alert_status_items[$this->status]); - } - if (!$this->default_filters['free_search']) { - $filters_to_serialize[] = sprintf(__("Free Search: %s"), - $this->free_search); - } - - $string = '(' . implode(' - ', $filters_to_serialize) . ')'; - - return $string; - - //~ $status_text = $this->alert_status_items[$this->status]; - //~ $standby_text = $this->alert_standby_items[$this->standby]; - //~ $group_text = groups_get_name($this->group, true); - - //~ return sprintf(__('(Status: %s - Standby: %s - Group: %s - Free Search: %s)'), - //~ $status_text, $standby_text, $group_text, $this->free_search); - } - } } - -?> diff --git a/pandora_console/mobile/operation/events.php b/pandora_console/mobile/operation/events.php index d60fc248cc..cca5d7d18e 100644 --- a/pandora_console/mobile/operation/events.php +++ b/pandora_console/mobile/operation/events.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,829 +10,901 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +class Events +{ -class Events { - private $correct_acl = false; - private $acl = "ER"; - - private $default = true; - private $default_filters = array(); - - private $free_search = ''; - private $hours_old = 8; - private $status = 3; - private $type = "all"; - private $severity = -1; - private $filter = 0; - private $group = 0; - private $id_agent = 0; - private $all_events = false; - - private $columns = null; - - private $readOnly = false; - - function __construct() { - $system = System::getInstance(); - - $this->columns = array('agent' => 1); - - if ($system->checkACL($this->acl)) { - $this->correct_acl = true; - } - else { - $this->correct_acl = false; - } - } - - public function setReadOnly() { - $this->readOnly = true; - } - - public function ajax($parameter2 = false) { - $system = System::getInstance(); - - if (!$this->correct_acl) { - return; - } - else { - switch ($parameter2) { - case 'get_events': - if ($system->getRequest('agent_events', '0') == 1) { - $this->disabledColumns(array('agent')); - $filters = array('id_agent' => $system->getRequest('id_agent', 0)); - $this->setFilters($filters); - $this->setReadOnly(); - $this->eventsGetFilters(); - } - else { - $this->eventsGetFilters(); - } - - $page = $system->getRequest('page', 0); - - $system = System::getInstance(); - - $listEvents = $this->getListEvents($page); - $events_db = $listEvents['events']; - $total_events = $listEvents['total']; - - $events = array(); - $end = 1; - - foreach ($events_db as $event) { - $end = 0; - - switch ($event['estado']) { - case 0: - $img_st = "images/star_white.png"; - break; - case 1: - $img_st = "images/tick_white.png"; - break; - case 2: - $img_st = "images/hourglass_white.png"; - break; - } - - if($event['criticity'] == EVENT_CRIT_WARNING || - $event['criticity'] == EVENT_CRIT_MAINTENANCE || - $event['criticity'] == EVENT_CRIT_MINOR) { - $img_st = str_replace("white.png", "dark.png", $img_st); - } - - $status_icon = html_print_image($img_st, true, false, false, false, false, true); - - $row = array(); - $row[] = '' . __('Event Name') . '
                ' . io_safe_output(str_replace(array(' ',''), ' ', $event['evento'])) . '
                '; - - if ($event["id_agente"] == 0) { - $agent_name = __('System'); - } - else { - $agent_name = '' . ui_print_agent_name ($event["id_agente"], true, 'agent_small', '', false, '', '', false, false) . ''; - } - - $row_1 = '' . $agent_name . ''; - $row_1 .= '' . ui_print_timestamp ($event['timestamp_rep'], true, array('units' => 'tiny')) . $status_icon . ''; - - $row[] = $row_1; - - $row[] = get_priority_class ($event["criticity"]); - $events[$event['id_evento']] = $row; - } - - echo json_encode(array('end' => $end, 'events' => $events)); - - break; - case 'get_detail_event': - $system = System::getInstance(); - - $id_event = $system->getRequest('id_event', 0); - - $meta = false; - if ($system->getConfig('metaconsole')) - $meta = true; - - $event = events_get_event($id_event, false, $meta); - if ($event) { - //Check if it is a event from module. - if ($event['id_agentmodule'] > 0) { - $event['module_graph_link'] = - '' . - html_print_image('images/chart_curve.png', true, array ("style" => 'vertical-align: middle;'), false, false, false, true) . - ''; - } - else { - $event['module_graph_link'] = '' . __('N/A') . ''; - } - - if ($event['id_agente'] > 0) { - $event['agent'] = "" . - agents_get_alias($event['id_agente']) . - ""; - } - else { - $event['agent'] = '' . __('N/A') . ''; - } - - $event['evento'] = io_safe_output($event['evento']); - - $event['clean_tags'] = events_clean_tags($event['tags']); - $event["timestamp"] = date($system->getConfig("date_format"), $event["utimestamp"]); - if (empty($event["owner_user"])) { - $event["owner_user"] = '' . __('N/A') . ''; - } - else { - $user_owner = db_get_value('fullname', 'tusuario', 'id_user', $event["owner_user"]); - if (empty($user_owner)) { - $user_owner = $event['owner_user']; - } - $event["owner_user"] = $user_owner; - } - - $event["event_type"] = events_print_type_description($event["event_type"], true); - $event["event_type"] .= ' '; - $event["event_type"] .= events_print_type_img ($event["event_type"], true); - - if (!isset($group_rep)) - $group_rep = 0; - - if ($group_rep != 0) { - if ($event["event_rep"] <= 1) { - $event["event_repeated"] = '' . __('No') . ''; - } - else { - $event["event_repeated"] = sprintf("%d Times",$event["event_rep"]); - } - } - else { - $event["event_repeated"] = '' . __('No') . ''; - } - - $event_criticity = get_priority_name ($event["criticity"]); - - 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; - } + private $correct_acl = false; - $event["criticity"] = ' ' . $event_criticity; - $event["criticity"] .= html_print_image ($img_sev, true, - array ("class" => "image_status", - "width" => 12, - "height" => 12, - "title" => $event_criticity), false, false, false, true); - - 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 ($system->getConfig("date_format"), $event['ack_utimestamp']); - $event["acknowledged_by"] = $user_ack . - ' (' . $date_ack . ')'; - } - else { - $event["acknowledged_by"] = '' . __('N/A') . ''; - } - - // Get Status - switch ($event['estado']) { - case 0: - $img_st = "images/star_dark.png"; - $title_st = __('New event'); - break; - case 1: - $img_st = "images/tick.png"; - $title_st = __('Event validated'); - break; - case 2: - $img_st = "images/hourglass.png"; - $title_st = __('Event in process'); - break; - } - $event["status"] = $title_st; - $event["status"] .= ' '; - $event["status"] .= html_print_image($img_st,true, false, false, false, false, true); - - $event["group"] = groups_get_name ($event["id_grupo"], true); - $event["group"] .= ui_print_group_icon ($event["id_grupo"], true); - - $event["tags"] = tags_get_tags_formatted($event["tags"]); - if (empty($event["tags"])) { - $event["tags"] = ''.__('N/A').''; - } + private $acl = 'ER'; - $event_comments = db_get_value('user_comment', 'tevento', 'id_evento', $id_event); - $event_comments_array = array(); - $event_comments_array = json_decode($event_comments, true); - // Support for new format only. - if (empty($event_comments_array)) { - $comment = ''.__('N/A').''; - } else { - $comment = ''; - $event_comments_array = array_reverse($event_comments_array); - foreach($event_comments_array as $c) { - $comment .= date ($system->getConfig("date_format"), $c['utimestamp']) . ' (' . $c['id_user'] . ')'; - $c['comment'] = io_safe_output($c['comment']); - $c['comment'] = str_replace("\n", "
                ", $c['comment']); - $comment .= '
                ' . $c['comment'] . '
                '; - } - } + private $default = true; - $event["comments"] = $comment; - - echo json_encode(array('correct' => 1, 'event' => $event)); - } - else { - echo json_encode(array('correct' => 0, 'event' => array())); - } - break; - case 'validate_event': - $system = System::getInstance(); - - $id_event = $system->getRequest('id_event', 0); - - if (events_change_status($id_event, EVENT_VALIDATE)) { - echo json_encode(array('correct' => 1)); - } - else { - echo json_encode(array('correct' => 0)); - } - break; - } - } - } - - public function disabledColumns($columns = null) { - if (!empty($columns)) { - foreach ($columns as $column) { - $this->columns[$column] = 1; - } - } - } - - private function eventsGetFilters() { - $system = System::getInstance(); - $user = User::getInstance(); - - $this->default_filters['severity'] = true; - $this->default_filters['group'] = true; - $this->default_filters['type'] = true; - $this->default_filters['status'] = true; - $this->default_filters['free_search'] = true; - $this->default_filters['hours_old'] = true; - - $this->hours_old = $system->getRequest('hours_old', 8); - if ($this->hours_old != 8) { - $this->default = false; - $this->default_filters['hours_old'] = false; - } - - $this->free_search = $system->getRequest('free_search', ''); - if ($this->free_search != '') { - $this->default = false; - $this->default_filters['free_search'] = false; - } - - $this->status = $system->getRequest('status', __("Status")); - if (($this->status === __("Status")) || ($this->status == 3)) { - $this->status = 3; - } - else { - $this->status = (int)$this->status; - $this->default = false; - $this->default_filters['status'] = false; - } - - $this->type = $system->getRequest('type', __("Type")); - if ($this->type === __("Type")) { - $this->type = "all"; - } - else { - $this->default = false; - $this->default_filters['type'] = false; - } - - $this->group = $system->getRequest('group', __("Group")); - if (!$user->isInGroup($this->acl, $this->group)) { - $this->group = 0; - } - if (($this->group === __("Group")) || ($this->group == 0)) { - $this->group = 0; - } - else { - $this->default = false; - $this->default_filters['group'] = false; - } - - $this->severity = $system->getRequest('severity', __("Severity")); - if ($this->severity === __("Severity")) { - $this->severity = -1; - } - else { - $this->default = false; - $this->default_filters['severity'] = false; - } - - $this->filter = $system->getRequest('filter', __('Preset Filters')); - if (($this->filter === __("Preset Filters")) || ($this->filter == 0)) { - $this->filter = 0; - } - else { - $this->default = false; - } - - ///The user set a preset filter - if ($this->filter > 0) { - $this->loadPresetFilter(); - } - - $this->limit = $system->getRequest('limit', -1); - } - - public function setFilters($filters) { - if (isset($filters['id_agent'])) { - $this->id_agent = $filters['id_agent']; - } - - if (isset($filters['all_events'])) { - $this->all_events = $filters['all_events']; - } - } - - private function loadPresetFilter() { - $filter = db_get_row('tevent_filter', 'id_filter', $this->filter); - - $this->free_search = $filter['search']; - $this->hours_old = $filter['event_view_hr']; - $this->status = $filter['status']; - $this->type = $filter['event_type']; - $this->severity = $filter['severity']; - } - - public function show() { - if (!$this->correct_acl) { - $this->show_fail_acl(); - } - else { - $this->eventsGetFilters(); - $this->show_events(); - } - } - - private function show_fail_acl() { - $error['type'] = 'onStart'; - $error['title_text'] = __('You don\'t have access to this page'); - $error['content_text'] = System::getDefaultACLFailText(); - if (class_exists("HomeEnterprise")) - $home = new HomeEnterprise(); - else - $home = new Home(); - $home->show($error); - } - - public function get_event_dialog_error_options($options) { - $options['type'] = 'hidden'; - - $options['dialog_id'] = 'detail_event_dialog_error'; - $options['title_text'] = __('ERROR: Event detail'); - $options['content_text'] = '' . - __('Error connecting to DB.') . ''; - - return $options; - } - - public function get_event_dialog_options() { - $ui = Ui::getInstance(); + private $default_filters = []; - $options['type'] = 'hidden'; - - $options['dialog_id'] = 'detail_event_dialog'; - - $options['title_close_button'] = true; - $options['title_text'] = __('Event detail'); + private $free_search = ''; - //Content - ob_start(); - ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
                - __('Validate'), - 'id' => 'validate_button', - 'href' => 'javascript: validateEvent();'); - $options['content_text'] .= $ui->createButton($options_button); - $options_hidden = array( - 'id' => 'event_id', - 'value' => 0, - 'type' => 'hidden' - ); - $options['content_text'] .= $ui->getInput($options_hidden); - $options['content_text'] .= ''; + ?> diff --git a/pandora_console/operation/agentes/group_view.php b/pandora_console/operation/agentes/group_view.php index 640de2010c..c4e98bc986 100644 --- a/pandora_console/operation/agentes/group_view.php +++ b/pandora_console/operation/agentes/group_view.php @@ -3,7 +3,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -11,62 +10,63 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars -require_once ("include/config.php"); -require_once ("include/functions_reporting.php"); -require_once ($config['homedir'] . "/include/functions_agents.php"); -require_once ($config['homedir'] . '/include/functions_users.php'); -require_once ("include/functions_groupview.php"); +require_once 'include/config.php'; +require_once 'include/functions_reporting.php'; +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_users.php'; +require_once 'include/functions_groupview.php'; -check_login (); +check_login(); // ACL Check -$agent_a = check_acl ($config['id_user'], 0, "AR"); -$agent_w = check_acl ($config['id_user'], 0, "AW"); +$agent_a = check_acl($config['id_user'], 0, 'AR'); +$agent_w = check_acl($config['id_user'], 0, 'AW'); if (!$agent_a && !$agent_w) { - db_pandora_audit("ACL Violation", - "Trying to access Agent view (Grouped)"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent view (Grouped)' + ); + include 'general/noaccess.php'; + exit; } + // Update network modules for this group // Check for Network FLAG change request // Made it a subquery, much faster on both the database and server side -if (isset ($_GET["update_netgroup"])) { - $group = get_parameter_get ("update_netgroup", 0); - - if (check_acl ($config['id_user'], $group, "AW")) { - if ($group == 0) { - db_process_sql_update('tagente_modulo', array('flag' => 1)); - } - else { - db_process_sql("UPDATE `tagente_modulo` +if (isset($_GET['update_netgroup'])) { + $group = get_parameter_get('update_netgroup', 0); + + if (check_acl($config['id_user'], $group, 'AW')) { + if ($group == 0) { + db_process_sql_update('tagente_modulo', ['flag' => 1]); + } else { + db_process_sql( + 'UPDATE `tagente_modulo` SET `flag` = 1 WHERE `id_agente` = ANY(SELECT id_agente FROM tagente - WHERE id_grupo = " . $group . ")"); - } - } - else { - db_pandora_audit("ACL Violation", "Trying to set flag for groups"); - require ("general/noaccess.php"); - exit; - } + WHERE id_grupo = '.$group.')' + ); + } + } else { + db_pandora_audit('ACL Violation', 'Trying to set flag for groups'); + include 'general/noaccess.php'; + exit; + } } -if ($config["realtimestats"] == 0) { - $updated_time =""; - $updated_time .= __('Last update'). " : ". ui_print_timestamp (db_get_sql ("SELECT min(utimestamp) FROM tgroup_stat"), true); - $updated_time .= ""; -} -else { - // $updated_info = __("Updated at realtime"); - $updated_info = ""; +if ($config['realtimestats'] == 0) { + $updated_time = ""; + $updated_time .= __('Last update').' : '.ui_print_timestamp(db_get_sql('SELECT min(utimestamp) FROM tgroup_stat'), true); + $updated_time .= ''; +} else { + // $updated_info = __("Updated at realtime"); + $updated_info = ''; } // Header -ui_print_page_header (__("Group view"), "images/group.png", false, "", false, $updated_time); +ui_print_page_header(__('Group view'), 'images/group.png', false, '', false, $updated_time); $total_agentes = 0; $monitor_ok = 0; @@ -81,40 +81,40 @@ $agents_ok = 0; $agents_warning = 0; $all_alerts_fired = 0; -//Groups and tags +// Groups and tags $result_groups_info = groupview_get_groups_list( - $config['id_user'], - ($agent_a == true) ? 'AR' : (($agent_w == true) ? 'AW' : 'AR') + $config['id_user'], + ($agent_a == true) ? 'AR' : (($agent_w == true) ? 'AW' : 'AR') ); $result_groups = $result_groups_info['groups']; $count = $result_groups_info['counter']; -if ($result_groups[0]["_id_"] == 0) { - $total_agentes = $result_groups[0]["_total_agents_"]; - $monitor_ok = $result_groups[0]["_monitors_ok_"]; - $monitor_warning = $result_groups[0]["_monitors_warning_"]; - $monitor_critical = $result_groups[0]["_monitors_critical_"]; - $monitor_unknown = $result_groups[0]["_monitors_unknown_"]; - $monitor_not_init = $result_groups[0]["_monitors_not_init_"]; - - $agents_unknown = $result_groups[0]["_agents_unknown_"]; - $agents_notinit = $result_groups[0]["_agents_not_init_"]; - $agents_critical = $result_groups[0]["_agents_critical_"]; - $agents_warning = $result_groups[0]["_agents_warning_"]; - $agents_ok = $result_groups[0]["_agents_ok_"]; +if ($result_groups[0]['_id_'] == 0) { + $total_agentes = $result_groups[0]['_total_agents_']; + $monitor_ok = $result_groups[0]['_monitors_ok_']; + $monitor_warning = $result_groups[0]['_monitors_warning_']; + $monitor_critical = $result_groups[0]['_monitors_critical_']; + $monitor_unknown = $result_groups[0]['_monitors_unknown_']; + $monitor_not_init = $result_groups[0]['_monitors_not_init_']; - $all_alerts_fired = $result_groups[0]["_monitors_alerts_fired_"]; + $agents_unknown = $result_groups[0]['_agents_unknown_']; + $agents_notinit = $result_groups[0]['_agents_not_init_']; + $agents_critical = $result_groups[0]['_agents_critical_']; + $agents_warning = $result_groups[0]['_agents_warning_']; + $agents_ok = $result_groups[0]['_agents_ok_']; + + $all_alerts_fired = $result_groups[0]['_monitors_alerts_fired_']; } -$total = $monitor_ok + $monitor_warning + $monitor_critical + $monitor_unknown + $monitor_not_init; +$total = ($monitor_ok + $monitor_warning + $monitor_critical + $monitor_unknown + $monitor_not_init); -//Modules -$total_ok =0; -$total_warning =0; -$total_critical =0; -$total_unknown =0; -$total_monitor_not_init =0; -//Agents +// Modules +$total_ok = 0; +$total_warning = 0; +$total_critical = 0; +$total_unknown = 0; +$total_monitor_not_init = 0; +// Agents $total_agent_unknown = 0; $total_agent_critical = 0; $total_not_init = 0; @@ -122,380 +122,406 @@ $total_agent_warning = 0; $total_agent_ok = 0; if ($total > 0) { - //Modules - $total_ok = format_numeric (($monitor_ok*100)/$total,2); - $total_warning = format_numeric (($monitor_warning*100)/$total,2); - $total_critical = format_numeric (($monitor_critical*100)/$total,2); - $total_unknown = format_numeric (($monitor_unknown*100)/$total,2); - $total_monitor_not_init = format_numeric (($monitor_not_init*100)/$total,2); + // Modules + $total_ok = format_numeric((($monitor_ok * 100) / $total), 2); + $total_warning = format_numeric((($monitor_warning * 100) / $total), 2); + $total_critical = format_numeric((($monitor_critical * 100) / $total), 2); + $total_unknown = format_numeric((($monitor_unknown * 100) / $total), 2); + $total_monitor_not_init = format_numeric((($monitor_not_init * 100) / $total), 2); } + if ($total_agentes > 0) { - //Agents - $total_agent_unknown = format_numeric (($agents_unknown*100)/$total_agentes,2); - $total_agent_critical = format_numeric (($agents_critical*100)/$total_agentes,2); - $total_agent_warning = format_numeric (($agents_warning*100)/$total_agentes,2); - $total_agent_ok = format_numeric (($agents_ok*100)/$total_agentes,2); - $total_not_init = format_numeric (($agents_notinit*100)/$total_agentes,2); + // Agents + $total_agent_unknown = format_numeric((($agents_unknown * 100) / $total_agentes), 2); + $total_agent_critical = format_numeric((($agents_critical * 100) / $total_agentes), 2); + $total_agent_warning = format_numeric((($agents_warning * 100) / $total_agentes), 2); + $total_agent_ok = format_numeric((($agents_ok * 100) / $total_agentes), 2); + $total_not_init = format_numeric((($agents_notinit * 100) / $total_agentes), 2); } echo ''; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; -echo "
                " . __("Summary of the status groups") . "
                " . __("Agents") . "" . __("Modules") . "
                "; - echo "". $total_agent_critical ."%"; - echo "". $total_agent_warning ."%"; - echo "". $total_agent_ok ."%"; - echo "". $total_agent_unknown ."%"; - echo "". $total_not_init ."%"; - echo ""; - echo "". $total_critical ."%"; - echo "". $total_warning ."%"; - echo "". $total_ok ."%"; - echo "". $total_unknown ."%"; - echo "". $total_monitor_not_init ."%"; - echo "
                "; + echo ''; + echo "".__('Summary of the status groups').''; + echo ''; + echo ''; + echo "".__('Agents').''; + echo "".__('Modules').''; + echo ''; + echo ""; + echo ""; + echo "".$total_agent_critical.'%'; + echo "".$total_agent_warning.'%'; + echo "".$total_agent_ok.'%'; + echo "".$total_agent_unknown.'%'; + echo "".$total_not_init.'%'; + echo ''; + echo ""; + echo "".$total_critical.'%'; + echo "".$total_warning.'%'; + echo "".$total_ok.'%'; + echo "".$total_unknown.'%'; + echo "".$total_monitor_not_init.'%'; + echo ''; + echo ''; +echo ''; if ($count == 1) { - if ($result_groups[0]['_id_'] == 0) { - unset($result_groups[0]); - } + if ($result_groups[0]['_id_'] == 0) { + unset($result_groups[0]); + } } ui_pagination($count); if (!empty($result_groups)) { + echo ''; + echo ''; + echo ''; + echo "'; + echo "'; + echo ''; - echo '
                ".__('Agents').'".__('Modules').'
                '; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - - foreach ($result_groups as $data) { - $groups_id = $data["_id_"]; + echo ''; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo "'; + echo ''; - // Calculate entire row color - if ($groups_id != 0) { - if ($data["_monitors_alerts_fired_"] > 0) { - $color_class = 'group_view_alrm'; - $status_image = ui_print_status_image ('agent_alertsfired_ball.png', "", true); - } - elseif ($data["_monitors_critical_"] > 0) { - $color_class = 'group_view_crit'; - $status_image = ui_print_status_image ('agent_critical_ball.png', "", true); - } - elseif ($data["_monitors_warning_"] > 0) { - $color_class = 'group_view_warn'; - $status_image = ui_print_status_image ('agent_warning_ball.png', "", true); - } - elseif (($data["_monitors_unknown_"] > 0) || ($data["_agents_unknown_"] > 0)) { - $color_class = 'group_view_unk'; - $status_image = ui_print_status_image ('agent_no_monitors_ball.png', "", true); - } - elseif ($data["_monitors_ok_"] > 0) { - - $color_class = 'group_view_ok'; - $status_image = ui_print_status_image ('agent_ok_ball.png', "", true); - } - else { - $color_class = ''; - $status_image = ui_print_status_image ('agent_no_data_ball.png', "", true); - } - } - else { - $color_class = ''; - $status_image = ui_print_status_image ('agent_no_data_ball.png', "", true); - } - - echo ""; - - // Force - echo ""; - - $prefix = ""; - if (!isset($data['_is_tag_'])) { - if ($data['_id_'] != 0) { - $prefix = '    '; - } - } - - // Groupname and Tags - echo ""; - echo ""; - - // Total agents - echo "'; + + $prefix = ''; + if (!isset($data['_is_tag_'])) { + if ($data['_id_'] != 0) { + $prefix = '    '; + } + } + + // Groupname and Tags + echo ''; + + // Total agents + echo ""; - - // Agents unknown - echo ""; - - // Agents not init - echo ""; - - // Agents Normal - echo ""; - - // Agents warning - echo ""; - - // Agents critical - echo "'; - if ($data["_agents_critical_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_agents_critical_"] . ""; - } - echo ""; - - // Monitors unknown - echo ""; - - // Monitors not init - echo ""; - - // Monitors OK - echo ""; - - // Monitors Warning - echo ""; - - // Monitors Critical - echo ""; - - // Alerts fired - echo "'; + + // Agents not init + echo "'; + + // Agents Normal + echo "'; + + // Agents warning + echo "'; + + // Agents critical + echo "'; + + // Monitors unknown + echo "'; + + // Monitors not init + echo "'; + + // Monitors OK + echo "'; + + // Monitors Warning + echo "'; + + // Monitors Critical + echo "'; + + // Alerts fired + echo "'; - - echo ""; - } - echo '
                " . __("Agents") . "" . __("Modules") . "
                " . __("Force") . "" . __("Group") . "/" . __("Tags") . "" . __("Total") . "" . __("Unknown") . "" . __("Not init") . "" . __("Normal") . "" . __("Warning") . "" . __("Critical") . "" . __("Unknown") . "" . __("Not init") . "" . __("Normal") . "" . __("Warning") . "" . __("Critical") . "" . __("Alert fired") . "
                ".__('Force').'".__('Group').'/'.__('Tags').'".__('Total').'".__('Unknown').'".__('Not init').'".__('Normal').'".__('Warning').'".__('Critical').'".__('Unknown').'".__('Not init').'".__('Normal').'".__('Warning').'".__('Critical').'".__('Alert fired').'
                "; - if (!isset($data['_is_tag_']) && check_acl ($config['id_user'], $data['_id_'], "AW")) { - echo '' . - html_print_image("images/target.png", true, array("border" => '0', "title" => __('Force'))) . ''; - } - echo ""; - if (isset($data['_is_tag_'])) { - $deep = ""; - $link = ""; - } else { - $deep = groups_get_group_deep ($data['_id_']); - $link = ""; - } - - $group_name = "" . ui_print_truncate_text($data['_name_'], 50) . ""; - - $item_icon = ''; - if (isset($data['_iconImg_']) && !empty($data['_iconImg_'])) - $item_icon = $data['_iconImg_']; + foreach ($result_groups as $data) { + $groups_id = $data['_id_']; - if ($data['_name_'] != "All") { - echo $deep . $link . $group_name . ""; - } - else { - $hint = ''; - if (enterprise_hook('agents_is_using_secondary_groups')) { - $hint = ui_print_help_tip(__("This %s installation are using the secondary groups feature. For this reason, an agent can be counted several times.", get_product_name())); - } - echo $link . $group_name . "" . $hint; - } + // Calculate entire row color + if ($groups_id != 0) { + if ($data['_monitors_alerts_fired_'] > 0) { + $color_class = 'group_view_alrm'; + $status_image = ui_print_status_image('agent_alertsfired_ball.png', '', true); + } else if ($data['_monitors_critical_'] > 0) { + $color_class = 'group_view_crit'; + $status_image = ui_print_status_image('agent_critical_ball.png', '', true); + } else if ($data['_monitors_warning_'] > 0) { + $color_class = 'group_view_warn'; + $status_image = ui_print_status_image('agent_warning_ball.png', '', true); + } else if (($data['_monitors_unknown_'] > 0) || ($data['_agents_unknown_'] > 0)) { + $color_class = 'group_view_unk'; + $status_image = ui_print_status_image('agent_no_monitors_ball.png', '', true); + } else if ($data['_monitors_ok_'] > 0) { + $color_class = 'group_view_ok'; + $status_image = ui_print_status_image('agent_ok_ball.png', '', true); + } else { + $color_class = ''; + $status_image = ui_print_status_image('agent_no_data_ball.png', '', true); + } + } else { + $color_class = ''; + $status_image = ui_print_status_image('agent_no_data_ball.png', '', true); + } - if (isset($data['_is_tag_'])){ - echo '' . html_print_image("images/tag.png", true, array("border" => '0', "style" => 'width:18px;margin-left:5px', "title" => __('Tag'))) . '' ; - } + echo "
                "; - if (isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; + if (!isset($data['_is_tag_']) && check_acl($config['id_user'], $data['_id_'], 'AW')) { + echo ''.html_print_image('images/target.png', true, ['border' => '0', 'title' => __('Force')]).''; + } + + echo ''; + if (isset($data['_is_tag_'])) { + $deep = ''; + $link = ""; + } else { + $deep = groups_get_group_deep($data['_id_']); + $link = ""; + } + + $group_name = "".ui_print_truncate_text($data['_name_'], 50).''; + + $item_icon = ''; + if (isset($data['_iconImg_']) && !empty($data['_iconImg_'])) { + $item_icon = $data['_iconImg_']; + } + + if ($data['_name_'] != 'All') { + echo $deep.$link.$group_name.''; + } else { + $hint = ''; + if (enterprise_hook('agents_is_using_secondary_groups')) { + $hint = ui_print_help_tip(__('This %s installation are using the secondary groups feature. For this reason, an agent can be counted several times.', get_product_name())); + } + + echo $link.$group_name.''.$hint; + } + + if (isset($data['_is_tag_'])) { + echo ''.html_print_image('images/tag.png', true, ['border' => '0', 'style' => 'width:18px;margin-left:5px', 'title' => __('Tag')]).''; + } + + echo '"; + if (isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; - } - if ($data["_id_"] == 0) { - echo $link . $total_agentes . ""; - } - if ($data["_total_agents_"] > 0 && $data["_id_"] != 0) { - echo $link . $data["_total_agents_"] . ""; - } - echo ""; - if (isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($agents_unknown != 0)) { - echo $link . $agents_unknown . ""; - } - if ($data["_agents_unknown_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_agents_unknown_"] . ""; - } - echo ""; - if (isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($agents_notinit != 0)) { - echo $link . $agents_notinit . ""; - } + } - if ($data["_agents_not_init_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_agents_not_init_"] . ""; - } - echo ""; - if (isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($agents_ok != 0)) { - echo $link . $agents_ok . ""; - } + if ($data['_id_'] == 0) { + echo $link.$total_agentes.''; + } - if ($data["_agents_ok_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_agents_ok_"] . ""; - } - echo ""; - if (isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($agents_warning != 0)) { - echo $link . $agents_warning . ""; - } + if ($data['_total_agents_'] > 0 && $data['_id_'] != 0) { + echo $link.$data['_total_agents_'].''; + } - if ($data["_agents_warning_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_agents_warning_"] . ""; - } - echo ""; - if (isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($agents_critical != 0)) { - echo $link . $agents_critical . ""; - } + echo '"; - if (!isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($monitor_unknown != 0)) { - echo $link . $monitor_unknown . ""; - } - if ($data["_monitors_unknown_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_monitors_unknown_"] . ""; - } - echo ""; - if (!isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($monitor_not_init != 0)) { - echo $link . $monitor_not_init . ""; - } - if ($data["_monitors_not_init_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_monitors_not_init_"] . ""; - } - echo ""; - if (!isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($monitor_ok != 0)) { - echo $link . $monitor_ok . ""; - } - if ($data["_monitors_ok_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_monitors_ok_"] . ""; - } - echo ""; - if (!isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($monitor_warning != 0)) { - echo $link . $monitor_warning . ""; - } - if ($data["_monitors_warning_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_monitors_warning_"] . ""; - } - echo ""; - if (!isset($data['_is_tag_'])) { - $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($monitor_critical != 0)) { - echo $link . $monitor_critical . ""; - } - if ($data["_monitors_critical_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_monitors_critical_"] . ""; - } - echo ""; - if (!isset($data['_is_tag_'])) { - $link = ""; + if (isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($agents_unknown != 0)) { + echo $link.$agents_unknown.''; + } + + if ($data['_agents_unknown_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_agents_unknown_'].''; + } + + echo '"; + if (isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($agents_notinit != 0)) { + echo $link.$agents_notinit.''; + } + + if ($data['_agents_not_init_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_agents_not_init_'].''; + } + + echo '"; + if (isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($agents_ok != 0)) { + echo $link.$agents_ok.''; + } + + if ($data['_agents_ok_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_agents_ok_'].''; + } + + echo '"; + if (isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($agents_warning != 0)) { + echo $link.$agents_warning.''; + } + + if ($data['_agents_warning_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_agents_warning_'].''; + } + + echo '"; + if (isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($agents_critical != 0)) { + echo $link.$agents_critical.''; + } + + if ($data['_agents_critical_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_agents_critical_'].''; + } + + echo '"; + if (!isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($monitor_unknown != 0)) { + echo $link.$monitor_unknown.''; + } + + if ($data['_monitors_unknown_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_monitors_unknown_'].''; + } + + echo '"; + if (!isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($monitor_not_init != 0)) { + echo $link.$monitor_not_init.''; + } + + if ($data['_monitors_not_init_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_monitors_not_init_'].''; + } + + echo '"; + if (!isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($monitor_ok != 0)) { + echo $link.$monitor_ok.''; + } + + if ($data['_monitors_ok_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_monitors_ok_'].''; + } + + echo '"; + if (!isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($monitor_warning != 0)) { + echo $link.$monitor_warning.''; + } + + if ($data['_monitors_warning_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_monitors_warning_'].''; + } + + echo '"; + if (!isset($data['_is_tag_'])) { + $link = ""; + } else { + $link = ""; + } + + if (($data['_id_'] == 0) && ($monitor_critical != 0)) { + echo $link.$monitor_critical.''; + } + + if ($data['_monitors_critical_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_monitors_critical_'].''; + } + + echo '"; + if (!isset($data['_is_tag_'])) { + $link = ""; - } else { - $link = ""; - } - if (($data["_id_"] == 0) && ($all_alerts_fired != 0)) { - echo $link . $all_alerts_fired . ""; - } - if ($data["_monitors_alerts_fired_"] > 0 && ($data["_id_"] != 0)) { - echo $link . $data["_monitors_alerts_fired_"] . ""; - } - echo '
                '; + } + + if (($data['_id_'] == 0) && ($all_alerts_fired != 0)) { + echo $link.$all_alerts_fired.''; + } + + if ($data['_monitors_alerts_fired_'] > 0 && ($data['_id_'] != 0)) { + echo $link.$data['_monitors_alerts_fired_'].''; + } + + echo ''; + + echo ''; + } + + echo ''; } else { - ui_print_info_message ( __('There are no defined agents')); + ui_print_info_message(__('There are no defined agents')); } -?> diff --git a/pandora_console/operation/agentes/interface_traffic_graph_win.php b/pandora_console/operation/agentes/interface_traffic_graph_win.php index 7346e90805..72e8f8989f 100644 --- a/pandora_console/operation/agentes/interface_traffic_graph_win.php +++ b/pandora_console/operation/agentes/interface_traffic_graph_win.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,20 +11,19 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Don't start a session before this import. // The session is configured and started inside the config process. -require_once ('../../include/config.php'); -require_once ($config['homedir'] . '/include/auth/mysql.php'); -require_once ($config['homedir'] . '/include/functions.php'); -require_once ($config['homedir'] . '/include/functions_db.php'); -require_once ($config['homedir'] . '/include/functions_reporting.php'); -require_once ($config['homedir'] . '/include/functions_graph.php'); -require_once ($config['homedir'] . '/include/functions_custom_graphs.php'); -require_once ($config['homedir'] . '/include/functions_modules.php'); -require_once ($config['homedir'] . '/include/functions_agents.php'); -require_once ($config['homedir'] . '/include/functions_tags.php'); -enterprise_include_once ('include/functions_agents.php'); +require_once '../../include/config.php'; +require_once $config['homedir'].'/include/auth/mysql.php'; +require_once $config['homedir'].'/include/functions.php'; +require_once $config['homedir'].'/include/functions_db.php'; +require_once $config['homedir'].'/include/functions_reporting.php'; +require_once $config['homedir'].'/include/functions_graph.php'; +require_once $config['homedir'].'/include/functions_custom_graphs.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_tags.php'; +enterprise_include_once('include/functions_agents.php'); check_login(); @@ -34,316 +32,313 @@ $params = json_decode($params_json, true); // Metaconsole connection to the node $server_id = (int) (isset($params['server']) ? $params['server'] : 0); -if ($config["metaconsole"] && !empty($server_id)) { - $server = metaconsole_get_connection_by_id($server_id); +if ($config['metaconsole'] && !empty($server_id)) { + $server = metaconsole_get_connection_by_id($server_id); - // Error connecting - if (metaconsole_connect($server) !== NOERR) { - echo ""; - echo ""; - ui_print_error_message(__('There was a problem connecting with the node')); - echo ""; - echo ""; - exit; - } + // Error connecting + if (metaconsole_connect($server) !== NOERR) { + echo ''; + echo ''; + ui_print_error_message(__('There was a problem connecting with the node')); + echo ''; + echo ''; + exit; + } } $user_language = get_user_language($config['id_user']); -if (file_exists ('../../include/languages/'.$user_language.'.mo')) { - $l10n = new gettext_reader (new CachedFileReader ('../../include/languages/'.$user_language.'.mo')); - $l10n->load_tables(); +if (file_exists('../../include/languages/'.$user_language.'.mo')) { + $l10n = new gettext_reader(new CachedFileReader('../../include/languages/'.$user_language.'.mo')); + $l10n->load_tables(); } echo ''; $interface_name = (string) $params['interface_name']; $agent_id = (int) $params['agent_id']; -$interface_traffic_modules = array( - __('In') => (int) $params['traffic_module_in'], - __('Out') => (int) $params['traffic_module_out'] - ); +$interface_traffic_modules = [ + __('In') => (int) $params['traffic_module_in'], + __('Out') => (int) $params['traffic_module_out'], +]; ?> - + 0) { - $query = ui_get_url_refresh(false); +// Parsing the refresh before sending any header + $refresh = (int) get_parameter('refresh', SECONDS_5MINUTES); +if ($refresh > 0) { + $query = ui_get_url_refresh(false); - echo ''; - } + echo ''; +} ?> - - <?php echo __('%s Interface Graph', get_product_name()) . ' (' .agents_get_alias($agent_id) . ' - ' . $interface_name; ?>) - - - - - - - - - - + period_select_init(periodSelectId); + }; + --> + + + $now){ - $date = $now; - } +if ($date > $now) { + $date = $now; +} - $urlImage = ui_get_full_url(false); + $urlImage = ui_get_full_url(false); - echo '
                '; + echo '
                '; - $height = 400; - $width = '90%'; + $height = 400; + $width = '90%'; - $params =array( - 'period' => $period, - 'width' => $width, - 'height' => $height, - 'unit_name' => array_fill(0, count($interface_traffic_modules), $config["interface_unit"]), - 'date' => $date, - 'homeurl' => $config['homeurl'], - 'percentil' => (($show_percentil)? $config['percentil'] : null), - 'fullscale' => $fullscale, - 'zoom' => $zoom - ); + $params = [ + 'period' => $period, + 'width' => $width, + 'height' => $height, + 'unit_name' => array_fill(0, count($interface_traffic_modules), $config['interface_unit']), + 'date' => $date, + 'homeurl' => $config['homeurl'], + 'percentil' => (($show_percentil) ? $config['percentil'] : null), + 'fullscale' => $fullscale, + 'zoom' => $zoom, + ]; - if($config['type_interface_charts'] == 'line'){ - $stacked = CUSTOM_GRAPH_LINE; - } - else{ - $stacked = CUSTOM_GRAPH_AREA; - } + if ($config['type_interface_charts'] == 'line') { + $stacked = CUSTOM_GRAPH_LINE; + } else { + $stacked = CUSTOM_GRAPH_AREA; + } - $params_combined = array( - 'weight_list' => array(), - 'projection' => false, - 'labels' => array_keys($interface_traffic_modules), - 'from_interface' => true, - 'modules_series' => array_values($interface_traffic_modules), - 'return' => 0, - 'stacked' => $stacked - ); + $params_combined = [ + 'weight_list' => [], + 'projection' => false, + 'labels' => array_keys($interface_traffic_modules), + 'from_interface' => true, + 'modules_series' => array_values($interface_traffic_modules), + 'return' => 0, + 'stacked' => $stacked, + ]; - graphic_combined_module( - array_values($interface_traffic_modules), - $params, - $params_combined - ); + graphic_combined_module( + array_values($interface_traffic_modules), + $params, + $params_combined + ); - echo '
                '; + echo '
                '; - /////////////////////////// - // SIDE MENU - /////////////////////////// - $side_layer_params = array(); - // TOP TEXT + // + // SIDE MENU + // + $side_layer_params = []; + // TOP TEXT + $side_layer_params['top_text'] = "
                ".html_print_image('/images/config.disabled.png', true, ['width' => '16px'], false, false, false, true).' '.__('Graph configuration menu').'
                '; + $side_layer_params['body_text'] = "'; // outer + // SIZE + $side_layer_params['width'] = 500; - // ICONS - $side_layer_params['icon_closed'] = '/images/graphmenu_arrow_hide.png'; - $side_layer_params['icon_open'] = '/images/graphmenu_arrow.png'; + // POSITION + $side_layer_params['position'] = 'left'; - // SIZE - $side_layer_params['width'] = 500; + html_print_side_layer($side_layer_params); - // POSITION - $side_layer_params['position'] = 'left'; + // Hidden div to forced title + html_print_div(['id' => 'forced_title_layer', 'class' => 'forced_title_layer', 'hidden' => true]); + ?> - html_print_side_layer($side_layer_params); - - // Hidden div to forced title - html_print_div(array('id' => 'forced_title_layer', 'class' => 'forced_title_layer', 'hidden' => true)); -?> - - + diff --git a/pandora_console/operation/agentes/networkmap.dinamic.php b/pandora_console/operation/agentes/networkmap.dinamic.php index 9e93ad9cc5..ae4b696aba 100644 --- a/pandora_console/operation/agentes/networkmap.dinamic.php +++ b/pandora_console/operation/agentes/networkmap.dinamic.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,280 +11,322 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars global $config; -check_login (); -if (defined('_id_') && _id_ != "_id_") { - $id = _id_; -} -else { - define("_id_", "_id_"); - $id = get_parameter('id_networkmap', true); +check_login(); +if (defined('_id_') && _id_ != '_id_') { + $id = _id_; +} else { + define('_id_', '_id_'); + $id = get_parameter('id_networkmap', true); } $activeTab = get_parameter('activeTab', true); if (enterprise_installed()) { - include_once("enterprise/dashboard/widgets/network_map.php"); - if ($id_networkmap) { - $id = $id_networkmap; - } - if ($tab) { - $activeTab = $tab; - } + include_once 'enterprise/dashboard/widgets/network_map.php'; + if ($id_networkmap) { + $id = $id_networkmap; + } + + if ($tab) { + $activeTab = $tab; + } } -if (defined("_activeTab_") && _activeTab_ != "_activeTab_") { - $activeTab = _activeTab_; - $tab = $activeTab; + +if (defined('_activeTab_') && _activeTab_ != '_activeTab_') { + $activeTab = _activeTab_; + $tab = $activeTab; } // Networkmap id required if (!isset($id)) { - db_pandora_audit("ACL Violation", - "Trying to access node graph builder"); - require ("general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access node graph builder' + ); + include 'general/noaccess.php'; + exit; } // Get the group for ACL if (!isset($store_group)) { - $store_group = db_get_value("id_group", "tmap", "id", $id); - if ($store_group === false) { - db_pandora_audit("ACL Violation", - "Trying to accessnode graph builder"); - require ("general/noaccess.php"); - exit; - } + $store_group = db_get_value('id_group', 'tmap', 'id', $id); + if ($store_group === false) { + db_pandora_audit( + 'ACL Violation', + 'Trying to accessnode graph builder' + ); + include 'general/noaccess.php'; + exit; + } } // ACL for the networkmap permission -if (!isset($networkmap_read)) - $networkmap_read = check_acl ($config['id_user'], $store_group, "MR"); -if (!isset($networkmap_write)) - $networkmap_write = check_acl ($config['id_user'], $store_group, "MW"); -if (!isset($networkmap_manage)) - $networkmap_manage = check_acl ($config['id_user'], $store_group, "MM"); - -if (!$networkmap_read && !$networkmap_write && !$networkmap_manage) { - db_pandora_audit("ACL Violation", - "Trying to access node graph builder"); - include ("general/noaccess.php"); - exit; +if (!isset($networkmap_read)) { + $networkmap_read = check_acl($config['id_user'], $store_group, 'MR'); } -require_once ('include/functions_networkmap.php'); +if (!isset($networkmap_write)) { + $networkmap_write = check_acl($config['id_user'], $store_group, 'MW'); +} + +if (!isset($networkmap_manage)) { + $networkmap_manage = check_acl($config['id_user'], $store_group, 'MM'); +} + +if (!$networkmap_read && !$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access node graph builder' + ); + include 'general/noaccess.php'; + exit; +} + +require_once 'include/functions_networkmap.php'; $strict_user = db_get_value('strict_acl', 'tusuario', 'id_user', $config['id_user']); $networkmap = db_get_row('tmap', 'id', $id); -$pure = (int) get_parameter ('pure', 0); - -/* Main code */ +$pure = (int) get_parameter('pure', 0); + +// Main code if ($pure == 1) { - $buttons['screen'] = array('active' => false, - 'text' => '' . - html_print_image("images/normal_screen.png", true, - array ('title' => __('Normal screen'))) . - ''); -} -else { - if (!$dash_mode) { - $buttons['screen'] = array('active' => false, - 'text' => '' . - html_print_image("images/full_screen.png", true, - array ('title' => __('Full screen'))) . - ''); - $buttons['list'] = array('active' => false, - 'text' => '' . - html_print_image("images/list.png", true, - array ('title' => __('List of networkmap'))) . - ''); - } + $buttons['screen'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/normal_screen.png', + true, + ['title' => __('Normal screen')] + ).'', + ]; +} else { + if (!$dash_mode) { + $buttons['screen'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/full_screen.png', + true, + ['title' => __('Full screen')] + ).'', + ]; + $buttons['list'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/list.png', + true, + ['title' => __('List of networkmap')] + ).'', + ]; + } } -ui_print_page_header(io_safe_output($networkmap['name']), - "images/bricks.png", false, "network_map_enterprise", - false, $buttons, false, '', $config['item_title_size_text']); +ui_print_page_header( + io_safe_output($networkmap['name']), + 'images/bricks.png', + false, + 'network_map_enterprise', + false, + $buttons, + false, + '', + $config['item_title_size_text'] +); global $width; global $height; -if (_id_ != "_id_") { - $width = array(); - $height = array(); +if (_id_ != '_id_') { + $width = []; + $height = []; } if (empty($width)) { - $width = 600; + $width = 600; } + if (empty($height)) { - $height = 650; + $height = 650; } -if ($activeTab == "radial_dynamic") { - include_once("include/functions_graph.php"); - - echo "
                "; - - $filter = array(); - if ($networkmap['source'] == 0) { - $filter['group'] = $networkmap['source_data']; - } - $map_filter = json_decode($networkmap['filter'], true); - if (isset($map_filter['dont_show_subgroups']) && $map_filter['dont_show_subgroups']) { - $filter['dont_show_subgroups'] = true; - } - else { - $filter['dont_show_subgroups'] = false; - } - if (!empty($module_group)) { - $filter['module_group'] = $module_group; - } +if ($activeTab == 'radial_dynamic') { + include_once 'include/functions_graph.php'; - echo graph_monitor_wheel($width, $height, $filter, $strict_user); - - echo "
                "; - return; + echo "
                "; + + $filter = []; + if ($networkmap['source'] == 0) { + $filter['group'] = $networkmap['source_data']; + } + + $map_filter = json_decode($networkmap['filter'], true); + if (isset($map_filter['dont_show_subgroups']) && $map_filter['dont_show_subgroups']) { + $filter['dont_show_subgroups'] = true; + } else { + $filter['dont_show_subgroups'] = false; + } + + if (!empty($module_group)) { + $filter['module_group'] = $module_group; + } + + echo graph_monitor_wheel($width, $height, $filter, $strict_user); + + echo '
                '; + return; } $networkmap = db_get_row('tmap', 'id', $id); switch ($networkmap['generation_method']) { - case 0: - $layout = "circular"; - break; - case 1: - $layout = "flat"; - break; - case 2: - $layout = "radial"; - break; - case 3: - $layout = "neato"; - break; - case 4: - $layout = "spring1"; - break; - case 5: - $layout = "spring2"; - break; + case 0: + $layout = 'circular'; + break; + + case 1: + $layout = 'flat'; + break; + + case 2: + $layout = 'radial'; + break; + + case 3: + $layout = 'neato'; + break; + + case 4: + $layout = 'spring1'; + break; + + case 5: + $layout = 'spring2'; + break; } // Set filter -$filter = networkmap_get_filter ($layout); +$filter = networkmap_get_filter($layout); if (!isset($text_filter)) { - $text_filter = ''; + $text_filter = ''; } // Generate dot file -$graph = networkmap_generate_hash(__('Pandora FMS'), $group, $simple, - $font_size, $layout, $nooverlap, $zoom, $ranksep, $center, $regen, - $pure, $id, $show_snmp_modules, true, true, - $text_filter, $strict_user); +$graph = networkmap_generate_hash( + __('Pandora FMS'), + $group, + $simple, + $font_size, + $layout, + $nooverlap, + $zoom, + $ranksep, + $center, + $regen, + $pure, + $id, + $show_snmp_modules, + true, + true, + $text_filter, + $strict_user +); networkmap_print_jsdata($graph); -$zoom_default = file($config['homedir'] . '/images/zoom_default.svg'); +$zoom_default = file($config['homedir'].'/images/zoom_default.svg'); ?>
                - +
                '; ?> diff --git a/pandora_console/operation/agentes/pandora_networkmap.editor.php b/pandora_console/operation/agentes/pandora_networkmap.editor.php index 6163c47f8f..ebdb0bbb90 100644 --- a/pandora_console/operation/agentes/pandora_networkmap.editor.php +++ b/pandora_console/operation/agentes/pandora_networkmap.editor.php @@ -1,15 +1,14 @@ id = 'form_editor'; - - $table->width = '98%'; - $table->class = "databox_color"; - - $table->head = array (); - - $table->size = array(); - $table->size[0] = '30%'; - - $table->style = array (); - $table->style[0] = 'font-weight: bold; width: 150px;'; - $table->data = array (); - - $table->data[0][0] = __('Name'); - $table->data[0][1] = html_print_input_text ('name', $name, '', 30, - 100,true); - - $table->data[1][0] = __('Group'); - $table->data[1][1] = html_print_select_groups($config['id_user'], "AR", - true, 'id_group', $id_group, '', '', '', true); - - $table->data[2][0] = __('Node radius'); - $table->data[2][1] = html_print_input_text ('node_radius', $node_radius, '', 2, - 10,true); - - $table->data[3][0] = __('Description'); - $table->data[3][1] = html_print_textarea ('description', 7, 25, $description, '', true); + ui_print_error_message(__('Not found networkmap.')); +} else { + $table = null; + $table->id = 'form_editor'; - $table->data[4][0] = __('Position X'); - $table->data[4][1] = html_print_input_text ('pos_x', $offset_x, '', 2, 10,true); - $table->data[5][0] = __('Position Y'); - $table->data[5][1] = html_print_input_text ('pos_y', $offset_y, '', 2, 10,true); + $table->width = '98%'; + $table->class = 'databox_color'; - $table->data[6][0] = __('Zoom scale'); - if ($scale_z == "") { - $scale_z = 0.5; - } - $table->data[6][1] = html_print_input_text ('scale_z', $scale_z, '', 2, 10,true) . ui_print_help_tip (__('Introduce zoom level. 1 = Highest resolution. Figures may include decimals'), true); - - $table->data['source'][0] = __('Source'); - $table->data['source'][1] = - html_print_radio_button('source', 'group', __('Group'), $source, true, $disabled_source) . - html_print_radio_button('source', 'recon_task', __('Recon task'), $source, true, $disabled_source) . - html_print_radio_button('source', 'ip_mask', __('CIDR IP mask'), $source, true, $disabled_source); - - $table->data['source_data_recon_task'][0] = __('Source from recon task'); - $table->data['source_data_recon_task'][0] .= ui_print_help_tip( - __('It is setted any recon task, the nodes get from the recontask IP mask instead from the group.'), true); - $table->data['source_data_recon_task'][1] = html_print_select( - $list_recon_tasks, 'recon_task_id', $recon_task_id, '', __('None'), 0, true, false, true, '', $disabled_source); - $table->data['source_data_recon_task'][1] .= ui_print_help_tip( - __('Show only the task with the recon script "SNMP L2 Recon".'), true); - - $table->data['source_data_ip_mask'][0] = __('Source from CIDR IP mask'); - $table->data['source_data_ip_mask'][1] = - html_print_input_text('ip_mask', $ip_mask, '', 20, 255, true, $disabled_source); - - $table->data['source_data_dont_show_subgroups'][0] = __('Don\'t show subgroups:'); - $table->data['source_data_dont_show_subgroups'][1] = - html_print_checkbox ('dont_show_subgroups', '1', $dont_show_subgroups, true, $disabled_source); - - $methods = array( - 'twopi' => 'radial', - 'dot' => 'flat', - 'circo' => 'circular', - 'neato' => 'spring1', - 'fdp' => 'spring2', - 'radial_dinamic' => 'radial dinamic' - ); - - $table->data[7][0] = __('Method generation networkmap'); - $table->data[7][1] = html_print_select($methods, 'method', $method, - '', '', 'twopi', true, false, true, '', - $disabled_generation_method_select); + $table->head = []; - $itemClass = ""; - if ($disabled_source) { - $itemClass = "disabled"; - } - $table->data['nodesep'][0] = __('Node separation'); - $table->data['nodesep'][1] = html_print_input_text ('node_sep', $node_sep, '', 5, 10,true, $disabled_source, false, $itemClass) . ui_print_help_tip (__('Separation between nodes. By default 0.25'), true); - - $table->data['ranksep'][0] = __('Rank separation'); - $table->data['ranksep'][1] = html_print_input_text ('rank_sep', $rank_sep, '', 5, 10,true, $disabled_source, false, $itemClass) . ui_print_help_tip (__('Only flat and radial. Separation between arrows. By default 0.5 in flat and 1.0 in radial'), true); - - $table->data['mindist'][0] = __('Min nodes dist'); - $table->data['mindist'][1] = html_print_input_text ('mindist', $mindist, '', 5, 10,true, $disabled_source, false, $itemClass) . ui_print_help_tip (__('Only circular. Minimum separation between all nodes. By default 1.0'), true); + $table->size = []; + $table->size[0] = '30%'; - $table->data['kval'][0] = __('Default ideal node separation'); - $table->data['kval'][1] = html_print_input_text ('kval', $kval, '', 5, 10,true, $disabled_source, false, $itemClass) . ui_print_help_tip (__('Only fdp. Default ideal node separation in the layout. By default 0.3'), true); + $table->style = []; + $table->style[0] = 'font-weight: bold; width: 150px;'; + $table->data = []; - echo '
                '; - - html_print_table($table); - - echo "
                "; - if ($new_networkmap) { - html_print_input_hidden ('save_networkmap', 1); - html_print_submit_button (__('Save networkmap'), 'crt', false, - 'class="sub"'); - } - if ($edit_networkmap) { - html_print_input_hidden ('id_networkmap', $id); - html_print_input_hidden ('update_networkmap', 1); - html_print_submit_button (__('Update networkmap'), 'crt', false, - 'class="sub"'); - } - echo ""; - echo "
                "; + $table->data[0][0] = __('Name'); + $table->data[0][1] = html_print_input_text( + 'name', + $name, + '', + 30, + 100, + true + ); + + $table->data[1][0] = __('Group'); + $table->data[1][1] = html_print_select_groups( + $config['id_user'], + 'AR', + true, + 'id_group', + $id_group, + '', + '', + '', + true + ); + + $table->data[2][0] = __('Node radius'); + $table->data[2][1] = html_print_input_text( + 'node_radius', + $node_radius, + '', + 2, + 10, + true + ); + + $table->data[3][0] = __('Description'); + $table->data[3][1] = html_print_textarea('description', 7, 25, $description, '', true); + + $table->data[4][0] = __('Position X'); + $table->data[4][1] = html_print_input_text('pos_x', $offset_x, '', 2, 10, true); + $table->data[5][0] = __('Position Y'); + $table->data[5][1] = html_print_input_text('pos_y', $offset_y, '', 2, 10, true); + + $table->data[6][0] = __('Zoom scale'); + if ($scale_z == '') { + $scale_z = 0.5; + } + + $table->data[6][1] = html_print_input_text('scale_z', $scale_z, '', 2, 10, true).ui_print_help_tip(__('Introduce zoom level. 1 = Highest resolution. Figures may include decimals'), true); + + $table->data['source'][0] = __('Source'); + $table->data['source'][1] = html_print_radio_button('source', 'group', __('Group'), $source, true, $disabled_source).html_print_radio_button('source', 'recon_task', __('Recon task'), $source, true, $disabled_source).html_print_radio_button('source', 'ip_mask', __('CIDR IP mask'), $source, true, $disabled_source); + + $table->data['source_data_recon_task'][0] = __('Source from recon task'); + $table->data['source_data_recon_task'][0] .= ui_print_help_tip( + __('It is setted any recon task, the nodes get from the recontask IP mask instead from the group.'), + true + ); + $table->data['source_data_recon_task'][1] = html_print_select( + $list_recon_tasks, + 'recon_task_id', + $recon_task_id, + '', + __('None'), + 0, + true, + false, + true, + '', + $disabled_source + ); + $table->data['source_data_recon_task'][1] .= ui_print_help_tip( + __('Show only the task with the recon script "SNMP L2 Recon".'), + true + ); + + $table->data['source_data_ip_mask'][0] = __('Source from CIDR IP mask'); + $table->data['source_data_ip_mask'][1] = html_print_input_text('ip_mask', $ip_mask, '', 20, 255, true, $disabled_source); + + $table->data['source_data_dont_show_subgroups'][0] = __('Don\'t show subgroups:'); + $table->data['source_data_dont_show_subgroups'][1] = html_print_checkbox('dont_show_subgroups', '1', $dont_show_subgroups, true, $disabled_source); + + $methods = [ + 'twopi' => 'radial', + 'dot' => 'flat', + 'circo' => 'circular', + 'neato' => 'spring1', + 'fdp' => 'spring2', + 'radial_dinamic' => 'radial dinamic', + ]; + + $table->data[7][0] = __('Method generation networkmap'); + $table->data[7][1] = html_print_select( + $methods, + 'method', + $method, + '', + '', + 'twopi', + true, + false, + true, + '', + $disabled_generation_method_select + ); + + $itemClass = ''; + if ($disabled_source) { + $itemClass = 'disabled'; + } + + $table->data['nodesep'][0] = __('Node separation'); + $table->data['nodesep'][1] = html_print_input_text('node_sep', $node_sep, '', 5, 10, true, $disabled_source, false, $itemClass).ui_print_help_tip(__('Separation between nodes. By default 0.25'), true); + + $table->data['ranksep'][0] = __('Rank separation'); + $table->data['ranksep'][1] = html_print_input_text('rank_sep', $rank_sep, '', 5, 10, true, $disabled_source, false, $itemClass).ui_print_help_tip(__('Only flat and radial. Separation between arrows. By default 0.5 in flat and 1.0 in radial'), true); + + $table->data['mindist'][0] = __('Min nodes dist'); + $table->data['mindist'][1] = html_print_input_text('mindist', $mindist, '', 5, 10, true, $disabled_source, false, $itemClass).ui_print_help_tip(__('Only circular. Minimum separation between all nodes. By default 1.0'), true); + + $table->data['kval'][0] = __('Default ideal node separation'); + $table->data['kval'][1] = html_print_input_text('kval', $kval, '', 5, 10, true, $disabled_source, false, $itemClass).ui_print_help_tip(__('Only fdp. Default ideal node separation in the layout. By default 0.3'), true); + + echo '
                '; + + html_print_table($table); + + echo "
                "; + if ($new_networkmap) { + html_print_input_hidden('save_networkmap', 1); + html_print_submit_button( + __('Save networkmap'), + 'crt', + false, + 'class="sub"' + ); + } + + if ($edit_networkmap) { + html_print_input_hidden('id_networkmap', $id); + html_print_input_hidden('update_networkmap', 1); + html_print_submit_button( + __('Update networkmap'), + 'crt', + false, + 'class="sub"' + ); + } + + echo ''; + echo '
                '; } ?> diff --git a/pandora_console/operation/agentes/pandora_networkmap.php b/pandora_console/operation/agentes/pandora_networkmap.php index 73b83029d8..604d800307 100644 --- a/pandora_console/operation/agentes/pandora_networkmap.php +++ b/pandora_console/operation/agentes/pandora_networkmap.php @@ -1,15 +1,14 @@ $id)); - } - - $result_txt = ui_print_result_message($result, - __('Succesfully updated'), __('Could not be updated'), '', - true); - } + if (!$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } + + $name = (string) get_parameter('name', ''); + + // Default size values + $width = 4000; + $height = 4000; + + $method = (string) get_parameter('method', 'fdp'); + + $dont_show_subgroups = 0; + $node_radius = (int) get_parameter('node_radius', 40); + $description = get_parameter('description', ''); + + $values = []; + $values['name'] = $name; + $values['id_group'] = $id_group; + $values['source_period'] = 60; + $values['width'] = $width; + $values['height'] = $height; + $values['id_user'] = $config['id_user']; + $values['description'] = $description; + $values['source'] = 0; + $values['source_data'] = $id_group; + + + if (!$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } + + $filter = []; + $filter['dont_show_subgroups'] = $dont_show_subgroups; + $filter['node_radius'] = $node_radius; + $filter['empty_map'] = 1; + $values['filter'] = json_encode($filter); + + $result = false; + if (!empty($name)) { + $result = db_process_sql_insert( + 'tmap', + $values + ); + } + + $result_txt = ui_print_result_message( + $result, + __('Succesfully created'), + __('Could not be created'), + '', + true + ); + + $id = $result; + define('_id_', $id); + + $tab = 'view'; + } else if ($update_empty_networkmap) { + $id_group = (int) get_parameter('id_group', 0); + + // ACL for the new network map + $networkmap_write_new = check_acl($config['id_user'], $id_group, 'MW'); + $networkmap_manage_new = check_acl($config['id_user'], $id_group, 'MM'); + + if (!$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } + + $name = (string) get_parameter('name', ''); + + $recon_task_id = (int) get_parameter( + 'recon_task_id', + 0 + ); + + $source = (string) get_parameter('source', 'group'); + + $values = []; + $values['name'] = $name; + $values['id_group'] = $id_group; + + $values['generation_method'] = 4; + + $description = get_parameter('description', ''); + $values['description'] = $description; + + $dont_show_subgroups = 0; + $node_radius = (int) get_parameter('node_radius', 40); + $row = db_get_row('tmap', 'id', $id); + $filter = json_decode($row['filter'], true); + $filter['dont_show_subgroups'] = $dont_show_subgroups; + $filter['node_radius'] = $node_radius; + + $values['filter'] = json_encode($filter); + + $result = false; + if (!empty($name)) { + $result = db_process_sql_update( + 'tmap', + $values, + ['id' => $id] + ); + } + + $result_txt = ui_print_result_message( + $result, + __('Succesfully updated'), + __('Could not be updated'), + '', + true + ); + } } $result_txt = ''; // The networkmap doesn't exist yet if ($new_networkmap || $save_networkmap) { - if ($new_networkmap) { - if ($networkmaps_write || $networkmaps_manage) { - require('pandora_networkmap.editor.php'); - return; - } - else { - db_pandora_audit("ACL Violation", - "Trying to access networkmap"); - require ("general/noaccess.php"); - return; - } - } - if ($save_networkmap) { - $id_group = (int) get_parameter('id_group', 0); - - // ACL for the network map - // $networkmap_read = check_acl ($config['id_user'], $id_group, "MR"); - $networkmap_write = check_acl ($config['id_user'], $id_group, "MW"); - $networkmap_manage = check_acl ($config['id_user'], $id_group, "MM"); - - if (!$networkmap_write && !$networkmap_manage) { - db_pandora_audit("ACL Violation", - "Trying to access networkmap"); - require ("general/noaccess.php"); - return; - } - - $name = (string) get_parameter('name', ''); - - // Default size values - $width = 4000; - $height = 4000; - - $method = (string) get_parameter('method', 'fdp'); - - $recon_task_id = (int) get_parameter( - 'recon_task_id', 0); - $ip_mask = get_parameter( - 'ip_mask', ''); - $source = (string)get_parameter('source', 'group'); - $dont_show_subgroups = (int)get_parameter('dont_show_subgroups', 0); - $node_radius = (int)get_parameter('node_radius', 40); - $description = get_parameter('description', ''); + if ($new_networkmap) { + if ($networkmaps_write || $networkmaps_manage) { + include 'pandora_networkmap.editor.php'; + return; + } else { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } + } - $offset_x = get_parameter('pos_x'); - $offset_y = get_parameter('pos_y'); - $scale_z = get_parameter('scale_z', 0.5); + if ($save_networkmap) { + $id_group = (int) get_parameter('id_group', 0); - $node_sep = get_parameter('node_sep', "0.25"); - if ($method == "twopi") { - $rank_sep = get_parameter('rank_sep', "1.0"); - } - else { - $rank_sep = get_parameter('rank_sep', "0.5"); - } - $mindist = get_parameter('mindist', "1.0"); - $kval = get_parameter('kval', "0.3"); - - $values = array(); - $values['name'] = $name; - $values['id_group'] = $id_group; - $values['source_period'] = 60; - $values['width'] = $width; - $values['height'] = $height; - $values['id_user'] = $config['id_user']; - $values['description'] = $description; - - switch ($method) { - case 'twopi': - $values['generation_method'] = 2; - break; - case 'dot': - $values['generation_method'] = 1; - break; - case 'circo': - $values['generation_method'] = 0; - break; - case 'neato': - $values['generation_method'] = 3; - break; - case 'fdp': - $values['generation_method'] = 4; - break; - case 'radial_dinamic': - $values['generation_method'] = 6; - break; - default: - $values['generation_method'] = 2; - break; - } - - if ($source == 'group') { - $values['source'] = 0; - $values['source_data'] = $id_group; - } - else if ($source == 'recon_task') { - $values['source'] = 1; - $values['source_data'] = $recon_task_id; - } - else if ($source == 'ip_mask') { - $values['source'] = 2; - $values['source_data'] = $ip_mask; - } - - if (!$networkmap_write && !$networkmap_manage) { - db_pandora_audit("ACL Violation", - "Trying to access networkmap"); - require ("general/noaccess.php"); - return; - } - - $filter = array(); - $filter['dont_show_subgroups'] = $dont_show_subgroups; - $filter['node_radius'] = $node_radius; - $filter['x_offs'] = $offset_x; - $filter['y_offs'] = $offset_y; - $filter['z_dash'] = $scale_z; - $filter['node_sep'] = $node_sep; - $filter['rank_sep'] = $rank_sep; - $filter['mindist'] = $mindist; - $filter['kval'] = $kval; + // ACL for the network map + // $networkmap_read = check_acl ($config['id_user'], $id_group, "MR"); + $networkmap_write = check_acl($config['id_user'], $id_group, 'MW'); + $networkmap_manage = check_acl($config['id_user'], $id_group, 'MM'); - $values['filter'] = json_encode($filter); - - $result = false; - if (!empty($name)) { - $result = db_process_sql_insert('tmap', - $values); - } - - $result_txt = ui_print_result_message($result, - __('Succesfully created'), __('Could not be created'), '', - true); - - $id = $result; - define("_id_", $id); + if (!$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } - $tab = "view"; + $name = (string) get_parameter('name', ''); - if ($values['generation_method'] == 6) { - $tab = "r_dinamic"; - define("_activeTab_", 'radial_dynamic'); - } - } + // Default size values + $width = 4000; + $height = 4000; + + $method = (string) get_parameter('method', 'fdp'); + + $recon_task_id = (int) get_parameter( + 'recon_task_id', + 0 + ); + $ip_mask = get_parameter( + 'ip_mask', + '' + ); + $source = (string) get_parameter('source', 'group'); + $dont_show_subgroups = (int) get_parameter('dont_show_subgroups', 0); + $node_radius = (int) get_parameter('node_radius', 40); + $description = get_parameter('description', ''); + + $offset_x = get_parameter('pos_x'); + $offset_y = get_parameter('pos_y'); + $scale_z = get_parameter('scale_z', 0.5); + + $node_sep = get_parameter('node_sep', '0.25'); + if ($method == 'twopi') { + $rank_sep = get_parameter('rank_sep', '1.0'); + } else { + $rank_sep = get_parameter('rank_sep', '0.5'); + } + + $mindist = get_parameter('mindist', '1.0'); + $kval = get_parameter('kval', '0.3'); + + $values = []; + $values['name'] = $name; + $values['id_group'] = $id_group; + $values['source_period'] = 60; + $values['width'] = $width; + $values['height'] = $height; + $values['id_user'] = $config['id_user']; + $values['description'] = $description; + + switch ($method) { + case 'twopi': + $values['generation_method'] = 2; + break; + + case 'dot': + $values['generation_method'] = 1; + break; + + case 'circo': + $values['generation_method'] = 0; + break; + + case 'neato': + $values['generation_method'] = 3; + break; + + case 'fdp': + $values['generation_method'] = 4; + break; + + case 'radial_dinamic': + $values['generation_method'] = 6; + break; + + default: + $values['generation_method'] = 2; + break; + } + + if ($source == 'group') { + $values['source'] = 0; + $values['source_data'] = $id_group; + } else if ($source == 'recon_task') { + $values['source'] = 1; + $values['source_data'] = $recon_task_id; + } else if ($source == 'ip_mask') { + $values['source'] = 2; + $values['source_data'] = $ip_mask; + } + + if (!$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } + + $filter = []; + $filter['dont_show_subgroups'] = $dont_show_subgroups; + $filter['node_radius'] = $node_radius; + $filter['x_offs'] = $offset_x; + $filter['y_offs'] = $offset_y; + $filter['z_dash'] = $scale_z; + $filter['node_sep'] = $node_sep; + $filter['rank_sep'] = $rank_sep; + $filter['mindist'] = $mindist; + $filter['kval'] = $kval; + + $values['filter'] = json_encode($filter); + + $result = false; + if (!empty($name)) { + $result = db_process_sql_insert( + 'tmap', + $values + ); + } + + $result_txt = ui_print_result_message( + $result, + __('Succesfully created'), + __('Could not be created'), + '', + true + ); + + $id = $result; + define('_id_', $id); + + $tab = 'view'; + + if ($values['generation_method'] == 6) { + $tab = 'r_dinamic'; + define('_activeTab_', 'radial_dynamic'); + } + } } // The networkmap exists else if ($update_networkmap || $copy_networkmap || $delete) { - $id = (int) get_parameter('id_networkmap', 0); - - // Networkmap id required - if (empty($id)) { - db_pandora_audit("ACL Violation", - "Trying to access networkmap"); - require ("general/noaccess.php"); - return; - } - - $id_group_old = db_get_value('id_group', 'tmap', 'id', $id); - if ($id_group_old === false) { - db_pandora_audit("ACL Violation", - "Trying to accessnode graph builder"); - require ("general/noaccess.php"); - return; - } - - // ACL for the network map - $networkmap_write = check_acl ($config['id_user'], $id_group_old, "MW"); - $networkmap_manage = check_acl ($config['id_user'], $id_group_old, "MM"); - - if (!$networkmap_write && !$networkmap_manage) { - db_pandora_audit("ACL Violation", - "Trying to access networkmap"); - require ("general/noaccess.php"); - return; - } - - if ($update_networkmap) { - $id_group = (int) get_parameter('id_group', 0); - - // ACL for the new network map - $networkmap_write_new = check_acl ($config['id_user'], $id_group, "MW"); - $networkmap_manage_new = check_acl ($config['id_user'], $id_group, "MM"); - - if (!$networkmap_write && !$networkmap_manage) { - db_pandora_audit("ACL Violation", - "Trying to access networkmap"); - require ("general/noaccess.php"); - return; - } - - $name = (string) get_parameter('name', ''); - - $recon_task_id = (int) get_parameter( - 'recon_task_id', 0); - - $source = (string)get_parameter('source', 'group'); + $id = (int) get_parameter('id_networkmap', 0); - $offset_x = get_parameter('pos_x'); - $offset_y = get_parameter('pos_y'); - $scale_z = get_parameter('scale_z', 0.5); - - $values = array(); - $values['name'] = $name; - $values['id_group'] = $id_group; + // Networkmap id required + if (empty($id)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } - $description = get_parameter('description', ''); - $values['description'] = $description; - - $dont_show_subgroups = (int)get_parameter('dont_show_subgroups', 0); - $node_radius = (int)get_parameter('node_radius', 40); - $row = db_get_row('tmap', 'id', $id); - $filter = json_decode($row['filter'], true); - $filter['dont_show_subgroups'] = $dont_show_subgroups; - $filter['node_radius'] = $node_radius; - $filter['x_offs'] = $offset_x; - $filter['y_offs'] = $offset_y; - $filter['z_dash'] = $scale_z; - - $values['filter'] = json_encode($filter); - - $result = false; - if (!empty($name)) { - $result = db_process_sql_update('tmap', - $values, array('id' => $id)); - } - - $result_txt = ui_print_result_message($result, - __('Succesfully updated'), __('Could not be updated'), '', - true); - - if ($result) { - // If change the group, the map must be regenerated - if ($id_group != $id_group_old) { - networkmap_delete_nodes($id); - } - $networkmap_write = $networkmap_write_new; - $networkmap_manage = $networkmap_manage_new; - } - } - if ($copy_networkmap) { - $id = (int) get_parameter('id_networkmap', 0); - - $result = duplicate_networkmap($id); - $result_txt = ui_print_result_message($result, - __('Succesfully duplicate'), __('Could not be duplicated'), '', - true); - } - if ($delete) { - $id = (int)get_parameter('id_networkmap', 0); - - $result = networkmap_delete_networkmap($id); - - $result_txt = ui_print_result_message($result, - __('Succesfully deleted'), __('Could not be deleted'), '', - true); - } + $id_group_old = db_get_value('id_group', 'tmap', 'id', $id); + if ($id_group_old === false) { + db_pandora_audit( + 'ACL Violation', + 'Trying to accessnode graph builder' + ); + include 'general/noaccess.php'; + return; + } + + // ACL for the network map + $networkmap_write = check_acl($config['id_user'], $id_group_old, 'MW'); + $networkmap_manage = check_acl($config['id_user'], $id_group_old, 'MM'); + + if (!$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } + + if ($update_networkmap) { + $id_group = (int) get_parameter('id_group', 0); + + // ACL for the new network map + $networkmap_write_new = check_acl($config['id_user'], $id_group, 'MW'); + $networkmap_manage_new = check_acl($config['id_user'], $id_group, 'MM'); + + if (!$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } + + $name = (string) get_parameter('name', ''); + + $recon_task_id = (int) get_parameter( + 'recon_task_id', + 0 + ); + + $source = (string) get_parameter('source', 'group'); + + $offset_x = get_parameter('pos_x'); + $offset_y = get_parameter('pos_y'); + $scale_z = get_parameter('scale_z', 0.5); + + $values = []; + $values['name'] = $name; + $values['id_group'] = $id_group; + + $description = get_parameter('description', ''); + $values['description'] = $description; + + $dont_show_subgroups = (int) get_parameter('dont_show_subgroups', 0); + $node_radius = (int) get_parameter('node_radius', 40); + $row = db_get_row('tmap', 'id', $id); + $filter = json_decode($row['filter'], true); + $filter['dont_show_subgroups'] = $dont_show_subgroups; + $filter['node_radius'] = $node_radius; + $filter['x_offs'] = $offset_x; + $filter['y_offs'] = $offset_y; + $filter['z_dash'] = $scale_z; + + $values['filter'] = json_encode($filter); + + $result = false; + if (!empty($name)) { + $result = db_process_sql_update( + 'tmap', + $values, + ['id' => $id] + ); + } + + $result_txt = ui_print_result_message( + $result, + __('Succesfully updated'), + __('Could not be updated'), + '', + true + ); + + if ($result) { + // If change the group, the map must be regenerated + if ($id_group != $id_group_old) { + networkmap_delete_nodes($id); + } + + $networkmap_write = $networkmap_write_new; + $networkmap_manage = $networkmap_manage_new; + } + } + + if ($copy_networkmap) { + $id = (int) get_parameter('id_networkmap', 0); + + $result = duplicate_networkmap($id); + $result_txt = ui_print_result_message( + $result, + __('Succesfully duplicate'), + __('Could not be duplicated'), + '', + true + ); + } + + if ($delete) { + $id = (int) get_parameter('id_networkmap', 0); + + $result = networkmap_delete_networkmap($id); + + $result_txt = ui_print_result_message( + $result, + __('Succesfully deleted'), + __('Could not be deleted'), + '', + true + ); + } } switch ($tab) { - case 'r_dinamic': - require('networkmap.dinamic.php'); - break; - case 'edit': - require('pandora_networkmap.editor.php'); - break; - case 'view': - require('pandora_networkmap.view.php'); - break; - case 'list': - $old_networkmaps_enterprise = array(); - $old_networkmaps_open = array(); - - if (enterprise_installed()) { - $old_networkmaps_enterprise = db_get_all_rows_sql("SELECT * FROM tnetworkmap_enterprise"); - if ($old_networkmaps_enterprise === false) $old_networkmaps_enterprise = array(); - } - $old_networkmaps_open = db_get_all_rows_sql("SELECT * FROM tnetwork_map"); - - $ent_maps_to_migrate = array(); - foreach ($old_networkmaps_enterprise as $old_map_ent) { - $old_map_options = json_decode($old_map_ent['options'], true); - - if (!isset($old_map_options['migrated'])) { - $ent_maps_to_migrate[] = $old_map_ent['id']; - } - } + case 'r_dinamic': + include 'networkmap.dinamic.php'; + break; - $open_maps_to_migrate = array(); - if(isset($old_networkmaps_open) && is_array($old_networkmaps_open)){ - foreach ($old_networkmaps_open as $old_map_open) { - $text_filter = $old_map_open['text_filter']; - if ($text_filter != "migrated") { - $open_maps_to_migrate[] = $old_map_open['id_networkmap']; - } - } - } + case 'edit': + include 'pandora_networkmap.editor.php'; + break; - if (!empty($ent_maps_to_migrate) || !empty($open_maps_to_migrate)) { - ?> -
                -

                Networkmaps are not migrated, wait while migration is processed...

                -
                - -
                - - width = "100%"; - $table->class = "databox data"; - $table->headstyle['copy'] = 'text-align: center;'; - $table->headstyle['edit'] = 'text-align: center;'; - - $table->style = array(); - $table->style['name'] = ''; - if(enterprise_installed()) { - $table->style['nodes'] = 'text-align: center;'; - } - $table->style['groups'] = 'text-align: left;'; - if ($networkmaps_write || $networkmaps_manage) { - $table->style['copy'] = 'text-align: center;'; - $table->style['edit'] = 'text-align: center;'; - $table->style['delete'] = 'text-align: center;'; - } - - $table->size = array(); - $table->size['name'] = '60%'; - if(enterprise_installed()) { - $table->size['nodes'] = '30px'; - } - $table->size['groups'] = '400px'; - if ($networkmaps_write || $networkmaps_manage) { - $table->size['copy'] = '30px'; - $table->size['edit'] = '30px'; - $table->size['delete'] = '30px'; - } - - $table->head = array(); - $table->head['name'] = __('Name'); - if(enterprise_installed()) { - $table->head['nodes'] = __('Nodes'); - } - $table->head['groups'] = __('Groups'); - if ($networkmaps_write || $networkmaps_manage) { - $table->head['copy'] = __('Copy'); - $table->head['edit'] = __('Edit'); - $table->head['delete'] = __('Delete'); - } - $id_groups = array_keys(users_get_groups()); - - $network_maps = db_get_all_rows_filter('tmap', - array('id_group' => $id_groups)); - - if ($network_maps !== false) { - $table->data = array(); - - foreach ($network_maps as $network_map) { - // ACL for the network map - $networkmap_read = check_acl ($config['id_user'], $network_map['id_group'], "MR"); - $networkmap_write = check_acl ($config['id_user'], $network_map['id_group'], "MW"); - $networkmap_manage = check_acl ($config['id_user'], $network_map['id_group'], "MM"); - - if (!$networkmap_read && !$networkmap_write && !$networkmap_manage) { - db_pandora_audit("ACL Violation", - "Trying to access networkmap enterprise"); - require ("general/noaccess.php"); - return; - } - - $data = array(); - if ($network_map['generation_method'] == 6) { - $data['name'] = '' . - $network_map['name'] . ''; - } - else { - $data['name'] = '' . - $network_map['name'] . ''; - } - - if ($network_map['id_group'] > 0) { - $nodes = db_get_all_rows_sql("SELECT style FROM titem WHERE id_map = " . $network_map['id'] . " AND deleted = 0"); - $count = 0; - foreach ($nodes as $node) { - $node_style = json_decode($node['style'], true); - if ($node_style['id_group'] == $network_map['id_group']) { - $count++; - } - } - } - else { - $count = db_get_value_sql( - 'SELECT COUNT(*) + case 'view': + include 'pandora_networkmap.view.php'; + break; + + case 'list': + $old_networkmaps_enterprise = []; + $old_networkmaps_open = []; + + if (enterprise_installed()) { + $old_networkmaps_enterprise = db_get_all_rows_sql('SELECT * FROM tnetworkmap_enterprise'); + if ($old_networkmaps_enterprise === false) { + $old_networkmaps_enterprise = []; + } + } + + $old_networkmaps_open = db_get_all_rows_sql('SELECT * FROM tnetwork_map'); + + $ent_maps_to_migrate = []; + foreach ($old_networkmaps_enterprise as $old_map_ent) { + $old_map_options = json_decode($old_map_ent['options'], true); + + if (!isset($old_map_options['migrated'])) { + $ent_maps_to_migrate[] = $old_map_ent['id']; + } + } + + $open_maps_to_migrate = []; + if (isset($old_networkmaps_open) && is_array($old_networkmaps_open)) { + foreach ($old_networkmaps_open as $old_map_open) { + $text_filter = $old_map_open['text_filter']; + if ($text_filter != 'migrated') { + $open_maps_to_migrate[] = $old_map_open['id_networkmap']; + } + } + } + + if (!empty($ent_maps_to_migrate) || !empty($open_maps_to_migrate)) { + ?> +
                +

                Networkmaps are not migrated, wait while migration is processed...

                +
                + +
                + + width = '100%'; + $table->class = 'databox data'; + $table->headstyle['copy'] = 'text-align: center;'; + $table->headstyle['edit'] = 'text-align: center;'; + + $table->style = []; + $table->style['name'] = ''; + if (enterprise_installed()) { + $table->style['nodes'] = 'text-align: center;'; + } + + $table->style['groups'] = 'text-align: left;'; + if ($networkmaps_write || $networkmaps_manage) { + $table->style['copy'] = 'text-align: center;'; + $table->style['edit'] = 'text-align: center;'; + $table->style['delete'] = 'text-align: center;'; + } + + $table->size = []; + $table->size['name'] = '60%'; + if (enterprise_installed()) { + $table->size['nodes'] = '30px'; + } + + $table->size['groups'] = '400px'; + if ($networkmaps_write || $networkmaps_manage) { + $table->size['copy'] = '30px'; + $table->size['edit'] = '30px'; + $table->size['delete'] = '30px'; + } + + $table->head = []; + $table->head['name'] = __('Name'); + if (enterprise_installed()) { + $table->head['nodes'] = __('Nodes'); + } + + $table->head['groups'] = __('Groups'); + if ($networkmaps_write || $networkmaps_manage) { + $table->head['copy'] = __('Copy'); + $table->head['edit'] = __('Edit'); + $table->head['delete'] = __('Delete'); + } + + $id_groups = array_keys(users_get_groups()); + + $network_maps = db_get_all_rows_filter( + 'tmap', + ['id_group' => $id_groups] + ); + + if ($network_maps !== false) { + $table->data = []; + + foreach ($network_maps as $network_map) { + // ACL for the network map + $networkmap_read = check_acl($config['id_user'], $network_map['id_group'], 'MR'); + $networkmap_write = check_acl($config['id_user'], $network_map['id_group'], 'MW'); + $networkmap_manage = check_acl($config['id_user'], $network_map['id_group'], 'MM'); + + if (!$networkmap_read && !$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap enterprise' + ); + include 'general/noaccess.php'; + return; + } + + $data = []; + if ($network_map['generation_method'] == 6) { + $data['name'] = ''.$network_map['name'].''; + } else { + $data['name'] = ''.$network_map['name'].''; + } + + if ($network_map['id_group'] > 0) { + $nodes = db_get_all_rows_sql('SELECT style FROM titem WHERE id_map = '.$network_map['id'].' AND deleted = 0'); + $count = 0; + foreach ($nodes as $node) { + $node_style = json_decode($node['style'], true); + if ($node_style['id_group'] == $network_map['id_group']) { + $count++; + } + } + } else { + $count = db_get_value_sql( + 'SELECT COUNT(*) FROM titem - WHERE id_map = ' . $network_map['id'] . ' AND deleted = 0 AND type = 0'); - } - - if (empty($count)) - $count = 0; - - if(enterprise_installed()) { - if (($count == 0) && ($network_map['source'] != 'empty')) { - if ($network_map['generated']) { - $data['nodes'] = __('Empty map'); - } - else { - $data['nodes'] = __('Pending to generate'); - } - } - else { - $data['nodes'] = ($network_map['id_group'] == 0) ? $count - 1 : $count; //PandoraFMS node is not an agent - } - } - - $data['groups'] = ui_print_group_icon ($network_map['id_group'], true); - - if ($networkmap_write || $networkmap_manage) { - $data['copy'] = '' . - html_print_image("images/copy.png", true) . ''; - $data['edit'] = '' . - html_print_image("images/config.png", true) . ''; - $data['delete'] = '' . - html_print_image('images/cross.png', true) . ''; - } - - $table->data[] = $data; - } - - html_print_table($table); - } - else{ - ui_print_info_message ( array('no_close'=>true, 'message'=> __('There are no maps defined.') ) ); - } - - if ($networkmaps_write || $networkmaps_manage) { - echo "
                "; - echo '
                '; - html_print_input_hidden ('new_networkmap', 1); - html_print_submit_button (__('Create networkmap'), 'crt', false, 'class="sub next" style="float: right;"'); - echo "
                "; - echo "
                "; + WHERE id_map = '.$network_map['id'].' AND deleted = 0 AND type = 0' + ); + } - if (enterprise_installed()) { - echo "
                "; - echo '
                '; - html_print_input_hidden ('new_empty_networkmap', 1); - html_print_submit_button (__('Create empty networkmap'), 'crt', false, 'class="sub next" style="float: right; margin-right:20px;"'); - echo "
                "; - echo "
                "; - } - } - - break; + if (empty($count)) { + $count = 0; + } + + if (enterprise_installed()) { + if (($count == 0) && ($network_map['source'] != 'empty')) { + if ($network_map['generated']) { + $data['nodes'] = __('Empty map'); + } else { + $data['nodes'] = __('Pending to generate'); + } + } else { + $data['nodes'] = ($network_map['id_group'] == 0) ? ($count - 1) : $count; + // PandoraFMS node is not an agent + } + } + + $data['groups'] = ui_print_group_icon($network_map['id_group'], true); + + if ($networkmap_write || $networkmap_manage) { + $data['copy'] = ''.html_print_image('images/copy.png', true).''; + $data['edit'] = ''.html_print_image('images/config.png', true).''; + $data['delete'] = ''.html_print_image('images/cross.png', true).''; + } + + $table->data[] = $data; + } + + html_print_table($table); + } else { + ui_print_info_message(['no_close' => true, 'message' => __('There are no maps defined.') ]); + } + + if ($networkmaps_write || $networkmaps_manage) { + echo "
                "; + echo '
                '; + html_print_input_hidden('new_networkmap', 1); + html_print_submit_button(__('Create networkmap'), 'crt', false, 'class="sub next" style="float: right;"'); + echo '
                '; + echo '
                '; + + if (enterprise_installed()) { + echo "
                "; + echo '
                '; + html_print_input_hidden('new_empty_networkmap', 1); + html_print_submit_button(__('Create empty networkmap'), 'crt', false, 'class="sub next" style="float: right; margin-right:20px;"'); + echo '
                '; + echo '
                '; + } + } + break; } -?> + diff --git a/pandora_console/operation/agentes/pandora_networkmap.view.php b/pandora_console/operation/agentes/pandora_networkmap.view.php index d1916ea741..a9d570eed1 100644 --- a/pandora_console/operation/agentes/pandora_networkmap.view.php +++ b/pandora_console/operation/agentes/pandora_networkmap.view.php @@ -1,822 +1,915 @@ $z), - array('id' => $node)); - - echo json_encode($return); - - return; - } - - if ($update_fictional_point) { - $id_node = (int)get_parameter('id_node', 0); - $name = get_parameter('name', ''); - $shape = get_parameter('shape', 0); - $radious = (int)get_parameter('radious', 20); - $color = get_parameter('color', 0); - $networkmap = (int)get_parameter('networkmap', 0); - - $return = array(); - $return['correct'] = false; - - $row = db_get_row('titem', 'id', - $id_node); - $row['style'] = json_decode($row['style'], true); - $row['style']['shape'] = $shape; - //WORK AROUND FOR THE JSON ENCODE WITH FOR EXAMPLE Ñ OR Á - $row['style']['label'] = 'json_encode_crash_with_ut8_chars'; - $row['style']['color'] = $color; - $row['style']['networkmap'] = $networkmap; - $row['style']['width'] = $radious * 2; - $row['style']['height'] = $radious * 2; - $row['style'] = json_encode($row['style']); - $row['style'] = str_replace( - 'json_encode_crash_with_ut8_chars', $name, $row['style']); - - $return['correct'] = (bool)db_process_sql_update( - 'titem', $row, - array('id' => $id_node)); - - if ($return['correct']) { - $return['id_node'] = $id_node; - $return['shape'] = $shape; - $return['width'] = $radious * 2; - $return['height'] = $radious * 2; - $return['text'] = $name; - $return['color'] = $color; - $return['networkmap'] = $networkmap; - - $return['message'] = __('Success be updated.'); - } - else { - $return['message'] = __('Could not be updated.'); - } - - echo json_encode($return); - - return; - } - - if ($add_several_agents) { - $id = (int)get_parameter('id', 0); - $x = (int)get_parameter('x', 0); - $y = (int)get_parameter('y', 0); - $id_agents = get_parameter('id_agents', ''); - - $id_agents = json_decode($id_agents, true); - if ($id_agents === null) - $id_agents = array(); - - $return = array(); - $return['correct'] = true; - - $count = 0; - foreach ($id_agents as $id_agent) { - $id_node = add_agent_networkmap($id, '', - $x + ($count * 20), $y + ($count * 20), $id_agent); - - if ($id_node !== false) { - $node = db_get_row('titem', 'id', - $id_node); - $options = json_decode($node['options'], true); - - $data = array(); - $data['id_node'] = $id_node; - $data['source_data'] = $node['id_agent']; - $data['parent'] = $node['parent']; - $data['shape'] = $options['shape']; - $data['image'] = $options['image']; - $data['width'] = $options['width']; - $data['height'] = $options['height']; - $data['label'] = $options['text']; - $data['x'] = $node['x']; - $data['y'] = $node['y']; - $data['status'] = get_status_color_networkmap( - $id_agent); - $return['nodes'][] = $data; - } - $count++; - } - - echo json_encode($return); - - return; - } - - if ($get_tooltip_content) { - $id = (int)get_parameter('id', 0); - - // Get all module from agent - switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - $sql = sprintf (" +// --------------INIT AJAX----------------------------------------------- +if (is_ajax()) { + $update_refresh_state = (bool) get_parameter('update_refresh_state', false); + $set_center = (bool) get_parameter('set_center', false); + $erase_relation = (bool) get_parameter('erase_relation', false); + $search_agents = (bool) get_parameter('search_agents'); + $get_agent_pos_search = (bool) get_parameter('get_agent_pos_search', false); + $get_shape_node = (bool) get_parameter('get_shape_node', false); + $set_shape_node = (bool) get_parameter('set_shape_node', false); + $get_info_module = (bool) get_parameter('get_info_module', false); + $get_tooltip_content = (bool) get_parameter('get_tooltip_content', false); + $add_several_agents = (bool) get_parameter('add_several_agents', false); + $update_fictional_point = (bool) get_parameter('update_fictional_point', false); + $update_z = (bool) get_parameter('update_z', false); + $module_get_status = (bool) get_parameter('module_get_status', false); + $update_node_alert = (bool) get_parameter('update_node_alert', false); + $process_migration = (bool) get_parameter('process_migration', false); + + if ($module_get_status) { + $id = (int) get_parameter('id', 0); + + $return = []; + $return['correct'] = true; + $return['status'] = modules_get_agentmodule_status( + $id, + false, + false, + null + ); + + echo json_encode($return); + return; + } + + if ($update_z) { + $node = (int) get_parameter('node', 0); + + $return = []; + $return['correct'] = false; + + $z = db_get_value( + 'z', + 'titem', + 'id', + $node + ); + + $z++; + + $return['correct'] = (bool) db_process_sql_update( + 'titem', + ['z' => $z], + ['id' => $node] + ); + + echo json_encode($return); + + return; + } + + if ($update_fictional_point) { + $id_node = (int) get_parameter('id_node', 0); + $name = get_parameter('name', ''); + $shape = get_parameter('shape', 0); + $radious = (int) get_parameter('radious', 20); + $color = get_parameter('color', 0); + $networkmap = (int) get_parameter('networkmap', 0); + + $return = []; + $return['correct'] = false; + + $row = db_get_row( + 'titem', + 'id', + $id_node + ); + $row['style'] = json_decode($row['style'], true); + $row['style']['shape'] = $shape; + // WORK AROUND FOR THE JSON ENCODE WITH FOR EXAMPLE Ñ OR Á + $row['style']['label'] = 'json_encode_crash_with_ut8_chars'; + $row['style']['color'] = $color; + $row['style']['networkmap'] = $networkmap; + $row['style']['width'] = ($radious * 2); + $row['style']['height'] = ($radious * 2); + $row['style'] = json_encode($row['style']); + $row['style'] = str_replace( + 'json_encode_crash_with_ut8_chars', + $name, + $row['style'] + ); + + $return['correct'] = (bool) db_process_sql_update( + 'titem', + $row, + ['id' => $id_node] + ); + + if ($return['correct']) { + $return['id_node'] = $id_node; + $return['shape'] = $shape; + $return['width'] = ($radious * 2); + $return['height'] = ($radious * 2); + $return['text'] = $name; + $return['color'] = $color; + $return['networkmap'] = $networkmap; + + $return['message'] = __('Success be updated.'); + } else { + $return['message'] = __('Could not be updated.'); + } + + echo json_encode($return); + + return; + } + + if ($add_several_agents) { + $id = (int) get_parameter('id', 0); + $x = (int) get_parameter('x', 0); + $y = (int) get_parameter('y', 0); + $id_agents = get_parameter('id_agents', ''); + + $id_agents = json_decode($id_agents, true); + if ($id_agents === null) { + $id_agents = []; + } + + $return = []; + $return['correct'] = true; + + $count = 0; + foreach ($id_agents as $id_agent) { + $id_node = add_agent_networkmap( + $id, + '', + ($x + ($count * 20)), + ($y + ($count * 20)), + $id_agent + ); + + if ($id_node !== false) { + $node = db_get_row( + 'titem', + 'id', + $id_node + ); + $options = json_decode($node['options'], true); + + $data = []; + $data['id_node'] = $id_node; + $data['source_data'] = $node['id_agent']; + $data['parent'] = $node['parent']; + $data['shape'] = $options['shape']; + $data['image'] = $options['image']; + $data['width'] = $options['width']; + $data['height'] = $options['height']; + $data['label'] = $options['text']; + $data['x'] = $node['x']; + $data['y'] = $node['y']; + $data['status'] = get_status_color_networkmap( + $id_agent + ); + $return['nodes'][] = $data; + } + + $count++; + } + + echo json_encode($return); + + return; + } + + if ($get_tooltip_content) { + $id = (int) get_parameter('id', 0); + + // Get all module from agent + switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + $sql = sprintf( + ' SELECT * FROM tagente_estado, tagente_modulo LEFT JOIN tmodule_group ON tmodule_group.id_mg = tagente_modulo.id_module_group - WHERE tagente_modulo.id_agente_modulo = " . $id . " + WHERE tagente_modulo.id_agente_modulo = '.$id.' AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND tagente_modulo.disabled = 0 AND tagente_modulo.delete_pending = 0 - AND tagente_estado.utimestamp != 0"); - break; - // If Dbms is Oracle then field_list in sql statement has to be recoded. See oracle_list_all_field_table() - case "oracle": - $fields_tagente_estado = oracle_list_all_field_table( - 'tagente_estado', 'string'); - $fields_tagente_modulo = oracle_list_all_field_table( - 'tagente_modulo', 'string'); - $fields_tmodule_group = oracle_list_all_field_table( - 'tmodule_group', 'string'); - - $sql = sprintf (" - SELECT " . $fields_tagente_estado . ', ' . - $fields_tagente_modulo . ', ' . - $fields_tmodule_group . - " FROM tagente_estado, tagente_modulo + AND tagente_estado.utimestamp != 0' + ); + break; + + // If Dbms is Oracle then field_list in sql statement has to be recoded. See oracle_list_all_field_table() + case 'oracle': + $fields_tagente_estado = oracle_list_all_field_table( + 'tagente_estado', + 'string' + ); + $fields_tagente_modulo = oracle_list_all_field_table( + 'tagente_modulo', + 'string' + ); + $fields_tmodule_group = oracle_list_all_field_table( + 'tmodule_group', + 'string' + ); + + $sql = sprintf( + ' + SELECT '.$fields_tagente_estado.', '.$fields_tagente_modulo.', '.$fields_tmodule_group.' FROM tagente_estado, tagente_modulo LEFT JOIN tmodule_group ON tmodule_group.id_mg = tagente_modulo.id_module_group - WHERE tagente_modulo.id_agente_modulo = " . $id . " + WHERE tagente_modulo.id_agente_modulo = '.$id.' AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND tagente_modulo.disabled = 0 AND tagente_modulo.delete_pending = 0 - AND tagente_estado.utimestamp != 0"); - break; - } - - $modules = db_get_all_rows_sql ($sql); - if (empty ($modules)) { - $module = array (); - } - else { - $module = $modules[0]; - } - - $return = array(); - $return['correct'] = true; - - $return['content'] = '
                + AND tagente_estado.utimestamp != 0' + ); + break; + } + + $modules = db_get_all_rows_sql($sql); + if (empty($modules)) { + $module = []; + } else { + $module = $modules[0]; + } + + $return = []; + $return['correct'] = true; + + $return['content'] = '
                '; - - $return['content'] .= - "" . __('Name: ') . "" . - ui_print_string_substr($module["nombre"], 30, true) . - "
                "; - - if ($module["id_policy_module"]) { - $linked = policies_is_module_linked( - $module['id_agente_modulo']); - $id_policy = db_get_value_sql(' + + $return['content'] .= ''.__('Name: ').''.ui_print_string_substr($module['nombre'], 30, true).'
                '; + + if ($module['id_policy_module']) { + $linked = policies_is_module_linked( + $module['id_agente_modulo'] + ); + $id_policy = db_get_value_sql( + ' SELECT id_policy FROM tpolicy_modules - WHERE id = ' . $module["id_policy_module"]); - - if ($id_policy != "") - $name_policy = db_get_value_sql( - 'SELECT name + WHERE id = '.$module['id_policy_module'] + ); + + if ($id_policy != '') { + $name_policy = db_get_value_sql( + 'SELECT name FROM tpolicies - WHERE id = ' . $id_policy); - else - $name_policy = __("Unknown"); - - $policyInfo = policies_info_module_policy( - $module["id_policy_module"]); - - $adopt = false; - if (policies_is_module_adopt($module['id_agente_modulo'])) { - $adopt = true; - } - - if ($linked) { - if ($adopt) { - $img = 'images/policies_brick.png'; - $title = __('(Adopt) ') . $name_policy; - } - else { - $img = 'images/policies.png'; - $title = $name_policy; - } - } - else { - if ($adopt) { - $img = 'images/policies_not_brick.png'; - $title = __('(Unlinked) (Adopt) ') . $name_policy; - } - else { - $img = 'images/unlinkpolicy.png'; - $title = __('(Unlinked) ') . $name_policy; - } - } - - $return['content'] .= - "" . __('Policy: ') . "" . $title . "
                "; - } - - $status = STATUS_MODULE_WARNING; - $title = ""; - - if ($module["estado"] == 1) { - $status = STATUS_MODULE_CRITICAL; - $title = __('CRITICAL'); - } - elseif ($module["estado"] == 2) { - $status = STATUS_MODULE_WARNING; - $title = __('WARNING'); - } - elseif ($module["estado"] == 0) { - $status = STATUS_MODULE_OK; - $title = __('NORMAL'); - } - elseif ($module["estado"] == 3) { - $last_status = modules_get_agentmodule_last_status( - $module['id_agente_modulo']); - switch($last_status) { - case 0: - $status = STATUS_MODULE_OK; - $title = __('UNKNOWN') . " - " . __('Last status') . - " " . __('NORMAL'); - break; - case 1: - $status = STATUS_MODULE_CRITICAL; - $title = __('UNKNOWN') . " - " . __('Last status') . - " " . __('CRITICAL'); - break; - case 2: - $status = STATUS_MODULE_WARNING; - $title = __('UNKNOWN') . " - " . __('Last status') . - " " . __('WARNING'); - break; - } - } - - if (is_numeric($module["datos"])) { - $title .= ": " . format_for_graph($module["datos"]); - } - else { - $title .= ": " . substr(io_safe_output($module["datos"]), 0, - 42); - } - - $return['content'] .= - "" . __('Status: ') . "" . - ui_print_status_image($status, $title, true) . "
                "; - - if ($module["id_tipo_modulo"] == 24) { // log4x - switch($module["datos"]) { - case 10: - $salida = "TRACE"; - $style = "font-weight:bold; color:darkgreen;"; - break; - case 20: - $salida = "DEBUG"; - $style = "font-weight:bold; color:darkgreen;"; - break; - case 30: - $salida = "INFO"; - $style = "font-weight:bold; color:darkgreen;"; - break; - case 40: - $salida = "WARN"; - $style = "font-weight:bold; color:darkorange;"; - break; - case 50: - $salida = "ERROR"; - $style = "font-weight:bold; color:red;"; - break; - case 60: - $salida = "FATAL"; - $style = "font-weight:bold; color:red;"; - break; - } - $salida = "$salida"; - } - else { - if (is_numeric($module["datos"])) { - $salida = format_numeric($module["datos"]); - } - else { - $salida = ui_print_module_string_value( - $module["datos"], $module["id_agente_modulo"], - $module["current_interval"], $module["module_name"]); - } - } - - $return['content'] .= - "" . __('Data: ') . "" . $salida . "
                "; - - $return['content'] .= - "" . __('Last contact: ') . "" . - ui_print_timestamp ($module["utimestamp"], true, - array('style' => 'font-size: 7pt')) . - "
                "; - - $return['content'] .= ' + WHERE id = '.$id_policy + ); + } else { + $name_policy = __('Unknown'); + } + + $policyInfo = policies_info_module_policy( + $module['id_policy_module'] + ); + + $adopt = false; + if (policies_is_module_adopt($module['id_agente_modulo'])) { + $adopt = true; + } + + if ($linked) { + if ($adopt) { + $img = 'images/policies_brick.png'; + $title = __('(Adopt) ').$name_policy; + } else { + $img = 'images/policies.png'; + $title = $name_policy; + } + } else { + if ($adopt) { + $img = 'images/policies_not_brick.png'; + $title = __('(Unlinked) (Adopt) ').$name_policy; + } else { + $img = 'images/unlinkpolicy.png'; + $title = __('(Unlinked) ').$name_policy; + } + } + + $return['content'] .= ''.__('Policy: ').''.$title.'
                '; + } + + $status = STATUS_MODULE_WARNING; + $title = ''; + + if ($module['estado'] == 1) { + $status = STATUS_MODULE_CRITICAL; + $title = __('CRITICAL'); + } else if ($module['estado'] == 2) { + $status = STATUS_MODULE_WARNING; + $title = __('WARNING'); + } else if ($module['estado'] == 0) { + $status = STATUS_MODULE_OK; + $title = __('NORMAL'); + } else if ($module['estado'] == 3) { + $last_status = modules_get_agentmodule_last_status( + $module['id_agente_modulo'] + ); + switch ($last_status) { + case 0: + $status = STATUS_MODULE_OK; + $title = __('UNKNOWN').' - '.__('Last status').' '.__('NORMAL'); + break; + + case 1: + $status = STATUS_MODULE_CRITICAL; + $title = __('UNKNOWN').' - '.__('Last status').' '.__('CRITICAL'); + break; + + case 2: + $status = STATUS_MODULE_WARNING; + $title = __('UNKNOWN').' - '.__('Last status').' '.__('WARNING'); + break; + } + } + + if (is_numeric($module['datos'])) { + $title .= ': '.format_for_graph($module['datos']); + } else { + $title .= ': '.substr( + io_safe_output($module['datos']), + 0, + 42 + ); + } + + $return['content'] .= ''.__('Status: ').''.ui_print_status_image($status, $title, true).'
                '; + + if ($module['id_tipo_modulo'] == 24) { + // log4x + switch ($module['datos']) { + case 10: + $salida = 'TRACE'; + $style = 'font-weight:bold; color:darkgreen;'; + break; + + case 20: + $salida = 'DEBUG'; + $style = 'font-weight:bold; color:darkgreen;'; + break; + + case 30: + $salida = 'INFO'; + $style = 'font-weight:bold; color:darkgreen;'; + break; + + case 40: + $salida = 'WARN'; + $style = 'font-weight:bold; color:darkorange;'; + break; + + case 50: + $salida = 'ERROR'; + $style = 'font-weight:bold; color:red;'; + break; + + case 60: + $salida = 'FATAL'; + $style = 'font-weight:bold; color:red;'; + break; + } + + $salida = "$salida"; + } else { + if (is_numeric($module['datos'])) { + $salida = format_numeric($module['datos']); + } else { + $salida = ui_print_module_string_value( + $module['datos'], + $module['id_agente_modulo'], + $module['current_interval'], + $module['module_name'] + ); + } + } + + $return['content'] .= ''.__('Data: ').''.$salida.'
                '; + + $return['content'] .= ''.__('Last contact: ').''.ui_print_timestamp( + $module['utimestamp'], + true, + ['style' => 'font-size: 7pt'] + ).'
                '; + + $return['content'] .= '
                '; - - echo json_encode($return); - - return; - } - - if ($set_shape_node) { - $id = (int)get_parameter('id', 0); - $shape = get_parameter('shape', 'circle'); - - $return = array(); - $return['correct'] = false; - - $node = db_get_row_filter('titem', - array('id' => $id)); - $style = json_decode($node['style'], true); - - $style['shape'] = $shape; - $style = json_encode($style); - - $return['correct'] = db_process_sql_update( - 'titem', - array('style' => $style), array('id' => $id)); - - echo json_encode($return); - - return; - } - - if ($get_shape_node) { - $id = (int)get_parameter('id', 0); - - $return = array(); - $return['correct'] = true; - - $node = db_get_row_filter('titem', - array('id' => $id)); - $node['style'] = json_decode($node['style'], true); - - $return['shape'] = $node['style']['shape']; - - echo json_encode($return); - - return; - } - - if ($get_agent_pos_search) { - $id = (int)get_parameter('id', 0); - $name = (string)get_parameter('name'); - - $return = array(); - $return['correct'] = true; - - $node = db_get_row_filter('titem', - array('id_map' => $id, - 'options' => '%\"label\":\"%' . $name . '%\"%')); - $return['x'] = $node['x']; - $return['y'] = $node['y']; - - echo json_encode($return); - - return; - } - - if ($search_agents) { - require_once ('include/functions_agents.php'); - - $id = (int)get_parameter('id', 0); - /* q is what autocomplete plugin gives */ - $string = (string) get_parameter('q'); - - $agents = db_get_all_rows_filter('titem', - array('id_map' => $id, - 'options' => '%\"label\":\"%' . $string . '%\"%')); - - if ($agents === false) - $agents = array(); - - $data = array(); - foreach ($agents as $agent) { - $style = json_decode($agent['style'], true); - $data[] = array('name' => $style['label']); - } - - echo json_encode($data); - - return; - } - - if ($update_refresh_state) { - $refresh_state = (int)get_parameter('refresh_state', 60); - $id = (int)get_parameter('id', 0); - - $filter = db_get_value('filter', 'tmap', - 'id', $id); - $filter = json_decode($filter, true); - $filter['source_period'] = $refresh_state; - $filter = json_encode($filter); - - $correct = db_process_sql_update('tmap', - array('filter' => $filter), array('id' => $id)); - - $return = array(); - $return['correct'] = false; - - if ($correct) - $return['correct'] = true; - - echo json_encode($return); - - return; - } - - if ($set_center) { - $id = (int)get_parameter('id', 0); - $x = (int)get_parameter('x', 0); - $y = (int)get_parameter('y', 0); - $scale = (float)get_parameter('scale', 0); - - $networkmap = db_get_row('tmap', 'id', $id); - - $array_filter = json_decode($networkmap['filter']); - if (isset($array_filter->z_dash)) { - $array_filter->z_dash = number_format($scale,2); - } - $filter = json_encode($array_filter); - // ACL for the network map - // $networkmap_read = check_acl ($config['id_user'], $networkmap['id_group'], "MR"); - $networkmap_write = check_acl ($config['id_user'], $networkmap['id_group'], "MW"); - $networkmap_manage = check_acl ($config['id_user'], $networkmap['id_group'], "MM"); - - if (!$networkmap_write && !$networkmap_manage) { - db_pandora_audit("ACL Violation", - "Trying to access networkmap"); - echo json_encode($return); - return; - } - - $networkmap['center_x'] = $x; - $networkmap['center_y'] = $y; - db_process_sql_update('tmap', - array('center_x' => $networkmap['center_x'], 'center_y' => $networkmap['center_y'], 'filter' => $filter), - array('id' => $id)); - - $return = array(); - $return['correct'] = true; - - echo json_encode($return); - - return; - } - - if ($erase_relation) { - $id = (int)get_parameter('id', 0); - $child = (int)get_parameter('child', 0); - $parent = (int)get_parameter('parent', 0); - - $where = array(); - $where['id_map'] = $id; - $where['id_child'] = $child; - $where['id_parent'] = $parent; - - $return = array(); - $return['correct'] = db_process_sql_delete( - 'trel_item', $where); - - echo json_encode($return); - - return; - } - - //Popup - $get_status_node = (bool)get_parameter('get_status_node', false); - $get_status_module = (bool)get_parameter('get_status_module', - false); - - if ($get_status_node) { - $id = (int)get_parameter('id', 0); - - $return = array(); - $return['correct'] = true; - - $return['status_agent'] = get_status_color_networkmap($id); - - echo json_encode($return); - - return; - } - - if ($get_status_module) { - $id = (int)get_parameter('id', 0); - - $return = array(); - $return['correct'] = true; - $return['id'] = $id; - $return['status_color'] = get_status_color_module_networkmap( - $id); - - echo json_encode($return); - - return; - } - - if ($update_node_alert) { - $map_id = (int)get_parameter('map_id', 0); - - $filter = db_get_value('filter', 'tmap', 'id', $map_id); - $filter = json_decode($filter, true); - - $return = array(); - $return['correct'] = false; - if (!isset($filter['alert'])) { - $return['correct'] = true; - $filter['alert'] = 1; - $filter = json_encode($filter); - $values = array('filter' => $filter); - db_process_sql_update('tmap', $values, array('id' => $map_id)); - } - - echo json_encode($return); - - return; - } - - if ($process_migration) { - $old_maps_ent = get_parameter('old_maps_ent', true); - - $old_maps_open = get_parameter('old_maps_open', true); - - $return_data = array(); - - $return_data['ent'] = true; - if ($old_maps_ent != 0) { - $old_maps_ent = explode(",", $old_maps_ent); - if (enterprise_installed()) { - foreach ($old_maps_ent as $id_ent_map) { - $return = migrate_older_networkmap_enterprise($id_ent_map); - - if (!$return) { - $return_data['ent'] = false; - break; - } - else { - $old_networkmap_ent = db_get_row_filter('tnetworkmap_enterprise', - array('id' => $id_ent_map)); - - $options = json_decode($old_networkmap_ent, true); - $options['migrated'] = "migrated"; - - $values['options'] = json_encode($options); - - $return_update = db_process_sql_update('tnetworkmap_enterprise', $values, array('id' => $id_ent_map)); - if (!$return_update) { - $return_data['ent'] = false; - break; - } - } - } - } - } - - $return_data['open'] = true; - if ($old_maps_open != 0) { - $old_maps_open = explode(",", $old_maps_open); - foreach ($old_maps_open as $id_open_map) { - $return = migrate_older_open_maps($id_open_map); - - if (!$return) { - $return_data['open'] = false; - break; - } - else { - $values['text_filter'] = "migrated"; - - $return_update = db_process_sql_update('tnetwork_map', $values, array('id_networkmap' => $id_open_map)); - if (!$return_update) { - $return_data['open'] = false; - break; - } - } - } - } - - echo json_encode($return_data); - - return; - } + echo json_encode($return); + + return; + } + + if ($set_shape_node) { + $id = (int) get_parameter('id', 0); + $shape = get_parameter('shape', 'circle'); + + $return = []; + $return['correct'] = false; + + $node = db_get_row_filter( + 'titem', + ['id' => $id] + ); + $style = json_decode($node['style'], true); + + $style['shape'] = $shape; + $style = json_encode($style); + + $return['correct'] = db_process_sql_update( + 'titem', + ['style' => $style], + ['id' => $id] + ); + + echo json_encode($return); + + return; + } + + if ($get_shape_node) { + $id = (int) get_parameter('id', 0); + + $return = []; + $return['correct'] = true; + + $node = db_get_row_filter( + 'titem', + ['id' => $id] + ); + $node['style'] = json_decode($node['style'], true); + + $return['shape'] = $node['style']['shape']; + + echo json_encode($return); + + return; + } + + if ($get_agent_pos_search) { + $id = (int) get_parameter('id', 0); + $name = (string) get_parameter('name'); + + $return = []; + $return['correct'] = true; + + $node = db_get_row_filter( + 'titem', + [ + 'id_map' => $id, + 'options' => '%\"label\":\"%'.$name.'%\"%', + ] + ); + $return['x'] = $node['x']; + $return['y'] = $node['y']; + + echo json_encode($return); + + return; + } + + if ($search_agents) { + include_once 'include/functions_agents.php'; + + $id = (int) get_parameter('id', 0); + // q is what autocomplete plugin gives + $string = (string) get_parameter('q'); + + $agents = db_get_all_rows_filter( + 'titem', + [ + 'id_map' => $id, + 'options' => '%\"label\":\"%'.$string.'%\"%', + ] + ); + + if ($agents === false) { + $agents = []; + } + + $data = []; + foreach ($agents as $agent) { + $style = json_decode($agent['style'], true); + $data[] = ['name' => $style['label']]; + } + + echo json_encode($data); + + return; + } + + if ($update_refresh_state) { + $refresh_state = (int) get_parameter('refresh_state', 60); + $id = (int) get_parameter('id', 0); + + $filter = db_get_value( + 'filter', + 'tmap', + 'id', + $id + ); + $filter = json_decode($filter, true); + $filter['source_period'] = $refresh_state; + $filter = json_encode($filter); + + $correct = db_process_sql_update( + 'tmap', + ['filter' => $filter], + ['id' => $id] + ); + + $return = []; + $return['correct'] = false; + + if ($correct) { + $return['correct'] = true; + } + + echo json_encode($return); + + return; + } + + if ($set_center) { + $id = (int) get_parameter('id', 0); + $x = (int) get_parameter('x', 0); + $y = (int) get_parameter('y', 0); + $scale = (float) get_parameter('scale', 0); + + $networkmap = db_get_row('tmap', 'id', $id); + + $array_filter = json_decode($networkmap['filter']); + if (isset($array_filter->z_dash)) { + $array_filter->z_dash = number_format($scale, 2); + } + + $filter = json_encode($array_filter); + + // ACL for the network map + // $networkmap_read = check_acl ($config['id_user'], $networkmap['id_group'], "MR"); + $networkmap_write = check_acl($config['id_user'], $networkmap['id_group'], 'MW'); + $networkmap_manage = check_acl($config['id_user'], $networkmap['id_group'], 'MM'); + + if (!$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + echo json_encode($return); + return; + } + + $networkmap['center_x'] = $x; + $networkmap['center_y'] = $y; + db_process_sql_update( + 'tmap', + [ + 'center_x' => $networkmap['center_x'], + 'center_y' => $networkmap['center_y'], + 'filter' => $filter, + ], + ['id' => $id] + ); + + $return = []; + $return['correct'] = true; + + echo json_encode($return); + + return; + } + + if ($erase_relation) { + $id = (int) get_parameter('id', 0); + $child = (int) get_parameter('child', 0); + $parent = (int) get_parameter('parent', 0); + + $where = []; + $where['id_map'] = $id; + $where['id_child'] = $child; + $where['id_parent'] = $parent; + + $return = []; + $return['correct'] = db_process_sql_delete( + 'trel_item', + $where + ); + + echo json_encode($return); + + return; + } + + // Popup + $get_status_node = (bool) get_parameter('get_status_node', false); + $get_status_module = (bool) get_parameter( + 'get_status_module', + false + ); + + if ($get_status_node) { + $id = (int) get_parameter('id', 0); + + $return = []; + $return['correct'] = true; + + $return['status_agent'] = get_status_color_networkmap($id); + + echo json_encode($return); + + return; + } + + if ($get_status_module) { + $id = (int) get_parameter('id', 0); + + $return = []; + $return['correct'] = true; + $return['id'] = $id; + $return['status_color'] = get_status_color_module_networkmap( + $id + ); + + echo json_encode($return); + + return; + } + + if ($update_node_alert) { + $map_id = (int) get_parameter('map_id', 0); + + $filter = db_get_value('filter', 'tmap', 'id', $map_id); + $filter = json_decode($filter, true); + + $return = []; + $return['correct'] = false; + if (!isset($filter['alert'])) { + $return['correct'] = true; + $filter['alert'] = 1; + $filter = json_encode($filter); + $values = ['filter' => $filter]; + db_process_sql_update('tmap', $values, ['id' => $map_id]); + } + + echo json_encode($return); + + return; + } + + if ($process_migration) { + $old_maps_ent = get_parameter('old_maps_ent', true); + + $old_maps_open = get_parameter('old_maps_open', true); + + $return_data = []; + + $return_data['ent'] = true; + if ($old_maps_ent != 0) { + $old_maps_ent = explode(',', $old_maps_ent); + if (enterprise_installed()) { + foreach ($old_maps_ent as $id_ent_map) { + $return = migrate_older_networkmap_enterprise($id_ent_map); + + if (!$return) { + $return_data['ent'] = false; + break; + } else { + $old_networkmap_ent = db_get_row_filter( + 'tnetworkmap_enterprise', + ['id' => $id_ent_map] + ); + + $options = json_decode($old_networkmap_ent, true); + $options['migrated'] = 'migrated'; + + $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; + } + } + } + } + } + + $return_data['open'] = true; + if ($old_maps_open != 0) { + $old_maps_open = explode(',', $old_maps_open); + foreach ($old_maps_open as $id_open_map) { + $return = migrate_older_open_maps($id_open_map); + + if (!$return) { + $return_data['open'] = false; + break; + } 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; + } + } + } + } + + echo json_encode($return_data); + + return; + } } -//--------------END AJAX------------------------------------------------ -if (_id_ != "_id_") { - $id = _id_; -} -else { - $id = (int) get_parameter('id_networkmap', 0); + +// --------------END AJAX------------------------------------------------ +if (_id_ != '_id_') { + $id = _id_; +} else { + $id = (int) get_parameter('id_networkmap', 0); } // Print some params to handle it in js -html_print_input_hidden ('product_name', get_product_name()); -html_print_input_hidden ('center_logo', ui_get_full_url(ui_get_logo_to_center_networkmap())); +html_print_input_hidden('product_name', get_product_name()); +html_print_input_hidden('center_logo', ui_get_full_url(ui_get_logo_to_center_networkmap())); $dash_mode = 0; -$map_dash_details = array(); +$map_dash_details = []; $networkmap = db_get_row('tmap', 'id', $id); if (enterprise_installed()) { - include_once("enterprise/dashboard/widgets/network_map.php"); - if ($id_networkmap) { - $id = $id_networkmap; - $dash_mode = $dashboard_mode; - $x_offs = $x_offset; - $y_offs = $y_offset; - $z_dash = $zoom_dash; - $map_dash_details['x_offs'] = $x_offs; - $map_dash_details['y_offs'] = $y_offs; - $map_dash_details['z_dash'] = $z_dash; + include_once 'enterprise/dashboard/widgets/network_map.php'; + if ($id_networkmap) { + $id = $id_networkmap; + $dash_mode = $dashboard_mode; + $x_offs = $x_offset; + $y_offs = $y_offset; + $z_dash = $zoom_dash; + $map_dash_details['x_offs'] = $x_offs; + $map_dash_details['y_offs'] = $y_offs; + $map_dash_details['z_dash'] = $z_dash; - $networkmap = db_get_row('tmap', 'id', $id); - } - else { - $networkmap_filter = json_decode($networkmap['filter'], true); - if ($networkmap_filter['x_offs'] != null) { - $map_dash_details['x_offs'] = $networkmap_filter['x_offs']; - } - else { - $map_dash_details['x_offs'] = 0; - } - if ($networkmap_filter['y_offs'] != null) { - $map_dash_details['y_offs'] = $networkmap_filter['y_offs']; - } - else { - $map_dash_details['y_offs'] = 0; - } - if ($networkmap_filter['z_dash'] != null) { - $map_dash_details['z_dash'] = $networkmap_filter['z_dash']; - } - else { - $map_dash_details['z_dash'] = 0; - } - } + $networkmap = db_get_row('tmap', 'id', $id); + } else { + $networkmap_filter = json_decode($networkmap['filter'], true); + if ($networkmap_filter['x_offs'] != null) { + $map_dash_details['x_offs'] = $networkmap_filter['x_offs']; + } else { + $map_dash_details['x_offs'] = 0; + } + + if ($networkmap_filter['y_offs'] != null) { + $map_dash_details['y_offs'] = $networkmap_filter['y_offs']; + } else { + $map_dash_details['y_offs'] = 0; + } + + if ($networkmap_filter['z_dash'] != null) { + $map_dash_details['z_dash'] = $networkmap_filter['z_dash']; + } else { + $map_dash_details['z_dash'] = 0; + } + } } if ($networkmap === false) { - ui_print_page_header(__('Networkmap'), - "images/bricks.png", false, "network_map_enterprise", false); - ui_print_error_message(__('Not found networkmap.')); - - return; -} -else { - // ACL for the network map - $networkmap_read = check_acl ($config['id_user'], $networkmap['id_group'], "MR"); - $networkmap_write = check_acl ($config['id_user'], $networkmap['id_group'], "MW"); - $networkmap_manage = check_acl ($config['id_user'], $networkmap['id_group'], "MM"); - - if (!$networkmap_read && !$networkmap_write && !$networkmap_manage) { - db_pandora_audit("ACL Violation", - "Trying to access networkmap"); - require ("general/noaccess.php"); - return; - } - - $user_readonly = !$networkmap_write && !$networkmap_manage; - - $pure = (int) get_parameter ('pure', 0); - - /* Main code */ - if ($pure == 1) { - $buttons['screen'] = array('active' => false, - 'text' => '' . - html_print_image("images/normal_screen.png", true, - array ('title' => __('Normal screen'))) . - ''); - } - else { - if (!$dash_mode) { - $buttons['screen'] = array('active' => false, - 'text' => '' . - html_print_image("images/full_screen.png", true, - array ('title' => __('Full screen'))) . - ''); - $buttons['list'] = array('active' => false, - 'text' => '' . - html_print_image("images/list.png", true, - array ('title' => __('List of networkmap'))) . - ''); - } - } - - if (!$dash_mode) { - ui_print_page_header($networkmap['name'], - "images/bricks.png", false, "network_map_enterprise", - false, $buttons, false, '', $config['item_title_size_text']); - } - - $nodes_and_relations = networkmap_process_networkmap($id); - - show_networkmap($id, $user_readonly, $nodes_and_relations, $dash_mode, $map_dash_details); + ui_print_page_header( + __('Networkmap'), + 'images/bricks.png', + false, + 'network_map_enterprise', + false + ); + ui_print_error_message(__('Not found networkmap.')); + + return; +} else { + // ACL for the network map + $networkmap_read = check_acl($config['id_user'], $networkmap['id_group'], 'MR'); + $networkmap_write = check_acl($config['id_user'], $networkmap['id_group'], 'MW'); + $networkmap_manage = check_acl($config['id_user'], $networkmap['id_group'], 'MM'); + + if (!$networkmap_read && !$networkmap_write && !$networkmap_manage) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access networkmap' + ); + include 'general/noaccess.php'; + return; + } + + $user_readonly = !$networkmap_write && !$networkmap_manage; + + $pure = (int) get_parameter('pure', 0); + + // Main code + if ($pure == 1) { + $buttons['screen'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/normal_screen.png', + true, + ['title' => __('Normal screen')] + ).'', + ]; + } else { + if (!$dash_mode) { + $buttons['screen'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/full_screen.png', + true, + ['title' => __('Full screen')] + ).'', + ]; + $buttons['list'] = [ + 'active' => false, + 'text' => ''.html_print_image( + 'images/list.png', + true, + ['title' => __('List of networkmap')] + ).'', + ]; + } + } + + if (!$dash_mode) { + ui_print_page_header( + $networkmap['name'], + 'images/bricks.png', + false, + 'network_map_enterprise', + false, + $buttons, + false, + '', + $config['item_title_size_text'] + ); + } + + $nodes_and_relations = networkmap_process_networkmap($id); + + show_networkmap($id, $user_readonly, $nodes_and_relations, $dash_mode, $map_dash_details); } ?> - - - - + 0) { + $query = ui_get_url_refresh(false); + echo ''; + } + ?> + + <?php echo __('%s Realtime Module Graph', get_product_name()); ?> + + + + + + + - - - + ?> + + + + $config['extensions'] = extensions_get_extensions(false, '../../'); + if (!extensions_is_enabled_extension('realtime_graphs.php')) { + ui_print_error_message(__('Realtime extension is not enabled.')); + return; + } else { + include_once '../../extensions/realtime_graphs.php'; + } + + pandora_realtime_graphs(); + ?> + + diff --git a/pandora_console/operation/agentes/snapshot_view.php b/pandora_console/operation/agentes/snapshot_view.php index e386514aec..5ab46ed6b4 100644 --- a/pandora_console/operation/agentes/snapshot_view.php +++ b/pandora_console/operation/agentes/snapshot_view.php @@ -1,134 +1,132 @@ -load_tables(); -} - -$id = get_parameter('id'); -$id_node = get_parameter("id_node", 0); - -// Get the data -if ($id_node > 0) { - $connection = metaconsole_get_connection_by_id($id_node); - if (metaconsole_load_external_db($connection) != NOERR) { - ui_print_error_message(__('Cannot connect with node to display the module data.')); - exit; - } -} -$row_module = modules_get_agentmodule($id); - -// Retrieve data -$utimestamp = get_parameter("timestamp", ''); -if($utimestamp == '') { - // Retrieve last data - $row_state = db_get_row('tagente_estado', 'id_agente_modulo', $id); - $last_timestamp = date("Y-m-d H:i:s", $row_state['utimestamp']); -} else { - // Retrieve target data - $state = db_get_row('tagente_estado', 'id_agente_modulo', $id, array('id_agente')); - $row_state = db_get_row_filter('tagente_datos_string', array('id_agente_modulo' => $id, 'utimestamp' => $utimestamp), false, 'AND', 1); - $row_state['id_agente'] = $state['id_agente']; - $last_timestamp = date("Y-m-d H:i:s", $row_state['utimestamp']); -} - -// Build the info -$label = get_parameter ("label", io_safe_output($row_module['module_name'])); -$last_data = io_safe_output($row_state["datos"]); -$refresh = (int) get_parameter ("refr", $row_state['current_interval']); - -// ACL check -$all_groups = agents_get_all_groups_agent ($row_state['id_agente']); -if (!check_acl_one_of_groups($config['id_user'], $all_groups, "AR")) { - require ($config['homedir'] . "/general/noaccess.php"); - exit; -} -?> - - - 0) { - $query = ui_get_url_refresh (false); - echo ''; - } - ?> - - <?php echo __("%s Snapshot data view for module (%s)", get_product_name(), $label); ?> - - - - "; - echo __("Current data at %s", $last_timestamp); - echo ""; - if (is_image_data($last_data)) { - echo '
                image
                '; - } - else { - $last_data = preg_replace ('//', '>', $last_data); - $last_data = preg_replace ('/\n/i','
                ',$last_data); - $last_data = preg_replace ('/\s/i',' ',$last_data); - echo "
                "; - echo $last_data; - echo "
                "; - ?> - - - - +load_tables(); +} + +$id = get_parameter('id'); +$id_node = get_parameter('id_node', 0); + +// Get the data +if ($id_node > 0) { + $connection = metaconsole_get_connection_by_id($id_node); + if (metaconsole_load_external_db($connection) != NOERR) { + ui_print_error_message(__('Cannot connect with node to display the module data.')); + exit; + } +} + +$row_module = modules_get_agentmodule($id); + +// Retrieve data +$utimestamp = get_parameter('timestamp', ''); +if ($utimestamp == '') { + // Retrieve last data + $row_state = db_get_row('tagente_estado', 'id_agente_modulo', $id); + $last_timestamp = date('Y-m-d H:i:s', $row_state['utimestamp']); +} else { + // Retrieve target data + $state = db_get_row('tagente_estado', 'id_agente_modulo', $id, ['id_agente']); + $row_state = db_get_row_filter('tagente_datos_string', ['id_agente_modulo' => $id, 'utimestamp' => $utimestamp], false, 'AND', 1); + $row_state['id_agente'] = $state['id_agente']; + $last_timestamp = date('Y-m-d H:i:s', $row_state['utimestamp']); +} + +// Build the info +$label = get_parameter('label', io_safe_output($row_module['module_name'])); +$last_data = io_safe_output($row_state['datos']); +$refresh = (int) get_parameter('refr', $row_state['current_interval']); + +// ACL check +$all_groups = agents_get_all_groups_agent($row_state['id_agente']); +if (!check_acl_one_of_groups($config['id_user'], $all_groups, 'AR')) { + include $config['homedir'].'/general/noaccess.php'; + exit; +} +?> + + + 0) { + $query = ui_get_url_refresh(false); + echo ''; + } + ?> + + <?php echo __('%s Snapshot data view for module (%s)', get_product_name(), $label); ?> + + + + "; + echo __('Current data at %s', $last_timestamp); + echo ''; + if (is_image_data($last_data)) { + echo '
                image
                '; + } else { + $last_data = preg_replace('//', '>', $last_data); + $last_data = preg_replace('/\n/i', '
                ', $last_data); + $last_data = preg_replace('/\s/i', ' ', $last_data); + echo "
                "; + echo $last_data; + echo '
                '; + ?> + + + + diff --git a/pandora_console/operation/agentes/stat_win.php b/pandora_console/operation/agentes/stat_win.php index adb210dd70..78cd56cfcc 100644 --- a/pandora_console/operation/agentes/stat_win.php +++ b/pandora_console/operation/agentes/stat_win.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,41 +11,40 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Don't start a session before this import. // The session is configured and started inside the config process. -require_once ('../../include/config.php'); -require_once ($config['homedir'] . '/include/auth/mysql.php'); -require_once ($config['homedir'] . '/include/functions.php'); -require_once ($config['homedir'] . '/include/functions_db.php'); -require_once ($config['homedir'] . '/include/functions_reporting.php'); -require_once ($config['homedir'] . '/include/functions_graph.php'); -require_once ($config['homedir'] . '/include/functions_modules.php'); -require_once ($config['homedir'] . '/include/functions_agents.php'); -require_once ($config['homedir'] . '/include/functions_tags.php'); +require_once '../../include/config.php'; +require_once $config['homedir'].'/include/auth/mysql.php'; +require_once $config['homedir'].'/include/functions.php'; +require_once $config['homedir'].'/include/functions_db.php'; +require_once $config['homedir'].'/include/functions_reporting.php'; +require_once $config['homedir'].'/include/functions_graph.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_tags.php'; enterprise_include_once('include/functions_agents.php'); -check_login (); +check_login(); // Metaconsole connection to the node -$server_id = (int) get_parameter("server"); +$server_id = (int) get_parameter('server'); if (is_metaconsole() && !empty($server_id)) { - $server = metaconsole_get_connection_by_id($server_id); - // Error connecting - if (metaconsole_connect($server) !== NOERR) { - echo ""; - echo ""; - ui_print_error_message(__('There was a problem connecting with the node')); - echo ""; - echo ""; - exit; - } + $server = metaconsole_get_connection_by_id($server_id); + // Error connecting + if (metaconsole_connect($server) !== NOERR) { + echo ''; + echo ''; + ui_print_error_message(__('There was a problem connecting with the node')); + echo ''; + echo ''; + exit; + } } -$user_language = get_user_language ($config['id_user']); -if (file_exists ('../../include/languages/'.$user_language.'.mo')) { - $l10n = new gettext_reader (new CachedFileReader ('../../include/languages/'.$user_language.'.mo')); - $l10n->load_tables(); +$user_language = get_user_language($config['id_user']); +if (file_exists('../../include/languages/'.$user_language.'.mo')) { + $l10n = new gettext_reader(new CachedFileReader('../../include/languages/'.$user_language.'.mo')); + $l10n->load_tables(); } echo ''; @@ -54,399 +52,450 @@ echo ' - - 0) { - $query = ui_get_url_refresh (false); - echo ''; - } - ?> - - <?php echo __("%s Graph", get_product_name()) . ' (' . $alias . ' - ' . $label; ?>) - - - - - - - - + + + + + - - - - "; - echo"

                " . __('The CSV export has been successful.') . "

                "; - echo"
                "; - // Module id - $id = (int) get_parameter ("id", 0); - // Agent id - $agent_id = (int) modules_get_agentmodule_agent($id); + period_select_init(periodSelectId); + }; + + + + + "; + echo '

                '.__('The CSV export has been successful.').'

                '; + echo ''; + // Module id + $id = (int) get_parameter('id', 0); + // Agent id + $agent_id = (int) modules_get_agentmodule_agent($id); - if (empty($id) || empty($agent_id)) { - ui_print_error_message(__('There was a problem locating the source of the graph')); - exit; - } + if (empty($id) || empty($agent_id)) { + ui_print_error_message(__('There was a problem locating the source of the graph')); + exit; + } - // ACL - $all_groups = agents_get_all_groups_agent($agent_id); - if (!check_acl_one_of_groups ($config["id_user"], $all_groups, "AR")) { - require ($config['homedir'] . "/general/noaccess.php"); - exit; - } + // ACL + $all_groups = agents_get_all_groups_agent($agent_id); + if (!check_acl_one_of_groups($config['id_user'], $all_groups, 'AR')) { + include $config['homedir'].'/general/noaccess.php'; + exit; + } - $draw_alerts = get_parameter("draw_alerts", 0); + $draw_alerts = get_parameter('draw_alerts', 0); - $period = get_parameter ("period"); - $id = get_parameter ("id", 0); - $label = get_parameter ("label", ""); - $label_graph = base64_decode(get_parameter ("label", "")); - $start_date = get_parameter ("start_date", date("Y/m/d")); - $start_time = get_parameter ("start_time", date("H:i:s")); - $draw_events = get_parameter ("draw_events", 0); - $graph_type = get_parameter ("type", "sparse"); - $zoom = get_parameter ("zoom", $config['zoom_graph']); - $baseline = get_parameter ("baseline", 0); - $show_events_graph = get_parameter ("show_events_graph", 0); - $show_percentil = get_parameter ("show_percentil", 0); - $time_compare_separated = get_parameter ("time_compare_separated", 0); - $time_compare_overlapped = get_parameter ("time_compare_overlapped", 0); - $unknown_graph = get_parameter_checkbox ("unknown_graph", 1); + $period = get_parameter('period'); + $id = get_parameter('id', 0); + $label = get_parameter('label', ''); + $label_graph = base64_decode(get_parameter('label', '')); + $start_date = get_parameter('start_date', date('Y/m/d')); + $start_time = get_parameter('start_time', date('H:i:s')); + $draw_events = get_parameter('draw_events', 0); + $graph_type = get_parameter('type', 'sparse'); + $zoom = get_parameter('zoom', $config['zoom_graph']); + $baseline = get_parameter('baseline', 0); + $show_events_graph = get_parameter('show_events_graph', 0); + $show_percentil = get_parameter('show_percentil', 0); + $time_compare_separated = get_parameter('time_compare_separated', 0); + $time_compare_overlapped = get_parameter('time_compare_overlapped', 0); + $unknown_graph = get_parameter_checkbox('unknown_graph', 1); - $fullscale_sent = get_parameter ("fullscale_sent", 0); - if(!$fullscale_sent){ - if(!isset($config['full_scale_option']) || $config['full_scale_option'] == 0){ - $fullscale = 0; - } - elseif($config['full_scale_option'] == 1){ - $fullscale = 1; - } - elseif($config['full_scale_option'] == 2){ - if($graph_type == 'boolean'){ - $fullscale = 1; - }else{ - $fullscale = 0; - } - } - } - else{ - $fullscale = get_parameter('fullscale', 0); - } + $fullscale_sent = get_parameter('fullscale_sent', 0); + if (!$fullscale_sent) { + if (!isset($config['full_scale_option']) || $config['full_scale_option'] == 0) { + $fullscale = 0; + } else if ($config['full_scale_option'] == 1) { + $fullscale = 1; + } else if ($config['full_scale_option'] == 2) { + if ($graph_type == 'boolean') { + $fullscale = 1; + } else { + $fullscale = 0; + } + } + } else { + $fullscale = get_parameter('fullscale', 0); + } - // To avoid the horizontal overflow - $width -= 20; + // To avoid the horizontal overflow + $width -= 20; - $time_compare = false; + $time_compare = false; - if ($time_compare_separated) { - $time_compare = 'separated'; - } - else if ($time_compare_overlapped) { - $time_compare = 'overlapped'; - } + if ($time_compare_separated) { + $time_compare = 'separated'; + } else if ($time_compare_overlapped) { + $time_compare = 'overlapped'; + } - if ($zoom > 1) { - $height = $height * ($zoom / 2.1); - $width = $width * ($zoom / 1.4); - } + if ($zoom > 1) { + $height = ($height * ($zoom / 2.1)); + $width = ($width * ($zoom / 1.4)); + } - // Build date - $date = strtotime("$start_date $start_time"); - $now = time(); + // Build date + $date = strtotime("$start_date $start_time"); + $now = time(); - if ($date > $now) - $date = $now; + if ($date > $now) { + $date = $now; + } - $urlImage = ui_get_full_url(false, false, false, false); + $urlImage = ui_get_full_url(false, false, false, false); - $unit = db_get_value('unit', 'tagente_modulo', 'id_agente_modulo', $id); + $unit = db_get_value('unit', 'tagente_modulo', 'id_agente_modulo', $id); - echo '
                '; + echo '
                '; - $width = '90%'; - $height = '450'; + $width = '90%'; + $height = '450'; - switch ($graph_type) { - case 'boolean': - case 'sparse': - case 'string': - $params =array( - 'agent_module_id' => $id, - 'period' => $period, - 'show_events' => $draw_events, - 'title' => $label_graph, - 'unit_name' => $unit, - 'show_alerts' => $draw_alerts, - 'date' => $date, - 'unit' => $unit, - 'baseline' => $baseline, - 'homeurl' => $urlImage, - 'adapt_key' => 'adapter_' . $graph_type, - 'compare' => $time_compare, - 'show_unknown' => $unknown_graph, - 'percentil' => (($show_percentil)? $config['percentil'] : null), - 'type_graph' => $config['type_module_charts'], - 'fullscale' => $fullscale, - 'zoom' => $zoom - ); - echo grafico_modulo_sparse ($params); - echo '
                '; - if ($show_events_graph){ - $width = '500'; - echo graphic_module_events($id, $width, $height, - $period, $config['homeurl'], $zoom, - 'adapted_' . $graph_type, $date, true); - } - break; - default: - echo fs_error_image ('../images'); - break; - } - echo '
                '; + switch ($graph_type) { + case 'boolean': + case 'sparse': + case 'string': + $params = [ + 'agent_module_id' => $id, + 'period' => $period, + 'show_events' => $draw_events, + 'title' => $label_graph, + 'unit_name' => $unit, + 'show_alerts' => $draw_alerts, + 'date' => $date, + 'unit' => $unit, + 'baseline' => $baseline, + 'homeurl' => $urlImage, + 'adapt_key' => 'adapter_'.$graph_type, + 'compare' => $time_compare, + 'show_unknown' => $unknown_graph, + 'percentil' => (($show_percentil) ? $config['percentil'] : null), + 'type_graph' => $config['type_module_charts'], + 'fullscale' => $fullscale, + 'zoom' => $zoom, + ]; + echo grafico_modulo_sparse($params); + echo '
                '; + if ($show_events_graph) { + $width = '500'; + echo graphic_module_events( + $id, + $width, + $height, + $period, + $config['homeurl'], + $zoom, + 'adapted_'.$graph_type, + $date, + true + ); + } + break; - //////////////////////////////////////////////////////////////// - // SIDE MENU - //////////////////////////////////////////////////////////////// - $params = array(); - // TOP TEXT - //Use the no_meta parameter because this image is only in the base console - $params['top_text'] = "
                " . html_print_image('images/wrench_blanco.png', true, array('width' => '16px'), false, false, true) . ' ' . __('Graph configuration menu') . ui_print_help_icon ("graphs",true, $config["homeurl"], "images/help_w.png", true) . "
                "; - $params['body_text'] = "'; - if (!empty($server_id)) - $params['body_text'] .= html_print_input_hidden ("server", $server_id, true); + // + // SIDE MENU + // + $params = []; + // TOP TEXT + // Use the no_meta parameter because this image is only in the base console + $params['top_text'] = "
                ".html_print_image('images/wrench_blanco.png', true, ['width' => '16px'], false, false, true).' '.__('Graph configuration menu').ui_print_help_icon('graphs', true, $config['homeurl'], 'images/help_w.png', true).'
                '; + $params['body_text'] = "'; // outer + $form_table = html_print_table($table, true); + $form_table .= '
                '.html_print_submit_button( + __('Reload'), + 'submit', + false, + 'class="sub upd"', + true + ).'
                '; - // ICONS - $params['icon_closed'] = '/images/graphmenu_arrow_hide.png'; - $params['icon_open'] = '/images/graphmenu_arrow.png'; + unset($table); - // SIZE - $params['width'] = 500; + $table = new stdClass(); + $table->id = 'stat_win_form'; + $table->width = '100%'; + $table->cellspacing = 2; + $table->cellpadding = 2; + $table->class = 'databox'; - // POSITION - $params['position'] = 'left'; + $data = []; + $data[0] = html_print_div( + [ + 'id' => 'field_list', + 'content' => $form_table, + 'style' => 'overflow: auto; height: 220px', + ], + true + ); + $table->data[] = $data; + $table->rowclass[] = ''; - html_print_side_layer($params); + $params['body_text'] .= html_print_table($table, true); + $params['body_text'] .= ''; + $params['body_text'] .= '
                '; + // outer + // ICONS + $params['icon_closed'] = '/images/graphmenu_arrow_hide.png'; + $params['icon_open'] = '/images/graphmenu_arrow.png'; - // Hidden div to forced title - html_print_div(array('id' => 'forced_title_layer', - 'class' => 'forced_title_layer', 'hidden' => true)); - ?> + // SIZE + $params['width'] = 500; - + // POSITION + $params['position'] = 'left'; + + html_print_side_layer($params); + + // Hidden div to forced title + html_print_div( + [ + 'id' => 'forced_title_layer', + 'class' => 'forced_title_layer', + 'hidden' => true, + ] + ); + ?> + + diff --git a/pandora_console/operation/agentes/status_events.php b/pandora_console/operation/agentes/status_events.php index 714fa40352..825a4c2c42 100755 --- a/pandora_console/operation/agentes/status_events.php +++ b/pandora_console/operation/agentes/status_events.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,58 +11,55 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars check_login(); if (!isset($id_agente)) { - require ("general/noaccess.php"); - exit; + include 'general/noaccess.php'; + exit; } -require_once ("include/functions_events.php"); +require_once 'include/functions_events.php'; ui_toggle( - "
                " . - html_print_image('images/spinner.gif', true) . - "
                ", - __('Latest events for this agent'), - __('Latest events for this agent'), - false); + "
                ".html_print_image('images/spinner.gif', true).'
                ', + __('Latest events for this agent'), + __('Latest events for this agent'), + false +); ?> diff --git a/pandora_console/operation/agentes/status_monitor.php b/pandora_console/operation/agentes/status_monitor.php index 5ae0748599..ada6cd6ec6 100644 --- a/pandora_console/operation/agentes/status_monitor.php +++ b/pandora_console/operation/agentes/status_monitor.php @@ -5,7 +5,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -13,85 +12,87 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; check_login(); -if (! check_acl ($config['id_user'], 0, 'AR') - && ! check_acl ($config['id_user'], 0, 'AW') && - ! check_acl ($config['id_user'], 0, 'AM')) { - db_pandora_audit('ACL Violation', - 'Trying to access Agent Management'); - require ('general/noaccess.php'); - return; +if (! check_acl($config['id_user'], 0, 'AR') + && ! check_acl($config['id_user'], 0, 'AW') + && ! check_acl($config['id_user'], 0, 'AM') +) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent Management' + ); + include 'general/noaccess.php'; + return; } -require_once($config['homedir'] . '/include/functions_agents.php'); -require_once($config['homedir'] . '/include/functions_modules.php'); -require_once($config['homedir'] . '/include/functions_users.php'); -enterprise_include_once ('include/functions_metaconsole.php'); +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_users.php'; +enterprise_include_once('include/functions_metaconsole.php'); -$isFunctionPolicies = enterprise_include_once ('include/functions_policies.php'); +$isFunctionPolicies = enterprise_include_once('include/functions_policies.php'); -if (! defined ('METACONSOLE')) { - //Header - ui_print_page_header (__('Monitor detail'), - 'images/brick.png', false); -} -else { - - ui_meta_print_header(__('Monitor view')); +if (! defined('METACONSOLE')) { + // Header + ui_print_page_header( + __('Monitor detail'), + 'images/brick.png', + false + ); +} else { + ui_meta_print_header(__('Monitor view')); } -$ag_freestring = (string)get_parameter ('ag_freestring'); -$moduletype = (string) get_parameter ('moduletype'); -$datatype = (string) get_parameter ('datatype'); -$ag_modulename = (string) get_parameter ('ag_modulename'); -$refr = (int) get_parameter('refr', 0); -$offset = (int) get_parameter ('offset', 0); -$status = (int) get_parameter ('status', 4); -$modulegroup = (int) get_parameter ('modulegroup', -1); -$tag_filter = (int) get_parameter('tag_filter', 0); +$ag_freestring = (string) get_parameter('ag_freestring'); +$moduletype = (string) get_parameter('moduletype'); +$datatype = (string) get_parameter('datatype'); +$ag_modulename = (string) get_parameter('ag_modulename'); +$refr = (int) get_parameter('refr', 0); +$offset = (int) get_parameter('offset', 0); +$status = (int) get_parameter('status', 4); +$modulegroup = (int) get_parameter('modulegroup', -1); +$tag_filter = (int) get_parameter('tag_filter', 0); // Sort functionality -$sortField = get_parameter('sort_field'); -$sort = get_parameter('sort', 'none'); -//When the previous page was a visualmap and show only one module -$id_module = (int) get_parameter('id_module', 0); -$ag_custom_fields = (array) get_parameter('ag_custom_fields', array()); +$sortField = get_parameter('sort_field'); +$sort = get_parameter('sort', 'none'); +// When the previous page was a visualmap and show only one module +$id_module = (int) get_parameter('id_module', 0); +$ag_custom_fields = (array) get_parameter('ag_custom_fields', []); $module_option = (int) get_parameter('module_option', 1); if (!is_metaconsole()) { - $ag_group = (int) get_parameter ('ag_group', 0); -} -else { - $ag_group = get_parameter ('ag_group', 0); - $ag_group_metaconsole = $ag_group; + $ag_group = (int) get_parameter('ag_group', 0); +} else { + $ag_group = get_parameter('ag_group', 0); + $ag_group_metaconsole = $ag_group; } $ag_custom_fields_params = ''; if (!empty($ag_custom_fields)) { - foreach ($ag_custom_fields as $id => $value) { - if (!empty($value)) - $ag_custom_fields_params .= - '&ag_custom_fields[' . $id . ']=' . $value; - } + foreach ($ag_custom_fields as $id => $value) { + if (!empty($value)) { + $ag_custom_fields_params .= '&ag_custom_fields['.$id.']='.$value; + } + } } + if ($id_module) { - $status = -1; - $ag_modulename = modules_get_agentmodule_name($id_module); - $ag_freestring = modules_get_agentmodule_agent_alias($id_module); + $status = -1; + $ag_modulename = modules_get_agentmodule_name($id_module); + $ag_freestring = modules_get_agentmodule_agent_alias($id_module); } enterprise_hook('open_meta_frame'); // Get Groups and profiles from user -$user_groups = implode (',', array_keys (users_get_groups (false,'AR',false))); +$user_groups = implode(',', array_keys(users_get_groups(false, 'AR', false))); -//////////////////////////////////// // Begin Build SQL sentences -$sql_from = " FROM tagente_modulo +$sql_from = ' FROM tagente_modulo INNER JOIN tagente ON tagente_modulo.id_agente = tagente.id_agente LEFT JOIN tagent_secondary_group tasg @@ -103,146 +104,141 @@ $sql_from = " FROM tagente_modulo INNER JOIN ttipo_modulo ON tagente_modulo.id_tipo_modulo = ttipo_modulo.id_tipo LEFT JOIN ttag_module - ON tagente_modulo.id_agente_modulo = ttag_module.id_agente_modulo"; + ON tagente_modulo.id_agente_modulo = ttag_module.id_agente_modulo'; $sql_conditions = ' WHERE tagente.disabled = 0'; if (is_numeric($ag_group)) { - $id_ag_group = 0; -} -else { - $id_ag_group = db_get_value('id_grupo', 'tgrupo', 'nombre', $ag_group); + $id_ag_group = 0; +} else { + $id_ag_group = db_get_value('id_grupo', 'tgrupo', 'nombre', $ag_group); } // Agent group selector if (!is_metaconsole()) { - if ($ag_group > 0 && check_acl ($config['id_user'], $ag_group, 'AR')) { - $sql_conditions_group = sprintf ( - ' AND (tagente.id_grupo = %d OR tasg.id_group = %d)', - $ag_group, $ag_group - ); - } - elseif ($user_groups != '') { - // User has explicit permission on group 1 ? - $sql_conditions_group = ' AND ( + if ($ag_group > 0 && check_acl($config['id_user'], $ag_group, 'AR')) { + $sql_conditions_group = sprintf( + ' AND (tagente.id_grupo = %d OR tasg.id_group = %d)', + $ag_group, + $ag_group + ); + } else if ($user_groups != '') { + // User has explicit permission on group 1 ? + $sql_conditions_group = ' AND ( tagente.id_grupo IN ('.$user_groups.') OR tasg.id_group IN ('.$user_groups.') )'; - } -} -else { - if (((int)$ag_group !== 0) && (check_acl ($config['id_user'], $id_ag_group, 'AR'))) { - $sql_conditions_group = sprintf ( - ' AND (tagente.id_grupo IN (%s) OR tasg.id_group IN (%s))', - $ag_group, $ag_group - ); - } - elseif ($user_groups != '') { - // User has explicit permission on group 1 ? - $sql_conditions_group = ' AND ( + } +} else { + if (((int) $ag_group !== 0) && (check_acl($config['id_user'], $id_ag_group, 'AR'))) { + $sql_conditions_group = sprintf( + ' AND (tagente.id_grupo IN (%s) OR tasg.id_group IN (%s))', + $ag_group, + $ag_group + ); + } else if ($user_groups != '') { + // User has explicit permission on group 1 ? + $sql_conditions_group = ' AND ( tagente.id_grupo IN ('.$user_groups.') OR tasg.id_group IN ('.$user_groups.') )'; - } + } } // Module group if (is_metaconsole()) { - if ($modulegroup != '-1') - $sql_conditions .= sprintf (' AND tagente_modulo.id_module_group IN (%s)', $modulegroup); -} -else if ($modulegroup > -1) { - $sql_conditions .= sprintf (' AND tagente_modulo.id_module_group = \'%d\'', $modulegroup); - + if ($modulegroup != '-1') { + $sql_conditions .= sprintf(' AND tagente_modulo.id_module_group IN (%s)', $modulegroup); + } +} else if ($modulegroup > -1) { + $sql_conditions .= sprintf(' AND tagente_modulo.id_module_group = \'%d\'', $modulegroup); } // Module name selector if ($ag_modulename != '') { - $sql_conditions .= " AND tagente_modulo.nombre LIKE '%" .$ag_modulename. "%'"; + $sql_conditions .= " AND tagente_modulo.nombre LIKE '%".$ag_modulename."%'"; } if ($module_option !== 0) { - if ($module_option == 1) { - // Only enabled - $sql_conditions .= sprintf (' AND tagente_modulo.disabled = 0'); - } - else if ($module_option == 2) { - // Only disabled - $sql_conditions .= sprintf (' AND tagente_modulo.disabled = 1'); - } + if ($module_option == 1) { + // Only enabled + $sql_conditions .= sprintf(' AND tagente_modulo.disabled = 0'); + } else if ($module_option == 2) { + // Only disabled + $sql_conditions .= sprintf(' AND tagente_modulo.disabled = 1'); + } } if ($datatype != '') { - $sql_conditions .= sprintf (' AND ttipo_modulo.id_tipo =' .$datatype); + $sql_conditions .= sprintf(' AND ttipo_modulo.id_tipo ='.$datatype); } if ($moduletype != '') { - $sql_conditions .= sprintf (' AND tagente_modulo.id_modulo =' .$moduletype); + $sql_conditions .= sprintf(' AND tagente_modulo.id_modulo ='.$moduletype); } // Freestring selector if ($ag_freestring != '') { - $sql_conditions .= ' AND (tagente.nombre COLLATE utf8_general_ci LIKE \'%%' . $ag_freestring . '%%\' - OR tagente.alias COLLATE utf8_general_ci LIKE \'%%' . $ag_freestring . '%%\' - OR tagente_modulo.nombre COLLATE utf8_general_ci LIKE \'%%' . $ag_freestring . '%%\' - OR tagente_modulo.descripcion COLLATE utf8_general_ci LIKE \'%%' . $ag_freestring . '%%\')'; + $sql_conditions .= ' AND (tagente.nombre COLLATE utf8_general_ci LIKE \'%%'.$ag_freestring.'%%\' + OR tagente.alias COLLATE utf8_general_ci LIKE \'%%'.$ag_freestring.'%%\' + OR tagente_modulo.nombre COLLATE utf8_general_ci LIKE \'%%'.$ag_freestring.'%%\' + OR tagente_modulo.descripcion COLLATE utf8_general_ci LIKE \'%%'.$ag_freestring.'%%\')'; } // Status selector -if ($status == AGENT_MODULE_STATUS_NORMAL) { //Normal - $sql_conditions .= ' AND tagente_estado.estado = 0 +if ($status == AGENT_MODULE_STATUS_NORMAL) { + // Normal + $sql_conditions .= ' AND tagente_estado.estado = 0 AND (utimestamp > 0 OR (tagente_modulo.id_tipo_modulo IN(21,22,23,100))) '; -} -elseif ($status == AGENT_MODULE_STATUS_CRITICAL_BAD) { //Critical - $sql_conditions .= ' AND tagente_estado.estado = 1 AND utimestamp > 0'; -} -elseif ($status == AGENT_MODULE_STATUS_WARNING) { //Warning - $sql_conditions .= ' AND tagente_estado.estado = 2 AND utimestamp > 0'; -} -elseif ($status == AGENT_MODULE_STATUS_NOT_NORMAL) { //Not normal - $sql_conditions .= ' AND tagente_estado.estado <> 0'; -} -elseif ($status == AGENT_MODULE_STATUS_UNKNOWN) { //Unknown - $sql_conditions .= ' AND tagente_estado.estado = 3 AND tagente_estado.utimestamp <> 0'; -} -elseif ($status == AGENT_MODULE_STATUS_NOT_INIT) { //Not init - $sql_conditions .= ' AND tagente_estado.utimestamp = 0 +} else if ($status == AGENT_MODULE_STATUS_CRITICAL_BAD) { + // Critical + $sql_conditions .= ' AND tagente_estado.estado = 1 AND utimestamp > 0'; +} else if ($status == AGENT_MODULE_STATUS_WARNING) { + // Warning + $sql_conditions .= ' AND tagente_estado.estado = 2 AND utimestamp > 0'; +} else if ($status == AGENT_MODULE_STATUS_NOT_NORMAL) { + // Not normal + $sql_conditions .= ' AND tagente_estado.estado <> 0'; +} else if ($status == AGENT_MODULE_STATUS_UNKNOWN) { + // Unknown + $sql_conditions .= ' AND tagente_estado.estado = 3 AND tagente_estado.utimestamp <> 0'; +} else if ($status == AGENT_MODULE_STATUS_NOT_INIT) { + // Not init + $sql_conditions .= ' AND tagente_estado.utimestamp = 0 AND tagente_modulo.id_tipo_modulo NOT IN (21,22,23,100)'; } // Filter by agent custom fields -$sql_conditions_custom_fields = ""; +$sql_conditions_custom_fields = ''; if (!empty($ag_custom_fields)) { + $cf_filter = []; + foreach ($ag_custom_fields as $field_id => $value) { + if (!empty($value)) { + $cf_filter[] = '(tagent_custom_data.id_field = '.$field_id.' AND tagent_custom_data.description LIKE \'%'.$value.'%\')'; + } + } - $cf_filter = array(); - foreach ($ag_custom_fields as $field_id => $value) { - if (!empty($value)) { - $cf_filter[] = '(tagent_custom_data.id_field = ' . $field_id . - ' AND tagent_custom_data.description LIKE \'%'.$value.'%\')'; - } - } - if (!empty($cf_filter)) { - $sql_conditions_custom_fields = ' AND tagente.id_agente IN ( + if (!empty($cf_filter)) { + $sql_conditions_custom_fields = ' AND tagente.id_agente IN ( SELECT tagent_custom_data.id_agent FROM tagent_custom_data - WHERE ' . implode(' AND ', $cf_filter) . ')'; - } + WHERE '.implode(' AND ', $cf_filter).')'; + } } -//Filter by tag +// Filter by tag if ($tag_filter !== 0) { - if (is_metaconsole()) { - $sql_conditions .= ' AND tagente_modulo.id_agente_modulo IN ( + if (is_metaconsole()) { + $sql_conditions .= ' AND tagente_modulo.id_agente_modulo IN ( SELECT ttag_module.id_agente_modulo FROM ttag_module WHERE ttag_module.id_tag IN ('.$tag_filter.'))'; - } - else { - $sql_conditions .= ' AND tagente_modulo.id_agente_modulo IN ( + } else { + $sql_conditions .= ' AND tagente_modulo.id_agente_modulo IN ( SELECT ttag_module.id_agente_modulo FROM ttag_module - WHERE ttag_module.id_tag = ' . $tag_filter . ')'; - } + WHERE ttag_module.id_tag = '.$tag_filter.')'; + } } @@ -251,50 +247,67 @@ if ($tag_filter !== 0) { $sql_conditions_tags = ''; if (!users_is_admin()) { - if ($ag_group !== 0) { - $sql_conditions_tags = tags_get_acl_tags($config['id_user'], - $ag_group, 'AR', 'module_condition', 'AND', 'tagente_modulo', - true, array(), false); - } else { - // Fix: for tag functionality groups have to be all user_groups (propagate ACL funct!) - $groups = users_get_groups($config['id_user']); - $sql_conditions_tags = tags_get_acl_tags( - $config['id_user'], array_keys($groups), 'AR', - 'module_condition', 'AND', 'tagente_modulo', true, array(), - false); - } - if (is_numeric($sql_conditions_tags)) { - $sql_conditions_tags = ' AND 1 = 0'; - } + if ($ag_group !== 0) { + $sql_conditions_tags = tags_get_acl_tags( + $config['id_user'], + $ag_group, + 'AR', + 'module_condition', + 'AND', + 'tagente_modulo', + true, + [], + false + ); + } else { + // Fix: for tag functionality groups have to be all user_groups (propagate ACL funct!) + $groups = users_get_groups($config['id_user']); + $sql_conditions_tags = tags_get_acl_tags( + $config['id_user'], + array_keys($groups), + 'AR', + 'module_condition', + 'AND', + 'tagente_modulo', + true, + [], + false + ); + } + + if (is_numeric($sql_conditions_tags)) { + $sql_conditions_tags = ' AND 1 = 0'; + } } // Two modes of filter. All the filters and only ACLs filter -$sql_conditions_all = $sql_conditions . $sql_conditions_group . $sql_conditions_tags . $sql_conditions_custom_fields; +$sql_conditions_all = $sql_conditions.$sql_conditions_group.$sql_conditions_tags.$sql_conditions_custom_fields; // Get count to paginate -if (!defined('METACONSOLE')) - $count = db_get_sql ('SELECT COUNT(DISTINCT tagente_modulo.id_agente_modulo)' . $sql_from . $sql_conditions_all); +if (!defined('METACONSOLE')) { + $count = db_get_sql('SELECT COUNT(DISTINCT tagente_modulo.id_agente_modulo)'.$sql_from.$sql_conditions_all); +} // Get limit_sql depend of the metaconsole or standard mode if (is_metaconsole()) { - // Offset will be used to get the subset of modules - $inferior_limit = $offset; - $superior_limit = $config['block_size'] + $offset; - // Offset reset to get all elements - $offset = 0; - if (!isset($config['meta_num_elements'])) - $config['meta_num_elements'] = 100; - - $limit_sql = $config['meta_num_elements']; + // Offset will be used to get the subset of modules + $inferior_limit = $offset; + $superior_limit = ($config['block_size'] + $offset); + // Offset reset to get all elements + $offset = 0; + if (!isset($config['meta_num_elements'])) { + $config['meta_num_elements'] = 100; + } + + $limit_sql = $config['meta_num_elements']; +} else { + $limit_sql = $config['block_size']; } -else - $limit_sql = $config['block_size']; // End Build SQL sentences -///////////////////////////////////// - +// // Start Build Search Form -///////////////////////////////////// +// $table = new StdClass(); $table->width = '100%'; $table->cellspacing = 0; @@ -307,267 +320,385 @@ $table->style[3] = 'font-weight: bold;'; $table->style[4] = 'font-weight: bold;'; $table->data[0][0] = __('Group'); -$table->data[0][1] = html_print_select_groups($config['id_user'], 'AR', - true, 'ag_group', $ag_group, '', '', '0', true, false, - false, '', false, '', false, false, - 'id_grupo', false); +$table->data[0][1] = html_print_select_groups( + $config['id_user'], + 'AR', + true, + 'ag_group', + $ag_group, + '', + '', + '0', + true, + false, + false, + '', + false, + '', + false, + false, + 'id_grupo', + false +); -$fields = array (); +$fields = []; $fields[AGENT_MODULE_STATUS_NORMAL] = __('Normal'); $fields[AGENT_MODULE_STATUS_WARNING] = __('Warning'); $fields[AGENT_MODULE_STATUS_CRITICAL_BAD] = __('Critical'); $fields[AGENT_MODULE_STATUS_UNKNOWN] = __('Unknown'); -$fields[AGENT_MODULE_STATUS_NOT_NORMAL] = __('Not normal'); //default +$fields[AGENT_MODULE_STATUS_NOT_NORMAL] = __('Not normal'); +// default $fields[AGENT_MODULE_STATUS_NOT_INIT] = __('Not init'); $table->data[0][2] = __('Monitor status'); -$table->data[0][3] = html_print_select ($fields, 'status', $status, '', __('All'), -1, - true, false, true, '', false, 'width: 150px;'); +$table->data[0][3] = html_print_select( + $fields, + 'status', + $status, + '', + __('All'), + -1, + true, + false, + true, + '', + false, + 'width: 150px;' +); -$rows_select = array(); +$rows_select = []; $table->data[0][4] = __('Module group'); $rows_select[0] = __('Not assigned'); if (!is_metaconsole()) { - $rows = db_get_all_rows_sql('SELECT * - FROM tmodule_group ORDER BY name'); - $rows = io_safe_output($rows); - if (!empty($rows)) - foreach ($rows as $module_group) - $rows_select[$module_group['id_mg']] = $module_group['name']; -} -else { - $rows_select = modules_get_modulegroups(); + $rows = db_get_all_rows_sql( + 'SELECT * + FROM tmodule_group ORDER BY name' + ); + $rows = io_safe_output($rows); + if (!empty($rows)) { + foreach ($rows as $module_group) { + $rows_select[$module_group['id_mg']] = $module_group['name']; + } + } +} else { + $rows_select = modules_get_modulegroups(); } + $table->data[0][5] = html_print_select($rows_select, 'modulegroup', $modulegroup, '', __('All'), -1, true, false, true, '', false, 'width: 120px;'); $table->rowspan[0][6] = 2; -$table->data[0][6] = html_print_submit_button (__('Show'), 'uptbutton', - false, 'class="sub search" style="margin-top:0px;"',true); +$table->data[0][6] = html_print_submit_button( + __('Show'), + 'uptbutton', + false, + 'class="sub search" style="margin-top:0px;"', + true +); $table->data[1][0] = __('Module name'); -$table->data[1][1] = html_print_autocomplete_modules('ag_modulename', - $ag_modulename, false, true, '', array(), true); +$table->data[1][1] = html_print_autocomplete_modules( + 'ag_modulename', + $ag_modulename, + false, + true, + '', + [], + true +); $table->data[1][2] = __('Search'); -$table->data[1][3] = html_print_input_text ('ag_freestring', $ag_freestring, '', 20, 30, true); +$table->data[1][3] = html_print_input_text('ag_freestring', $ag_freestring, '', 20, 30, true); -$table->data[1][4] = __('Tags') . - ui_print_help_tip(__('Only it is show tags in use.'), true); +$table->data[1][4] = __('Tags').ui_print_help_tip(__('Only it is show tags in use.'), true); -$tags = array(); +$tags = []; $tags = tags_get_user_tags(); if (empty($tags)) { - $table->data[1][5] = __('No tags'); -} -else { - $table->data[1][5] = html_print_select ($tags, 'tag_filter', - $tag_filter, '', __('All'), '', true, false, true, '', false, 'width: 150px;'); + $table->data[1][5] = __('No tags'); +} else { + $table->data[1][5] = html_print_select( + $tags, + 'tag_filter', + $tag_filter, + '', + __('All'), + '', + true, + false, + true, + '', + false, + 'width: 150px;' + ); } - - $network_available = db_get_sql ("SELECT count(*) - FROM tserver - WHERE server_type = 1"); //POSTGRESQL AND ORACLE COMPATIBLE - $wmi_available = db_get_sql ("SELECT count(*) - FROM tserver - WHERE server_type = 6"); //POSTGRESQL AND ORACLE COMPATIBLE - $plugin_available = db_get_sql ("SELECT count(*) - FROM tserver - WHERE server_type = 4"); //POSTGRESQL AND ORACLE COMPATIBLE - $prediction_available = db_get_sql ("SELECT count(*) - FROM tserver - WHERE server_type = 5"); //POSTGRESQL AND ORACLE COMPATIBLE - $wux_available = db_get_sql ("SELECT count(*) - FROM tserver - WHERE server_type = 17"); //POSTGRESQL AND ORACLE COMPATIBLE +$network_available = db_get_sql( + 'SELECT count(*) + FROM tserver + WHERE server_type = 1' +); +// POSTGRESQL AND ORACLE COMPATIBLE +$wmi_available = db_get_sql( + 'SELECT count(*) + FROM tserver + WHERE server_type = 6' +); +// POSTGRESQL AND ORACLE COMPATIBLE +$plugin_available = db_get_sql( + 'SELECT count(*) + FROM tserver + WHERE server_type = 4' +); +// POSTGRESQL AND ORACLE COMPATIBLE +$prediction_available = db_get_sql( + 'SELECT count(*) + FROM tserver + WHERE server_type = 5' +); +// POSTGRESQL AND ORACLE COMPATIBLE +$wux_available = db_get_sql( + 'SELECT count(*) + FROM tserver + WHERE server_type = 17' +); +// POSTGRESQL AND ORACLE COMPATIBLE // Development mode to use all servers - if ($develop_bypass) { +if ($develop_bypass) { $network_available = 1; $wmi_available = 1; $plugin_available = 1; $prediction_available = 1; - } - - $typemodules = array (); - $typemodules[1] = __('Data server module'); - if ($network_available) - $typemodules[2] = __('Network server module'); - if ($plugin_available) - $typemodules[4] = __('Plugin server module'); - if ($wmi_available) - $typemodules[6] = __('WMI server module'); - if ($prediction_available) - $typemodules[5] = __('Prediction server module'); - if (enterprise_installed()) { - $typemodules[7] = __('Web server module'); - if ($wux_available) { - $typemodules[8] = __('Wux server module'); - } - } - - - $table->data[2][0] = ''.__('Server type').''; - - $table->data[2][1] = html_print_select ($typemodules, 'moduletype',$moduletype, '', __('All'),'', true, false, true, '', false, 'width: 150px;'); - - $monitor_options = array(0 => __('All'), 1 => __('Only enabled'), 2 => __('Only disabled')); - - $table->data[2][2] = ''.__('Show monitors...').''; - - $table->data[2][3] = html_print_select ($monitor_options, 'module_option', $module_option, '', '','', true, false, true, '', false, 'width: 150px;'); - - $table->data[2][4] = 'data[2][4] .= 'style="display:none"'; } - $table->data[2][4] .= '>'.__('Data type').''; - - - $table->data[2][5] .='
                '; - - - switch ($moduletype) - { - case 1: - $sql = sprintf ('SELECT id_tipo, descripcion - FROM ttipo_modulo - WHERE categoria IN (6,7,8,0,1,2,-1) order by descripcion '); - break; - case 2: - $sql = sprintf ('SELECT id_tipo, descripcion - FROM ttipo_modulo - WHERE categoria between 3 and 5 '); - break; - case 4: - $sql = sprintf ('SELECT id_tipo, descripcion - FROM ttipo_modulo - WHERE categoria between 0 and 2 '); - break; - case 6: - $sql = sprintf ('SELECT id_tipo, descripcion - FROM ttipo_modulo - WHERE categoria between 0 and 2 '); - break; - case 7: - $sql = sprintf ('SELECT id_tipo, descripcion - FROM ttipo_modulo - WHERE categoria = 9'); - break; - case 5: - $sql = sprintf ('SELECT id_tipo, descripcion - FROM ttipo_modulo - WHERE categoria = 0'); - break; - case 8: - $sql = sprintf ('SELECT id_tipo, descripcion - FROM ttipo_modulo - WHERE nombre = \'web_analysis\''); - break; - case '': - $sql = sprintf ('SELECT id_tipo, descripcion - FROM ttipo_modulo'); - break; - - } - $a = db_get_all_rows_sql($sql); - $table->data[2][5] .= ''; - - - - - $table->data[2][5] .= '
                '; + $typemodules = []; + $typemodules[1] = __('Data server module'); +if ($network_available) { + $typemodules[2] = __('Network server module'); +} + +if ($plugin_available) { + $typemodules[4] = __('Plugin server module'); +} + +if ($wmi_available) { + $typemodules[6] = __('WMI server module'); +} + +if ($prediction_available) { + $typemodules[5] = __('Prediction server module'); +} + +if (enterprise_installed()) { + $typemodules[7] = __('Web server module'); + if ($wux_available) { + $typemodules[8] = __('Wux server module'); + } +} -$table_custom_fields = new stdClass(); -$table_custom_fields->class = 'filters'; -$table_custom_fields->width = '100%'; +$table->data[2][0] = ''.__('Server type').''; + +$table->data[2][1] = html_print_select($typemodules, 'moduletype', $moduletype, '', __('All'), '', true, false, true, '', false, 'width: 150px;'); + +$monitor_options = [ + 0 => __('All'), + 1 => __('Only enabled'), + 2 => __('Only disabled'), +]; + +$table->data[2][2] = ''.__('Show monitors...').''; + +$table->data[2][3] = html_print_select($monitor_options, 'module_option', $module_option, '', '', '', true, false, true, '', false, 'width: 150px;'); + +$table->data[2][4] = 'data[2][4] .= 'style="display:none"'; +} + +$table->data[2][4] .= '>'.__('Data type').''; + + +$table->data[2][5] .= '
                '; + + +switch ($moduletype) { + case 1: + $sql = sprintf( + 'SELECT id_tipo, descripcion + FROM ttipo_modulo + WHERE categoria IN (6,7,8,0,1,2,-1) order by descripcion ' + ); + break; + + case 2: + $sql = sprintf( + 'SELECT id_tipo, descripcion + FROM ttipo_modulo + WHERE categoria between 3 and 5 ' + ); + break; + + case 4: + $sql = sprintf( + 'SELECT id_tipo, descripcion + FROM ttipo_modulo + WHERE categoria between 0 and 2 ' + ); + break; + + case 6: + $sql = sprintf( + 'SELECT id_tipo, descripcion + FROM ttipo_modulo + WHERE categoria between 0 and 2 ' + ); + break; + + case 7: + $sql = sprintf( + 'SELECT id_tipo, descripcion + FROM ttipo_modulo + WHERE categoria = 9' + ); + break; + + case 5: + $sql = sprintf( + 'SELECT id_tipo, descripcion + FROM ttipo_modulo + WHERE categoria = 0' + ); + break; + + case 8: + $sql = sprintf( + 'SELECT id_tipo, descripcion + FROM ttipo_modulo + WHERE nombre = \'web_analysis\'' + ); + break; + + case '': + $sql = sprintf( + 'SELECT id_tipo, descripcion + FROM ttipo_modulo' + ); + break; +} + +$a = db_get_all_rows_sql($sql); +$table->data[2][5] .= ''; + + + + + $table->data[2][5] .= '
                '; + + + $table_custom_fields = new stdClass(); + $table_custom_fields->class = 'filters'; + $table_custom_fields->width = '100%'; if (is_metaconsole()) { - $table_custom_fields->styleTable = 'margin-left:0px; margin-top:15px;'; - $table_custom_fields->cellpadding = '0'; - $table_custom_fields->cellspacing = '0'; + $table_custom_fields->styleTable = 'margin-left:0px; margin-top:15px;'; + $table_custom_fields->cellpadding = '0'; + $table_custom_fields->cellspacing = '0'; } -$table_custom_fields->style = array(); -if(!is_metaconsole()) - $table_custom_fields->style[0] = 'font-weight: bold; width: 150px;'; -else - $table_custom_fields->style[0] = 'font-weight: bold;'; -$table_custom_fields->colspan = array(); -$table_custom_fields->data = array(); + + $table_custom_fields->style = []; +if (!is_metaconsole()) { + $table_custom_fields->style[0] = 'font-weight: bold; width: 150px;'; +} else { + $table_custom_fields->style[0] = 'font-weight: bold;'; +} + +$table_custom_fields->colspan = []; +$table_custom_fields->data = []; $custom_fields = db_get_all_fields_in_table('tagent_custom_fields'); -if ($custom_fields === false) $custom_fields = array(); +if ($custom_fields === false) { + $custom_fields = []; +} foreach ($custom_fields as $custom_field) { - $row = array(); - $row[0] = $custom_field['name']; - - $custom_field_value = ""; - if (!empty($ag_custom_fields)) { - $custom_field_value = $ag_custom_fields[$custom_field['id_field']]; - if (empty($custom_field_value)) { - $custom_field_value = ""; - } - } - $row[1] = html_print_input_text ("ag_custom_fields[".$custom_field['id_field']."]", $custom_field_value, '', 100, 300, true); - - $table_custom_fields->data[] = $row; + $row = []; + $row[0] = $custom_field['name']; + + $custom_field_value = ''; + if (!empty($ag_custom_fields)) { + $custom_field_value = $ag_custom_fields[$custom_field['id_field']]; + if (empty($custom_field_value)) { + $custom_field_value = ''; + } + } + + $row[1] = html_print_input_text('ag_custom_fields['.$custom_field['id_field'].']', $custom_field_value, '', 100, 300, true); + + $table_custom_fields->data[] = $row; } -$filters = '
                '; +$filters = ''; if (is_metaconsole()) { - $table->colspan[3][0] = 7; - $table->cellstyle[3][0] = 'padding: 10px;'; - $table->data[3][0] = ui_toggle( - html_print_table($table_custom_fields, true), - __('Advanced Options'), '', true, true); - - $filters .= html_print_table($table, true); - $filters .= "
                "; - ui_toggle($filters, __('Show Options')); -} -else { - $table->colspan[3][0] = 7; - $table->cellstyle[3][0] = 'padding-left: 10px;'; - $table->data[3][0] = ui_toggle(html_print_table($table_custom_fields, - true), __('Agent custom fields'), '', true, true); - - $filters .= html_print_table($table, true); - $filters .= ''; - echo $filters; + $table->colspan[3][0] = 7; + $table->cellstyle[3][0] = 'padding: 10px;'; + $table->data[3][0] = ui_toggle( + html_print_table($table_custom_fields, true), + __('Advanced Options'), + '', + true, + true + ); + + $filters .= html_print_table($table, true); + $filters .= ''; + ui_toggle($filters, __('Show Options'), '', false); +} else { + $table->colspan[3][0] = 7; + $table->cellstyle[3][0] = 'padding-left: 10px;'; + $table->data[3][0] = ui_toggle( + html_print_table( + $table_custom_fields, + true + ), + __('Agent custom fields'), + '', + true, + true + ); + + $filters .= html_print_table($table, true); + $filters .= ''; + echo $filters; } + unset($table); // End Build Search Form -///////////////////////////////////// - +// // Sort functionality $selected = 'border: 1px solid black;'; $selectAgentNameUp = ''; @@ -585,152 +716,188 @@ $selectDataDown = ''; $selectTimestampUp = ''; $selectTimestampDown = ''; $order = null; + switch ($sortField) { - case 'agent_alias': - switch ($sort) { - case 'up': - $selectAgentNameUp = $selected; - $order = array('field' => 'tagente.alias', - 'order' => 'ASC'); - break; - case 'down': - $selectAgentNameDown = $selected; - $order = array('field' => 'tagente.alias', - 'order' => 'DESC'); - break; - } - break; - case 'type': - switch ($sort) { - case 'up': - $selectTypeUp = $selected; - $order = array( - 'field' => 'tagente_modulo.id_tipo_modulo', - 'order' => 'ASC'); - break; - case 'down': - $selectTypeDown = $selected; - $order = array( - 'field' => 'tagente_modulo.id_tipo_modulo', - 'order' => 'DESC'); - break; - } - break; - case 'moduletype': - switch ($sort) { - case 'up': - $selectTypeUp = $selected; - $order = array( - 'field' => 'tagente_modulo.id_modulo', - 'order' => 'ASC'); - break; - case 'down': - $selectTypeDown = $selected; - $order = array( - 'field' => 'tagente_modulo.id_modulo', - 'order' => 'DESC'); - break; - } - break; - case 'module_name': - switch ($sort) { - case 'up': - $selectModuleNameUp = $selected; - $order = array( - 'field' => 'tagente_modulo.nombre', - 'order' => 'ASC'); - break; - case 'down': - $selectModuleNameDown = $selected; - $order = array( - 'field' => 'tagente_modulo.nombre', - 'order' => 'DESC'); - break; - } - break; - case 'interval': - switch ($sort) { - case 'up': - $selectIntervalUp = $selected; - $order = array( - 'field' => 'tagente_modulo.module_interval', - 'order' => 'ASC'); - break; - case 'down': - $selectIntervalDown = $selected; - $order = array( - 'field' => 'tagente_modulo.module_interval', - 'order' => 'DESC'); - break; - } - break; - case 'status': - switch ($sort) { - case 'up': - $selectStatusUp = $selected; - $order = array( - 'field' => 'tagente_estado.estado', - 'order' => 'ASC'); - break; - case 'down': - $selectStatusDown = $selected; - $order = array( - 'field' => 'tagente_estado.estado', - 'order' => 'DESC'); - break; - } - break; - case 'timestamp': - switch ($sort) { - case 'up': - $selectTimestampUp = $selected; - $order = array( - 'field' => 'tagente_estado.utimestamp', - 'order' => 'ASC'); - break; - case 'down': - $selectTimestampDown = $selected; - $order = array( - 'field' => 'tagente_estado.utimestamp', - 'order' => 'DESC'); - break; - } - break; - case 'data': - switch ($sort) { - case 'up': - $selectTimestampUp = $selected; - $order = array( - 'field' => 'tagente_estado.datos', - 'order' => 'ASC'); - break; - case 'down': - $selectTimestampDown = $selected; - $order = array( - 'field' => 'tagente_estado.datos', - 'order' => 'DESC'); - break; - } - break; - default: - $selectAgentNameUp = $selected; - $selectAgentNameDown = ''; - $selectTypeUp = ''; - $selectTypeDown = ''; - $selectModuleNameUp = ''; - $selectModuleNameDown = ''; - $selectIntervalUp = ''; - $selectIntervalDown = ''; - $selectStatusUp = ''; - $selectStatusDown = ''; - $selectDataUp = ''; - $selectDataDown = ''; - $selectTimestampUp = ''; - $selectTimestampDown = ''; - $order = array( - 'field' => 'tagente.alias', - 'order' => 'ASC'); - break; + case 'agent_alias': + switch ($sort) { + case 'up': + $selectAgentNameUp = $selected; + $order = [ + 'field' => 'tagente.alias', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectAgentNameDown = $selected; + $order = [ + 'field' => 'tagente.alias', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'type': + switch ($sort) { + case 'up': + $selectTypeUp = $selected; + $order = [ + 'field' => 'tagente_modulo.id_tipo_modulo', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectTypeDown = $selected; + $order = [ + 'field' => 'tagente_modulo.id_tipo_modulo', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'moduletype': + switch ($sort) { + case 'up': + $selectTypeUp = $selected; + $order = [ + 'field' => 'tagente_modulo.id_modulo', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectTypeDown = $selected; + $order = [ + 'field' => 'tagente_modulo.id_modulo', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'module_name': + switch ($sort) { + case 'up': + $selectModuleNameUp = $selected; + $order = [ + 'field' => 'tagente_modulo.nombre', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectModuleNameDown = $selected; + $order = [ + 'field' => 'tagente_modulo.nombre', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'interval': + switch ($sort) { + case 'up': + $selectIntervalUp = $selected; + $order = [ + 'field' => 'tagente_modulo.module_interval', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectIntervalDown = $selected; + $order = [ + 'field' => 'tagente_modulo.module_interval', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'status': + switch ($sort) { + case 'up': + $selectStatusUp = $selected; + $order = [ + 'field' => 'tagente_estado.estado', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectStatusDown = $selected; + $order = [ + 'field' => 'tagente_estado.estado', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'timestamp': + switch ($sort) { + case 'up': + $selectTimestampUp = $selected; + $order = [ + 'field' => 'tagente_estado.utimestamp', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectTimestampDown = $selected; + $order = [ + 'field' => 'tagente_estado.utimestamp', + 'order' => 'DESC', + ]; + break; + } + break; + + case 'data': + switch ($sort) { + case 'up': + $selectTimestampUp = $selected; + $order = [ + 'field' => 'tagente_estado.datos', + 'order' => 'ASC', + ]; + break; + + case 'down': + $selectTimestampDown = $selected; + $order = [ + 'field' => 'tagente_estado.datos', + 'order' => 'DESC', + ]; + break; + } + break; + + default: + $selectAgentNameUp = $selected; + $selectAgentNameDown = ''; + $selectTypeUp = ''; + $selectTypeDown = ''; + $selectModuleNameUp = ''; + $selectModuleNameDown = ''; + $selectIntervalUp = ''; + $selectIntervalDown = ''; + $selectStatusUp = ''; + $selectStatusDown = ''; + $selectDataUp = ''; + $selectDataDown = ''; + $selectTimestampUp = ''; + $selectTimestampDown = ''; + $order = [ + 'field' => 'tagente.alias', + 'order' => 'ASC', + ]; + break; } $sql = 'SELECT @@ -772,633 +939,647 @@ $sql = 'SELECT tagente_modulo.critical_instructions, tagente_modulo.warning_instructions, tagente_modulo.unknown_instructions, - tagente_estado.utimestamp AS utimestamp' . - $sql_from . $sql_conditions_all . ' + tagente_estado.utimestamp AS utimestamp'.$sql_from.$sql_conditions_all.' GROUP BY tagente_modulo.id_agente_modulo - ORDER BY ' . $order['field'] . " " . $order['order'] . ' - LIMIT '.$offset.",".$limit_sql; + ORDER BY '.$order['field'].' '.$order['order'].' + LIMIT '.$offset.','.$limit_sql; -if (! defined ('METACONSOLE')) { - $result = db_get_all_rows_sql ($sql); - - if ($result === false) { - $result = array (); - } - else - ui_pagination ($count, false, $offset); -} -else { - // For each server defined and not disabled: - $servers = db_get_all_rows_sql ('SELECT * +// When you enter for the first time you have less than 4 query params in the url +$first_interaction = count($_GET) > 4; +// We do not show the modules until the user searches with the filter +if ($first_interaction) { + if (! defined('METACONSOLE')) { + $result = db_get_all_rows_sql($sql); + + if ($result === false) { + $result = []; + } else { + ui_pagination($count, false, $offset); + } + } else { + // For each server defined and not disabled: + $servers = db_get_all_rows_sql( + 'SELECT * FROM tmetaconsole_setup - WHERE disabled = 0'); - if ($servers === false) - $servers = array(); - - $result = array(); - $count_modules = 0; - foreach ($servers as $server) { - // If connection was good then retrieve all data server - if (metaconsole_connect($server) == NOERR) - $connection = true; - else - $connection = false; - - $result_server = db_get_all_rows_sql ($sql); - - if (!empty($result_server)) { - - // Create HASH login info - $pwd = $server['auth_token']; - $auth_serialized = json_decode($pwd,true); - - if (is_array($auth_serialized)) { - $pwd = $auth_serialized['auth_token']; - $api_password = $auth_serialized['api_password']; - $console_user = $auth_serialized['console_user']; - $console_password = $auth_serialized['console_password']; - } - - $user = $config['id_user']; - $user_rot13 = str_rot13($config['id_user']); - $hashdata = $user.$pwd; - $hashdata = md5($hashdata); - $url_hash = '&' . - 'loginhash=auto&' . - 'loginhash_data=' . $hashdata . '&' . - 'loginhash_user=' . $user_rot13; - - foreach ($result_server as $result_element_key => $result_element_value) { - - $result_server[$result_element_key]['server_id'] = $server['id']; - $result_server[$result_element_key]['server_name'] = $server['server_name']; - $result_server[$result_element_key]['server_url'] = $server['server_url'].'/'; - $result_server[$result_element_key]['hashdata'] = $hashdata; - $result_server[$result_element_key]['user'] = $config['id_user']; - $result_server[$result_element_key]['groups_in_server'] = - agents_get_all_groups_agent( - $result_element_value['id_agent'], - $result_element_value['id_group'] - ); - - $count_modules++; - - } - - $result = array_merge($result, $result_server); - } - metaconsole_restore_db(); - } - - if ($count_modules > $config['block_size']) { - ui_pagination ($count_modules, false, $offset); - } - - // Get number of elements of the pagination - $result = ui_meta_get_subset_array($result, $inferior_limit, $superior_limit); + WHERE disabled = 0' + ); + if ($servers === false) { + $servers = []; + } + + $result = []; + $count_modules = 0; + foreach ($servers as $server) { + // If connection was good then retrieve all data server + if (metaconsole_connect($server) == NOERR) { + $connection = true; + } else { + $connection = false; + } + + $result_server = db_get_all_rows_sql($sql); + + if (!empty($result_server)) { + // Create HASH login info + $pwd = $server['auth_token']; + $auth_serialized = json_decode($pwd, true); + + if (is_array($auth_serialized)) { + $pwd = $auth_serialized['auth_token']; + $api_password = $auth_serialized['api_password']; + $console_user = $auth_serialized['console_user']; + $console_password = $auth_serialized['console_password']; + } + + $user = $config['id_user']; + $user_rot13 = str_rot13($config['id_user']); + $hashdata = $user.$pwd; + $hashdata = md5($hashdata); + $url_hash = '&'.'loginhash=auto&'.'loginhash_data='.$hashdata.'&'.'loginhash_user='.$user_rot13; + + foreach ($result_server as $result_element_key => $result_element_value) { + $result_server[$result_element_key]['server_id'] = $server['id']; + $result_server[$result_element_key]['server_name'] = $server['server_name']; + $result_server[$result_element_key]['server_url'] = $server['server_url'].'/'; + $result_server[$result_element_key]['hashdata'] = $hashdata; + $result_server[$result_element_key]['user'] = $config['id_user']; + $result_server[$result_element_key]['groups_in_server'] = agents_get_all_groups_agent( + $result_element_value['id_agent'], + $result_element_value['id_group'] + ); + + $count_modules++; + } + + $result = array_merge($result, $result_server); + } + + metaconsole_restore_db(); + } + + if ($count_modules > $config['block_size']) { + ui_pagination($count_modules, false, $offset); + } + + // Get number of elements of the pagination + $result = ui_meta_get_subset_array($result, $inferior_limit, $superior_limit); + } } if (($config['dbtype'] == 'oracle') && ($result !== false)) { - for ($i=0; $i < count($result); $i++) { - unset($result[$i]['rnum']); - } + for ($i = 0; $i < count($result); $i++) { + unset($result[$i]['rnum']); + } } // Start Build List Result -///////////////////////////////////// +// if (!empty($result)) { - $table = new StdClass(); - $table->cellpadding = 0; - $table->cellspacing = 0; - $table->width = '100%'; - $table->class = 'databox data'; - $table->head = array (); - $table->data = array (); - $table->size = array (); - $table->align = array (); + $table = new StdClass(); + $table->cellpadding = 0; + $table->cellspacing = 0; + $table->width = '100%'; + $table->class = 'databox data'; + $table->head = []; + $table->data = []; + $table->size = []; + $table->align = []; - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) - $table->head[0] = '' . __('P.') . ''; + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { + $table->head[0] = ''.__('P.').''; + } - $table->head[1] = __('Agent'); - $table->head[1] .=' ' . html_print_image('images/sort_up.png', true, array('style' => $selectAgentNameUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectAgentNameDown, 'alt' => 'down')) . ''; + $table->head[1] = __('Agent'); + $table->head[1] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectAgentNameUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectAgentNameDown, 'alt' => 'down']).''; - $table->head[2] = __('Data Type'); - $table->head[2] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectTypeUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectTypeDown, 'alt' => 'down')) . ''; + $table->head[2] = __('Data Type'); + $table->head[2] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectTypeUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectTypeDown, 'alt' => 'down']).''; - $table->align[2] = 'left'; + $table->align[2] = 'left'; - $table->head[3] = __('Module name'); - $table->head[3] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectModuleNameUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectModuleNameDown, 'alt' => 'down')) . ''; + $table->head[3] = __('Module name'); + $table->head[3] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectModuleNameUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectModuleNameDown, 'alt' => 'down']).''; - $table->head[4] = __('Server type'); - $table->head[4] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectModuleNameUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectModuleNameDown, 'alt' => 'down')) . ''; + $table->head[4] = __('Server type'); + $table->head[4] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectModuleNameUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectModuleNameDown, 'alt' => 'down']).''; - $table->head[5] = __('Interval'); - $table->head[5] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectIntervalUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectIntervalDown, 'alt' => 'down')) . ''; - $table->align[5] = 'left'; + $table->head[5] = __('Interval'); + $table->head[5] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectIntervalUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectIntervalDown, 'alt' => 'down']).''; + $table->align[5] = 'left'; - $table->head[6] = __('Status'); - $table->head[6] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectStatusUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectStatusDown, 'alt' => 'down')) . ''; + $table->head[6] = __('Status'); + $table->head[6] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectStatusUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectStatusDown, 'alt' => 'down']).''; - $table->align[6] = 'left'; + $table->align[6] = 'left'; - $table->head[7] = __('Graph'); - $table->align[7] = 'left'; + $table->head[7] = __('Graph'); + $table->align[7] = 'left'; - $table->head[8] = __('Warn'); - $table->align[8] = 'left'; + $table->head[8] = __('Warn'); + $table->align[8] = 'left'; - $table->head[9] = __('Data'); - $table->align[9] = 'left'; - if ( is_metaconsole() ) { - $table->head[9] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectStatusUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectStatusDown, 'alt' => 'down')) . ''; - } + $table->head[9] = __('Data'); + $table->align[9] = 'left'; + if (is_metaconsole()) { + $table->head[9] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectStatusUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectStatusDown, 'alt' => 'down']).''; + } - $table->head[10] = __('Timestamp'); - $table->head[10] .= ' ' . html_print_image('images/sort_up.png', true, array('style' => $selectTimestampUp, 'alt' => 'up')) . '' . - '' . html_print_image('images/sort_down.png', true, array('style' => $selectTimestampDown, 'alt' => 'down')) . ''; - $table->align[10] = 'left'; + $table->head[10] = __('Timestamp'); + $table->head[10] .= ' '.html_print_image('images/sort_up.png', true, ['style' => $selectTimestampUp, 'alt' => 'up']).''.''.html_print_image('images/sort_down.png', true, ['style' => $selectTimestampDown, 'alt' => 'down']).''; + $table->align[10] = 'left'; - $id_type_web_content_string = db_get_value('id_tipo', 'ttipo_modulo', - 'nombre', 'web_content_string'); + $id_type_web_content_string = db_get_value( + 'id_tipo', + 'ttipo_modulo', + 'nombre', + 'web_content_string' + ); - foreach ($result as $row) { - //Avoid unset, null and false value - if (empty($row['server_name'])) - $row['server_name'] = ""; + foreach ($result as $row) { + // Avoid unset, null and false value + if (empty($row['server_name'])) { + $row['server_name'] = ''; + } - $is_web_content_string = (bool)db_get_value_filter('id_agente_modulo', - 'tagente_modulo', - array('id_agente_modulo' => $row['id_agente_modulo'], - 'id_tipo_modulo' => $id_type_web_content_string)); + $is_web_content_string = (bool) db_get_value_filter( + 'id_agente_modulo', + 'tagente_modulo', + [ + 'id_agente_modulo' => $row['id_agente_modulo'], + 'id_tipo_modulo' => $id_type_web_content_string, + ] + ); - //Fixed the goliat sends the strings from web - //without HTML entities - if ($is_web_content_string) { - $row['datos'] = io_safe_input($row['datos']); - } + // Fixed the goliat sends the strings from web + // without HTML entities + if ($is_web_content_string) { + $row['datos'] = io_safe_input($row['datos']); + } - //Fixed the data from Selenium Plugin - if ($row['datos'] != strip_tags($row['datos'])) { - $row['datos'] = io_safe_input($row['datos']); - } + // Fixed the data from Selenium Plugin + if ($row['datos'] != strip_tags($row['datos'])) { + $row['datos'] = io_safe_input($row['datos']); + } - $data = array (); - if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { - if(is_metaconsole()){ - $node = metaconsole_get_connection_by_id($row['server_id']); - if (metaconsole_load_external_db($node) !== NOERR) { - // Restore the default connection. - metaconsole_restore_db(); - $errors++; - break; - } - } + $data = []; + if ($isFunctionPolicies !== ENTERPRISE_NOT_HOOK) { + if (is_metaconsole()) { + $node = metaconsole_get_connection_by_id($row['server_id']); + if (metaconsole_load_external_db($node) !== NOERR) { + // Restore the default connection. + metaconsole_restore_db(); + $errors++; + break; + } + } - $policyInfo = policies_info_module_policy($row['id_agente_modulo']); + $policyInfo = policies_info_module_policy($row['id_agente_modulo']); - if ($policyInfo === false) - $data[0] = ''; - else { - $linked = policies_is_module_linked($row['id_agente_modulo']); + if ($policyInfo === false) { + $data[0] = ''; + } else { + $linked = policies_is_module_linked($row['id_agente_modulo']); - $adopt = false; - if (policies_is_module_adopt($row['id_agente_modulo'])) { - $adopt = true; - } + $adopt = false; + if (policies_is_module_adopt($row['id_agente_modulo'])) { + $adopt = true; + } - if ($linked) { - if ($adopt) { - $img = 'images/policies_brick.png'; - $title = __('(Adopt) ') . $policyInfo['name_policy']; - } - else { - $img = 'images/policies.png'; - $title = $policyInfo['name_policy']; - } - } - else { - if ($adopt) { - $img = 'images/policies_not_brick.png'; - $title = __('(Unlinked) (Adopt) ') . $policyInfo['name_policy']; - } - else { - $img = 'images/unlinkpolicy.png'; - $title = __('(Unlinked) ') . $policyInfo['name_policy']; - } - } - if(is_metaconsole()){ - $data[0] = '' . - html_print_image($img,true, array('title' => $title)) . - ''; - } - else{ - $data[0] = '' . - html_print_image($img,true, array('title' => $title)) . - ''; - } - } + if ($linked) { + if ($adopt) { + $img = 'images/policies_brick.png'; + $title = __('(Adopt) ').$policyInfo['name_policy']; + } else { + $img = 'images/policies.png'; + $title = $policyInfo['name_policy']; + } + } else { + if ($adopt) { + $img = 'images/policies_not_brick.png'; + $title = __('(Unlinked) (Adopt) ').$policyInfo['name_policy']; + } else { + $img = 'images/unlinkpolicy.png'; + $title = __('(Unlinked) ').$policyInfo['name_policy']; + } + } - if(is_metaconsole()){ - metaconsole_restore_db(); - } - } + if (is_metaconsole()) { + $data[0] = ''.html_print_image($img, true, ['title' => $title]).''; + } else { + $data[0] = ''.html_print_image($img, true, ['title' => $title]).''; + } + } - $agent_alias = !empty($row['agent_alias']) ? $row['agent_alias'] : $row['agent_name']; + if (is_metaconsole()) { + metaconsole_restore_db(); + } + } - // TODO: Calculate hash access before to use it more simply like other sections. I.E. Events view - if (defined('METACONSOLE')) { - $agent_link = ''; - $agent_alias = ui_print_truncate_text($agent_alias, - 'agent_small', false, true, false, '[…]', - 'font-size:7.5pt;'); - if (can_user_access_node ()) { - $data[1] = $agent_link . '' . $agent_alias . ''; - } - else { - $data[1] = $agent_alias; - } - } - else { - $data[1] = ''; - $data[1] .= ui_print_truncate_text($agent_alias, 'agent_medium', false, true, false, '[…]', 'font-size:7.5pt;'); - $data[1] .= ''; - } - - - $data[2] = html_print_image('images/' . modules_show_icon_type ($row['module_type']), true); - $agent_groups = is_metaconsole() - ? $row['groups_in_server'] - : agents_get_all_groups_agent($row['id_agent'], $row['id_group']); - if (check_acl_one_of_groups ($config['id_user'], $agent_groups, 'AW')) { - $show_edit_icon = true; - if (defined('METACONSOLE')) { - if (!can_user_access_node ()) { - $show_edit_icon = false; - } - - $url_edit_module = $row['server_url'] . 'index.php?' . - 'sec=gagente&' . - 'sec2=godmode/agentes/configurar_agente&' . - 'id_agente=' . $row['id_agent'] . '&' . - 'tab=module&' . - 'id_agent_module=' . $row['id_agente_modulo'] . '&' . - 'edit_module=1' . - '&loginhash=auto&loginhash_data=' . $row['hashdata'] . '&loginhash_user=' . str_rot13($row['user']); - } - else { - $url_edit_module = 'index.php?' . - 'sec=gagente&' . - 'sec2=godmode/agentes/configurar_agente&' . - 'id_agente=' . $row['id_agent'] . '&' . - 'tab=module&' . - 'id_agent_module=' . $row['id_agente_modulo'] . '&' . - 'edit_module=1'; - } - - if ($show_edit_icon) { - $data[2] .= '' . - html_print_image('images/config.png', true, - array('alt' => '0', 'border' => '', 'title' => __('Edit'))) . - ''; - } - } - - $data[3] = ui_print_truncate_text($row['module_name'], 'agent_small', false, true, true); - if ($row['extended_info'] != '') { - $data[3] .= ui_print_help_tip ($row['extended_info'], true, '/images/default_list.png'); - } - if ($row['tags'] != '') { - $data[3] .= html_print_image('/images/tag_red.png', true, - array( - 'title' => $row['tags'], - 'style' => 'width: 20px; margin-left: 3px;')); - } - $data[4] = servers_show_type ($row['id_modulo']); - - $data[5] = ($row['module_interval'] == 0) ? - human_time_description_raw($row['agent_interval']) - : - human_time_description_raw($row['module_interval']); - - if ($row['utimestamp'] == 0 && (($row['module_type'] < 21 || - $row['module_type'] > 23) && $row['module_type'] != 100)) { - $data[6] = ui_print_status_image(STATUS_MODULE_NO_DATA, - __('NOT INIT'), true); - } - elseif ($row['estado'] == 0) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_OK, - __('NORMAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_OK, - __('NORMAL') . ': ' . $row['datos'], true); - } - } - elseif ($row['estado'] == 1) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_CRITICAL, - __('CRITICAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_CRITICAL, - __('CRITICAL') . ': ' . $row['datos'], true); - } - } - elseif ($row['estado'] == 2) { - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_WARNING, - __('WARNING') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_WARNING, - __('WARNING') . ': ' . $row['datos'], true); - } - } - else { - $last_status = modules_get_agentmodule_last_status( - $row['id_agente_modulo']); - switch($last_status) { - case 0: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') . " " . - __('NORMAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') . " " . - __('NORMAL') . ': ' . $row['datos'], true); - } - break; - case 1: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') ." " . - __('CRITICAL') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') ." " . - __('CRITICAL') . ': ' . $row['datos'], true); - } - break; - case 2: - if (is_numeric($row['datos'])) { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') . " " . - __('WARNING') . ': ' . remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), true); - } - else { - $data[6] = ui_print_status_image(STATUS_MODULE_UNKNOWN, - __('UNKNOWN') . ' - ' . __('Last status') . " " . - __('WARNING') . ': ' . $row['datos'], true); - } - break; - } - } - - $data[7] = ""; - - $acl_graphs = false; - - // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions - if (!is_metaconsole()) { - $acl_graphs = check_acl($config['id_user'], $row['id_group'], 'RR'); - } - else { - $acl_graphs = true; - } - - if ($row['history_data'] == 1 && $acl_graphs) { - $graph_type = return_graphtype ($row['module_type']); - - $url = ui_get_full_url('operation/agentes/stat_win.php', false, false, false); - $handle = dechex(crc32($row['id_agente_modulo'].$row['module_name'])); - $win_handle = 'day_'.$handle; - - $graph_params = array( - 'type' => $graph_type, - 'period' => SECONDS_1DAY, - 'id' => $row['id_agente_modulo'], - 'label' => base64_encode($row['module_name']), - 'refresh' => SECONDS_10MINUTES - ); - - if (is_metaconsole() && isset($row['server_id'])) { - // Set the server id - $graph_params['server'] = $row['server_id']; - } - - $graph_params_str = http_build_query($graph_params); - - $link = 'winopeng(\''.$url.'?'.$graph_params_str.'\',\''.$win_handle.'\')'; + $agent_alias = !empty($row['agent_alias']) ? $row['agent_alias'] : $row['agent_name']; - $data[7] = get_module_realtime_link_graph($row); + // TODO: Calculate hash access before to use it more simply like other sections. I.E. Events view + if (defined('METACONSOLE')) { + $agent_link = ''; + $agent_alias = ui_print_truncate_text( + $agent_alias, + 'agent_small', + false, + true, + false, + '[…]', + 'font-size:7.5pt;' + ); + if (can_user_access_node()) { + $data[1] = $agent_link.''.$agent_alias.''; + } else { + $data[1] = $agent_alias; + } + } else { + $data[1] = ''; + $data[1] .= ui_print_truncate_text($agent_alias, 'agent_medium', false, true, false, '[…]', 'font-size:7.5pt;'); + $data[1] .= ''; + } - if(!is_snapshot_data($row['datos'])){ - $data[7] .= '' . html_print_image('images/chart_curve.png', true, array('border' => '0', 'alt' => '')) . ''; - } - $data[7] .= '' . - html_print_image ('images/binary.png', true, - array ('border' => '0', 'alt' => '')) . ''; - - $data[7] .= '' . - $row['module_name'] . - ''; - } - - $data[8] = ui_print_module_warn_value($row['max_warning'], - $row['min_warning'], $row['str_warning'], $row['max_critical'], - $row['min_critical'], $row['str_critical']); - if (is_numeric($row['datos']) && !modules_is_string_type($row['module_type'])) { - if ( $config['render_proc'] ) { - switch($row['module_type']) { - case 2: - case 6: - case 9: - case 18: - case 21: - case 31: - if ( $row['datos'] >= 1 ) - $salida = $config['render_proc_ok']; - else - $salida = $config['render_proc_fail']; - break; - default: - switch($row['module_type']) { - case 15: - $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); - if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') - $salida = human_milliseconds_to_string($row['datos']); - else - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - default: - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - } - break; - } - } - else { - switch($row['module_type']) { - case 15: - $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); - if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') - $salida = human_milliseconds_to_string($row['datos']); - else - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - default: - $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); - break; - } - } - - // Show units ONLY in numeric data types - if (isset($row['unit'])) { - $data_macro = modules_get_unit_macro($row['datos'],$row['unit']); - if($data_macro) { - $salida = $data_macro; - } else { - $salida .= ' ' . '' . io_safe_output($row['unit']) . ''; - if(strlen($salida) > $config['agent_size_text_small']) { - $salida = ui_print_truncate_text($salida, 'agent_small', true, true, false, '[…]', 'font-size:7.5pt;'); - //clean tag - $text_aux = explode(' $row['id_agente_modulo'], - 'interval' => $row['current_interval'], - 'module_name' => $row['module_name'], - 'id_node' => $row['server_id'] - )); - $salida = ui_get_snapshot_image($link, $is_snapshot) . '  '; - } else { - $sub_string = substr(io_safe_output($row['datos']), 0, 12); - if ($module_value == $sub_string) { - if ($module_value == 0 && !$sub_string) { - $salida = 0; - } - else { - $data_macro = modules_get_unit_macro($row['datos'],$row['unit']); - if($data_macro) { - $salida = $data_macro; - } else { - $salida = $row['datos']; - } - } - } - else { - //Fixed the goliat sends the strings from web - //without HTML entities - if ($is_web_content_string) { - $sub_string = substr($row['datos'], 0, 12); - } - else { - //Fixed the data from Selenium Plugin - if ($module_value != strip_tags($module_value)) { - $module_value = io_safe_input($module_value); - $sub_string = substr($row['datos'], 0, 12); - } - else { - $sub_string = substr(io_safe_output($row['datos']),0, 12); - } - } - - if ($module_value == $sub_string) { - $salida = $module_value; - } - else { - $salida = "" . - $module_value . - "" . - "" . - '' . - $sub_string . ' ' . - "" . - html_print_image('images/rosette.png', true) . ''; - } - } - } - } - - $data[9] = $salida; - - if ($row['module_interval'] > 0) - $interval = $row['module_interval']; - else - $interval = $row['agent_interval']; - - if ($row['estado'] == 3) { - $option = array ('html_attr' => 'class="redb"','style' => 'font-size:7pt;'); - } - else { - $option = array ('style' => 'font-size:7pt;'); - } - $data[10] = ui_print_timestamp ($row['utimestamp'], true, $option); - - array_push ($table->data, $data); - } - - html_print_table ($table); + if ($show_edit_icon) { + $data[2] .= ''.html_print_image( + 'images/config.png', + true, + [ + 'alt' => '0', + 'border' => '', + 'title' => __('Edit'), + ] + ).''; + } + } + + $data[3] = ui_print_truncate_text($row['module_name'], 'agent_small', false, true, true); + if ($row['extended_info'] != '') { + $data[3] .= ui_print_help_tip($row['extended_info'], true, '/images/default_list.png'); + } + + if ($row['tags'] != '') { + $data[3] .= html_print_image( + '/images/tag_red.png', + true, + [ + 'title' => $row['tags'], + 'style' => 'width: 20px; margin-left: 3px;', + ] + ); + } + + $data[4] = servers_show_type($row['id_modulo']); + + $data[5] = ($row['module_interval'] == 0) ? human_time_description_raw($row['agent_interval']) : human_time_description_raw($row['module_interval']); + + if ($row['utimestamp'] == 0 && (($row['module_type'] < 21 + || $row['module_type'] > 23) && $row['module_type'] != 100) + ) { + $data[6] = ui_print_status_image( + STATUS_MODULE_NO_DATA, + __('NOT INIT'), + true + ); + } else if ($row['estado'] == 0) { + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image( + STATUS_MODULE_OK, + __('NORMAL').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), + true + ); + } else { + $data[6] = ui_print_status_image( + STATUS_MODULE_OK, + __('NORMAL').': '.$row['datos'], + true + ); + } + } else if ($row['estado'] == 1) { + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image( + STATUS_MODULE_CRITICAL, + __('CRITICAL').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), + true + ); + } else { + $data[6] = ui_print_status_image( + STATUS_MODULE_CRITICAL, + __('CRITICAL').': '.$row['datos'], + true + ); + } + } else if ($row['estado'] == 2) { + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image( + STATUS_MODULE_WARNING, + __('WARNING').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), + true + ); + } else { + $data[6] = ui_print_status_image( + STATUS_MODULE_WARNING, + __('WARNING').': '.$row['datos'], + true + ); + } + } else { + $last_status = modules_get_agentmodule_last_status( + $row['id_agente_modulo'] + ); + switch ($last_status) { + case 0: + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image( + STATUS_MODULE_UNKNOWN, + __('UNKNOWN').' - '.__('Last status').' '.__('NORMAL').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), + true + ); + } else { + $data[6] = ui_print_status_image( + STATUS_MODULE_UNKNOWN, + __('UNKNOWN').' - '.__('Last status').' '.__('NORMAL').': '.$row['datos'], + true + ); + } + break; + + case 1: + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image( + STATUS_MODULE_UNKNOWN, + __('UNKNOWN').' - '.__('Last status').' '.__('CRITICAL').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), + true + ); + } else { + $data[6] = ui_print_status_image( + STATUS_MODULE_UNKNOWN, + __('UNKNOWN').' - '.__('Last status').' '.__('CRITICAL').': '.$row['datos'], + true + ); + } + break; + + case 2: + if (is_numeric($row['datos'])) { + $data[6] = ui_print_status_image( + STATUS_MODULE_UNKNOWN, + __('UNKNOWN').' - '.__('Last status').' '.__('WARNING').': '.remove_right_zeros(number_format($row['datos'], $config['graph_precision'])), + true + ); + } else { + $data[6] = ui_print_status_image( + STATUS_MODULE_UNKNOWN, + __('UNKNOWN').' - '.__('Last status').' '.__('WARNING').': '.$row['datos'], + true + ); + } + break; + } + } + + $data[7] = ''; + + $acl_graphs = false; + + // Avoid the check on the metaconsole. Too slow to show/hide an icon depending on the permissions + if (!is_metaconsole()) { + $acl_graphs = check_acl($config['id_user'], $row['id_group'], 'RR'); + } else { + $acl_graphs = true; + } + + if ($row['history_data'] == 1 && $acl_graphs) { + $graph_type = return_graphtype($row['module_type']); + + $url = ui_get_full_url('operation/agentes/stat_win.php', false, false, false); + $handle = dechex(crc32($row['id_agente_modulo'].$row['module_name'])); + $win_handle = 'day_'.$handle; + + $graph_params = [ + 'type' => $graph_type, + 'period' => SECONDS_1DAY, + 'id' => $row['id_agente_modulo'], + 'label' => base64_encode($row['module_name']), + 'refresh' => SECONDS_10MINUTES, + ]; + + if (is_metaconsole() && isset($row['server_id'])) { + // Set the server id + $graph_params['server'] = $row['server_id']; + } + + $graph_params_str = http_build_query($graph_params); + + $link = 'winopeng(\''.$url.'?'.$graph_params_str.'\',\''.$win_handle.'\')'; + + $data[7] = get_module_realtime_link_graph($row); + + if (!is_snapshot_data($row['datos'])) { + $data[7] .= ''.html_print_image('images/chart_curve.png', true, ['border' => '0', 'alt' => '']).''; + } + + $data[7] .= ''.html_print_image( + 'images/binary.png', + true, + [ + 'border' => '0', + 'alt' => '', + ] + ).''; + + $data[7] .= ''.$row['module_name'].''; + } + + $data[8] = ui_print_module_warn_value( + $row['max_warning'], + $row['min_warning'], + $row['str_warning'], + $row['max_critical'], + $row['min_critical'], + $row['str_critical'] + ); + + if (is_numeric($row['datos']) && !modules_is_string_type($row['module_type'])) { + if ($config['render_proc']) { + switch ($row['module_type']) { + case 2: + case 6: + case 9: + case 18: + case 21: + case 31: + if ($row['datos'] >= 1) { + $salida = $config['render_proc_ok']; + } else { + $salida = $config['render_proc_fail']; + } + break; + + default: + switch ($row['module_type']) { + case 15: + $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); + if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') { + $salida = human_milliseconds_to_string($row['datos']); + } else { + $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); + } + break; + + default: + $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); + break; + } + break; + } + } else { + switch ($row['module_type']) { + case 15: + $value = db_get_value('snmp_oid', 'tagente_modulo', 'id_agente_modulo', $row['id_agente_modulo']); + if ($value == '.1.3.6.1.2.1.1.3.0' || $value == '.1.3.6.1.2.1.25.1.1.0') { + $salida = human_milliseconds_to_string($row['datos']); + } else { + $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); + } + break; + + default: + $salida = remove_right_zeros(number_format($row['datos'], $config['graph_precision'])); + break; + } + } + + // Show units ONLY in numeric data types + if (isset($row['unit'])) { + $data_macro = modules_get_unit_macro($row['datos'], $row['unit']); + if ($data_macro) { + $salida = $data_macro; + } else { + $salida .= ' '.''.io_safe_output($row['unit']).''; + if (strlen($salida) > $config['agent_size_text_small']) { + $salida = ui_print_truncate_text($salida, 'agent_small', true, true, false, '[…]', 'font-size:7.5pt;'); + // clean tag + $text_aux = explode(' $row['id_agente_modulo'], + 'interval' => $row['current_interval'], + 'module_name' => $row['module_name'], + 'id_node' => $row['server_id'], + ] + ); + $salida = ui_get_snapshot_image($link, $is_snapshot).'  '; + } else { + $sub_string = substr(io_safe_output($row['datos']), 0, 12); + if ($module_value == $sub_string) { + if ($module_value == 0 && !$sub_string) { + $salida = 0; + } else { + $data_macro = modules_get_unit_macro($row['datos'], $row['unit']); + if ($data_macro) { + $salida = $data_macro; + } else { + $salida = $row['datos']; + } + } + } else { + // Fixed the goliat sends the strings from web + // without HTML entities + if ($is_web_content_string) { + $sub_string = substr($row['datos'], 0, 12); + } else { + // Fixed the data from Selenium Plugin + if ($module_value != strip_tags($module_value)) { + $module_value = io_safe_input($module_value); + $sub_string = substr($row['datos'], 0, 12); + } else { + $sub_string = substr(io_safe_output($row['datos']), 0, 12); + } + } + + if ($module_value == $sub_string) { + $salida = $module_value; + } else { + $salida = '".$module_value.''.'".''.$sub_string.' '."".html_print_image('images/rosette.png', true).''; + } + } + } + } + + $data[9] = $salida; + + if ($row['module_interval'] > 0) { + $interval = $row['module_interval']; + } else { + $interval = $row['agent_interval']; + } + + if ($row['estado'] == 3) { + $option = [ + 'html_attr' => 'class="redb"', + 'style' => 'font-size:7pt;', + ]; + } else { + $option = ['style' => 'font-size:7pt;']; + } + + $data[10] = ui_print_timestamp($row['utimestamp'], true, $option); + + array_push($table->data, $data); + } + + html_print_table($table); +} else { + if ($first_interaction) { + ui_print_info_message(['no_close' => true, 'message' => __('This group doesn\'t have any monitor')]); + } else { + ui_print_info_message(['no_close' => true, 'message' => __('Sorry no search parameters')]); + } } -else - ui_print_info_message ( array ( 'no_close' => true, 'message' => __('This group doesn\'t have any monitor') ) ); -// End Build List Result -///////////////////////////////////// +// End Build List Result +// echo "
                "; -//strict user hidden +// strict user hidden echo ''; @@ -1409,120 +1590,121 @@ ui_require_javascript_file('pandora_modules'); ?> \ No newline at end of file +function toggle_full_value(id) { + text = $('#hidden_value_module_' + id).html(); + old_text = $("#value_module_text_" + id).html(); + + $("#hidden_value_module_" + id).html(old_text); + + $("#value_module_text_" + id).html(text); +} + +// Show the modal window of an module +function show_module_detail_dialog(module_id, id_agent, server_name, offset, period, module_name) { + if (period == -1) { + if ($("#period").length == 1) { + period = $('#period').val(); + } + else { + period = ; + } + } + + + if ($('input[name=selection_mode]:checked').val()) { + + var selection_mode = $('input[name=selection_mode]:checked').val(); + var date_from = $('#text-date_from').val(); + var time_from = $('#text-time_from').val(); + var date_to = $('#text-date_to').val(); + var time_to = $('#text-time_to').val(); + + var extra_parameters = '&selection_mode=' + selection_mode + '&date_from=' + date_from + '&date_to=' + date_to + '&time_from=' + time_from + '&time_to=' + time_to; + + } + title = ; + $.ajax({ + type: "POST", + url: "", + data: "page=include/ajax/module&get_module_detail=1&server_name="+server_name+"&id_agent="+id_agent+"&id_module=" + module_id+"&offset="+offset+"&period="+period+extra_parameters, + dataType: "html", + success: function(data) { + $("#monitor_details_window").hide () + .empty () + .append (data) + .dialog ({ + resizable: true, + draggable: true, + modal: true, + title: title + module_name, + overlay: { + opacity: 0.5, + background: "black" + }, + width: 620, + height: 500 + }) + .show (); + + refresh_pagination_callback (module_id, id_agent, server_name,module_name); + } + }); +} + +function refresh_pagination_callback (module_id, id_agent, server_name,module_name) { + + $(".binary_dialog").click( function() { + var classes = $(this).attr('class'); + classes = classes.split(' '); + var offset_class = classes[2]; + offset_class = offset_class.split('_'); + var offset = offset_class[1]; + + var period = $('#period').val(); + + show_module_detail_dialog(module_id, id_agent, server_name, offset, period,module_name); + + return false; + }); +} + diff --git a/pandora_console/operation/agentes/tactical.php b/pandora_console/operation/agentes/tactical.php index 635d61c0d2..a4d3e6c98e 100755 --- a/pandora_console/operation/agentes/tactical.php +++ b/pandora_console/operation/agentes/tactical.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2011 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,54 +11,52 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars global $config; -require_once ("include/functions_events.php"); -require_once ("include/functions_servers.php"); -require_once ("include/functions_reporting.php"); -require_once ("include/functions_tactical.php"); -require_once ($config["homedir"] . '/include/functions_graph.php'); +require_once 'include/functions_events.php'; +require_once 'include/functions_servers.php'; +require_once 'include/functions_reporting.php'; +require_once 'include/functions_tactical.php'; +require_once $config['homedir'].'/include/functions_graph.php'; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "AR") && ! check_acl ($config['id_user'], 0, "AW")) { - db_pandora_audit("ACL Violation", - "Trying to access Agent view (Grouped)"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'AR') && ! check_acl($config['id_user'], 0, 'AW')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access Agent view (Grouped)' + ); + include 'general/noaccess.php'; + return; } -$is_admin = check_acl ($config['id_user'], 0, "PM"); +$is_admin = check_acl($config['id_user'], 0, 'PM'); $user_strict = (bool) db_get_value('strict_acl', 'tusuario', 'id_user', $config['id_user']); -$force_refresh = get_parameter ("force_refresh", ""); -$refresh = get_parameter ("refr", 0); +$force_refresh = get_parameter('force_refresh', ''); +$refresh = get_parameter('refr', 0); if ($force_refresh == 1) { - db_process_sql ("UPDATE tgroup_stat SET utimestamp = 0"); + db_process_sql('UPDATE tgroup_stat SET utimestamp = 0'); } -if ($config["realtimestats"] == 0) { - $updated_time =""; - $updated_time .= __('Last update'). " : ". ui_print_timestamp (db_get_sql ("SELECT min(utimestamp) FROM tgroup_stat"), true); - $updated_time .= ""; -} -else { -// $updated_info = __("Updated at realtime"); - $updated_info = ""; +if ($config['realtimestats'] == 0) { + $updated_time = ""; + $updated_time .= __('Last update').' : '.ui_print_timestamp(db_get_sql('SELECT min(utimestamp) FROM tgroup_stat'), true); + $updated_time .= ''; +} else { + // $updated_info = __("Updated at realtime"); + $updated_info = ''; } // Header -ui_print_page_header (__("Tactical view"), "", false, "", false, $updated_time); - -//Currently this function makes loading this page is impossible. Change -//and create new function. +ui_print_page_header(__('Tactical view'), '', false, '', false, $updated_time); +// Currently this function makes loading this page is impossible. Change +// and create new function. $all_data = tactical_status_modules_agents($config['id_user'], $user_strict, 'AR', $user_strict); -$data = array(); +$data = []; $data['monitor_not_init'] = (int) $all_data['_monitors_not_init_']; $data['monitor_unknown'] = (int) $all_data['_monitors_unknown_']; @@ -72,48 +69,43 @@ $data['monitor_alerts_fired'] = (int) $all_data['_monitors_alerts_fired_']; $data['total_agents'] = (int) $all_data['_total_agents_']; -$data["monitor_checks"] = (int) $all_data['_monitor_checks_']; +$data['monitor_checks'] = (int) $all_data['_monitor_checks_']; // Percentages if (!empty($all_data)) { - if ($data["monitor_not_normal"] > 0 && $data["monitor_checks"] > 0) { - $data['monitor_health'] = format_numeric (100 - ($data["monitor_not_normal"] / ($data["monitor_checks"] / 100)), 1); - } - else { - $data["monitor_health"] = 100; - } - - if ($data["monitor_not_init"] > 0 && $data["monitor_checks"] > 0) { - $data["module_sanity"] = format_numeric (100 - ($data["monitor_not_init"] / ($data["monitor_checks"] / 100)), 1); - } - else { - $data["module_sanity"] = 100; - } - - if (isset($data["alerts"])) { - if ($data["monitor_alerts_fired"] > 0 && $data["alerts"] > 0) { - $data["alert_level"] = format_numeric (100 - ($data["monitor_alerts_fired"] / ($data["alerts"] / 100)), 1); - } - else { - $data["alert_level"] = 100; - } - } - else { - $data["alert_level"] = 100; - $data["alerts"] = 0; - } - - $data["monitor_bad"] = $data["monitor_critical"] + $data["monitor_warning"]; - - if ($data["monitor_bad"] > 0 && $data["monitor_checks"] > 0) { - $data["global_health"] = format_numeric (100 - ($data["monitor_bad"] / ($data["monitor_checks"] / 100)), 1); - } - else { - $data["global_health"] = 100; - } - - $data["server_sanity"] = format_numeric (100 - $data["module_sanity"], 1); + if ($data['monitor_not_normal'] > 0 && $data['monitor_checks'] > 0) { + $data['monitor_health'] = format_numeric((100 - ($data['monitor_not_normal'] / ($data['monitor_checks'] / 100))), 1); + } else { + $data['monitor_health'] = 100; + } + + if ($data['monitor_not_init'] > 0 && $data['monitor_checks'] > 0) { + $data['module_sanity'] = format_numeric((100 - ($data['monitor_not_init'] / ($data['monitor_checks'] / 100))), 1); + } else { + $data['module_sanity'] = 100; + } + + if (isset($data['alerts'])) { + if ($data['monitor_alerts_fired'] > 0 && $data['alerts'] > 0) { + $data['alert_level'] = format_numeric((100 - ($data['monitor_alerts_fired'] / ($data['alerts'] / 100))), 1); + } else { + $data['alert_level'] = 100; + } + } else { + $data['alert_level'] = 100; + $data['alerts'] = 0; + } + + $data['monitor_bad'] = ($data['monitor_critical'] + $data['monitor_warning']); + + if ($data['monitor_bad'] > 0 && $data['monitor_checks'] > 0) { + $data['global_health'] = format_numeric((100 - ($data['monitor_bad'] / ($data['monitor_checks'] / 100))), 1); + } else { + $data['global_health'] = 100; + } + + $data['server_sanity'] = format_numeric((100 - $data['module_sanity']), 1); } echo ''; @@ -122,21 +114,22 @@ echo ''; //Left column - +echo ''; +// Left column echo '
                class = ""; +$table->width = '100%'; +$table->class = ''; $table->cellpadding = 2; $table->cellspacing = 2; $table->border = 0; -$table->head = array (); -$table->data = array (); -$table->style = array (); +$table->head = []; +$table->data = []; +$table->style = []; -$table->head[0] = '' . __('Report of State') . ''; -$stats = reporting_get_stats_indicators($data, 120, 10,false); +$table->head[0] = ''.__('Report of State').''; +$stats = reporting_get_stats_indicators($data, 120, 10, false); $status = ''; -foreach ( $stats as $stat ) { - $status .= '" ; +foreach ($stats as $stat) { + $status .= ''; } + $status .= '
                ' . $stat['title'] . '' . '' . $stat['graph'] . "
                '.$stat['title'].''.''.$stat['graph'].'
                '; $table->data[0][0] = $status; $table->rowclass[] = ''; @@ -144,14 +137,13 @@ $table->rowclass[] = ''; // --------------------------------------------------------------------- // Monitor checks // --------------------------------------------------------------------- - -$data_agents = array( - __('Critical') => $data['monitor_critical'], - __('Warning') => $data['monitor_warning'], - __('Normal') => $data['monitor_ok'], - __('Unknown') => $data['monitor_unknown'], - __('Not init') => $data['monitor_not_init'] - ); +$data_agents = [ + __('Critical') => $data['monitor_critical'], + __('Warning') => $data['monitor_warning'], + __('Normal') => $data['monitor_ok'], + __('Unknown') => $data['monitor_unknown'], + __('Not init') => $data['monitor_not_init'], +]; $table->data[1][0] = reporting_get_stats_alerts($data); $table->data[2][0] = reporting_get_stats_modules_status($data, 180, 100, false, $data_agents); @@ -160,85 +152,78 @@ $table->data[3][0] = reporting_get_stats_agents_monitors($data); $table->rowclass[] = ''; // --------------------------------------------------------------------- -// Server performance +// Server performance // --------------------------------------------------------------------- if ($is_admin) { - $table->data[4][0] = reporting_get_stats_servers(); - $table->rowclass[] = ''; + $table->data[4][0] = reporting_get_stats_servers(); + $table->rowclass[] = ''; } html_print_table($table); -echo '
                '; // --------------------------------------------------------------------- // Last events information // --------------------------------------------------------------------- +if (check_acl($config['id_user'], 0, 'ER')) { + $tags_condition = tags_get_acl_tags(false, 0, 'ER', 'event_condition'); + $event_filter = 'estado<>1'; + if (!empty($tags_condition)) { + $event_filter .= " AND ($tags_condition)"; + } -if (check_acl($config['id_user'],0,'ER')) { - $tags_condition = tags_get_acl_tags(false,0,'ER','event_condition'); - $event_filter = "estado<>1"; - if (!empty($tags_condition)) { - $event_filter .= " AND ($tags_condition)"; - } + if ($config['event_view_hr']) { + $event_filter .= ' AND utimestamp > (UNIX_TIMESTAMP(NOW()) - '.($config['event_view_hr'] * SECONDS_1HOUR).')'; + } - if ($config['event_view_hr']) { - $event_filter .= " AND utimestamp > (UNIX_TIMESTAMP(NOW()) - " . $config['event_view_hr'] * SECONDS_1HOUR . ")"; - } - - $events = events_print_event_table ($event_filter, 10, "100%",true,false,true); - ui_toggle($events, __('Latest events'),false,false); + $events = events_print_event_table($event_filter, 10, '100%', true, false, true); + ui_toggle($events, __('Latest events'), false, false); } // --------------------------------------------------------------------- // Server information // --------------------------------------------------------------------- if ($is_admin) { - $tiny = true; - require($config['homedir'] . '/godmode/servers/servers.build_table.php'); - + $tiny = true; + include $config['homedir'].'/godmode/servers/servers.build_table.php'; } + $out = '
                '; - $out .= '
                - ' . - __('Event graph') . - '' . - html_print_image('images/spinner.gif',true,array('id' => 'spinner_total_event_graph')) . '
                '; - $out .="
                "; - $out .= '
                - ' . - __('Event graph by agent') . - '' . - html_print_image('images/spinner.gif', true, array('id' => 'spinner_graphic_event_group')) . '
                '; - $out .= '
                '; + $out .= '
                + '.__('Event graph').''.html_print_image('images/spinner.gif', true, ['id' => 'spinner_total_event_graph']).'
                '; + $out .= '
                '; + $out .= '
                + '.__('Event graph by agent').''.html_print_image('images/spinner.gif', true, ['id' => 'spinner_graphic_event_group']).'
                '; + $out .= '
                '; echo $out; echo ''; echo ''; ?> \ No newline at end of file + $.ajax({type: "GET",url: "ajax.php",data: parameters, + success: function(data) { + $("#spinner_graphic_event_group").hide(); + $("#graphic_event_group").append(data); + } + }); + }); + \ No newline at end of file diff --git a/pandora_console/operation/agentes/url_address.php b/pandora_console/operation/agentes/url_address.php index f89462274e..a16da2ec1d 100644 --- a/pandora_console/operation/agentes/url_address.php +++ b/pandora_console/operation/agentes/url_address.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,20 +11,19 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -check_login (); +check_login(); -if (! check_acl ($config["id_user"], $id_grupo, "AW", $id_agente)) { - db_pandora_audit("ACL Violation", - "Trying to access agent manager"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], $id_grupo, 'AW', $id_agente)) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access agent manager' + ); + include 'general/noaccess.php'; + return; } -echo ""; - -?> +echo ''; diff --git a/pandora_console/operation/agentes/ver_agente.php b/pandora_console/operation/agentes/ver_agente.php index c26096f21a..e3171f61f4 100644 --- a/pandora_console/operation/agentes/ver_agente.php +++ b/pandora_console/operation/agentes/ver_agente.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,403 +11,421 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - // Load global vars global $config; -require_once ('include/functions_gis.php'); -require_once($config['homedir'] . '/include/functions_agents.php'); -require_once($config['homedir'] . '/include/functions_groups.php'); -require_once($config['homedir'] . '/include/functions_modules.php'); -require_once($config['homedir'] . '/include/functions_users.php'); -enterprise_include_once ('include/functions_metaconsole.php'); +require_once 'include/functions_gis.php'; +require_once $config['homedir'].'/include/functions_agents.php'; +require_once $config['homedir'].'/include/functions_groups.php'; +require_once $config['homedir'].'/include/functions_modules.php'; +require_once $config['homedir'].'/include/functions_users.php'; +enterprise_include_once('include/functions_metaconsole.php'); ui_require_javascript_file('openlayers.pandora'); -enterprise_include_once ('operation/agentes/ver_agente.php'); +enterprise_include_once('operation/agentes/ver_agente.php'); -check_login (); -if (is_ajax ()) { - $get_agent_json = (bool) get_parameter ('get_agent_json'); - $get_agent_modules_json = (bool) get_parameter ('get_agent_modules_json'); - $get_agent_status_tooltip = (bool) get_parameter ("get_agent_status_tooltip"); - $get_agents_group_json = (bool) get_parameter ("get_agents_group_json"); - $get_modules_group_json = (bool) get_parameter ("get_modules_group_json"); - $get_modules_group_value_name_json = (bool) get_parameter ("get_modules_group_value_name_json"); - $get_agent_modules_json_for_multiple_agents = (bool) get_parameter("get_agent_modules_json_for_multiple_agents"); - $get_agent_modules_alerts_json_for_multiple_agents = (bool) get_parameter("get_agent_modules_alerts_json_for_multiple_agents"); - $get_agent_modules_multiple_alerts_json_for_multiple_agents = (bool) get_parameter("get_agent_modules_multiple_alerts_json_for_multiple_agents"); - $get_agents_json_for_multiple_modules = (bool) get_parameter("get_agents_json_for_multiple_modules"); - $get_agent_modules_json_for_multiple_agents_id = (bool) get_parameter("get_agent_modules_json_for_multiple_agents_id"); - $get_agentmodule_status_tooltip = (bool) get_parameter ("get_agentmodule_status_tooltip"); - $get_group_status_tooltip = (bool) get_parameter ("get_group_status_tooltip"); - $get_agent_id = (bool) get_parameter ("get_agent_id"); - $get_agents_source_json = (bool) get_parameter ("get_agents_source_json"); - $cluster_mode = (bool) get_parameter ("cluster_mode",0); - $agent_alias = get_parameter('alias', ''); - $agents_inserted = get_parameter('agents_inserted', array()); - $id_group = (int) get_parameter('id_group'); - if ($get_agents_group_json) { - $id_group = (int) get_parameter('id_group'); - $recursion = get_parameter ('recursion'); - $id_os = get_parameter('id_os', ''); - $agent_name = get_parameter('name', ''); - - $privilege = (string) get_parameter ('privilege', "AR"); - // Is is possible add keys prefix to avoid auto sorting in js object conversion - $keys_prefix = (string) get_parameter ('keys_prefix', ''); - $status_agents = (int)get_parameter('status_agents', AGENT_STATUS_ALL); - - // Build filter - $filter = array(); - - if (!empty($id_os)) - $filter['id_os'] = $id_os; - if (!empty($agent_name)) - $filter['nombre'] = '%' . $agent_name . '%'; - if (!empty($agent_alias)) - $filter['alias'] = '%' . $agent_alias . '%'; - - $filter['status'] = $status_agents; - - if($cluster_mode){ - - $agent_id_os = db_get_all_rows_sql('select id_os from tconfig_os where id_os != 100'); - - foreach ($agent_id_os as $key => $value) { - $agent_id_os_array[] = $agent_id_os[$key]['id_os']; - } - - $filter['id_os'] = $agent_id_os_array; - - if($agents_inserted[0] != ''){ - - $agents_id_list = ''; - - foreach($agents_inserted as $elem) { +check_login(); +if (is_ajax()) { + $get_agent_json = (bool) get_parameter('get_agent_json'); + $get_agent_modules_json = (bool) get_parameter('get_agent_modules_json'); + $get_agent_status_tooltip = (bool) get_parameter('get_agent_status_tooltip'); + $get_agents_group_json = (bool) get_parameter('get_agents_group_json'); + $get_modules_group_json = (bool) get_parameter('get_modules_group_json'); + $get_modules_group_value_name_json = (bool) get_parameter('get_modules_group_value_name_json'); + $get_agent_modules_json_for_multiple_agents = (bool) get_parameter('get_agent_modules_json_for_multiple_agents'); + $get_agent_modules_alerts_json_for_multiple_agents = (bool) get_parameter('get_agent_modules_alerts_json_for_multiple_agents'); + $get_agent_modules_multiple_alerts_json_for_multiple_agents = (bool) get_parameter('get_agent_modules_multiple_alerts_json_for_multiple_agents'); + $get_agents_json_for_multiple_modules = (bool) get_parameter('get_agents_json_for_multiple_modules'); + $get_agent_modules_json_for_multiple_agents_id = (bool) get_parameter('get_agent_modules_json_for_multiple_agents_id'); + $get_agentmodule_status_tooltip = (bool) get_parameter('get_agentmodule_status_tooltip'); + $get_group_status_tooltip = (bool) get_parameter('get_group_status_tooltip'); + $get_agent_id = (bool) get_parameter('get_agent_id'); + $get_agents_source_json = (bool) get_parameter('get_agents_source_json'); + $cluster_mode = (bool) get_parameter('cluster_mode', 0); + $agent_alias = get_parameter('alias', ''); + $agents_inserted = get_parameter('agents_inserted', []); + $id_group = (int) get_parameter('id_group'); + if ($get_agents_group_json) { + $id_group = (int) get_parameter('id_group'); + $recursion = get_parameter('recursion'); + $id_os = get_parameter('id_os', ''); + $agent_name = get_parameter('name', ''); - if ($elem === end($agents_inserted)) { - $agents_id_list .= $elem; - } - else{ - $agents_id_list .= $elem.','; - } + $privilege = (string) get_parameter('privilege', 'AR'); + // Is is possible add keys prefix to avoid auto sorting in js object conversion + $keys_prefix = (string) get_parameter('keys_prefix', ''); + $status_agents = (int) get_parameter('status_agents', AGENT_STATUS_ALL); - } - - $agent_id_agente = db_get_all_rows_sql('select id_agente from tagente where id_agente not in ('.$agents_id_list.')'); - - foreach ($agent_id_agente as $key => $value) { - $agent_id_agente_array[] = $agent_id_agente[$key]['id_agente']; - } - - $filter['id_agente'] = $agent_id_agente_array; - - } - - } + // Build filter + $filter = []; - // Perform search - $agents = agents_get_group_agents($id_group,$filter,"lower",false,false,false,'|',$cluster_mode); - if (empty($agents)) $agents = array(); + if (!empty($id_os)) { + $filter['id_os'] = $id_os; + } - // Add keys prefix - if ($keys_prefix !== '') { - $i = 0; - foreach ($agents as $k => $v) { - $agents[$keys_prefix . $i] = array('id_agente' => $k, 'alias' => io_safe_output($v)); - unset($agents[$k]); - $i++; - } - } - - echo json_encode($agents); - return; - } + if (!empty($agent_name)) { + $filter['nombre'] = '%'.$agent_name.'%'; + } - if ($get_modules_group_json) { - $id_group = (int) get_parameter('id_module_group', 0); - $id_agents = get_parameter('id_agents'); - $selection = get_parameter('selection'); - - select_modules_for_agent_group($id_group, $id_agents, $selection); - } + if (!empty($agent_alias)) { + $filter['alias'] = '%'.$agent_alias.'%'; + } - if ($get_modules_group_value_name_json) { - $id_agents = get_parameter('id_agents'); - $selection = get_parameter('selection'); - - // No filter by module group - $modules = select_modules_for_agent_group(0, $id_agents, $selection, false, true); - echo json_encode($modules); - return; - - } - - if ($get_agent_json) { - $id_agent = (int) get_parameter ('id_agent'); - - $agent = db_get_row ('tagente', 'id_agente', $id_agent); - - echo json_encode ($agent); - return; - } - - if ($get_agent_modules_json_for_multiple_agents_id) { - $idAgents = get_parameter('id_agent'); - - $modules = db_get_all_rows_sql(' + $filter['status'] = $status_agents; + + if ($cluster_mode) { + $agent_id_os = db_get_all_rows_sql('select id_os from tconfig_os where id_os != 100'); + + foreach ($agent_id_os as $key => $value) { + $agent_id_os_array[] = $agent_id_os[$key]['id_os']; + } + + $filter['id_os'] = $agent_id_os_array; + + if ($agents_inserted[0] != '') { + $agents_id_list = ''; + + foreach ($agents_inserted as $elem) { + if ($elem === end($agents_inserted)) { + $agents_id_list .= $elem; + } else { + $agents_id_list .= $elem.','; + } + } + + $agent_id_agente = db_get_all_rows_sql('select id_agente from tagente where id_agente not in ('.$agents_id_list.')'); + + foreach ($agent_id_agente as $key => $value) { + $agent_id_agente_array[] = $agent_id_agente[$key]['id_agente']; + } + + $filter['id_agente'] = $agent_id_agente_array; + } + } + + // Perform search + $agents = agents_get_group_agents($id_group, $filter, 'lower', false, $recursion, false, '|', $cluster_mode); + if (empty($agents)) { + $agents = []; + } + + // Add keys prefix + if ($keys_prefix !== '') { + $i = 0; + foreach ($agents as $k => $v) { + $agents[$keys_prefix.$i] = [ + 'id_agente' => $k, + 'alias' => io_safe_output($v), + ]; + unset($agents[$k]); + $i++; + } + } + + echo json_encode($agents); + return; + } + + if ($get_modules_group_json) { + $id_group = (int) get_parameter('id_module_group', 0); + $id_agents = get_parameter('id_agents'); + $selection = get_parameter('selection'); + + select_modules_for_agent_group($id_group, $id_agents, $selection); + } + + if ($get_modules_group_value_name_json) { + $id_agents = get_parameter('id_agents'); + $selection = get_parameter('selection'); + + // No filter by module group + $modules = select_modules_for_agent_group(0, $id_agents, $selection, false, true); + echo json_encode($modules); + return; + } + + if ($get_agent_json) { + $id_agent = (int) get_parameter('id_agent'); + + $agent = db_get_row('tagente', 'id_agente', $id_agent); + + echo json_encode($agent); + return; + } + + if ($get_agent_modules_json_for_multiple_agents_id) { + $idAgents = get_parameter('id_agent'); + + $modules = db_get_all_rows_sql( + ' SELECT nombre, id_agente_modulo FROM tagente_modulo - WHERE id_agente IN (' . implode(',', $idAgents) . ')'); - - $return = array(); - foreach ($modules as $module) { - $return[$module['id_agente_modulo']] = io_safe_output($module['nombre']); - } - - echo json_encode($return); - return; - } - - if ($get_agents_json_for_multiple_modules) { - $nameModules = get_parameter('module_name'); - $selection_mode = get_parameter('selection_mode','common') == "all"; - $status_modulo = (int) get_parameter ('status_module', -1); + WHERE id_agente IN ('.implode(',', $idAgents).')' + ); - $names = select_agents_for_module_group( - $nameModules, - $selection_mode, - array ( - 'status' => $status_modulo - ), - "AW" - ); + $return = []; + foreach ($modules as $module) { + $return[$module['id_agente_modulo']] = io_safe_output($module['nombre']); + } - echo json_encode($names); - return; - } - - if ($get_agent_modules_alerts_json_for_multiple_agents) { - $idAgents = (array) get_parameter('id_agent'); - $templates = (array) get_parameter('templates'); - - $selection_mode = get_parameter('selection_mode','common'); - - $sql = 'SELECT DISTINCT(nombre) + echo json_encode($return); + return; + } + + if ($get_agents_json_for_multiple_modules) { + $nameModules = get_parameter('module_name'); + $selection_mode = get_parameter('selection_mode', 'common') == 'all'; + $status_modulo = (int) get_parameter('status_module', -1); + + $names = select_agents_for_module_group( + $nameModules, + $selection_mode, + ['status' => $status_modulo], + 'AW' + ); + + echo json_encode($names); + return; + } + + if ($get_agent_modules_alerts_json_for_multiple_agents) { + $idAgents = (array) get_parameter('id_agent'); + $templates = (array) get_parameter('templates'); + + $selection_mode = get_parameter('selection_mode', 'common'); + + $sql = 'SELECT DISTINCT(nombre) FROM tagente_modulo t1, talert_template_modules t2 WHERE t2.id_agent_module = t1.id_agente_modulo AND delete_pending = 0 - AND id_alert_template IN (' . implode(',', $templates) . ') - AND id_agente IN (' . implode(',', $idAgents) . ')'; - - if ($selection_mode == 'common') { - $sql .= ' AND ( + AND id_alert_template IN ('.implode(',', $templates).') + AND id_agente IN ('.implode(',', $idAgents).')'; + + if ($selection_mode == 'common') { + $sql .= ' AND ( SELECT count(nombre) FROM tagente_modulo t3, talert_template_modules t4 WHERE t4.id_agent_module = t3.id_agente_modulo AND delete_pending = 0 AND t1.nombre = t3.nombre - AND id_agente IN (' . implode(',', $idAgents) . ') - AND id_alert_template IN (' . implode(',', $templates) . ')) = (' . count($idAgents) . ')'; - } - - $sql .= ' ORDER BY t1.nombre'; - - $nameModules = db_get_all_rows_sql($sql); - - if ($nameModules == false) { - $nameModules = array(); - } - - $result = array(); - foreach($nameModules as $nameModule) { - $result[] = io_safe_output($nameModule['nombre']); - } - - echo json_encode($result); - return; - } - - if ($get_agent_modules_multiple_alerts_json_for_multiple_agents) { - $idAgents = get_parameter('id_agent'); - $id_template = get_parameter('template'); - - $selection_mode = get_parameter('selection_mode','common'); - - $sql = 'SELECT DISTINCT(nombre) + AND id_agente IN ('.implode(',', $idAgents).') + AND id_alert_template IN ('.implode(',', $templates).')) = ('.count($idAgents).')'; + } + + $sql .= ' ORDER BY t1.nombre'; + + $nameModules = db_get_all_rows_sql($sql); + + if ($nameModules == false) { + $nameModules = []; + } + + $result = []; + foreach ($nameModules as $nameModule) { + $result[] = io_safe_output($nameModule['nombre']); + } + + echo json_encode($result); + return; + } + + if ($get_agent_modules_multiple_alerts_json_for_multiple_agents) { + $idAgents = get_parameter('id_agent'); + $id_template = get_parameter('template'); + + $selection_mode = get_parameter('selection_mode', 'common'); + + $sql = 'SELECT DISTINCT(nombre) FROM tagente_modulo t1, talert_template_modules t2 WHERE t2.id_agent_module = t1.id_agente_modulo AND delete_pending = 0 AND id_alert_template = '.$id_template.' - AND id_agente IN (' . implode(',', $idAgents) . ')'; - - if ($selection_mode == 'common') { - $sql .= ' AND ( + AND id_agente IN ('.implode(',', $idAgents).')'; + + if ($selection_mode == 'common') { + $sql .= ' AND ( SELECT count(nombre) FROM tagente_modulo t3, talert_template_modules t4 WHERE t4.id_agent_module = t3.id_agente_modulo AND delete_pending = 0 AND t1.nombre = t3.nombre - AND id_agente IN (' . implode(',', $idAgents) . ') - AND id_alert_template = '.$id_template.') = (' . count($idAgents) . ')'; - } - - $sql .= ' ORDER BY t1.nombre'; - - $nameModules = db_get_all_rows_sql($sql); - - if ($nameModules == false) { - $nameModules = array(); - } - - $result = array(); - foreach($nameModules as $nameModule) { - $result[] = io_safe_output($nameModule['nombre']); - } - - echo json_encode($result); - return; - } + AND id_agente IN ('.implode(',', $idAgents).') + AND id_alert_template = '.$id_template.') = ('.count($idAgents).')'; + } - if ($get_agent_modules_json_for_multiple_agents) { - $idAgents = (array) get_parameter('id_agent'); - $tags = get_parameter('tags', null); - $module_types_excluded = get_parameter('module_types_excluded', array()); - $module_name = (string) get_parameter('name'); - $selection_mode = get_parameter('selection_mode', 'common'); - $serialized = get_parameter('serialized', ''); - $id_server = (int) get_parameter('id_server', 0); - $status_modulo = (int) get_parameter ('status_module', -1); - $metaconsole_server_name = null; - if (!empty($id_server)) { - $metaconsole_server_name = db_get_value('server_name', - 'tmetaconsole_setup', 'id', $id_server); - } + $sql .= ' ORDER BY t1.nombre'; - if (empty($idAgents[0])) { - echo json_encode(array()); - return; - } + $nameModules = db_get_all_rows_sql($sql); - $filter = '1 = 1'; + if ($nameModules == false) { + $nameModules = []; + } - $all = (string)get_parameter('all', 'all'); - switch ($all) { - default: - case 'all': - $filter .= ' AND 1 = 1'; - break; - case 'enabled': - $filter .= ' AND t1.disabled = 0'; - break; - } + $result = []; + foreach ($nameModules as $nameModule) { + $result[] = io_safe_output($nameModule['nombre']); + } - if (!empty($module_types_excluded) && is_array($module_types_excluded)) - $filter .= ' AND t1.id_tipo_modulo NOT IN (' . implode($module_types_excluded) . ')'; + echo json_encode($result); + return; + } - if (!empty($module_name)) { - $filter .= " AND t1.nombre COLLATE utf8_general_ci LIKE '%$module_name%'"; - } + if ($get_agent_modules_json_for_multiple_agents) { + $idAgents = (array) get_parameter('id_agent'); + $tags = get_parameter('tags', null); + $module_types_excluded = get_parameter('module_types_excluded', []); + $module_name = (string) get_parameter('name'); + $selection_mode = get_parameter('selection_mode', 'common'); + $serialized = get_parameter('serialized', ''); + $id_server = (int) get_parameter('id_server', 0); + $status_modulo = (int) get_parameter('status_module', -1); + $metaconsole_server_name = null; + if (!empty($id_server)) { + $metaconsole_server_name = db_get_value( + 'server_name', + 'tmetaconsole_setup', + 'id', + $id_server + ); + } - // Status selector - if ($status_modulo == AGENT_MODULE_STATUS_NORMAL) { //Normal - $sql_conditions .= ' estado = 0 AND utimestamp > 0 ) + if (empty($idAgents[0])) { + echo json_encode([]); + return; + } + + $filter = '1 = 1'; + + $all = (string) get_parameter('all', 'all'); + switch ($all) { + default: + case 'all': + $filter .= ' AND 1 = 1'; + break; + case 'enabled': + $filter .= ' AND t1.disabled = 0'; + break; + } + + if (!empty($module_types_excluded) && is_array($module_types_excluded)) { + $filter .= ' AND t1.id_tipo_modulo NOT IN ('.implode($module_types_excluded).')'; + } + + if (!empty($module_name)) { + $filter .= " AND t1.nombre COLLATE utf8_general_ci LIKE '%$module_name%'"; + } + + // Status selector + if ($status_modulo == AGENT_MODULE_STATUS_NORMAL) { + // Normal + $sql_conditions .= ' estado = 0 AND utimestamp > 0 ) OR (t1.id_tipo_modulo IN(21,22,23,100)) '; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_CRITICAL_BAD) { //Critical - $sql_conditions .= ' estado = 1 AND utimestamp > 0 )'; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_WARNING) { //Warning - $sql_conditions .= ' estado = 2 AND utimestamp > 0 )'; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_NOT_NORMAL) { //Not normal - $sql_conditions .= ' estado <> 0)'; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_UNKNOWN) { //Unknown - $sql_conditions .= ' estado = 3 AND utimestamp <> 0 )'; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_NOT_INIT) { //Not init - $sql_conditions .= ' utimestamp = 0 ) + } else if ($status_modulo == AGENT_MODULE_STATUS_CRITICAL_BAD) { + // Critical + $sql_conditions .= ' estado = 1 AND utimestamp > 0 )'; + } else if ($status_modulo == AGENT_MODULE_STATUS_WARNING) { + // Warning + $sql_conditions .= ' estado = 2 AND utimestamp > 0 )'; + } else if ($status_modulo == AGENT_MODULE_STATUS_NOT_NORMAL) { + // Not normal + $sql_conditions .= ' estado <> 0)'; + } else if ($status_modulo == AGENT_MODULE_STATUS_UNKNOWN) { + // Unknown + $sql_conditions .= ' estado = 3 AND utimestamp <> 0 )'; + } else if ($status_modulo == AGENT_MODULE_STATUS_NOT_INIT) { + // Not init + $sql_conditions .= ' utimestamp = 0 ) AND t1.id_tipo_modulo NOT IN (21,22,23,100)'; - } + } - if ($status_modulo != -1) { - $filter .= ' AND t1.id_agente_modulo IN (SELECT id_agente_modulo FROM tagente_estado where ' . $sql_conditions; - } + if ($status_modulo != -1) { + $filter .= ' AND t1.id_agente_modulo IN (SELECT id_agente_modulo FROM tagente_estado where '.$sql_conditions; + } - $sql_tags_join = ""; - $where_tags = ""; - if (tags_has_user_acl_tags($config['id_user'])) { - $where_tags = tags_get_acl_tags($config['id_user'], $id_groups, 'AR', - 'module_condition', 'AND', 'tagente_modulo', false, array(), true); + $sql_tags_join = ''; + $where_tags = ''; + if (tags_has_user_acl_tags($config['id_user'])) { + $where_tags = tags_get_acl_tags( + $config['id_user'], + $id_groups, + 'AR', + 'module_condition', + 'AND', + 'tagente_modulo', + false, + [], + true + ); - $sql_tags_join = "INNER JOIN tagente ON tagente.id_agente = t1.id_agente + $sql_tags_join = 'INNER JOIN tagente ON tagente.id_agente = t1.id_agente INNER JOIN ttag_module ON ttag_module.id_agente_modulo = t1.id_agente_modulo - LEFT JOIN tagent_secondary_group tasg ON tagente.id_agente = tasg.id_agent"; - } + LEFT JOIN tagent_secondary_group tasg ON tagente.id_agente = tasg.id_agent'; + } - if (is_metaconsole()) { - $result = array(); - $nameModules = array(); - $temp = array(); - $first = true; - $temp_element = array(); - $counter = 0; - $first_elements = array(); + if (is_metaconsole()) { + $result = []; + $nameModules = []; + $temp = []; + $first = true; + $temp_element = []; + $counter = 0; + $first_elements = []; - $array_mapped = array_map(function($item) use ($metaconsole_server_name) { - if (empty($metaconsole_server_name)) { - if (strstr($item, "|@_@|")) { - $row = explode ('|@_@|', $item); - } - else { - $row = explode ('|', $item); - } - $server_name = array_shift($row); - $id_agent = array_shift($row); - } - else { - $server_name = $metaconsole_server_name; - $id_agent = $item; - } + $array_mapped = array_map( + function ($item) use ($metaconsole_server_name) { + if (empty($metaconsole_server_name)) { + if (strstr($item, '|@_@|')) { + $row = explode('|@_@|', $item); + } else { + $row = explode('|', $item); + } - return array( - 'server_name' => $server_name, - 'id_agent' => $id_agent - ); + $server_name = array_shift($row); + $id_agent = array_shift($row); + } else { + $server_name = $metaconsole_server_name; + $id_agent = $item; + } - }, $idAgents); + return [ + 'server_name' => $server_name, + 'id_agent' => $id_agent, + ]; + }, + $idAgents + ); - $array_reduced = array_reduce($array_mapped, function($carry, $item) { + $array_reduced = array_reduce( + $array_mapped, + function ($carry, $item) { + if (!isset($carry[$item['server_name']])) { + $carry[$item['server_name']] = []; + } - if (!isset($carry[$item['server_name']])) - $carry[$item['server_name']] = array(); + $carry[$item['server_name']][] = $item['id_agent']; - $carry[$item['server_name']][] = $item['id_agent']; + return $carry; + }, + [] + ); - return $carry; + $last_modules_set = []; - }, array()); + foreach ($array_reduced as $server_name => $id_agents) { + // Metaconsole db connection + // $server_name can be the server id (ugly hack, I know) + if (is_numeric($server_name)) { + $connection = metaconsole_get_connection_by_id($server_name); + } else { + $connection = metaconsole_get_connection($server_name); + } - $last_modules_set = array(); + if (metaconsole_load_external_db($connection) != NOERR) { + continue; + } - foreach ($array_reduced as $server_name => $id_agents) { - //Metaconsole db connection - // $server_name can be the server id (ugly hack, I know) - if (is_numeric($server_name)) { - $connection = metaconsole_get_connection_by_id($server_name); - } - else { - $connection = metaconsole_get_connection($server_name); - } - - if (metaconsole_load_external_db($connection) != NOERR) { - continue; - } - - //Get agent's modules - $sql = sprintf( - 'SELECT t1.id_agente, t1.id_agente_modulo, t1.nombre + // Get agent's modules + $sql = sprintf( + 'SELECT t1.id_agente, t1.id_agente_modulo, t1.nombre FROM tagente_modulo t1 %s WHERE %s %s AND t1.delete_pending = 0 @@ -419,358 +436,428 @@ if (is_ajax ()) { WHERE t2.delete_pending = 0 AND t1.nombre = t2.nombre AND t2.id_agente IN (%s)) = (%d)', - $sql_tags_join, $filter, $where_tags, implode(',', $id_agents), - implode(',', $id_agents), count($id_agents)); + $sql_tags_join, + $filter, + $where_tags, + implode(',', $id_agents), + implode(',', $id_agents), + count($id_agents) + ); - $modules = db_get_all_rows_sql($sql); - if (empty($modules)) - $modules = array(); + $modules = db_get_all_rows_sql($sql); + if (empty($modules)) { + $modules = []; + } - $modules_aux = array(); - foreach ($modules as $key => $module) { - // Don't change this order, is used in the serialization - $module_data = array( - 'id_module' => $module['id_agente_modulo'], - 'id_agent' => $module['id_agente'], - 'server_name' => $server_name - ); - if (!isset($modules_aux[$module['nombre']])) - $modules_aux[$module['nombre']] = array(); - $modules_aux[$module['nombre']][] = $module_data; - } - $modules = $modules_aux; + $modules_aux = []; + foreach ($modules as $key => $module) { + // Don't change this order, is used in the serialization + $module_data = [ + 'id_module' => $module['id_agente_modulo'], + 'id_agent' => $module['id_agente'], + 'server_name' => $server_name, + ]; + if (!isset($modules_aux[$module['nombre']])) { + $modules_aux[$module['nombre']] = []; + } - // Build the next array using the common values - if (!empty($last_modules_set)) { - $modules = array_intersect_key($modules, $last_modules_set); + $modules_aux[$module['nombre']][] = $module_data; + } - array_walk($modules, function(&$module_data, $module_name) use ($last_modules_set) { - $module_data = array_merge($module_data, $last_modules_set[$module_name]); - }); - } - $last_modules_set = $modules; + $modules = $modules_aux; - //Restore db connection - metaconsole_restore_db(); - } + // Build the next array using the common values + if (!empty($last_modules_set)) { + $modules = array_intersect_key($modules, $last_modules_set); - $result = array(); - foreach ($last_modules_set as $module_name => $module_data) { - $value = ui_print_truncate_text(io_safe_output($module_name), 'module_medium', false, true); + array_walk( + $modules, + function (&$module_data, $module_name) use ($last_modules_set) { + $module_data = array_merge($module_data, $last_modules_set[$module_name]); + } + ); + } - $module_data_processed = array_map(function($item) { - // data: -> id_module | id_agent | server_name; - return implode('|', $item); - }, $module_data); - $key = implode(';', $module_data_processed); + $last_modules_set = $modules; - $result[$key] = $value; - } - asort($result); - } - else { - if($idAgents[0] < 0){ - if($selection_mode == 'common') { - $sql_agent_total = 'SELECT count(*) FROM tagente WHERE disabled=0'; - $agent_total = db_get_value_sql($sql_agent_total); - $sql = sprintf ("SELECT t1.nombre, t1.id_agente_modulo FROM tagente_modulo t1 + // Restore db connection + metaconsole_restore_db(); + } + + $result = []; + foreach ($last_modules_set as $module_name => $module_data) { + $value = ui_print_truncate_text(io_safe_output($module_name), 'module_medium', false, true); + + $module_data_processed = array_map( + function ($item) { + // data: -> id_module | id_agent | server_name; + return implode('|', $item); + }, + $module_data + ); + $key = implode(';', $module_data_processed); + + $result[$key] = $value; + } + + asort($result); + } else { + if ($idAgents[0] < 0) { + if ($selection_mode == 'common') { + $sql_agent_total = 'SELECT count(*) FROM tagente WHERE disabled=0'; + $agent_total = db_get_value_sql($sql_agent_total); + $sql = sprintf( + "SELECT t1.nombre, t1.id_agente_modulo FROM tagente_modulo t1 JOIN (SELECT COUNT(*) AS num_names, nombre FROM tagente_modulo WHERE disabled=0 AND delete_pending=0 GROUP BY nombre) AS tj ON tj.num_names = $agent_total AND tj.nombre = t1.nombre %s %s", - $sql_tags_join, (empty($where_tags)) ? "" : " WHERE 1=1 $where_tags"); - } else { - $sql = sprintf('SELECT t1.nombre, t1.id_agente_modulo FROM tagente_modulo t1 %s %s', - $sql_tags_join, (empty($where_tags)) ? "" : " WHERE 1=1 $where_tags"); - } - } - else { - $sql = sprintf ( - 'SELECT DISTINCT t1.nombre, t1.id_agente_modulo FROM tagente_modulo t1 + $sql_tags_join, + (empty($where_tags)) ? '' : " WHERE 1=1 $where_tags" + ); + } else { + $sql = sprintf( + 'SELECT t1.nombre, t1.id_agente_modulo FROM tagente_modulo t1 %s %s', + $sql_tags_join, + (empty($where_tags)) ? '' : " WHERE 1=1 $where_tags" + ); + } + } else { + $sql = sprintf( + 'SELECT DISTINCT t1.nombre, t1.id_agente_modulo FROM tagente_modulo t1 INNER JOIN tagente_estado t2 ON t1.id_agente_modulo = t2.id_agente_modulo %s WHERE %s AND t1.delete_pending = 0 - AND t1.id_agente IN ('. implode(',', $idAgents) .') + AND t1.id_agente IN ('.implode(',', $idAgents).') %s %s', - $sql_tags_join, $filter, ' AND t2.datos NOT LIKE "%image%"', $where_tags); + $sql_tags_join, + $filter, + ' AND t2.datos NOT LIKE "%image%"', + $where_tags + ); - if ($selection_mode == 'common') { - $sql .= ' AND ( + if ($selection_mode == 'common') { + $sql .= ' AND ( SELECT count(nombre) FROM tagente_modulo t2 WHERE t2.delete_pending = 0 AND t1.nombre = t2.nombre - AND t2.id_agente IN (' . implode(',', $idAgents) . ')) = (' . count($idAgents) . ')'; - } - elseif ($selection_mode == 'unknown') { - $sql .= 'AND t1.id_agente_modulo IN (SELECT id_agente_modulo FROM tagente_estado where estado = 3 OR estado = 4)'; - } - } + AND t2.id_agente IN ('.implode(',', $idAgents).')) = ('.count($idAgents).')'; + } else if ($selection_mode == 'unknown') { + $sql .= 'AND t1.id_agente_modulo IN (SELECT id_agente_modulo FROM tagente_estado where estado = 3 OR estado = 4)'; + } + } - $sql .= ' ORDER BY nombre'; - $nameModules = db_get_all_rows_sql($sql); - if ($tags != null) { - if ((count($tags) >= 1) && ($tags[0] != "") && ($tags[0] != -1)) { - $implode_tags = implode(",", $tags); - $tag_modules = db_get_all_rows_sql("SELECT DISTINCT id_agente_modulo FROM ttag_module WHERE id_tag IN (" . $implode_tags . ")"); - if ($tag_modules) { - $final_modules = array(); - foreach ($nameModules as $key => $module) { - $in_array = false; - foreach ($tag_modules as $t_module) { - if ($module['id_agente_modulo'] == $t_module['id_agente_modulo']) { - $in_array = true; - } - } - if ($in_array) { - $final_modules[] = $module; - } - } - $nameModules = $final_modules; - } - else { - $nameModules = array(); - } - } - } + $sql .= ' ORDER BY nombre'; + $nameModules = db_get_all_rows_sql($sql); + if ($tags != null) { + if ((count($tags) >= 1) && ($tags[0] != '') && ($tags[0] != -1)) { + $implode_tags = implode(',', $tags); + $tag_modules = db_get_all_rows_sql('SELECT DISTINCT id_agente_modulo FROM ttag_module WHERE id_tag IN ('.$implode_tags.')'); + if ($tag_modules) { + $final_modules = []; + foreach ($nameModules as $key => $module) { + $in_array = false; + foreach ($tag_modules as $t_module) { + if ($module['id_agente_modulo'] == $t_module['id_agente_modulo']) { + $in_array = true; + } + } - if ($nameModules == false) { - $nameModules = array(); - } + if ($in_array) { + $final_modules[] = $module; + } + } - $result = array(); - foreach ($nameModules as $nameModule) { - if (empty($serialized)) - $result[io_safe_output($nameModule['nombre'])] = - ui_print_truncate_text( - io_safe_output($nameModule['nombre']), 'module_medium', false, true); - else - $result[io_safe_output($nameModule['nombre']).'$*$'.implode('|', $idAgents)] = ui_print_truncate_text(io_safe_output($nameModule['nombre']), 'module_medium', false, true); - } - } + $nameModules = $final_modules; + } else { + $nameModules = []; + } + } + } - echo json_encode($result); - return; - } + if ($nameModules == false) { + $nameModules = []; + } - if ($get_agent_modules_json) { - $id_agent = (int) get_parameter ('id_agent'); - - // Use -1 as not received - $disabled = (int) get_parameter ('disabled', -1); - $delete_pending = (int) get_parameter ('delete_pending', -1); - // Use 0 as not received - $id_tipo_modulo = (int) get_parameter ('id_tipo_modulo', 0); - $status_modulo = (int) get_parameter ('status_module', -1); + $result = []; + foreach ($nameModules as $nameModule) { + if (empty($serialized)) { + $result[io_safe_output($nameModule['nombre'])] = ui_print_truncate_text( + io_safe_output($nameModule['nombre']), + 'module_medium', + false, + true + ); + } else { + $result[io_safe_output($nameModule['nombre']).'$*$'.implode('|', $idAgents)] = ui_print_truncate_text(io_safe_output($nameModule['nombre']), 'module_medium', false, true); + } + } + } - $tags = (array) get_parameter ('tags', array()); + echo json_encode($result); + return; + } - // Filter - $filter = array(); - if ($disabled !== -1) - $filter['disabled'] = $disabled; - if ($delete_pending !== -1) - $filter['delete_pending'] = $delete_pending; - if (!empty($id_tipo_modulo)) - $filter['id_tipo_modulo'] = $id_tipo_modulo; - if (empty($filter)) - $filter = false; - - $get_only_string_modules = get_parameter('get_only_string_modules', false); - if ($get_only_string_modules) { - $filter['tagente_modulo.id_tipo_modulo IN'] = "(17,23,3,10,33)"; - } + if ($get_agent_modules_json) { + $id_agent = (int) get_parameter('id_agent'); - // Status selector - if ($status_modulo == AGENT_MODULE_STATUS_NORMAL) { //Normal - $sql_conditions .= ' estado = 0 AND utimestamp > 0 ) + // Use -1 as not received + $disabled = (int) get_parameter('disabled', -1); + $delete_pending = (int) get_parameter('delete_pending', -1); + // Use 0 as not received + $id_tipo_modulo = (int) get_parameter('id_tipo_modulo', 0); + $status_modulo = (int) get_parameter('status_module', -1); + + $tags = (array) get_parameter('tags', []); + + // Filter + $filter = []; + if ($disabled !== -1) { + $filter['disabled'] = $disabled; + } + + if ($delete_pending !== -1) { + $filter['delete_pending'] = $delete_pending; + } + + if (!empty($id_tipo_modulo)) { + $filter['id_tipo_modulo'] = $id_tipo_modulo; + } + + if (empty($filter)) { + $filter = false; + } + + $get_only_string_modules = get_parameter('get_only_string_modules', false); + if ($get_only_string_modules) { + $filter['tagente_modulo.id_tipo_modulo IN'] = '(17,23,3,10,33)'; + } + + // Status selector + if ($status_modulo == AGENT_MODULE_STATUS_NORMAL) { + // Normal + $sql_conditions .= ' estado = 0 AND utimestamp > 0 ) OR (tagente_modulo.id_tipo_modulo IN(21,22,23,100)) '; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_CRITICAL_BAD) { //Critical - $sql_conditions .= ' estado = 1 AND utimestamp > 0 )'; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_WARNING) { //Warning - $sql_conditions .= ' estado = 2 AND utimestamp > 0 )'; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_NOT_NORMAL) { //Not normal - $sql_conditions .= ' estado <> 0 )'; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_UNKNOWN) { //Unknown - $sql_conditions .= ' estado = 3 AND utimestamp <> 0 )'; - } - elseif ($status_modulo == AGENT_MODULE_STATUS_NOT_INIT) { //Not init - $sql_conditions .= ' utimestamp = 0 ) + } else if ($status_modulo == AGENT_MODULE_STATUS_CRITICAL_BAD) { + // Critical + $sql_conditions .= ' estado = 1 AND utimestamp > 0 )'; + } else if ($status_modulo == AGENT_MODULE_STATUS_WARNING) { + // Warning + $sql_conditions .= ' estado = 2 AND utimestamp > 0 )'; + } else if ($status_modulo == AGENT_MODULE_STATUS_NOT_NORMAL) { + // Not normal + $sql_conditions .= ' estado <> 0 )'; + } else if ($status_modulo == AGENT_MODULE_STATUS_UNKNOWN) { + // Unknown + $sql_conditions .= ' estado = 3 AND utimestamp <> 0 )'; + } else if ($status_modulo == AGENT_MODULE_STATUS_NOT_INIT) { + // Not init + $sql_conditions .= ' utimestamp = 0 ) AND tagente_modulo.id_tipo_modulo NOT IN (21,22,23,100)'; - } - - if ($status_modulo != -1) { - $filter['tagente_modulo.id_agente_modulo IN'] = ' (SELECT id_agente_modulo FROM tagente_estado where ' . $sql_conditions; - } - - - $get_id_and_name = (bool) get_parameter ('get_id_and_name'); - $get_distinct_name = (bool) get_parameter ('get_distinct_name'); - - // Fields - $fields = '*'; - if ($get_id_and_name) - $fields = array('id_agente_modulo', 'nombre'); - if ($get_distinct_name) - $fields = array('DISTINCT(tagente_modulo.nombre)'); - - $indexed = (bool) get_parameter ('indexed', true); - $agentName = (string) get_parameter ('agent_name', null); - $server_name = (string) get_parameter ('server_name', null); - $server_id = (int) get_parameter ('server_id', 0); - /* This will force to get local modules although metaconsole is active, by default get all modules from all nodes */ - $force_local_modules = (int) get_parameter ('force_local_modules', 0); - - if ($agentName != null) { - $search = array(); - $search['alias'] = io_safe_output($agentName); - } - else - $search = false; + } - $force_tags = !empty($tags); - if ($force_tags) { - $filter['ttag_module.id_tag IN '] = "(" . implode(",", $tags) . ")"; - } - if (is_metaconsole() && !$force_local_modules) { - if (enterprise_include_once ('include/functions_metaconsole.php') !== ENTERPRISE_NOT_HOOK) { - $connection = metaconsole_get_connection($server_name); - if ($server_id > 0) { - $connection = metaconsole_get_connection_by_id($server_id); - } + if ($status_modulo != -1) { + $filter['tagente_modulo.id_agente_modulo IN'] = ' (SELECT id_agente_modulo FROM tagente_estado where '.$sql_conditions; + } - if (metaconsole_load_external_db($connection) == NOERR) { - /* Get all agents if no agent was given */ - if ($id_agent == 0) - $id_agent = array_keys( - agents_get_group_agents( - array_keys (users_get_groups ()), $search, "none")); - $agent_modules = agents_get_modules ($id_agent, $fields, $filter, $indexed, true, $force_tags); - } - // Restore db connection - metaconsole_restore_db(); - } - } - else { - /* Get all agents if no agent was given */ - if ($id_agent == 0) - $id_agent = array_keys( - agents_get_group_agents( - array_keys(users_get_groups ()), $search, "none")); - $agent_modules = agents_get_modules ($id_agent, $fields, $filter, $indexed, true, $force_tags); - } - if (empty($agent_modules)) - $agent_modules = array(); + $get_id_and_name = (bool) get_parameter('get_id_and_name'); + $get_distinct_name = (bool) get_parameter('get_distinct_name'); - foreach ($agent_modules as $key => $module) { - $agent_modules[$key]['nombre'] = io_safe_output($module['nombre']); - } + // Fields + $fields = '*'; + if ($get_id_and_name) { + $fields = [ + 'id_agente_modulo', + 'nombre', + ]; + } - $get_order_json = (bool)get_parameter('get_order_json', false); - if ($get_order_json) { - $new_elements = array(); - $index = 0; - foreach ($agent_modules as $key => $module) { - $new_elements[$index]['id_agente_modulo'] = $module['id_agente_modulo']; - $new_elements[$index]['nombre'] = io_safe_output($module['nombre']); - $index++; - } - $agent_modules = $new_elements; - } - - echo json_encode ($agent_modules); - - return; - } - - if ($get_agent_status_tooltip) { - $id_agent = (int) get_parameter ('id_agent'); - $metaconsole = (bool) get_parameter('metaconsole', false); - $id_server = (int) get_parameter('id_server', 0); //Metaconsole - - $server = null; - if ($metaconsole) { - $filter = array(); - if (!empty($id_agent)) - $filter['id_tagente'] = $id_agent; - if (!empty($id_server)) - $filter['id_tmetaconsole_setup'] = $id_server; - - $agent = db_get_row_filter('tmetaconsole_agent', $filter); - } - else { - $agent = db_get_row ('tagente', 'id_agente', $id_agent); - } - - if ($agent === false) { return; } - - echo '

                '.$agent['nombre'].'

                '; - echo ''.__('Main IP').': '.$agent['direccion'].'
                '; - echo ''.__('Group').': '; - - $hack_metaconsole = ''; - if ($metaconsole) { - $hack_metaconsole = '../../'; - } - echo html_print_image($hack_metaconsole . 'images/groups_small/'.groups_get_icon ($agent['id_grupo']).'.png', true); - echo groups_get_name ($agent['id_grupo']).'
                '; - - echo ''.__('Last contact').': '.human_time_comparation($agent['ultimo_contacto']).'
                '; - echo ''.__('Last remote contact').': '.human_time_comparation($agent['ultimo_contacto_remoto']).'
                '; - - if (!$metaconsole) { - # Fix : Only show agents with module with tags of user profile - $_user_tags = tags_get_user_tags($config['id_user'], 'RR'); - - $_sql_post = ''; - if (is_array($_user_tags) && !empty($_user_tags)) { - - $_tags = implode(',', array_keys($_user_tags)); - - $_sql_post .= ' AND tagente_modulo.id_agente_modulo IN (SELECT a.id_agente_modulo FROM tagente_modulo a, ttag_module b WHERE a.id_agente_modulo=b.id_agente_modulo AND b.id_tag IN (' . $_tags . ')) '; - - } - - $sql = sprintf ('SELECT tagente_modulo.descripcion, + if ($get_distinct_name) { + $fields = ['DISTINCT(tagente_modulo.nombre)']; + } + + $indexed = (bool) get_parameter('indexed', true); + $agentName = (string) get_parameter('agent_name', null); + $server_name = (string) get_parameter('server_name', null); + $server_id = (int) get_parameter('server_id', 0); + // This will force to get local modules although metaconsole is active, by default get all modules from all nodes + $force_local_modules = (int) get_parameter('force_local_modules', 0); + + if ($agentName != null) { + $search = []; + $search['alias'] = io_safe_output($agentName); + } else { + $search = false; + } + + $force_tags = !empty($tags); + if ($force_tags) { + $filter['ttag_module.id_tag IN '] = '('.implode(',', $tags).')'; + } + + if (is_metaconsole() && !$force_local_modules) { + if (enterprise_include_once('include/functions_metaconsole.php') !== ENTERPRISE_NOT_HOOK) { + $connection = metaconsole_get_connection($server_name); + if ($server_id > 0) { + $connection = metaconsole_get_connection_by_id($server_id); + } + + if (metaconsole_load_external_db($connection) == NOERR) { + // Get all agents if no agent was given + if ($id_agent == 0) { + $id_agent = array_keys( + agents_get_group_agents( + array_keys(users_get_groups()), + $search, + 'none' + ) + ); + } + + $agent_modules = agents_get_modules($id_agent, $fields, $filter, $indexed, true, $force_tags); + } + + // Restore db connection + metaconsole_restore_db(); + } + } else { + // Get all agents if no agent was given + if ($id_agent == 0) { + $id_agent = array_keys( + agents_get_group_agents( + array_keys(users_get_groups()), + $search, + 'none' + ) + ); + } + + $agent_modules = agents_get_modules($id_agent, $fields, $filter, $indexed, true, $force_tags); + } + + if (empty($agent_modules)) { + $agent_modules = []; + } + + foreach ($agent_modules as $key => $module) { + $agent_modules[$key]['nombre'] = io_safe_output($module['nombre']); + } + + $get_order_json = (bool) get_parameter('get_order_json', false); + if ($get_order_json) { + $new_elements = []; + $index = 0; + foreach ($agent_modules as $key => $module) { + $new_elements[$index]['id_agente_modulo'] = $module['id_agente_modulo']; + $new_elements[$index]['nombre'] = io_safe_output($module['nombre']); + $index++; + } + + $agent_modules = $new_elements; + } + + echo json_encode($agent_modules); + + return; + } + + if ($get_agent_status_tooltip) { + $id_agent = (int) get_parameter('id_agent'); + $metaconsole = (bool) get_parameter('metaconsole', false); + $id_server = (int) get_parameter('id_server', 0); + // Metaconsole + $server = null; + if ($metaconsole) { + $filter = []; + if (!empty($id_agent)) { + $filter['id_tagente'] = $id_agent; + } + + if (!empty($id_server)) { + $filter['id_tmetaconsole_setup'] = $id_server; + } + + $agent = db_get_row_filter('tmetaconsole_agent', $filter); + } else { + $agent = db_get_row('tagente', 'id_agente', $id_agent); + } + + if ($agent === false) { + return; + } + + echo '

                '.$agent['nombre'].'

                '; + echo ''.__('Main IP').': '.$agent['direccion'].'
                '; + echo ''.__('Group').': '; + + $hack_metaconsole = ''; + if ($metaconsole) { + $hack_metaconsole = '../../'; + } + + echo html_print_image($hack_metaconsole.'images/groups_small/'.groups_get_icon($agent['id_grupo']).'.png', true); + echo groups_get_name($agent['id_grupo']).'
                '; + + echo ''.__('Last contact').': '.human_time_comparation($agent['ultimo_contacto']).'
                '; + echo ''.__('Last remote contact').': '.human_time_comparation($agent['ultimo_contacto_remoto']).'
                '; + + if (!$metaconsole) { + // Fix : Only show agents with module with tags of user profile + $_user_tags = tags_get_user_tags($config['id_user'], 'RR'); + + $_sql_post = ''; + if (is_array($_user_tags) && !empty($_user_tags)) { + $_tags = implode(',', array_keys($_user_tags)); + + $_sql_post .= ' AND tagente_modulo.id_agente_modulo IN (SELECT a.id_agente_modulo FROM tagente_modulo a, ttag_module b WHERE a.id_agente_modulo=b.id_agente_modulo AND b.id_tag IN ('.$_tags.')) '; + } + + $sql = sprintf( + 'SELECT tagente_modulo.descripcion, tagente_modulo.nombre FROM tagente_estado, tagente_modulo WHERE tagente_modulo.id_agente = %d AND tagente_estado.id_agente_modulo = tagente_modulo.id_agente_modulo AND tagente_modulo.disabled = 0 - AND tagente_estado.estado = 1', $id_agent); - - $sql .= $_sql_post; - - $bad_modules = db_get_all_rows_sql ($sql); - - $sql = sprintf ('SELECT COUNT(*) + AND tagente_estado.estado = 1', + $id_agent + ); + + $sql .= $_sql_post; + + $bad_modules = db_get_all_rows_sql($sql); + + $sql = sprintf( + 'SELECT COUNT(*) FROM tagente_modulo WHERE id_agente = %d - AND disabled = 0', $id_agent); - $total_modules = db_get_sql ($sql); - - if ($bad_modules === false) - $size_bad_modules = 0; - else - $size_bad_modules = sizeof ($bad_modules); - - // Modules down - if ($size_bad_modules > 0) { - echo ''.__('Monitors down').': '.$size_bad_modules.' / '.$total_modules; - echo '
                  '; - foreach ($bad_modules as $module) { - echo '
                • '; - echo ui_print_truncate_text($module['nombre'], 'module_small'); - echo '
                • '; - } - echo '
                '; - } - - // Alerts (if present) - $sql = sprintf ('SELECT COUNT(talert_template_modules.id) + AND disabled = 0', + $id_agent + ); + $total_modules = db_get_sql($sql); + + if ($bad_modules === false) { + $size_bad_modules = 0; + } else { + $size_bad_modules = sizeof($bad_modules); + } + + // Modules down + if ($size_bad_modules > 0) { + echo ''.__('Monitors down').': '.$size_bad_modules.' / '.$total_modules; + echo '
                  '; + foreach ($bad_modules as $module) { + echo '
                • '; + echo ui_print_truncate_text($module['nombre'], 'module_small'); + echo '
                • '; + } + + echo '
                '; + } + + // Alerts (if present) + $sql = sprintf( + 'SELECT COUNT(talert_template_modules.id) FROM talert_template_modules, tagente_modulo, tagente WHERE tagente.id_agente = %d AND tagente.disabled = 0 @@ -778,12 +865,14 @@ if (is_ajax ()) { AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = talert_template_modules.id_agent_module AND talert_template_modules.times_fired > 0 ', - $id_agent); - - $alert_modules = (int) db_get_sql ($sql); - - if ($alert_modules > 0) { - $sql = sprintf ('SELECT tagente_modulo.nombre, talert_template_modules.last_fired + $id_agent + ); + + $alert_modules = (int) db_get_sql($sql); + + if ($alert_modules > 0) { + $sql = sprintf( + 'SELECT tagente_modulo.nombre, talert_template_modules.last_fired FROM talert_template_modules, tagente_modulo, tagente WHERE tagente.id_agente = %d AND tagente.disabled = 0 @@ -791,568 +880,601 @@ if (is_ajax ()) { AND tagente_modulo.disabled = 0 AND tagente_modulo.id_agente_modulo = talert_template_modules.id_agent_module AND talert_template_modules.times_fired > 0 ', - $id_agent); - - $alerts = db_get_all_rows_sql ($sql); - - echo ''.__('Alerts fired').':'; - echo "
                  "; - foreach ($alerts as $alert_item) { - echo '
                • '; - echo ui_print_truncate_text($alert_item['nombre']).' -> '; - echo human_time_comparation($alert_item['last_fired']); - echo '
                • '; - } - echo '
                '; - } - } - - return; - } - - if ($get_agentmodule_status_tooltip) { - $id_module = (int) get_parameter ('id_module'); - $metaconsole = (bool)get_parameter('metaconsole'); - $id_server = (int)get_parameter('id_server'); - - if ($metaconsole) { - $server = db_get_row('tmetaconsole_setup', 'id', $id_server); - - if (metaconsole_connect($server) != NOERR) { - return; - } - } - - $module = db_get_row ('tagente_modulo', 'id_agente_modulo', $id_module); - - echo '

                '; - echo html_print_image("images/brick.png", true) . ' '; - echo ui_print_truncate_text($module['nombre'], 'module_small', false, true, false).'

                '; - echo ''.__('Type').': '; - $agentmoduletype = modules_get_agentmodule_type ($module['id_agente_modulo']); - echo modules_get_moduletype_name ($agentmoduletype).' '; - echo html_print_image("images/" . modules_get_type_icon ($agentmoduletype), true) . '
                '; - echo ''.__('Module group').': '; - $modulegroup = modules_get_modulegroup_name (modules_get_agentmodule_modulegroup ($module['id_agente_modulo'])); - if ($modulegroup === false) { - echo __('None').'
                '; - } - else { - echo $modulegroup.'
                '; - } - echo ''.__('Agent').': '; - echo ui_print_truncate_text(modules_get_agentmodule_agent_alias($module['id_agente_modulo']), 'agent_small', false, true, false).'
                '; - - if ($module['id_tipo_modulo'] == 18) { - echo ''.__('Address').': '; - - // Get the IP/IPs from the module description - // Always the IP is the last part of the description (after the last space) - $ips = explode(' ', $module['descripcion']); - $ips = $ips[count($ips)-1]; - - $ips = explode(',', $ips); - if (count($ips) == 1) { - echo $ips[0]; - } - else { - echo '
                  '; - foreach ($ips as $ip) { - echo "
                • $ip
                • "; - } - echo '
                '; - } - } - - if ($metaconsole) { - metaconsole_restore_db(); - } - - return; - } - - if ($get_group_status_tooltip) { - $id_group = (int) get_parameter ('id_group'); - $group = db_get_row ('tgrupo', 'id_grupo', $id_group); - echo '

                ' . html_print_image("images/groups_small/" . groups_get_icon ($group['id_grupo']) . ".png", true); - echo ui_print_truncate_text($group['nombre'], GENERIC_SIZE_TEXT, false, true, false) . '

                '; - echo ''.__('Parent').': '; - if ($group['parent'] == 0) { - echo __('None') . '
                '; - } - else { - $group_parent = db_get_row ('tgrupo', 'id_grupo', $group['parent']); - echo html_print_image("images/groups_small/" . groups_get_icon ($group['parent']) . ".png", true); - echo $group_parent['nombre'] . '
                '; - } - echo '' . __('Sons') . ': '; - $groups_sons = db_get_all_fields_in_table ('tgrupo', 'parent', $group['id_grupo']); - if ($groups_sons === false) { - echo __('None').'
                '; - } - else { - echo '

                '; - foreach($groups_sons as $group_son) { - echo html_print_image("images/groups_small/" . groups_get_icon ($group_son['id_grupo']) . ".png", true); - echo $group_son['nombre'].'
                '; - } - } - - return; - } - - if ($get_agent_id) { - $agent_name = (string) get_parameter ("agent_name"); - - echo agents_get_agent_id ($agent_name); - return; - } - - if ($get_agents_source_json) { - $source = get_parameter('source', ''); - - if (empty($source)) { - $sql_report_log = 'SELECT id_agente, alias + $id_agent + ); + + $alerts = db_get_all_rows_sql($sql); + + echo ''.__('Alerts fired').':'; + echo '
                  '; + foreach ($alerts as $alert_item) { + echo '
                • '; + echo ui_print_truncate_text($alert_item['nombre']).' -> '; + echo human_time_comparation($alert_item['last_fired']); + echo '
                • '; + } + + echo '
                '; + } + } + + return; + } + + if ($get_agentmodule_status_tooltip) { + $id_module = (int) get_parameter('id_module'); + $metaconsole = (bool) get_parameter('metaconsole'); + $id_server = (int) get_parameter('id_server'); + + if ($metaconsole) { + $server = db_get_row('tmetaconsole_setup', 'id', $id_server); + + if (metaconsole_connect($server) != NOERR) { + return; + } + } + + $module = db_get_row('tagente_modulo', 'id_agente_modulo', $id_module); + + echo '

                '; + echo html_print_image('images/brick.png', true).' '; + echo ui_print_truncate_text($module['nombre'], 'module_small', false, true, false).'

                '; + echo ''.__('Type').': '; + $agentmoduletype = modules_get_agentmodule_type($module['id_agente_modulo']); + echo modules_get_moduletype_name($agentmoduletype).' '; + echo html_print_image('images/'.modules_get_type_icon($agentmoduletype), true).'
                '; + echo ''.__('Module group').': '; + $modulegroup = modules_get_modulegroup_name(modules_get_agentmodule_modulegroup($module['id_agente_modulo'])); + if ($modulegroup === false) { + echo __('None').'
                '; + } else { + echo $modulegroup.'
                '; + } + + echo ''.__('Agent').': '; + echo ui_print_truncate_text(modules_get_agentmodule_agent_alias($module['id_agente_modulo']), 'agent_small', false, true, false).'
                '; + + if ($module['id_tipo_modulo'] == 18) { + echo ''.__('Address').': '; + + // Get the IP/IPs from the module description + // Always the IP is the last part of the description (after the last space) + $ips = explode(' ', $module['descripcion']); + $ips = $ips[(count($ips) - 1)]; + + $ips = explode(',', $ips); + if (count($ips) == 1) { + echo $ips[0]; + } else { + echo '
                  '; + foreach ($ips as $ip) { + echo "
                • $ip
                • "; + } + + echo '
                '; + } + } + + if ($metaconsole) { + metaconsole_restore_db(); + } + + return; + } + + if ($get_group_status_tooltip) { + $id_group = (int) get_parameter('id_group'); + $group = db_get_row('tgrupo', 'id_grupo', $id_group); + echo '

                '.html_print_image('images/groups_small/'.groups_get_icon($group['id_grupo']).'.png', true); + echo ui_print_truncate_text($group['nombre'], GENERIC_SIZE_TEXT, false, true, false).'

                '; + echo ''.__('Parent').': '; + if ($group['parent'] == 0) { + echo __('None').'
                '; + } else { + $group_parent = db_get_row('tgrupo', 'id_grupo', $group['parent']); + echo html_print_image('images/groups_small/'.groups_get_icon($group['parent']).'.png', true); + echo $group_parent['nombre'].'
                '; + } + + echo ''.__('Sons').': '; + $groups_sons = db_get_all_fields_in_table('tgrupo', 'parent', $group['id_grupo']); + if ($groups_sons === false) { + echo __('None').'
                '; + } else { + echo '

                '; + foreach ($groups_sons as $group_son) { + echo html_print_image('images/groups_small/'.groups_get_icon($group_son['id_grupo']).'.png', true); + echo $group_son['nombre'].'
                '; + } + } + + return; + } + + if ($get_agent_id) { + $agent_name = (string) get_parameter('agent_name'); + + echo agents_get_agent_id($agent_name); + return; + } + + if ($get_agents_source_json) { + $source = get_parameter('source', ''); + + if (empty($source)) { + $sql_report_log = 'SELECT id_agente, alias FROM tagente, tagent_module_log WHERE tagente.id_agente = tagent_module_log.id_agent AND tagente.disabled = 0'; - } else { - $sql_report_log = 'SELECT id_agente, alias + } else { + $sql_report_log = 'SELECT id_agente, alias FROM tagente, tagent_module_log - WHERE tagente.id_agente = tagent_module_log.id_agent AND tagente.disabled = 0 AND tagent_module_log.source like "'. $source.'"'; - } - - $all_agent_log = db_get_all_rows_sql($sql_report_log); - - foreach ($all_agent_log as $key => $value) { - $agents2[$value['id_agente']] = $value['alias']; - } - - echo json_encode($agents2); - return; - } - - return; + WHERE tagente.id_agente = tagent_module_log.id_agent AND tagente.disabled = 0 AND tagent_module_log.source like "'.$source.'"'; + } + + $all_agent_log = db_get_all_rows_sql($sql_report_log); + + foreach ($all_agent_log as $key => $value) { + $agents2[$value['id_agente']] = $value['alias']; + } + + echo json_encode($agents2); + return; + } + + return; } -$id_agente = (int) get_parameter ("id_agente", 0); -if (empty ($id_agente)) { - return; +$id_agente = (int) get_parameter('id_agente', 0); +if (empty($id_agente)) { + return; } -$agent_a = check_acl ($config['id_user'], 0, "AR"); -$agent_w = check_acl ($config['id_user'], 0, "AW"); + +$agent_a = check_acl($config['id_user'], 0, 'AR'); +$agent_w = check_acl($config['id_user'], 0, 'AW'); $access = ($agent_a == true) ? 'AR' : (($agent_w == true) ? 'AW' : 'AR'); -$agent = db_get_row ('tagente', 'id_agente', $id_agente); +$agent = db_get_row('tagente', 'id_agente', $id_agente); // get group for this id_agente $id_grupo = $agent['id_grupo']; -$is_extra = enterprise_hook('policies_is_agent_extra_policy', array($id_agente)); +$is_extra = enterprise_hook('policies_is_agent_extra_policy', [$id_agente]); if ($is_extra === ENTERPRISE_NOT_HOOK) { - $is_extra = false; + $is_extra = false; } -$all_groups = agents_get_all_groups_agent ($id_agente, $id_grupo); +$all_groups = agents_get_all_groups_agent($id_agente, $id_grupo); -if (! check_acl_one_of_groups ($config['id_user'], $all_groups, "AR") && ! check_acl_one_of_groups ($config['id_user'], $all_groups, "AW", $id_agente) && !$is_extra) { - db_pandora_audit("ACL Violation", - "Trying to access (read) to agent ".agents_get_name($id_agente)); - include ("general/noaccess.php"); - return; +if (! check_acl_one_of_groups($config['id_user'], $all_groups, 'AR') && ! check_acl_one_of_groups($config['id_user'], $all_groups, 'AW', $id_agente) && !$is_extra) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access (read) to agent '.agents_get_name($id_agente) + ); + include 'general/noaccess.php'; + return; } // Check for Network FLAG change request $flag = get_parameter('flag', ''); if ($flag !== '') { - if ($flag == 1 && check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) { - $id_agent_module = get_parameter('id_agente_modulo'); - - db_process_sql_update('tagente_modulo', - array('flag' => 1), array('id_agente_modulo' => $id_agent_module)); - } + if ($flag == 1 && check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + $id_agent_module = get_parameter('id_agente_modulo'); + + db_process_sql_update( + 'tagente_modulo', + ['flag' => 1], + ['id_agente_modulo' => $id_agent_module] + ); + } } + // Check for Network FLAG change request -$flag_agent = get_parameter('flag_agent',''); +$flag_agent = get_parameter('flag_agent', ''); if ($flag_agent !== '') { - if ($flag_agent == 1 && check_acl_one_of_groups ($config['id_user'], $all_groups, "AW")) { - db_process_sql_update('tagente_modulo', array('flag' => 1), array('id_agente' =>$id_agente)); - } + if ($flag_agent == 1 && check_acl_one_of_groups($config['id_user'], $all_groups, 'AW')) { + db_process_sql_update('tagente_modulo', ['flag' => 1], ['id_agente' => $id_agente]); + } } -if ($agent["icon_path"]) { - $icon = gis_get_agent_icon_map($agent["id_agente"], true); -} -else { - $icon = 'images/bricks.png'; +if ($agent['icon_path']) { + $icon = gis_get_agent_icon_map($agent['id_agente'], true); +} else { + $icon = 'images/bricks.png'; } -///-------------Code for the tabs in the header of agent page----------- -$tab = get_parameter ("tab", "main"); +// -------------Code for the tabs in the header of agent page----------- +$tab = get_parameter('tab', 'main'); -/* Manage tab */ -$managetab = array(); +// Manage tab +$managetab = []; -if (check_acl_one_of_groups ($config['id_user'],$all_groups, "AW") || $is_extra) { - $managetab['text'] ='' - . html_print_image("images/setup.png", true, array ("title" => __('Manage'))) - . ''; - - if ($tab == 'manage') - $managetab['active'] = true; - else - $managetab['active'] = false; - - $managetab['godmode'] = 1; +if (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW') || $is_extra) { + $managetab['text'] = ''.html_print_image('images/setup.png', true, ['title' => __('Manage')]).''; + + if ($tab == 'manage') { + $managetab['active'] = true; + } else { + $managetab['active'] = false; + } + + $managetab['godmode'] = 1; } -/* Main tab */ -$maintab['text'] = '' - . html_print_image("images/agent_mc.png", true, array("title" => __('Main'))) - . ''; +// Main tab +$maintab['text'] = ''.html_print_image('images/agent_mc.png', true, ['title' => __('Main')]).''; -if ($tab == 'main') - $maintab['active'] = true; -else - $maintab['active'] = false; +if ($tab == 'main') { + $maintab['active'] = true; +} else { + $maintab['active'] = false; +} -/* Alert tab */ -$alerttab['text'] = '' - . html_print_image("images/op_alerts.png", true, array("title" => __('Alerts'))) - . ''; +// Alert tab +$alerttab['text'] = ''.html_print_image('images/op_alerts.png', true, ['title' => __('Alerts')]).''; -if ($tab == 'alert') - $alerttab['active'] = true; -else - $alerttab['active'] = false; +if ($tab == 'alert') { + $alerttab['active'] = true; +} else { + $alerttab['active'] = false; +} -/* Inventory */ -$inventorytab = enterprise_hook ('inventory_tab'); -if ($inventorytab == -1) - $inventorytab = ""; +// Inventory +$inventorytab = enterprise_hook('inventory_tab'); +if ($inventorytab == -1) { + $inventorytab = ''; +} -/* Collection */ +// Collection $collectiontab = enterprise_hook('collection_tab'); -if ($collectiontab == -1) - $collectiontab = ""; +if ($collectiontab == -1) { + $collectiontab = ''; +} -/* Policy */ +// Policy $policyTab = enterprise_hook('policy_tab'); -if ($policyTab == -1) - $policyTab = ""; - -/* WUX Console */ -$modules_wux = enterprise_hook('get_wux_modules' , array($id_agente)); -if($modules_wux){ - $wux_console_tab = enterprise_hook('wux_console_tab'); - if ($wux_console_tab == -1) - $wux_console_tab = ""; +if ($policyTab == -1) { + $policyTab = ''; } -$url_route_analyzer = enterprise_hook('get_url_route_analyzer_modules', array($id_agente)); +// WUX Console +$modules_wux = enterprise_hook('get_wux_modules', [$id_agente]); +if ($modules_wux) { + $wux_console_tab = enterprise_hook('wux_console_tab'); + if ($wux_console_tab == -1) { + $wux_console_tab = ''; + } +} + +$url_route_analyzer = enterprise_hook('get_url_route_analyzer_modules', [$id_agente]); if ($url_route_analyzer) { - $url_route_analyzer_tab = enterprise_hook('url_route_analyzer_tab'); - if ($url_route_analyzer_tab == -1) { - $url_route_analyzer_tab = ""; - } + $url_route_analyzer_tab = enterprise_hook('url_route_analyzer_tab'); + if ($url_route_analyzer_tab == -1) { + $url_route_analyzer_tab = ''; + } } -/* GIS tab */ -$gistab=array(); +// GIS tab +$gistab = []; if ($config['activate_gis']) { - $gistab['text'] = '' - .html_print_image("images/op_gis.png", true, array( "title" => __('GIS data'))) - .''; - - if ($tab == 'gis') - $gistab['active'] = true; - else - $gistab['active'] = false; + $gistab['text'] = ''.html_print_image('images/op_gis.png', true, [ 'title' => __('GIS data')]).''; + + if ($tab == 'gis') { + $gistab['active'] = true; + } else { + $gistab['active'] = false; + } } -/* Incident tab */ +// Incident tab $total_incidents = agents_get_count_incidents($id_agente); if ($total_incidents > 0) { - $incidenttab['text'] = '' - . html_print_image ("images/book_edit.png", true, array ("title" =>__('Incidents'))) - . ''; - - if ($tab == 'incident') - $incidenttab['active'] = true; - else - $incidenttab['active'] = false; + $incidenttab['text'] = ''.html_print_image('images/book_edit.png', true, ['title' => __('Incidents')]).''; + + if ($tab == 'incident') { + $incidenttab['active'] = true; + } else { + $incidenttab['active'] = false; + } } -/* Url address tab */ +// Url address tab if ($agent['url_address'] != '') { - $urladdresstab['text'] = '' - . html_print_image ("images/link.png", true, array ("title" =>__('Url address'))) - . ''; + $urladdresstab['text'] = ''.html_print_image('images/link.png', true, ['title' => __('Url address')]).''; +} + +if ($tab == 'url_address') { + $urladdresstab['active'] = true; +} else { + $urladdresstab['active'] = false; } -if ($tab == 'url_address') - $urladdresstab['active'] = true; -else - $urladdresstab['active'] = false; -/* Custom fields tab */ -$custom_fields['text'] = '' - . html_print_image("images/custom_field.png", true, array("title" => __('Custom fields'))) - . ''; +// Custom fields tab +$custom_fields['text'] = ''.html_print_image('images/custom_field.png', true, ['title' => __('Custom fields')]).''; if ($tab == 'custom_fields') { - $custom_fields['active'] = true; -} -else { - $custom_fields['active'] = false; + $custom_fields['active'] = true; +} else { + $custom_fields['active'] = false; } -/* Graphs tab */ -$graphs['text'] = '' - . html_print_image("images/chart.png", true, array("title" => __('Graphs'))) - . ''; +// Graphs tab +$graphs['text'] = ''.html_print_image('images/chart.png', true, ['title' => __('Graphs')]).''; if ($tab == 'graphs') { - $graphs['active'] = true; -} -else { - $graphs['active'] = false; + $graphs['active'] = true; +} else { + $graphs['active'] = false; } -/* Log viewer tab */ +// Log viewer tab if (enterprise_installed() && $config['log_collector']) { - $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; - $agent_has_logs = (bool) db_get_value('id_agent', 'tagent_module_log', 'id_agent', $id_agente); + $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'; + $agent_has_logs = (bool) db_get_value('id_agent', 'tagent_module_log', 'id_agent', $id_agente); - if ($agent_has_logs && !$is_windows) { - $log_viewer_tab = array(); - $log_viewer_tab['text'] = '' - . html_print_image("images/gm_log.png", true, array("title" => __('Log Viewer'))) - . ''; - $log_viewer_tab['active'] = $tab == 'log_viewer'; - } + if ($agent_has_logs && !$is_windows) { + $log_viewer_tab = []; + $log_viewer_tab['text'] = ''.html_print_image('images/gm_log.png', true, ['title' => __('Log Viewer')]).''; + $log_viewer_tab['active'] = $tab == 'log_viewer'; + } } -/* eHorus tab */ +// eHorus tab if ($config['ehorus_enabled'] && !empty($config['ehorus_custom_field']) - && (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW') || is_user_admin($config['id_user']))) { - $ehorus_agent_id = agents_get_agent_custom_field($id_agente, $config['ehorus_custom_field']); - if (!empty($ehorus_agent_id)) { - $tab_url = 'index.php?sec=estado&sec2=operation/agentes/ver_agente&tab=ehorus&id_agente='.$id_agente; - $ehorus_tab['text'] = '' - . html_print_image ('images/ehorus/ehorus.png', true, array ( 'title' => __('eHorus'))) - . ''; - - // Hidden subtab layer - $ehorus_tab['sub_menu'] = ''; - - $ehorus_tab['active'] = $tab == 'ehorus'; - } + && (check_acl_one_of_groups($config['id_user'], $all_groups, 'AW') || is_user_admin($config['id_user'])) +) { + $ehorus_agent_id = agents_get_agent_custom_field($id_agente, $config['ehorus_custom_field']); + if (!empty($ehorus_agent_id)) { + $tab_url = 'index.php?sec=estado&sec2=operation/agentes/ver_agente&tab=ehorus&id_agente='.$id_agente; + $ehorus_tab['text'] = ''.html_print_image('images/ehorus/ehorus.png', true, [ 'title' => __('eHorus')]).''; + + // Hidden subtab layer + $ehorus_tab['sub_menu'] = ''; + + $ehorus_tab['active'] = $tab == 'ehorus'; + } } -$onheader = array('manage' => $managetab, - 'main' => $maintab, - 'alert' => $alerttab, - 'inventory' => $inventorytab, - 'collection' => $collectiontab, - 'gis' => $gistab, - 'custom' => $custom_fields, - 'graphs' => $graphs, - 'policy' => $policyTab, - 'ux_console' => $ux_console_tab, - 'wux_console' => $wux_console_tab, - 'url_route_analyzer' => $url_route_analyzer_tab); +$onheader = [ + 'manage' => $managetab, + 'main' => $maintab, + 'alert' => $alerttab, + 'inventory' => $inventorytab, + 'collection' => $collectiontab, + 'gis' => $gistab, + 'custom' => $custom_fields, + 'graphs' => $graphs, + 'policy' => $policyTab, + 'ux_console' => $ux_console_tab, + 'wux_console' => $wux_console_tab, + 'url_route_analyzer' => $url_route_analyzer_tab, +]; -//Added after it exists +// Added after it exists // If the agent has incidents associated if ($total_incidents) { - $onheader['incident'] = $incidenttab; + $onheader['incident'] = $incidenttab; } + if ($agent['url_address'] != '') { - $onheader['url_address'] = $urladdresstab; + $onheader['url_address'] = $urladdresstab; } + // If the log viewer tab exists if (isset($log_viewer_tab) && !empty($log_viewer_tab)) { - $onheader['log_viewer'] = $log_viewer_tab; + $onheader['log_viewer'] = $log_viewer_tab; } + // If the ehorus id exists if (isset($ehorus_tab) && !empty($ehorus_tab)) { - $onheader['ehorus'] = $ehorus_tab; + $onheader['ehorus'] = $ehorus_tab; } -//Tabs for extensions +// Tabs for extensions foreach ($config['extensions'] as $extension) { - if (isset($extension['extension_ope_tab']) && !isset($extension['extension_god_tab'])) { - if (check_acl_one_of_groups($config['id_user'], $all_groups, $extension['extension_ope_tab']['acl'])) { - //VMware extension is only available for VMware OS - if ($extension['extension_ope_tab']['id'] === "vmware_manager") { - //Check if OS is vmware - $id_remote_field = db_get_value ("id_field", - "tagent_custom_fields", "name", "vmware_type"); - - $vmware_type = db_get_value_filter("description", - "tagent_custom_data", - array("id_field" => $id_remote_field, "id_agent" => $agent["id_agente"])); - - if ($vmware_type != "vm") { - continue; - } - } - - //RHEV extension is only available for RHEV Virtual Machines - if ($extension['extension_ope_tab']['id'] === "rhev_manager") { - //Get id for remote field "rhev_type" - $id_remote_field = db_get_value("id_field", "tagent_custom_fields", "name", "rhev_type"); - //Get rhev type for this agent - $rhev_type = db_get_value_filter ("description", "tagent_custom_data", array ("id_field" => $id_remote_field, "id_agent" => $agent['id_agente'])); - //Check if rhev type is a vm - if ($rhev_type != "vm") { - continue; - } - } - - $image = $extension['extension_ope_tab']['icon']; - $name = $extension['extension_ope_tab']['name']; - $id = $extension['extension_ope_tab']['id']; - - $id_extension = get_parameter('id_extension', ''); - - if ($id_extension == $id) { - $active = true; - } - else { - $active = false; - } - - $url = 'index.php?sec=estado&sec2=operation/agentes/ver_agente&tab=extension&id_agente='.$id_agente . '&id_extension=' . $id; - - $extension_tab = array('text' => '' . html_print_image ($image, true, array ( "title" => $name)) . '', 'active' => $active); - - $onheader = $onheader + array($id => $extension_tab); - } - } + if (isset($extension['extension_ope_tab']) && !isset($extension['extension_god_tab'])) { + if (check_acl_one_of_groups($config['id_user'], $all_groups, $extension['extension_ope_tab']['acl'])) { + // VMware extension is only available for VMware OS + if ($extension['extension_ope_tab']['id'] === 'vmware_manager') { + // Check if OS is vmware + $id_remote_field = db_get_value( + 'id_field', + 'tagent_custom_fields', + 'name', + 'vmware_type' + ); + + $vmware_type = db_get_value_filter( + 'description', + 'tagent_custom_data', + [ + 'id_field' => $id_remote_field, + 'id_agent' => $agent['id_agente'], + ] + ); + + if ($vmware_type != 'vm') { + continue; + } + } + + // RHEV extension is only available for RHEV Virtual Machines + if ($extension['extension_ope_tab']['id'] === 'rhev_manager') { + // Get id for remote field "rhev_type" + $id_remote_field = db_get_value('id_field', 'tagent_custom_fields', 'name', 'rhev_type'); + // Get rhev type for this agent + $rhev_type = db_get_value_filter('description', 'tagent_custom_data', ['id_field' => $id_remote_field, 'id_agent' => $agent['id_agente']]); + // Check if rhev type is a vm + if ($rhev_type != 'vm') { + continue; + } + } + + $image = $extension['extension_ope_tab']['icon']; + $name = $extension['extension_ope_tab']['name']; + $id = $extension['extension_ope_tab']['id']; + + $id_extension = get_parameter('id_extension', ''); + + if ($id_extension == $id) { + $active = true; + } else { + $active = false; + } + + $url = 'index.php?sec=estado&sec2=operation/agentes/ver_agente&tab=extension&id_agente='.$id_agente.'&id_extension='.$id; + + $extension_tab = [ + 'text' => ''.html_print_image($image, true, [ 'title' => $name]).'', + 'active' => $active, + ]; + + $onheader = ($onheader + [$id => $extension_tab]); + } + } } -if($tab == "wux_console_tab"){ - $help_header = "wux_console"; -} -else{ - $help_header = ""; +if ($tab == 'wux_console_tab') { + $help_header = 'wux_console'; +} else { + $help_header = ''; } -ui_print_page_header(agents_get_alias($id_agente), $icon, false, - $help_header, false, $onheader, false, '', $config['item_title_size_text']); +ui_print_page_header( + agents_get_alias($id_agente), + $icon, + false, + $help_header, + false, + $onheader, + false, + '', + $config['item_title_size_text'] +); switch ($tab) { - case "custom_fields": - require ("custom_fields.php"); - break; - case "gis": - require ("gis_view.php"); - break; - case "manage": - require ("estado_generalagente.php"); - break; - case "main": - require ("estado_generalagente.php"); - echo ""; - require ("estado_monitores.php"); - echo ""; - require ("alerts_status.php"); - echo ""; - require ("status_events.php"); - break; - case "data_view": - require ("datos_agente.php"); - break; - case "alert": - require ("alerts_status.php"); - break; - case "inventory": - enterprise_include ("operation/agentes/agent_inventory.php"); - break; - case "collection": - enterprise_include ("operation/agentes/collection_view.php"); - break; - case "policy": - enterprise_include ("operation/agentes/policy_view.php"); - break; - case "ux_console_tab": - enterprise_include ("operation/agentes/ux_console_view.php"); - break; - case "wux_console_tab": - enterprise_include ("operation/agentes/wux_console_view.php"); - break; - case "url_route_analyzer_tab": - enterprise_include ("operation/agentes/url_route_analyzer.php"); - break; - case "graphs"; - require("operation/agentes/graphs.php"); - break; - case "incident": - require("godmode/agentes/agent_incidents.php"); - break; - case "url_address": - require("operation/agentes/url_address.php"); - break; - case "log_viewer": - $embebed_into_agent_view = true; - enterprise_include ("operation/log/log_viewer.php"); - break; - case "ehorus": - require("operation/agentes/ehorus.php"); - break; - case "extension": - $found = false; - foreach($config['extensions'] as $extension) { - if (isset($extension['extension_ope_tab'])) { - $id = $extension['extension_ope_tab']['id']; - $function = $extension['extension_ope_tab']['function']; - - $id_extension = get_parameter('id_extension', ''); - - if ($id_extension == $id) { - call_user_func_array($function, array()); - $found = true; - } - } - } - if (!$found) { - ui_print_error_message ("Invalid tab specified in ".__FILE__.":".__LINE__); - } - break; + case 'custom_fields': + include 'custom_fields.php'; + break; + + case 'gis': + include 'gis_view.php'; + break; + + case 'manage': + include 'estado_generalagente.php'; + break; + + case 'main': + include 'estado_generalagente.php'; + echo ""; + include 'estado_monitores.php'; + echo ""; + include 'alerts_status.php'; + echo ""; + include 'status_events.php'; + break; + + case 'data_view': + include 'datos_agente.php'; + break; + + case 'alert': + include 'alerts_status.php'; + break; + + case 'inventory': + enterprise_include('operation/agentes/agent_inventory.php'); + break; + + case 'collection': + enterprise_include('operation/agentes/collection_view.php'); + break; + + case 'policy': + enterprise_include('operation/agentes/policy_view.php'); + break; + + case 'ux_console_tab': + enterprise_include('operation/agentes/ux_console_view.php'); + break; + + case 'wux_console_tab': + enterprise_include('operation/agentes/wux_console_view.php'); + break; + + case 'url_route_analyzer_tab': + enterprise_include('operation/agentes/url_route_analyzer.php'); + break; + + case 'graphs'; + include 'operation/agentes/graphs.php'; + break; + + case 'incident': + include 'godmode/agentes/agent_incidents.php'; + break; + + case 'url_address': + include 'operation/agentes/url_address.php'; + break; + + case 'log_viewer': + $embebed_into_agent_view = true; + enterprise_include('operation/log/log_viewer.php'); + break; + + case 'ehorus': + include 'operation/agentes/ehorus.php'; + break; + + case 'extension': + $found = false; + foreach ($config['extensions'] as $extension) { + if (isset($extension['extension_ope_tab'])) { + $id = $extension['extension_ope_tab']['id']; + $function = $extension['extension_ope_tab']['function']; + + $id_extension = get_parameter('id_extension', ''); + + if ($id_extension == $id) { + call_user_func_array($function, []); + $found = true; + } + } + } + + if (!$found) { + ui_print_error_message('Invalid tab specified in '.__FILE__.':'.__LINE__); + } + break; } -?> diff --git a/pandora_console/operation/events/event_statistics.php b/pandora_console/operation/events/event_statistics.php index 0a43a98884..437ec0f47c 100644 --- a/pandora_console/operation/events/event_statistics.php +++ b/pandora_console/operation/events/event_statistics.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,75 +11,80 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - - - - // Load global vars global $config; -require_once ($config["homedir"] . '/include/functions_graph.php'); +require_once $config['homedir'].'/include/functions_graph.php'; -check_login (); +check_login(); -if (! check_acl ($config['id_user'], 0, "ER") && ! check_acl ($config['id_user'], 0, "EW") && ! check_acl ($config['id_user'], 0, "EM")) { - db_pandora_audit("ACL Violation","Trying to access event viewer"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'ER') && ! check_acl($config['id_user'], 0, 'EW') && ! check_acl($config['id_user'], 0, 'EM')) { + db_pandora_audit('ACL Violation', 'Trying to access event viewer'); + include 'general/noaccess.php'; + return; } -//header -ui_print_page_header (__('Statistics'), "images/op_events.png",false, false); -echo ""; - echo ""; - echo ""; +// header +ui_print_page_header(__('Statistics'), 'images/op_events.png', false, false); +echo '
                "; - echo "

                " . __('Event graph') . "

                "; - echo "
                '; - echo ""; - echo ""; + echo ''; + echo "'; - echo ""; - echo ""; + echo "'; + echo ''; - echo ""; - echo ""; + echo ''; + echo "'; - echo ""; - echo ""; + echo "'; + echo ''; - echo ""; - echo ""; + echo ''; + echo "'; - $where = ''; - if (!users_is_admin()) { - $where = 'AND event_type NOT IN (\'recon_host_detected\', \'system\',\'error\', \'new_agent\', \'configuration_change\')'; - } - echo ""; - echo ""; + echo "'; + echo ''; - echo ""; - echo ""; + $where = ''; +if (!users_is_admin()) { + $where = 'AND event_type NOT IN (\'recon_host_detected\', \'system\',\'error\', \'new_agent\', \'configuration_change\')'; +} -echo "
                "; - echo "

                " . __('Event graph by user') . "

                "; - echo "
                "; + echo '

                '.__('Event graph').'

                '; + echo '
                "; - echo grafico_eventos_total(); - echo ""; + echo '

                '.__('Event graph by user').'

                '; + echo '
                "; - echo grafico_eventos_usuario(320, 296); - echo "
                "; + echo grafico_eventos_total(); + echo '
                "; - echo "

                " . __('Event graph by agent') . "

                "; - echo "
                "; + echo grafico_eventos_usuario(320, 296); + echo '
                "; - echo "

                " . __('Amount events validated') . "

                "; - echo "
                "; + echo '

                '.__('Event graph by agent').'

                '; + echo '
                "; - echo grafico_eventos_grupo(300, 200, $where); - echo ""; + echo '

                '.__('Amount events validated').'

                '; + echo '
                "; - $extra_filter = array(); - if (!users_is_admin()) { - $extra_filter['event_type'] = array('unknown','alert_fired','alert_recovered', - 'alert_ceased','alert_manual_validation', 'critical', - 'warning','normal'); - } - echo graph_events_validated(320, 296, $extra_filter); - echo "
                "; -?> + echo ''; + echo ""; + echo grafico_eventos_grupo(300, 200, $where); + echo ''; + + echo ""; + $extra_filter = []; +if (!users_is_admin()) { + $extra_filter['event_type'] = [ + 'unknown', + 'alert_fired', + 'alert_recovered', + 'alert_ceased', + 'alert_manual_validation', + 'critical', + 'warning', + 'normal', + ]; +} + + echo graph_events_validated(320, 296, $extra_filter); + echo ''; + echo ''; + +echo ''; diff --git a/pandora_console/operation/events/events.build_query.php b/pandora_console/operation/events/events.build_query.php index c06d2ac6c9..85d0de9a7d 100755 --- a/pandora_console/operation/events/events.build_query.php +++ b/pandora_console/operation/events/events.build_query.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,346 +11,389 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. +if (check_acl($id_user, 0, 'ER')) { + $groups = users_get_groups($id_user, 'ER'); +} else if (check_acl($id_user, 0, 'EW')) { + $groups = users_get_groups($id_user, 'EW'); +} else if (check_acl($id_user, 0, 'EM')) { + $groups = users_get_groups($id_user, 'EM'); +} -if (check_acl ($id_user, 0, "ER")) - $groups = users_get_groups($id_user, 'ER'); -elseif (check_acl ($id_user, 0, "EW")) - $groups = users_get_groups($id_user, 'EW'); -elseif (check_acl ($id_user, 0, "EM")) - $groups = users_get_groups($id_user, 'EM'); - - -$propagate = db_get_value('propagate','tgrupo','id_grupo',$id_group); +$propagate = db_get_value('propagate', 'tgrupo', 'id_grupo', $id_group); if ($id_group > 0) { - $filter_resume['groups'] = $id_group; - if ($propagate) { - $childrens_ids = array($id_group); - - $childrens = groups_get_childrens($id_group, null, true); - - if (!empty($childrens)) { - foreach ($childrens as $child) { - $childrens_ids[] = (int)$child['id_grupo']; - } - } - } - else { - $childrens_ids = array(); - } -} -else { - $childrens_ids = array_keys($groups); -} -//Group selection -if ($id_group > 0 && in_array ($id_group, array_keys ($groups))) { - if ($propagate) { - $childrens_str = implode(',', $childrens_ids); - $sql_post = " AND (id_grupo IN ($childrens_str) OR id_group IN ($childrens_str))"; - } - else { - //If a group is selected and it's in the groups allowed - $sql_post = " AND (id_grupo = $id_group OR id_group = $id_group)"; - } -} -else { - $sql_post = sprintf(" AND (id_grupo IN (%s) OR id_group IN (%s)) ", - implode (",", array_keys ($groups)), implode (",", array_keys ($groups))); + $filter_resume['groups'] = $id_group; + if ($propagate) { + $childrens_ids = [$id_group]; + + $childrens = groups_get_childrens($id_group, null, true); + + if (!empty($childrens)) { + foreach ($childrens as $child) { + $childrens_ids[] = (int) $child['id_grupo']; + } + } + } else { + $childrens_ids = []; + } +} else { + $childrens_ids = array_keys($groups); } -// Skip system messages if user is not PM -if (!check_acl ($id_user, 0, "PM")) { - $sql_post .= " AND id_grupo != 0"; +if (!isset($date_from)) { + $date_from = ''; +} + +if (!isset($date_to)) { + $date_to = ''; +} + +if (($date_from === '') && ($date_to === '')) { + if ($event_view_hr > 0) { + $filter_resume['hours_max'] = $event_view_hr; + $unixtime = (get_system_time() - ($event_view_hr * SECONDS_1HOUR)); + $sql_post .= ' AND (utimestamp > '.$unixtime.')'; + } +} else { + // Some of this values will have the user's timezone, + // so we need to reverse it to the system's timezone + // before using it into the db. + $fixed_offset = get_fixed_offset(); + + if (!empty($date_from)) { + if (empty($time_from)) { + $time_from = '00:00:00'; + } + + $utimestamp_from = (strtotime($date_from.' '.$time_from) - $fixed_offset); + $filter_resume['time_from'] = date(DATE_FORMAT.' '.TIME_FORMAT, $utimestamp_from); + $sql_post .= ' AND (utimestamp >= '.$utimestamp_from.')'; + } + + if (!empty($date_to)) { + if (empty($time_to)) { + $time_to = '23:59:59'; + } + + $utimestamp_to = (strtotime($date_to.' '.$time_to) - $fixed_offset); + $filter_resume['time_to'] = date(DATE_FORMAT.' '.TIME_FORMAT, $utimestamp_to); + $sql_post .= ' AND (utimestamp <= '.$utimestamp_to.')'; + } +} + +// Group selection. +if ($id_group > 0 && in_array($id_group, array_keys($groups))) { + if ($propagate) { + $childrens_str = implode(',', $childrens_ids); + $sql_post .= " AND (id_grupo IN ($childrens_str) OR id_group IN ($childrens_str))"; + } else { + // If a group is selected and it's in the groups allowed. + $sql_post .= " AND (id_grupo = $id_group OR id_group = $id_group)"; + } +} else { + if (!users_is_admin() && !users_can_manage_group_all('ER')) { + $sql_post .= sprintf( + ' AND (id_grupo IN (%s) OR id_group IN (%s)) ', + implode(',', array_keys($groups)), + implode(',', array_keys($groups)) + ); + } +} + +// Skip system messages if user is not PM. +if (!check_acl($id_user, 0, 'PM')) { + $sql_post .= ' AND id_grupo != 0'; } switch ($status) { - case 0: - case 1: - case 2: - $filter_resume['status'] = $status; - $sql_post .= " AND estado = " . $status; - break; - case 3: - $filter_resume['status'] = $status; - $sql_post .= " AND (estado = 0 OR estado = 2)"; - break; + case 0: + case 1: + case 2: + $filter_resume['status'] = $status; + $sql_post .= ' AND estado = '.$status; + break; + + case 3: + $filter_resume['status'] = $status; + $sql_post .= ' AND (estado = 0 OR estado = 2)'; + break; } $events_wi_cdata = db_get_all_rows_sql('SELECT id_evento,custom_data from tevento WHERE custom_data != ""'); $count_events = 0; $events_wi_cdata_id = 'OR id_evento IN ('; -if ($events_wi_cdata === false) $events_wi_cdata = array(); -foreach ($events_wi_cdata as $key => $value) { - $needle = base64_decode($value['custom_data']); - if (($needle != "") && ($search != "")) { - if(strpos(strtolower($needle),strtolower($search)) != false){ - $events_wi_cdata_id .= $value['id_evento']; - $count_events++; - } - } +if ($events_wi_cdata === false) { + $events_wi_cdata = []; +} - if ($value !== end($events_wi_cdata) && $count_events > 0) { - $events_wi_cdata_id .= ','; - $events_wi_cdata_id = str_replace(',,', ',', $events_wi_cdata_id); - } +foreach ($events_wi_cdata as $key => $value) { + $needle = base64_decode($value['custom_data']); + if (($needle != '') && ($search != '')) { + if (strpos(strtolower($needle), strtolower($search)) != false) { + $events_wi_cdata_id .= $value['id_evento']; + $count_events++; + } + } + + if ($value !== end($events_wi_cdata) && $count_events > 0) { + $events_wi_cdata_id .= ','; + $events_wi_cdata_id = str_replace(',,', ',', $events_wi_cdata_id); + } } $events_wi_cdata_id .= ')'; $events_wi_cdata_id = str_replace(',)', ')', $events_wi_cdata_id); -if($count_events == 0){ - $events_wi_cdata_id = ''; +if ($count_events == 0) { + $events_wi_cdata_id = ''; } -if ($search != "") { - $filter_resume['free_search'] = $search; - $sql_post .= " AND (evento LIKE '%". $search . "%' OR id_evento LIKE '%$search%' ".$events_wi_cdata_id.")"; +if ($search != '') { + $filter_resume['free_search'] = $search; + $sql_post .= " AND (evento LIKE '%".$search."%' OR id_evento LIKE '%$search%' ".$events_wi_cdata_id.')'; } -if ($event_type != "") { - $filter_resume['event_type'] = $event_type; - // If normal, warning, could be several (going_up_warning, going_down_warning... too complex - // for the user so for him is presented 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 ($event_type != '') { + $filter_resume['event_type'] = $event_type; + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex + // for the user so for him is presented 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) { - $filter_resume['severity'] = $severity; - 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; - } + $filter_resume['severity'] = $severity; + 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; + } } if ($id_extra != '') { - $sql_post .= " AND id_extra LIKE '%$id_extra%'"; + $sql_post .= " AND id_extra LIKE '%$id_extra%'"; } if ($user_comment != '') { - $sql_post .= " AND user_comment LIKE '%$user_comment%'"; + $sql_post .= " AND user_comment LIKE '%$user_comment%'"; } if ($source != '') { - $sql_post .= " AND source LIKE '%$source%'"; + $sql_post .= " AND source LIKE '%$source%'"; } -// In metaconsole mode the agent search is performed by name +// In metaconsole mode the agent search is performed by name. if ($meta) { - $text_agent = get_parameter("text_agent",""); - $id_agent = get_parameter('id_agent',0); - if($id_agent){ - $sql_post .= " AND agent_name IN (SELECT nombre FROM tmetaconsole_agent WHERE - id_tagente =".$id_agent." AND alias LIKE '".io_safe_input($text_agent)."')"; - $filter_resume['agent'] = $text_agent; - } -} -else { - switch ($id_agent) { - case 0: - break; - case -1: - // Agent doesnt exist. No results will returned - $sql_post .= " AND 1 = 0"; - break; - default: - $filter_resume['agent'] = $id_agent; - $sql_post .= " AND id_agente = " . $id_agent; - break; - } + $text_agent = get_parameter('text_agent', ''); + $id_agent = get_parameter('id_agent', 0); + if ($id_agent) { + $sql_post .= ' AND agent_name IN (SELECT nombre FROM tmetaconsole_agent WHERE + id_tagente ='.$id_agent." AND alias LIKE '".io_safe_input($text_agent)."')"; + $filter_resume['agent'] = $text_agent; + } +} else { + switch ($id_agent) { + case 0: + break; + + case -1: + // Agent doesnt exist. No results will returned. + $sql_post .= ' AND 1 = 0'; + break; + + default: + $filter_resume['agent'] = $id_agent; + $sql_post .= ' AND id_agente = '.$id_agent; + break; + } } -if ($meta) { - //There is another filter. -} -else { - if (!empty($text_module)) { - $filter_resume['module'] = $text_module; - $sql_post .= " AND id_agentmodule IN ( +if (!$meta) { + if (!empty($text_module)) { + $filter_resume['module'] = $text_module; + $sql_post .= " AND id_agentmodule IN ( SELECT id_agente_modulo FROM tagente_modulo WHERE nombre = '$text_module' )"; - } + } } -if ($id_user_ack != "0") { - $filter_resume['user_ack'] = $id_user_ack; - $sql_post .= " AND id_usuario = '" . $id_user_ack . "'"; +if ($id_user_ack != '0') { + $filter_resume['user_ack'] = $id_user_ack; + $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) { - $filter_resume['hours_max'] = $event_view_hr; - $unixtime = get_system_time () - ($event_view_hr * SECONDS_1HOUR); - $sql_post .= " AND (utimestamp > " . $unixtime . ")"; - } -} -else { - // Some of this values will have the user's timezone, - // so we need to reverse it to the system's timezone - // before using it into the db - $fixed_offset = get_fixed_offset(); - - if (!empty($date_from)) { - if (empty($time_from)) $time_from = "00:00:00"; - - $utimestamp_from = strtotime($date_from . " " . $time_from) - $fixed_offset; - $filter_resume['time_from'] = date(DATE_FORMAT . " " . TIME_FORMAT, $utimestamp_from); - $sql_post .= " AND (utimestamp >= " . $utimestamp_from . ")"; - } - if (!empty($date_to)) { - if (empty($time_to)) $time_to = "23:59:59"; - - $utimestamp_to = strtotime($date_to . " " . $time_to) - $fixed_offset; - $filter_resume['time_to'] = date(DATE_FORMAT . " " . TIME_FORMAT, $utimestamp_to); - $sql_post .= " AND (utimestamp <= " . $utimestamp_to . ")"; - } -} - -//Search by tag +// Search by tag. if (!empty($tag_with)) { - - if (!users_is_admin()) { - $user_tags = array_flip(tags_get_tags_for_module_search()); - if($user_tags != null){ - foreach ($tag_with as $id_tag) { - if (!array_search($id_tag,$user_tags)) { - return false; - } - } - } - } - - $sql_post .= ' AND ( '; - $first = true; - $filter_resume['tag_inc'] = $tag_with; - foreach ($tag_with as $id_tag) { - if ($first){ - $sql_post .= " ( "; - $first = false; - } else { - $sql_post .= " AND ( "; - } - $sql_post .= "tags LIKE '" . tags_get_name($id_tag) . "'"; - $sql_post .= " OR "; - $sql_post .= "tags LIKE '" . tags_get_name($id_tag) . ",%'"; - $sql_post .= " OR "; - $sql_post .= "tags LIKE '%," . tags_get_name($id_tag) . "'"; - $sql_post .= " OR "; - $sql_post .= "tags LIKE '%," . tags_get_name($id_tag) . ",%'"; - $sql_post .= ' ) '; - } - $sql_post .= ' ) '; + if (!users_is_admin()) { + $user_tags = array_flip(tags_get_tags_for_module_search()); + if ($user_tags != null) { + foreach ($tag_with as $id_tag) { + if (!array_search($id_tag, $user_tags)) { + return false; + } + } + } + } + + $sql_post .= ' AND ( '; + $first = true; + $filter_resume['tag_inc'] = $tag_with; + foreach ($tag_with as $id_tag) { + if ($first) { + $sql_post .= ' ( '; + $first = false; + } else { + $sql_post .= ' AND ( '; + } + + $sql_post .= "tags LIKE '".tags_get_name($id_tag)."'"; + $sql_post .= ' OR '; + $sql_post .= "tags LIKE '".tags_get_name($id_tag).",%'"; + $sql_post .= ' OR '; + $sql_post .= "tags LIKE '%,".tags_get_name($id_tag)."'"; + $sql_post .= ' OR '; + $sql_post .= "tags LIKE '%,".tags_get_name($id_tag).",%'"; + $sql_post .= ' ) '; + } + + $sql_post .= ' ) '; } + if (!empty($tag_without)) { - $sql_post .= ' AND ( '; - $first = true; - $filter_resume['tag_no_inc'] = $tag_without; - foreach ($tag_without as $id_tag) { - if ($first) $first = false; - else $sql_post .= " AND "; - - $sql_post .= "tags NOT LIKE '%" . tags_get_name($id_tag) . "%'"; - } - $sql_post .= ' ) '; + $sql_post .= ' AND ( '; + $first = true; + $filter_resume['tag_no_inc'] = $tag_without; + foreach ($tag_without as $id_tag) { + if ($first) { + $first = false; + } else { + $sql_post .= ' AND '; + } + + $sql_post .= "tags NOT LIKE '%".tags_get_name($id_tag)."%'"; + } + + $sql_post .= ' ) '; } -// Filter/Only alerts +// Filter/Only alerts. if (isset($filter_only_alert)) { - if ($filter_only_alert == 0) { - $filter_resume['alerts'] = $filter_only_alert; - $sql_post .= " AND event_type NOT LIKE '%alert%'"; - } - else if ($filter_only_alert == 1) { - $filter_resume['alerts'] = $filter_only_alert; - $sql_post .= " AND event_type LIKE '%alert%'"; - } + if ($filter_only_alert == 0) { + $filter_resume['alerts'] = $filter_only_alert; + $sql_post .= " AND event_type NOT LIKE '%alert%'"; + } else if ($filter_only_alert == 1) { + $filter_resume['alerts'] = $filter_only_alert; + $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. +if ($id_group > 0 && in_array($id_group, array_keys($groups))) { + $group_array = (array) $id_group; +} else { + $group_array = array_keys($groups); } -if (check_acl ($id_user, 0, "ER")) - $tags_acls_condition = tags_get_acl_tags($id_user, $group_array, 'ER', - 'event_condition', 'AND', '', $meta, array(), true); //FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)" -elseif (check_acl ($id_user, 0, "EW")) - $tags_acls_condition = tags_get_acl_tags($id_user, $group_array, 'EW', - 'event_condition', 'AND', '', $meta, array(), true); //FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)" -elseif (check_acl ($id_user, 0, "EM")) - $tags_acls_condition = tags_get_acl_tags($id_user, $group_array, 'EM', - 'event_condition', 'AND', '', $meta, array(), 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; +if (check_acl($id_user, 0, 'ER')) { + $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)". +} else if (check_acl($id_user, 0, 'EW')) { + $tags_acls_condition = tags_get_acl_tags( + $id_user, + $group_array, + 'EW', + 'event_condition', + 'AND', + '', + $meta, + [], + true + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". +} else if (check_acl($id_user, 0, 'EM')) { + $tags_acls_condition = tags_get_acl_tags( + $id_user, + $group_array, + 'EM', + 'event_condition', + 'AND', + '', + $meta, + [], + true + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". } -// Metaconsole fitlers +if (($tags_acls_condition != ERR_WRONG_PARAMETERS) && ($tags_acls_condition != ERR_ACL) && ($tags_acls_condition != -110000)) { + $sql_post .= $tags_acls_condition; +} + +// Metaconsole fitlers. if ($meta) { - - if ($server_id) { - $filter_resume['server'] = $server_id; - $sql_post .= " AND server_id = " . $server_id; - } else { - $enabled_nodes = db_get_all_rows_sql(' + if ($server_id) { + $filter_resume['server'] = $server_id; + $sql_post .= ' AND server_id = '.$server_id; + } 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 = array(); - } else { - $enabled_nodes_id = array(0); - } - foreach ($enabled_nodes as $en) { - $enabled_nodes_id[] = $en['id']; - } - $sql_post .= ' AND server_id IN (' . - implode(',',$enabled_nodes_id) . ')'; - } - } + 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).')'; + } + } } -?> diff --git a/pandora_console/operation/events/events.build_table.php b/pandora_console/operation/events/events.build_table.php index 92b7eecad8..8ed0f10eed 100644 --- a/pandora_console/operation/events/events.build_table.php +++ b/pandora_console/operation/events/events.build_table.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,917 +11,1080 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - global $config; -require_once ($config["homedir"] . "/include/functions_ui.php"); +require_once $config['homedir'].'/include/functions_ui.php'; -$sort_field = get_parameter("sort_field", "timestamp"); -$sort = get_parameter("sort", "down"); +$sort_field = get_parameter('sort_field', 'timestamp'); +$sort = get_parameter('sort', 'down'); + +$response_id = get_parameter('response_id', ''); $table = new stdClass(); -if(!isset($table->width)) { - $table->width = '100%'; +if (!isset($table->width)) { + $table->width = '100%'; } -$table->id = "eventtable"; + +$table->id = 'eventtable'; $table->cellpadding = 4; $table->cellspacing = 4; -if(!isset($table->class)) { - $table->class = "databox data"; +if (!isset($table->class)) { + $table->class = 'databox data'; } -$table->head = array (); -$table->data = array (); -$params = array ( - // Pandora sections - "sec" => "eventos", - "sec2" => "operation/events/events", +$table->head = []; +$table->data = []; - // Events query params - "search" => io_safe_input($search), - "event_type" => $event_type, - "severity" => $severity, - "status" => $status, - "id_group" => $id_group, - "recursion" => $recursion, - "refr" => (int)get_parameter("refr", 0), - "id_agent" => $id_agent, - "id_agent_module" => $id_agent_module, - "pagination" => $pagination, - "group_rep" => $group_rep, - "event_view_hr" => $event_view_hr, - "id_user_ack" => $id_user_ack, - "tag_with" => $tag_with_base64, - "tag_without" => $tag_without_base64, - "filter_only_alert" => $filter_only_alert, - "offset" => $offset, - "toogle_filter" => "no", - "filter_id" => $filter_id, - "id_name" => $id_name, - "history" => (int)$history, - "section" => $section, - "open_filter" => $open_filter, - "date_from" => $date_from, - "date_to" => $date_to, - "pure" => $config["pure"], +$params = [ + // Pandora sections + 'sec' => 'eventos', + 'sec2' => 'operation/events/events', - // Display params - "offset" => $offset, - "disabled" => $disabled, - "sort" => $sort, - "sort_field" => $sort_field -); + // Events query params + 'search' => io_safe_input($search), + 'event_type' => $event_type, + 'severity' => $severity, + 'status' => $status, + 'id_group' => $id_group, + 'recursion' => $recursion, + 'refr' => (int) get_parameter('refr', 0), + 'id_agent' => $id_agent, + 'id_agent_module' => $id_agent_module, + 'pagination' => $pagination, + 'group_rep' => $group_rep, + 'event_view_hr' => $event_view_hr, + 'id_user_ack' => $id_user_ack, + 'tag_with' => $tag_with_base64, + 'tag_without' => $tag_without_base64, + 'filter_only_alert' => $filter_only_alert, + 'offset' => $offset, + 'toogle_filter' => 'no', + 'filter_id' => $filter_id, + 'id_name' => $id_name, + 'history' => (int) $history, + 'section' => $section, + 'open_filter' => $open_filter, + 'date_from' => $date_from, + 'date_to' => $date_to, + 'pure' => $config['pure'], + + // Display params + 'offset' => $offset, + 'disabled' => $disabled, + 'sort' => $sort, + 'sort_field' => $sort_field, +]; if ($group_rep == 2) { - $table->class = "databox filters data"; - $table->head[1] = __('Agent'); - $table->head[5] = __('More detail'); + $table->class = 'databox filters data'; + $table->head[1] = __('Agent'); + $table->head[5] = __('More detail'); - //$url = html_print_sort_arrows( - // array_merge($params, array('sort_field' => 'status')), - // 'sort' - //); + // $url = html_print_sort_arrows( + // array_merge($params, array('sort_field' => 'status')), + // 'sort' + // ); + $params_sort_field_status = array_merge($params, ['sort_field' => 'status']); + $url = 'index.php?'.http_build_query($params_sort_field_status, '', '&'); - $params_sort_field_status = array_merge($params, array('sort_field' => 'status')); - $url = "index.php?" . http_build_query($params_sort_field_status, '', '&'); + foreach ($result as $key => $res) { + if ($res['event_type'] == 'alert_fired') { + $table->rowstyle[$key] = 'background: #FFA631;'; + } else if ($res['event_type'] == 'going_up_critical' || $res['event_type'] == 'going_down_critical') { + $table->rowstyle[$key] = 'background: #FC4444;'; + } else if ($res['event_type'] == 'going_up_warning' || $res['event_type'] == 'going_down_warning') { + $table->rowstyle[$key] = 'background: #FAD403;'; + } else if ($res['event_type'] == 'going_up_normal' || $res['event_type'] == 'going_down_normal') { + $table->rowstyle[$key] = 'background: #80BA27;'; + } else if ($res['event_type'] == 'going_unknown') { + $table->rowstyle[$key] = 'background: #B2B2B2;'; + } - foreach ($result as $key => $res) { - - if ($res['event_type'] == 'alert_fired') { - $table->rowstyle[$key] = 'background: #FFA631;'; - } - elseif ($res['event_type'] == 'going_up_critical' || $res['event_type'] == 'going_down_critical'){ - $table->rowstyle[$key] = 'background: #FC4444;'; - } - elseif ($res['event_type'] == 'going_up_warning' || $res['event_type'] == 'going_down_warning'){ - $table->rowstyle[$key] = 'background: #FAD403;'; - } - elseif ($res['event_type'] == 'going_up_normal' || $res['event_type'] == 'going_down_normal'){ - $table->rowstyle[$key] = 'background: #80BA27;'; - } - elseif ($res['event_type'] == 'going_unknown'){ - $table->rowstyle[$key] = 'background: #B2B2B2;'; - } - - - if ($meta) - $table->data[$key][1] = __('The Agent: ') . '"' . - $res['id_agent'] . '", ' . __(' has ') . - $res['total'] . __(' events.'); - else - $table->data[$key][1] = __('The Agent: ') . '"' . - agents_get_alias($res['id_agent']) . '", ' . __(' has ') . - $res['total'] . __(' events.'); - - $uniq = uniqid(); - if ($meta) { - $table->data[$key][2] = 'data[$key][1] = __('The Agent: ').'"'.$res['id_agent'].'", '.__(' has ').$res['total'].__(' events.'); + } else { + $table->data[$key][1] = __('The Agent: ').'"'.agents_get_alias($res['id_agent']).'", '.__(' has ').$res['total'].__(' events.'); + } + + $uniq = uniqid(); + if ($meta) { + $table->data[$key][2] = 'id.'-'.$uniq.'-0","'.$res['id_agent'].'",'.$res['id_server'].');\' />'; - } - else { - $table->data[$key][2] = 'data[$key][2] = 'id.'-'.$uniq.'-0",'.$res['id_agent'].',false);\'/>'; - } - $table->cellstyle[$uniq][0] = "display:none;"; - $table->data[$uniq][0] = false; - } - - if ($result) { - if ($allow_pagination) { - ui_pagination ($total_events, $url, $offset, $pagination); - } - - html_print_table ($table); - - if ($allow_pagination) { - ui_pagination ($total_events, $url, $offset, $pagination); - } - } - else { - echo '
                ' . __('No events') . '
                '; - } -} -else { - //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->head[$i] = __('ID') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'event_id')), - 'sort' - ); + $table->cellstyle[$uniq][0] = 'display:none;'; + $table->data[$uniq][0] = false; + } - $table->align[$i] = 'left'; + if ($result) { + if ($allow_pagination) { + ui_pagination($total_events, $url, $offset, $pagination); + } - $i++; - foreach ($show_fields as $k_s => $fields) { - if ($fields == 'server_name') { - $table->head[$i] = __('Server'); - $table->align[$i] = 'left'; - $i++; - } - if ($fields == 'id_evento') { - $table->head[$i] = __('Event ID') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'event_id')), - 'sort' - ); - $table->align[$i] = 'left'; + html_print_table($table); - $i++; - } - if ($fields == 'evento') { - $table->head[$i] = __('Event Name') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'event_name')), - 'sort' - ); - $table->align[$i] = 'left'; - $table->style[$i] = 'min-width: 200px; max-width: 350px; word-break: break-all;'; - $i++; - } - if ($fields == 'id_agente') { - $table->head[$i] = __('Agent name') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'agent_id')), - 'sort' - ); - $table->align[$i] = 'left'; - $table->style[$i] = 'max-width: 350px; word-break: break-all;'; - $i++; - } - if ($fields == 'timestamp') { - $table->head[$i] = __('Timestamp') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'timestamp')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'id_usuario') { - $table->head[$i] = __('User') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'user_id')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'owner_user') { - $table->head[$i] = __('Owner') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'owner')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'id_grupo') { - $table->head[$i] = __('Group') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'group_id')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'event_type') { - $table->head[$i] = __('Event Type') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'event_type')), - 'sort' - ); - $table->align[$i] = 'left'; - - $table->style[$i] = 'min-width: 85px;'; - $i++; - } - if ($fields == 'id_agentmodule') { - $table->head[$i] = __('Module Name') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'module_name')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'id_alert_am') { - $table->head[$i] = __('Alert') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'alert_id')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } + if ($allow_pagination) { + ui_pagination($total_events, $url, $offset, $pagination); + } + } else { + echo '
                '.__('No events').'
                '; + } +} else { + // 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']); + } - if ($fields == 'criticity') { - $table->head[$i] = __('Severity') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'criticity')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'user_comment') { - $table->head[$i] = __('Comment') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'comment')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'tags') { - $table->head[$i] = __('Tags') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'tags')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'source') { - $table->head[$i] = __('Source') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'source')), - 'sort' - );$table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'id_extra') { - $table->head[$i] = __('Extra ID') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'extra_id')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'ack_utimestamp') { - $table->head[$i] = __('ACK Timestamp') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'ack_utimestamp')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'instructions') { - $table->head[$i] = __('Instructions'); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'data') { - $table->head[$i] = __('Data') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'data')), - 'sort' - ); - $table->align[$i] = 'left'; - - $i++; - } - if ($fields == 'module_status') { - $table->head[$i] = __('Module Status') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'module_status')), - 'sort' - );$table->align[$i] = 'left'; - - $i++; - } - } + // headers + $i = 0; + $table->head[$i] = __('ID').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'event_id']), + 'sort' + ); - if (in_array('estado', $show_fields)) { - $table->head[$i] = ''.__('Status') . html_print_sort_arrows( - array_merge($params, array('sort_field' => 'status')), - 'sort' - ).''; - $table->align[$i] = 'left'; - $table->style[$i] = 'white-space: nowrap !important; width: 1px !important;'; - $i++; - } + $table->align[$i] = 'left'; + + $i++; + foreach ($show_fields as $k_s => $fields) { + if ($fields == 'server_name') { + $table->head[$i] = __('Server'); + $table->align[$i] = 'left'; + $i++; + } + + if ($fields == 'id_evento') { + $table->head[$i] = __('Event ID').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'event_id']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'evento') { + $table->head[$i] = __('Event Name').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'event_name']), + 'sort' + ); + $table->align[$i] = 'left'; + $table->style[$i] = 'min-width: 200px; max-width: 350px; word-break: break-all;'; + $i++; + } + + if ($fields == 'id_agente') { + $table->head[$i] = __('Agent name').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'agent_id']), + 'sort' + ); + $table->align[$i] = 'left'; + $table->style[$i] = 'max-width: 350px; word-break: break-all;'; + $i++; + } + + if ($fields == 'timestamp') { + $table->head[$i] = __('Timestamp').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'timestamp']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'id_usuario') { + $table->head[$i] = __('User').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'user_id']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'owner_user') { + $table->head[$i] = __('Owner').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'owner']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'id_grupo') { + $table->head[$i] = __('Group').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'group_id']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'event_type') { + $table->head[$i] = __('Event Type').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'event_type']), + 'sort' + ); + $table->align[$i] = 'left'; + + $table->style[$i] = 'min-width: 85px;'; + $i++; + } + + if ($fields == 'id_agentmodule') { + $table->head[$i] = __('Module Name').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'module_name']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'id_alert_am') { + $table->head[$i] = __('Alert').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'alert_id']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'criticity') { + $table->head[$i] = __('Severity').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'criticity']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'user_comment') { + $table->head[$i] = __('Comment').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'comment']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'tags') { + $table->head[$i] = __('Tags').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'tags']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'source') { + $table->head[$i] = __('Source').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'source']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'id_extra') { + $table->head[$i] = __('Extra ID').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'extra_id']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'ack_utimestamp') { + $table->head[$i] = __('ACK Timestamp').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'ack_utimestamp']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'instructions') { + $table->head[$i] = __('Instructions'); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'data') { + $table->head[$i] = __('Data').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'data']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + + if ($fields == 'module_status') { + $table->head[$i] = __('Module Status').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'module_status']), + 'sort' + ); + $table->align[$i] = 'left'; + + $i++; + } + } + + if (in_array('estado', $show_fields)) { + $table->head[$i] = ''.__('Status').html_print_sort_arrows( + array_merge($params, ['sort_field' => 'status']), + 'sort' + ).''; + $table->align[$i] = 'left'; + $table->style[$i] = 'white-space: nowrap !important; width: 1px !important;'; + $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'; - } - else { - $table->head[$i] = ''; - } - } + if ($i != 0 && $allow_action) { + $table->head[$i] = __('Action'); + $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(); - } + $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'; + } else { + $table->head[$i] = ''; + } + } - $show_delete_button = false; - $show_validate_button = false; + 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(); + } - $idx = 0; - - if($meta){ - $alias_array = array(); - } - //Arrange data. We already did ACL's in the query - foreach ($result as $event) { - $data = array (); - - 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; - } - - $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++; - - 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; - } - foreach ($show_fields as $k_s => $fields) { - if ($fields == 'server_name') { - 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 ($fields == 'id_evento') { - $data[$i] = $event["id_evento"]; - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - - if ($fields == 'evento') { - // Event description - $data[$i] = ''; - if($allow_action) { - $data[$i] .= ''; - } - $data[$i] .= '' . ui_print_truncate_text (strip_tags(io_safe_output($event["evento"])), 160) . ''; - if($allow_action) { - $data[$i] .= ''; - } - $data[$i] .= ''; - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - - if ($fields == 'id_agente') { - $data[$i] = ''; - - if ($event["id_agente"] > 0) { - // Agent name - if ($meta) { - if(!empty($event["agent_name"])){ - if(!array_key_exists($event["agent_name"],$alias_array)){ - $alias_array [$event["agent_name"]] = db_get_value("alias","tmetaconsole_agent","nombre",$event["agent_name"]); - } - } - $agent_link = ''; - if (can_user_access_node ()) { - $data[$i] = '' . $agent_link . $alias_array [$event["agent_name"]] . ''; - } - else { - $data[$i] = $alias_array [$event["agent_name"]] ; - } - } - else { - $agent = db_get_row ("tagente","id_agente",$event["id_agente"]); - $data[$i] .= ''; - $data[$i] .= '' . $agent['alias'] . ''; - } - } - else { - $data[$i] .= ''; - } - $data[$i] .= ''; - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - - if ($fields == 'timestamp') { - //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 ($fields == 'id_usuario') { - $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 ($fields == 'owner_user') { - $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 ($fields == 'id_grupo') { - 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 ($fields == 'event_type') { - $data[$i] = events_print_type_description($event["event_type"], true); - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - - if ($fields == 'id_agentmodule') { - 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 ($fields == 'id_alert_am') { - if($meta) { - $data[$i] = $event["alert_template_name"]; - } - else { - if ($event["id_alert_am"] != 0) { - $sql = 'SELECT name + $show_delete_button = false; + $show_validate_button = false; + + $idx = 0; + + if ($meta) { + $alias_array = []; + } + + // 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; + } + + $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++; + + 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; + } + + foreach ($show_fields as $k_s => $fields) { + if ($fields == 'server_name') { + 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 ($fields == 'id_evento') { + $data[$i] = $event['id_evento']; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($fields == 'evento') { + // Event description + $data[$i] = ''; + if ($allow_action) { + $data[$i] .= ''; + } + + $data[$i] .= ''.ui_print_truncate_text(strip_tags(io_safe_output($event['evento'])), 160).''; + if ($allow_action) { + $data[$i] .= ''; + } + + $data[$i] .= ''; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($fields == 'id_agente') { + $data[$i] = ''; + + if ($event['id_agente'] > 0) { + // Agent name + if ($meta) { + if (!empty($event['agent_name'])) { + if (!array_key_exists($event['agent_name'], $alias_array)) { + $alias_array[$event['agent_name']] = db_get_value('alias', 'tmetaconsole_agent', 'nombre', $event['agent_name']); + } + } + + $agent_link = ''; + if (can_user_access_node()) { + $data[$i] = ''.$agent_link.$alias_array[$event['agent_name']].''; + } else { + $data[$i] = $alias_array[$event['agent_name']]; + } + } else { + $agent = db_get_row('tagente', 'id_agente', $event['id_agente']); + $data[$i] .= ''; + $data[$i] .= ''.$agent['alias'].''; + } + } else { + $data[$i] .= ''; + } + + $data[$i] .= ''; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($fields == 'timestamp') { + // 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 ($fields == 'id_usuario') { + $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 ($fields == 'owner_user') { + $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 ($fields == 'id_grupo') { + 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 ($fields == 'event_type') { + $data[$i] = events_print_type_description($event['event_type'], true); + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($fields == 'id_agentmodule') { + 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 ($fields == 'id_alert_am') { + 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 ($fields == 'criticity') { - $data[$i] = get_priority_name ($event["criticity"]); - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - - if ($fields == 'user_comment') { - $safe_event_user_comment = strip_tags(io_safe_output($event["user_comment"])); - $line_breaks = array("\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)) { + WHERE id = '.$event['id_alert_am'].');'; - if($myclass == 'datos_yellow'){ - $comments_help_tip = ui_print_help_tip_border($event_user_comment_str, true); - } - else{ - $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 ($fields == 'tags') { - $data[$i] = tags_get_tags_formatted($event['tags']); - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - - if ($fields == 'source') { - $data[$i] = $event["source"]; - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - - if ($fields == 'id_extra') { - $data[$i] = $event["id_extra"]; - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - - if ($fields == 'ack_utimestamp') { - 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 ($fields == 'instructions') { - switch($event['event_type']) { - case 'going_unknown': - if(!empty($event["unknown_instructions"])) { - $data[$i] = html_print_image('images/page_white_text.png', true, array('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, array('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, array('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, array('title' => str_replace("\n","
                ", io_safe_output($event["critical_instructions"])))); - } - elseif(!empty($event["warning_instructions"])) { - $data[$i] = html_print_image('images/page_white_text.png', true, array('title' => str_replace("\n","
                ", io_safe_output($event["warning_instructions"])))); - } - elseif(!empty($event["unknown_instructions"])) { - $data[$i] = html_print_image('images/page_white_text.png', true, array('title' => str_replace("\n","
                ", io_safe_output($event["unknown_instructions"])))); - } - break; - } - - if (!isset($data[$i])) { - $data[$i] = ''; - } - - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - if ($fields == 'data') { - $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 ($fields == 'module_status') { - $data[$i] = modules_get_modules_status ($event["module_status"]); - $table->cellclass[count($table->data)][$i] = $myclass; - $i++; - } - } + $templateName = db_get_sql($sql); + $data[$i] = ''.$templateName.''; + } else { + $data[$i] = ''; + } + } - if (in_array('estado', $show_fields)) { - $data[$i] = html_print_image ($img_st, true, - array ("class" => "image_status", - "title" => $title_st, - "id" => 'status_img_'.$event["id_evento"])); - $table->cellstyle[count($table->data)][$i] = 'background: #F3F3F3; white-space: nowrap; width: 1px;'; - $i++; - } - - if ($i != 0 && $allow_action) { - //Actions - $data[$i] = ''; - $data[$i] .= html_print_input_hidden('event_title_'.$event["id_evento"], "#".$event["id_evento"]." - " . strip_tags(io_safe_output($event["evento"])), true); - $data[$i] .= html_print_image ("images/eye.png", true, - array ("title" => __('Show more'))); - $data[$i] .= ''; + $table->cellclass[count($table->data)][$i] = $myclass; + $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, - array ("title" => __('Validate event'))); - $data[$i] .= ''; - // Display the go to in progress status button - if ($event["estado"] != 2) { - $data[$i] .= ''; - $data[$i] .= html_print_image ("images/hourglass.png", true, - array ("title" => __('Change to in progress status'))); - $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, - array ("title" => __('Delete event'), "id" => 'delete_cross_' . $event['id_evento'])); - $data[$i] .= ''; - } - else { - $data[$i] .= html_print_image ( - "images/cross.disabled.png", - true, - array ( - "title" => __('Is not allowed delete events in process'), - "id" => "delete-" . $event['id_evento'] - ) - ); - $data[$i] .= ' '; - } - } - } + if ($fields == 'criticity') { + $data[$i] = get_priority_name($event['criticity']); + $table->cellclass[count($table->data)][$i] = $myclass; + $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++; - } + if ($fields == 'user_comment') { + $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 = ''; - echo '
                '; - if (!empty ($table->data)) { - - if ($allow_pagination) { - $params_to_paginate = $params; - unset($params_to_paginate['offset']); - $url_paginate = "index.php?" . http_build_query($params_to_paginate, '', '&'); - ui_pagination ($total_events, $url_paginate, $offset, $pagination); - } - - if ($allow_action) { - echo '
                '; - echo ""; - } - - if (defined("METACONSOLE")) - echo '
                '; - else - echo '
                '; - html_print_table ($table); - echo '
                '; - - if ($allow_action) { - - echo '
                '; - if (!$readonly && $show_validate_button) { - html_print_button(__('In progress selected'), 'validate_button', false, 'validate_selected(2);', 'class="sub ok"'); - echo " "; - html_print_button(__('Validate selected'), 'validate_button', false, 'validate_selected(1);', 'class="sub ok"'); - // Fix: validated_selected JS function has to be included with the proper user ACLs - ?> - - - - '; - echo ''; - } - } - else { - echo '
                ' . __('No events') . '
                '; - } - echo '
                '; + 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)) { + if ($myclass == 'datos_yellow') { + $comments_help_tip = ui_print_help_tip_border($event_user_comment_str, true); + } else { + $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 ($fields == 'tags') { + $data[$i] = tags_get_tags_formatted($event['tags']); + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($fields == 'source') { + $data[$i] = $event['source']; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($fields == 'id_extra') { + $data[$i] = $event['id_extra']; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($fields == 'ack_utimestamp') { + 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 ($fields == 'instructions') { + 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; + } + + if (!isset($data[$i])) { + $data[$i] = ''; + } + + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($fields == 'data') { + $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 ($fields == 'module_status') { + $data[$i] = modules_get_modules_status($event['module_status']); + $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; white-space: nowrap; width: 1px;'; + $i++; + } + + if ($i != 0 && $allow_action) { + // Actions + $data[$i] = ''; + $data[$i] .= html_print_input_hidden('event_title_'.$event['id_evento'], '#'.$event['id_evento'].' - '.strip_tags(io_safe_output($event['evento'])), true); + $data[$i] .= html_print_image( + 'images/eye.png', + true, + ['title' => __('Show more')] + ); + $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] .= ''; + // Display the go to in progress status button + if ($event['estado'] != 2) { + $data[$i] .= ''; + $data[$i] .= html_print_image( + 'images/hourglass.png', + true, + ['title' => __('Change to in progress status')] + ); + $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'), + 'id' => 'delete-'.$event['id_evento'], + ] + ); + $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++; + } + + echo '
                '; + if (!empty($table->data)) { + if ($allow_pagination) { + $params_to_paginate = $params; + unset($params_to_paginate['offset']); + $url_paginate = 'index.php?'.http_build_query($params_to_paginate, '', '&'); + ui_pagination($total_events, $url_paginate, $offset, $pagination); + } + + if ($allow_action) { + echo '
                '; + echo ""; + } + + if (defined('METACONSOLE')) { + echo '
                '; + } else { + echo '
                '; + } + + html_print_table($table); + echo '
                '; + + if ($allow_action) { + echo '
                '; + if (!$readonly && $show_validate_button) { + $array_events_actions['in_progress_selected'] = 'In progress selected'; + $array_events_actions['validate_selected'] = 'Validate selected'; + // Fix: validated_selected JS function has to be included with the proper user ACLs + ?> + + + + '; + echo ''; + + $sql_event_resp = "SELECT id, name FROM tevent_response WHERE type LIKE 'command'"; + $event_responses = db_get_all_rows_sql($sql_event_resp); + + foreach ($event_responses as $val) { + $array_events_actions[$val['id']] = $val['name']; + } + + if ($config['event_replication'] != 1) { + echo '
                '; + echo '
                '; + html_print_select($array_events_actions, 'response_id', '', '', '', 0, false, false, false); + echo '  '; + html_print_button(__('Execute event response'), 'submit_event_response', false, 'execute_event_response(true);', 'class="sub next"'); + echo "'; + echo '
                '; + echo ''; + echo '
                '; + } + } + + ?> + + '.__('No events').'
                '; + } + + echo '
                '; } -?> + diff --git a/pandora_console/operation/events/events.php b/pandora_console/operation/events/events.php index ad692695ae..18e1e77ffc 100644 --- a/pandora_console/operation/events/events.php +++ b/pandora_console/operation/events/events.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,30 +11,35 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Load global vars global $config; -require_once ($config['homedir']."/include/functions_events.php"); //Event processing functions -require_once ($config['homedir']."/include/functions_alerts.php"); //Alerts processing functions -require_once ($config['homedir'].'/include/functions_agents.php'); //Agents functions -require_once ($config['homedir'].'/include/functions_users.php'); //Users functions -require_once ($config['homedir'].'/include/functions_graph.php'); -require_once ($config['homedir'].'/include/functions_ui.php'); +require_once $config['homedir'].'/include/functions_events.php'; +// Event processing functions +require_once $config['homedir'].'/include/functions_alerts.php'; +// Alerts processing functions +require_once $config['homedir'].'/include/functions_agents.php'; +// Agents functions +require_once $config['homedir'].'/include/functions_users.php'; +// Users functions +require_once $config['homedir'].'/include/functions_graph.php'; +require_once $config['homedir'].'/include/functions_ui.php'; -check_login (); +check_login(); -if (! check_acl ($config["id_user"], 0, "ER") && ! check_acl ($config["id_user"], 0, "EW") && ! check_acl ($config["id_user"], 0, "EM")) { - db_pandora_audit("ACL Violation", - "Trying to access event viewer"); - require ("general/noaccess.php"); - return; +if (! check_acl($config['id_user'], 0, 'ER') && ! check_acl($config['id_user'], 0, 'EW') && ! check_acl($config['id_user'], 0, 'EM')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access event viewer' + ); + include 'general/noaccess.php'; + return; } // Set metaconsole mode $meta = false; -if (enterprise_installed() && defined("METACONSOLE")) { - $meta = true; +if (enterprise_installed() && defined('METACONSOLE')) { + $meta = true; } // Get the history mode @@ -43,1025 +47,1054 @@ $history = (bool) get_parameter('history', 0); $readonly = false; if (!$meta) { - if (isset($config['event_replication']) && - $config['event_replication'] == 1) { - - if ((bool)$config['show_events_in_local']) { - $readonly = true; - } - } + if (isset($config['event_replication']) + && $config['event_replication'] == 1 + ) { + if ((bool) $config['show_events_in_local']) { + $readonly = true; + } + } } -if (is_ajax ()) { - $get_event_tooltip = (bool) get_parameter ('get_event_tooltip'); - $validate_event = (bool) get_parameter ('validate_event'); - $delete_event = (bool) get_parameter ('delete_event'); - $get_events_fired = (bool) get_parameter('get_events_fired'); - $standby_alert = (bool) get_parameter('standby_alert'); - $meta = get_parameter('meta', 0); - $history = get_parameter('history', 0); - - if ($get_event_tooltip) { - $id = (int) get_parameter ('id'); - $event = events_get_event ($id); - if ($event === false) - return; - - echo '

                ' . __('Event') . '

                '; - echo '' . __('Type') . ':
                '; - - events_print_type_img ($event["event_type"]); - echo ' '; - if ($event["event_type"] == "system") { - echo __('System'); - } - elseif ($event["id_agente"] > 0) { - // Agent name - echo agents_get_alias($event["id_agente"]); - } - else { - echo ''; - } - echo '
                '; - echo '' . __('Timestamp') . ':
                '; - ui_print_timestamp ($event['utimestamp']); - - echo '
                '; - echo '' . __('Description') . ':
                '; - echo $event['evento']; - - return; - } - - if ($validate_event) { - $id = (int) get_parameter ("id"); - $similars = (bool) get_parameter ('similars'); - $comment = (string) get_parameter ('comment'); - $new_status = get_parameter ('new_status'); - - // Set off the standby mode when close an event - if ($new_status == 1) { - $event = events_get_event ($id); - alerts_agent_module_standby ($event['id_alert_am'], 0); - } - - $return = events_change_status ($id, $new_status, $meta); - if ($return) - echo 'ok'; - else - echo 'error'; - return; - } - - if ($delete_event) { - $id = (array) get_parameter ("id"); - $similars = (bool) get_parameter ('similars'); - - $return = events_delete_event ($id, $similars, $meta, $history); - - if ($return) - echo 'ok'; - else - echo 'error'; - return; - } - - if ($get_events_fired) { - - $id = get_parameter('id_row'); - $idGroup = get_parameter('id_group'); - $agents = get_parameter('agents', null); +if (is_ajax()) { + $get_event_tooltip = (bool) get_parameter('get_event_tooltip'); + $validate_event = (bool) get_parameter('validate_event'); + $delete_event = (bool) get_parameter('delete_event'); + $get_events_fired = (bool) get_parameter('get_events_fired'); + $standby_alert = (bool) get_parameter('standby_alert'); + $meta = get_parameter('meta', 0); + $history = get_parameter('history', 0); - $query = ' AND id_evento > ' . $id; - - $type = array(); - $alert = get_parameter('alert_fired'); - if ($alert == 'true') { - $resultAlert = alerts_get_event_status_group($idGroup, - array('alert_fired','alert_ceased'), $query, $agents); - } - $critical = get_parameter('critical'); - if ($critical == 'true') { - $resultCritical = alerts_get_event_status_group($idGroup, - 'going_up_critical', $query, $agents); - } - $warning = get_parameter('warning'); - if ($warning == 'true') { - $resultWarning = alerts_get_event_status_group($idGroup, - 'going_up_warning', $query, $agents); - } - $unknown = get_parameter('unknown'); - if ($unknown == 'true') { - $resultUnknown = alerts_get_event_status_group($idGroup, - 'going_unknown', $query, $agents); - } - - if ($resultAlert) { - $return = array('fired' => $resultAlert, - 'sound' => $config['sound_alert']); - $event = events_get_event($resultAlert); + if ($get_event_tooltip) { + $id = (int) get_parameter('id'); + $event = events_get_event($id); + if ($event === false) { + return; + } - $module_name = modules_get_agentmodule_name($event['id_agentmodule']); - $agent_name = agents_get_alias($event['id_agente']); + echo '

                '.__('Event').'

                '; + echo ''.__('Type').':
                '; - $return['message'] = io_safe_output($agent_name) . " - " . __('Alert fired in module ') . io_safe_output($module_name) . - " - " . $event['timestamp']; - } - else if ($resultCritical) { - $return = array('fired' => $resultCritical, - 'sound' => $config['sound_critical']); - $event = events_get_event($resultCritical); + events_print_type_img($event['event_type']); + echo ' '; + if ($event['event_type'] == 'system') { + echo __('System'); + } else if ($event['id_agente'] > 0) { + // Agent name + echo agents_get_alias($event['id_agente']); + } else { + echo ''; + } - $module_name = modules_get_agentmodule_name($event['id_agentmodule']); - $agent_name = agents_get_alias($event['id_agente']); + echo '
                '; + echo ''.__('Timestamp').':
                '; + ui_print_timestamp($event['utimestamp']); - $return['message'] = io_safe_output($agent_name) . " - " . __('Module ') . io_safe_output($module_name) . __(' is going to critical') . - " - " . $event['timestamp']; - } - else if ($resultWarning) { - $return = array('fired' => $resultWarning, - 'sound' => $config['sound_warning']); - $event = events_get_event($resultWarning); + echo '
                '; + echo ''.__('Description').':
                '; + echo $event['evento']; - $module_name = modules_get_agentmodule_name($event['id_agentmodule']); - $agent_name = agents_get_alias($event['id_agente']); + return; + } - $return['message'] = io_safe_output($agent_name) . " - " . __('Module ') . io_safe_output($module_name) . __(' is going to warning') . - " - " . $event['timestamp']; - } - else if ($resultUnknown) { - $return = array('fired' => $resultUnknown, - 'sound' => $config['sound_alert']); - $event = events_get_event($resultUnknown); + if ($validate_event) { + $id = (int) get_parameter('id'); + $similars = (bool) get_parameter('similars'); + $comment = (string) get_parameter('comment'); + $new_status = get_parameter('new_status'); - $module_name = modules_get_agentmodule_name($event['id_agentmodule']); - $agent_name = agents_get_alias($event['id_agente']); + // Set off the standby mode when close an event + if ($new_status == 1) { + $event = events_get_event($id); + alerts_agent_module_standby($event['id_alert_am'], 0); + } - $return['message'] = io_safe_output($agent_name) . " - " . __('Module ') . io_safe_output($module_name) . __(' is going to unknown') . - " - " . $event['timestamp']; - } - else { - $return = array('fired' => 0); - } - - echo io_json_mb_encode($return); - } - - return; + $return = events_change_status($id, $new_status, $meta); + if ($return) { + echo 'ok'; + } else { + echo 'error'; + } + + return; + } + + if ($delete_event) { + $id = (array) get_parameter('id'); + $similars = (bool) get_parameter('similars'); + + $return = events_delete_event($id, $similars, $meta, $history); + + if ($return) { + echo 'ok'; + } else { + echo 'error'; + } + + return; + } + + if ($get_events_fired) { + $id = get_parameter('id_row'); + $idGroup = get_parameter('id_group'); + $agents = get_parameter('agents', null); + + $query = ' AND id_evento > '.$id; + + $type = []; + $alert = get_parameter('alert_fired'); + if ($alert == 'true') { + $resultAlert = alerts_get_event_status_group( + $idGroup, + [ + 'alert_fired', + 'alert_ceased', + ], + $query, + $agents + ); + } + + $critical = get_parameter('critical'); + if ($critical == 'true') { + $resultCritical = alerts_get_event_status_group( + $idGroup, + 'going_up_critical', + $query, + $agents + ); + } + + $warning = get_parameter('warning'); + if ($warning == 'true') { + $resultWarning = alerts_get_event_status_group( + $idGroup, + 'going_up_warning', + $query, + $agents + ); + } + + $unknown = get_parameter('unknown'); + if ($unknown == 'true') { + $resultUnknown = alerts_get_event_status_group( + $idGroup, + 'going_unknown', + $query, + $agents + ); + } + + if ($resultAlert) { + $return = [ + 'fired' => $resultAlert, + 'sound' => $config['sound_alert'], + ]; + $event = events_get_event($resultAlert); + + $module_name = modules_get_agentmodule_name($event['id_agentmodule']); + $agent_name = agents_get_alias($event['id_agente']); + + $return['message'] = io_safe_output($agent_name).' - '.__('Alert fired in module ').io_safe_output($module_name).' - '.$event['timestamp']; + } else if ($resultCritical) { + $return = [ + 'fired' => $resultCritical, + 'sound' => $config['sound_critical'], + ]; + $event = events_get_event($resultCritical); + + $module_name = modules_get_agentmodule_name($event['id_agentmodule']); + $agent_name = agents_get_alias($event['id_agente']); + + $return['message'] = io_safe_output($agent_name).' - '.__('Module ').io_safe_output($module_name).__(' is going to critical').' - '.$event['timestamp']; + } else if ($resultWarning) { + $return = [ + 'fired' => $resultWarning, + 'sound' => $config['sound_warning'], + ]; + $event = events_get_event($resultWarning); + + $module_name = modules_get_agentmodule_name($event['id_agentmodule']); + $agent_name = agents_get_alias($event['id_agente']); + + $return['message'] = io_safe_output($agent_name).' - '.__('Module ').io_safe_output($module_name).__(' is going to warning').' - '.$event['timestamp']; + } else if ($resultUnknown) { + $return = [ + 'fired' => $resultUnknown, + 'sound' => $config['sound_alert'], + ]; + $event = events_get_event($resultUnknown); + + $module_name = modules_get_agentmodule_name($event['id_agentmodule']); + $agent_name = agents_get_alias($event['id_agente']); + + $return['message'] = io_safe_output($agent_name).' - '.__('Module ').io_safe_output($module_name).__(' is going to unknown').' - '.$event['timestamp']; + } else { + $return = ['fired' => 0]; + } + + echo io_json_mb_encode($return); + } + + return; } enterprise_hook('open_meta_frame'); if (!$meta) { - if (isset($config['event_replication']) && - $config['event_replication'] == 1) { - - if ($config['show_events_in_local'] == 0) { - db_pandora_audit("ACL Violation", - "Trying to access event viewer. View disabled due event replication."); - ui_print_info_message(array('message' => __('Event viewer is disabled due event replication. For more information, please contact with the administrator'), 'no_close' => true)); - return; - } - else { - $readonly = true; - } - } + if (isset($config['event_replication']) + && $config['event_replication'] == 1 + ) { + if ($config['show_events_in_local'] == 0) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access event viewer. View disabled due event replication.' + ); + ui_print_info_message(['message' => __('Event viewer is disabled due event replication. For more information, please contact with the administrator'), 'no_close' => true]); + return; + } else { + $readonly = true; + } + } } -$offset = (int) get_parameter ("offset", 0); -$id_group = (int) get_parameter('id_group', 0);//0 all -//********************************************************************** +$offset = (int) get_parameter('offset', 0); +$id_group = (int) get_parameter('id_group', 0); +// 0 all +// ********************************************************************** // TODO // This code is disabled for to enabled in Pandora 5.1 // but it needs a field in tevent_filter. // -//$recursion = (bool)get_parameter('recursion', false); //Flag show in child groups -//********************************************************************** -$recursion = (bool)get_parameter('recursion', true); //Flag show in child groups -$event_type = get_parameter ("event_type", ''); // 0 all -$severity = (int) get_parameter ("severity", -1); // -1 all -$status = (int) get_parameter ("status", 3); // -1 all, 0 only new, 1 only validated, 2 only in process, 3 only not validated, -$id_agent = (int) get_parameter ("id_agent", 0); -$pagination = (int) get_parameter ("pagination", $config["block_size"]); -$event_view_hr = (int) get_parameter ("event_view_hr", $history ? 0 : $config["event_view_hr"]); -$id_user_ack = get_parameter ("id_user_ack", 0); -$group_rep = (int) get_parameter ("group_rep", 1); -$delete = (bool) get_parameter ("delete"); -$validate = (bool) get_parameter ("validate", 0); -$section = (string) get_parameter ("section", "list"); +// $recursion = (bool)get_parameter('recursion', false); //Flag show in child groups +// ********************************************************************** +$recursion = (bool) get_parameter('recursion', true); +// Flag show in child groups +$event_type = get_parameter('event_type', ''); +// 0 all +$severity = (int) get_parameter('severity', -1); +// -1 all +$status = (int) get_parameter('status', 3); +// -1 all, 0 only new, 1 only validated, 2 only in process, 3 only not validated, +$id_agent = (int) get_parameter('id_agent', 0); +$pagination = (int) get_parameter('pagination', $config['block_size']); +$event_view_hr = (int) get_parameter('event_view_hr', $history ? 0 : $config['event_view_hr']); +$id_user_ack = get_parameter('id_user_ack', 0); +$group_rep = (int) get_parameter('group_rep', 1); +$delete = (bool) get_parameter('delete'); +$validate = (bool) get_parameter('validate', 0); +$section = (string) get_parameter('section', 'list'); $filter_only_alert = (int) get_parameter('filter_only_alert', -1); $filter_id = (int) get_parameter('filter_id', 0); $id_name = (string) get_parameter('id_name', ''); $open_filter = (int) get_parameter('open_filter', 0); -$date_from = (string)get_parameter('date_from', ''); -$date_to = (string)get_parameter('date_to', ''); -$time_from = (string)get_parameter('time_from', ''); -$time_to = (string)get_parameter('time_to', ''); -$server_id = (int)get_parameter('server_id', 0); -$text_agent = (string) get_parameter("text_agent"); -$refr = (int) get_parameter ('refresh'); +$date_from = (string) get_parameter('date_from', ''); +$date_to = (string) get_parameter('date_to', ''); +$time_from = (string) get_parameter('time_from', ''); +$time_to = (string) get_parameter('time_to', ''); +$server_id = (int) get_parameter('server_id', 0); +$text_agent = (string) get_parameter('text_agent'); +$refr = (int) get_parameter('refresh'); $id_extra = (string) get_parameter('id_extra'); $user_comment = (string) get_parameter('user_comment'); $source = (string) get_parameter('source'); if ($id_agent != 0) { - $text_agent = agents_get_alias($id_agent); - if ($text_agent == false) { - $text_agent = ''; - $id_agent = 0; - } + $text_agent = agents_get_alias($id_agent); + if ($text_agent == false) { + $text_agent = ''; + $id_agent = 0; + } } else { - if (!$meta) { - $text_agent = ''; - } + if (!$meta) { + $text_agent = ''; + } } $text_module = (string) get_parameter('module_search', ''); -$id_agent_module = get_parameter('module_search_hidden', get_parameter('id_agent_module',0)); +$id_agent_module = get_parameter('module_search_hidden', get_parameter('id_agent_module', 0)); if ($id_agent_module != 0) { - $text_module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $id_agent_module); - if ($text_module == false) { - $text_module = ''; - } + $text_module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $id_agent_module); + if ($text_module == false) { + $text_module = ''; + } } else { - $text_module = ''; + $text_module = ''; } -$tag_with_json = base64_decode(get_parameter("tag_with", '')) ; +$tag_with_json = base64_decode(get_parameter('tag_with', '')); $tag_with_json_clean = io_safe_output($tag_with_json); $tag_with_base64 = base64_encode($tag_with_json_clean); $tag_with = json_decode($tag_with_json_clean, true); -if (empty($tag_with)) $tag_with = array(); -$tag_with = array_diff($tag_with, array(0 => 0)); +if (empty($tag_with)) { + $tag_with = []; +} -$tag_without_json = base64_decode(get_parameter("tag_without", '')); +$tag_with = array_diff($tag_with, [0 => 0]); + +$tag_without_json = base64_decode(get_parameter('tag_without', '')); $tag_without_json_clean = io_safe_output($tag_without_json); $tag_without_base64 = base64_encode($tag_without_json_clean); $tag_without = json_decode($tag_without_json_clean, true); -if (empty($tag_without)) $tag_without = array(); -$tag_without = array_diff($tag_without, array(0 => 0)); - -$search = get_parameter ("search"); - -users_get_groups ($config["id_user"], "ER"); - -$ids = (array) get_parameter ("eventid", -1); - -$params = "search=" . io_safe_input($search) . - "&event_type=" . $event_type . - "&severity=" . $severity . - "&status=" . $status . - "&id_group=" . $id_group . - "&recursion=" . $recursion . - "&refresh=" . (int)get_parameter("refresh", 0) . - "&id_agent=" . $id_agent . - "&id_agent_module=" . $id_agent_module . - "&pagination=" . $pagination . - "&group_rep=" . $group_rep . - "&event_view_hr=" . $event_view_hr . - "&id_user_ack=" . $id_user_ack . - "&tag_with=". $tag_with_base64 . - "&tag_without=" . $tag_without_base64 . - "&filter_only_alert" . $filter_only_alert . - "&offset=" . $offset . - "&toogle_filter=no" . - "&filter_id=" . $filter_id . - "&id_name=" . $id_name . - "&history=" . (int)$history . - "&section=" . $section . - "&open_filter=" . $open_filter . - "&date_from=" . $date_from . - "&date_to=" . $date_to . - "&time_from=" . $time_from . - "&time_to=" . $time_to; - -if ($meta) { - $params .= "&text_agent=" . $text_agent; - $params .= "&server_id=" . $server_id; +if (empty($tag_without)) { + $tag_without = []; } -$url = "index.php?sec=eventos&sec2=operation/events/events&" . $params; +$tag_without = array_diff($tag_without, [0 => 0]); + +$search = get_parameter('search'); + +users_get_groups($config['id_user'], 'ER'); + +$ids = (array) get_parameter('eventid', -1); + +$params = 'search='.io_safe_input($search).'&event_type='.$event_type.'&severity='.$severity.'&status='.$status.'&id_group='.$id_group.'&recursion='.$recursion.'&refresh='.(int) get_parameter('refresh', 0).'&id_agent='.$id_agent.'&id_agent_module='.$id_agent_module.'&pagination='.$pagination.'&group_rep='.$group_rep.'&event_view_hr='.$event_view_hr.'&id_user_ack='.$id_user_ack.'&tag_with='.$tag_with_base64.'&tag_without='.$tag_without_base64.'&filter_only_alert'.$filter_only_alert.'&offset='.$offset.'&toogle_filter=no'.'&filter_id='.$filter_id.'&id_name='.$id_name.'&history='.(int) $history.'&section='.$section.'&open_filter='.$open_filter.'&date_from='.$date_from.'&date_to='.$date_to.'&time_from='.$time_from.'&time_to='.$time_to; + +if ($meta) { + $params .= '&text_agent='.$text_agent; + $params .= '&server_id='.$server_id; +} + +$url = 'index.php?sec=eventos&sec2=operation/events/events&'.$params; // Header -if ($config["pure"] == 0 || $meta) { - $pss = get_user_info($config['id_user']); - $hashup = md5($config['id_user'] . $pss['password']); - - // Fullscreen - $fullscreen['active'] = false; - $fullscreen['text'] = '' . - html_print_image("images/full_screen.png", true, array ("title" => __('Full screen'))) .''; - - // Event list - $list['active'] = false; - $list['text'] = '' . - html_print_image("images/events_list.png", true, array("title" => __('Event list'))) . ''; - - // History event list - $history_list['active'] = false; - $history_list['text'] = '' . - html_print_image("images/books.png", true, array("title" => __('History event list'))) . ''; - - // RSS - $rss['active'] = false; - $rss['text'] = '' . - html_print_image("images/rss.png", true, array ("title" => __('RSS Events'))) .''; - - // Marquee - $marquee['active'] = false; - $marquee['text'] = '' . - html_print_image("images/heart.png", true, array ("title" => __('Marquee display'))) .''; - - // CSV - $csv['active'] = false; - $csv['text'] = '' . - html_print_image("images/csv_mc.png", true, array ("title" => __('Export to CSV file'))) .''; - - // Sound events - $sound_event['active'] = false; - $sound_event['text'] = '' . html_print_image('images/sound.png', true, array('title' => __('Sound events'))) . ''; - - // If the user has administrator permission display manage tab - if (check_acl ($config["id_user"], 0, "EW") || check_acl ($config["id_user"], 0, "EM")) { - // Manage events - $manage_events['active'] = false; - $manage_events['text'] = '' . - html_print_image("images/setup.png", true, array ("title" => __('Manage events'))) . ''; - - $manage_events['godmode'] = true; - - $onheader = array( - 'manage_events' => $manage_events, - 'fullscreen' => $fullscreen, - 'list' => $list, - 'history' => $history_list, - 'rss' => $rss, - 'marquee' => $marquee, - 'csv' => $csv, - 'sound_event' => $sound_event) ; - } - else { - $onheader = array('fullscreen' => $fullscreen, - 'list' => $list, - 'history' => $history_list, - 'rss' => $rss, - 'marquee' => $marquee, - 'csv' => $csv, - 'sound_event' => $sound_event); - } - - // If the history event is not ebabled, dont show the history tab - if (!isset($config['metaconsole_events_history']) || $config['metaconsole_events_history'] != 1) { - unset($onheader['history']); - } - - switch ($section) { - case 'sound_event': - $onheader['sound_event']['active'] = true; - $section_string = __('Sound events'); - break; - case 'history': - $onheader['history']['active'] = true; - $section_string = __('History'); - break; - default: - $onheader['list']['active'] = true; - $section_string = __('List'); - break; - } +if ($config['pure'] == 0 || $meta) { + $pss = get_user_info($config['id_user']); + $hashup = md5($config['id_user'].$pss['password']); + + // Fullscreen + $fullscreen['active'] = false; + $fullscreen['text'] = ''.html_print_image('images/full_screen.png', true, ['title' => __('Full screen')]).''; + + // Event list + $list['active'] = false; + $list['text'] = ''.html_print_image('images/events_list.png', true, ['title' => __('Event list')]).''; + + // History event list + $history_list['active'] = false; + $history_list['text'] = ''.html_print_image('images/books.png', true, ['title' => __('History event list')]).''; + + // RSS + $rss['active'] = false; + $rss['text'] = ''.html_print_image('images/rss.png', true, ['title' => __('RSS Events')]).''; + + // Marquee + $marquee['active'] = false; + $marquee['text'] = ''.html_print_image('images/heart.png', true, ['title' => __('Marquee display')]).''; + + // CSV + $csv['active'] = false; + $csv['text'] = ''.html_print_image('images/csv_mc.png', true, ['title' => __('Export to CSV file')]).''; + + // Sound events + $sound_event['active'] = false; + $sound_event['text'] = ''.html_print_image('images/sound.png', true, ['title' => __('Sound events')]).''; + + // If the user has administrator permission display manage tab + if (check_acl($config['id_user'], 0, 'EW') || check_acl($config['id_user'], 0, 'EM')) { + // Manage events + $manage_events['active'] = false; + $manage_events['text'] = ''.html_print_image('images/setup.png', true, ['title' => __('Manage events')]).''; + + $manage_events['godmode'] = true; + + $onheader = [ + 'manage_events' => $manage_events, + 'fullscreen' => $fullscreen, + 'list' => $list, + 'history' => $history_list, + 'rss' => $rss, + 'marquee' => $marquee, + 'csv' => $csv, + 'sound_event' => $sound_event, + ]; + } else { + $onheader = [ + 'fullscreen' => $fullscreen, + 'list' => $list, + 'history' => $history_list, + 'rss' => $rss, + 'marquee' => $marquee, + 'csv' => $csv, + 'sound_event' => $sound_event, + ]; + } + + // If the history event is not ebabled, dont show the history tab + if (!isset($config['metaconsole_events_history']) || $config['metaconsole_events_history'] != 1) { + unset($onheader['history']); + } + + switch ($section) { + case 'sound_event': + $onheader['sound_event']['active'] = true; + $section_string = __('Sound events'); + break; + + case 'history': + $onheader['history']['active'] = true; + $section_string = __('History'); + break; + + default: + $onheader['list']['active'] = true; + $section_string = __('List'); + break; + } - /* Hello there! :) + /* + Hello there! :) - We added some of what seems to be "buggy" messages to the openSource version recently. This is not to force open-source users to move to the enterprise version, this is just to inform people using Pandora FMS open source that it requires skilled people to maintain and keep it running smoothly without professional support. This does not imply open-source version is limited in any way. If you check the recently added code, it contains only warnings and messages, no limitations except one: we removed the option to add custom logo in header. In the Update Manager section, it warns about the 'danger’ of applying automated updates without a proper backup, remembering in the process that the Enterprise version comes with a human-tested package. Maintaining an OpenSource version with more than 500 agents is not so easy, that's why someone using a Pandora with 8000 agents should consider asking for support. It's not a joke, we know of many setups with a huge number of agents, and we hate to hear that “its becoming unstable and slow” :( + We added some of what seems to be "buggy" messages to the openSource version recently. This is not to force open-source users to move to the enterprise version, this is just to inform people using Pandora FMS open source that it requires skilled people to maintain and keep it running smoothly without professional support. This does not imply open-source version is limited in any way. If you check the recently added code, it contains only warnings and messages, no limitations except one: we removed the option to add custom logo in header. In the Update Manager section, it warns about the 'danger’ of applying automated updates without a proper backup, remembering in the process that the Enterprise version comes with a human-tested package. Maintaining an OpenSource version with more than 500 agents is not so easy, that's why someone using a Pandora with 8000 agents should consider asking for support. It's not a joke, we know of many setups with a huge number of agents, and we hate to hear that “its becoming unstable and slow” :( - You can of course remove the warnings, that's why we include the source and do not use any kind of trick. And that's why we added here this comment, to let you know this does not reflect any change in our opensource mentality of does the last 14 years. + You can of course remove the warnings, that's why we include the source and do not use any kind of trick. And that's why we added here this comment, to let you know this does not reflect any change in our opensource mentality of does the last 14 years. - */ + */ - if (! defined ('METACONSOLE')) { - unset($onheader['history']); - ui_print_page_header (__("Events"), "images/op_events.png", - false, "eventview", false, $onheader,true, "eventsmodal"); - } - else { - unset($onheader['rss']); - unset($onheader['marquee']); - unset($onheader['csv']); - unset($onheader['sound_event']); - unset($onheader['fullscreen']); - ui_meta_print_header(__("Events"), $section_string, $onheader); - } - - ?> - - '; + if (! defined('METACONSOLE')) { + unset($onheader['history']); + ui_print_page_header( + __('Events'), + 'images/op_events.png', + false, + 'eventview', + false, + $onheader, + true, + 'eventsmodal' + ); + } else { + unset($onheader['rss']); + unset($onheader['marquee']); + unset($onheader['csv']); + unset($onheader['sound_event']); + unset($onheader['fullscreen']); + ui_meta_print_header(__('Events'), $section_string, $onheader); + } - echo ''; - // Floating menu - End - - ui_require_jquery_file('countdown'); - ui_require_css_file('countdown'); + echo ''; + echo '
                '; + + echo '
                '; + // Floating menu - End + ui_require_jquery_file('countdown'); } // Error div for ajax messages echo "
                "; -echo "
                "; +echo '
                '; if (($section == 'validate') && ($ids[0] == -1)) { - $section = 'list'; - ui_print_error_message (__('No events selected')); + $section = 'list'; + ui_print_error_message(__('No events selected')); } -//Process validation (pass array or single value) +// Process validation (pass array or single value) if ($validate) { - $ids = get_parameter ("eventid", -1); - $comment = get_parameter ("comment", ''); - $new_status = get_parameter ("select_validate", 1); - $ids = explode(',',$ids); - $standby_alert = (bool) get_parameter("standby-alert"); - - // Avoid to re-set inprocess events - if ($new_status == 2) { - foreach ($ids as $key => $id) { - $event = events_get_event($id); - if ($event['estado'] == 2) { - unset($ids[$key]); - } - } - } - - if (isset($ids[0]) && $ids[0] != -1) { - $return = events_change_status ($ids, $new_status, $meta); - - if ($new_status == 1) { - ui_print_result_message ($return, - __('Successfully validated'), - __('Could not be validated')); - } - elseif ($new_status == 2) { - ui_print_result_message ($return, - __('Successfully set in process'), - __('Could not be set in process')); - } - } + $ids = get_parameter('eventid', -1); + $comment = get_parameter('comment', ''); + $new_status = get_parameter('select_validate', 1); + $ids = explode(',', $ids); + $standby_alert = (bool) get_parameter('standby-alert'); + + // Avoid to re-set inprocess events + if ($new_status == 2) { + foreach ($ids as $key => $id) { + $event = events_get_event($id); + if ($event['estado'] == 2) { + unset($ids[$key]); + } + } + } + + if (isset($ids[0]) && $ids[0] != -1) { + $return = events_change_status($ids, $new_status, $meta); + + if ($new_status == 1) { + ui_print_result_message( + $return, + __('Successfully validated'), + __('Could not be validated') + ); + } else if ($new_status == 2) { + ui_print_result_message( + $return, + __('Successfully set in process'), + __('Could not be set in process') + ); + } + } } -//Process deletion (pass array or single value) +// Process deletion (pass array or single value) if ($delete) { - $ids = (array) get_parameter ("validate_ids", -1); - - if ($ids[0] != -1) { - $return = events_delete_event ($ids, ($group_rep == 1), $meta); - ui_print_result_message ($return, - __('Successfully deleted'), - __('Could not be deleted')); - } - require_once($config['homedir'] . '/operation/events/events_list.php'); -} -else { - switch ($section) { - case 'list': - case 'history': - require_once($config['homedir'] . '/operation/events/events_list.php'); - break; - } + $ids = (array) get_parameter('validate_ids', -1); + + // Discard deleting in progress events + $in_process_status = db_get_all_rows_sql( + ' + SELECT id_evento + FROM tevento + WHERE estado=2' + ); + + foreach ($in_process_status as $val) { + if (($key = array_search($val['id_evento'], $ids)) !== false) { + unset($ids[$key]); + } + } + + if ($ids[0] != -1) { + $return = events_delete_event($ids, ($group_rep == 1), $meta); + ui_print_result_message( + $return, + __('Successfully deleted'), + __('Could not be deleted') + ); + } + + include_once $config['homedir'].'/operation/events/events_list.php'; +} else { + switch ($section) { + case 'list': + case 'history': + include_once $config['homedir'].'/operation/events/events_list.php'; + break; + } } echo "
                "; echo "
                "; -ui_require_jquery_file ('bgiframe'); +ui_require_jquery_file('bgiframe'); ui_require_javascript_file('pandora_events'); enterprise_hook('close_meta_frame'); ui_require_javascript_file('wz_jsgraphics'); ui_require_javascript_file('pandora_visual_console'); -$ignored_params['refresh']=''; +$ignored_params['refresh'] = ''; ?> $fields, - 'event_type' => $types, - 'severity' => $severities, - 'duplicate' => $repeated_sel, - 'alerts' => $alert_events_titles, - 'groups' => $user_groups_array - ) - ) +enterprise_hook( + 'print_event_tags_active_filters', + [ + $filter_resume, + [ + 'status' => $fields, + 'event_type' => $types, + 'severity' => $severities, + 'duplicate' => $repeated_sel, + 'alerts' => $alert_events_titles, + 'groups' => $user_groups_array, + ], + ] ); if (!empty($result)) { - //~ Checking the event tags exactly. The event query filters approximated tags to keep events - //~ with several tags - $acltags = tags_get_user_groups_and_tags ($config['id_user'], $access, true); + // ~ Checking the event tags exactly. The event query filters approximated tags to keep events + // ~ with several tags + $acltags = tags_get_user_groups_and_tags($config['id_user'], $access, true); - foreach ($result as $key=>$event_data) { - $has_tags = events_checks_event_tags($event_data, $acltags); - if (!$has_tags) { - unset($result[$key]); - } - } + foreach ($result as $key => $event_data) { + $has_tags = events_checks_event_tags($event_data, $acltags); + if (!$has_tags) { + unset($result[$key]); + } + } } // Delete rnum field generated by oracle_recode_query() function if (($config['dbtype'] == 'oracle') && ($result !== false)) { - for ($i=0; $i < count($result); $i++) { - unset($result[$i]['rnum']); - } + for ($i = 0; $i < count($result); $i++) { + unset($result[$i]['rnum']); + } } if ($group_rep == 0) { - $sql = "SELECT COUNT(DISTINCT id_evento) + $sql = "SELECT COUNT(DISTINCT id_evento) FROM $event_table te $event_lj WHERE 1=1 $sql_post"; - $total_events = (int) db_get_sql ($sql); -} -elseif ($group_rep == 1) { - $total_events = events_get_events_grouped($sql_post, false, - false, $meta, $history, true, false); -} -elseif ($group_rep == 2) { - $sql = "SELECT COUNT(*) FROM (select id_agente as total from $event_table te + $total_events = (int) db_get_sql($sql); +} else if ($group_rep == 1) { + $total_events = events_get_events_grouped( + $sql_post, + false, + false, + $meta, + $history, + true, + false + ); +} else if ($group_rep == 2) { + $sql = "SELECT COUNT(*) FROM (select id_agente as total from $event_table te $event_lj WHERE id_agente > 0 $sql_post GROUP BY id_agente ORDER BY id_agente ) AS t"; - $total_events = (int) db_get_sql ($sql); + $total_events = (int) db_get_sql($sql); } -if (empty ($result)) { - $result = array (); +if (empty($result)) { + $result = []; } $allow_action = true; $allow_pagination = true; $id_group_filter = $id_group; -require('events.build_table.php'); +require 'events.build_table.php'; enterprise_hook('close_meta_frame'); unset($table); // Values to be used from javascript library -html_print_input_hidden('ajax_file', - ui_get_full_url("ajax.php", false, false, false)); -html_print_input_hidden('meta', (int)$meta); -html_print_input_hidden('history', (int)$history); +html_print_input_hidden( + 'ajax_file', + ui_get_full_url('ajax.php', false, false, false) +); +html_print_input_hidden('meta', (int) $meta); +html_print_input_hidden('history', (int) $history); html_print_input_hidden('filterid', $is_filter); ui_require_jquery_file('json'); @@ -879,751 +995,751 @@ ui_include_time_picker(); diff --git a/pandora_console/operation/events/events_marquee.php b/pandora_console/operation/events/events_marquee.php index 12425fd3b6..4834207172 100644 --- a/pandora_console/operation/events/events_marquee.php +++ b/pandora_console/operation/events/events_marquee.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,114 +11,117 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - error_reporting(1); // Local settings for marquee extension -$MAX_MARQUEE_EVENTS=10; -$MARQUEE_INTERVAL=90; -$MARQUEE_FONT_SIZE="32px"; -$MARQUEE_SPEED=12; +$MAX_MARQUEE_EVENTS = 10; +$MARQUEE_INTERVAL = 90; +$MARQUEE_FONT_SIZE = '32px'; +$MARQUEE_SPEED = 12; -$output = ""; +$output = ''; // Don't start a session before this import. // The session is configured and started inside the config process. -require_once "../../include/config.php"; -require_once "../../include/functions.php"; -require_once "../../include/functions_db.php"; -require_once "../../include/functions_api.php"; -require_once ('../../include/functions_users.php'); +require_once '../../include/config.php'; +require_once '../../include/functions.php'; +require_once '../../include/functions_db.php'; +require_once '../../include/functions_api.php'; +require_once '../../include/functions_users.php'; global $config; -$config["id_user"] = $_SESSION["id_usuario"]; +$config['id_user'] = $_SESSION['id_usuario']; // http://es2.php.net/manual/en/ref.session.php#64525 // Session locking concurrency speedup! -check_login (); +check_login(); -$event_a = check_acl ($config['id_user'], 0, "ER"); -$event_w = check_acl ($config['id_user'], 0, "EW"); -$event_m = check_acl ($config['id_user'], 0, "EM"); +$event_a = check_acl($config['id_user'], 0, 'ER'); +$event_w = check_acl($config['id_user'], 0, 'EW'); +$event_m = check_acl($config['id_user'], 0, 'EM'); $access = ($event_a == true) ? 'ER' : (($event_w == true) ? 'EW' : (($event_m == true) ? 'EM' : 'ER')); if (!isInACL($_SERVER['REMOTE_ADDR'])) { - db_pandora_audit("ACL Violation", - "Trying to access marquee without ACL Access"); - require ("../../general/noaccess.php"); - exit; + db_pandora_audit( + 'ACL Violation', + 'Trying to access marquee without ACL Access' + ); + include '../../general/noaccess.php'; + exit; } -$groups = users_get_groups ($config["id_user"], $access); +$groups = users_get_groups($config['id_user'], $access); -//Otherwise select all groups the user has rights to. +// Otherwise select all groups the user has rights to. if (!empty($groups)) { - $sql_group_filter = " AND id_grupo IN (".implode (",", array_keys ($groups)).")"; -} -else { - $sql_group_filter = ""; + $sql_group_filter = ' AND id_grupo IN ('.implode(',', array_keys($groups)).')'; +} else { + $sql_group_filter = ''; } // Skip system messages if user is not PM -if (!check_acl ($config["id_user"], 0, "PM")) { - $sql_group_filter .= " AND id_grupo != 0"; +if (!check_acl($config['id_user'], 0, 'PM')) { + $sql_group_filter .= ' AND id_grupo != 0'; } -switch ($config["dbtype"]) { - case "mysql": - $sql = "SELECT evento, timestamp, id_agente +switch ($config['dbtype']) { + case 'mysql': + $sql = "SELECT evento, timestamp, id_agente FROM tevento WHERE 1=1 $sql_group_filter ORDER BY utimestamp DESC LIMIT 0 , $MAX_MARQUEE_EVENTS"; - break; - case "postgresql": - $sql = "SELECT evento, timestamp, id_agente + break; + + case 'postgresql': + $sql = "SELECT evento, timestamp, id_agente FROM tevento WHERE 1=1 $sql_group_filter ORDER BY utimestamp DESC LIMIT $MAX_MARQUEE_EVENTS OFFSET 0"; - break; - case "oracle": - $sql = "SELECT evento, timestamp, id_agente + break; + + case 'oracle': + $sql = "SELECT evento, timestamp, id_agente FROM tevento WHERE (1=1 $sql_group_filter ) AND rownum <= $MAX_MARQUEE_EVENTS ORDER BY utimestamp DESC"; - break; + break; } -$result = db_get_all_rows_sql ($sql); +$result = db_get_all_rows_sql($sql); foreach ($result as $row) { - $agente = ""; - if ($row["id_agente"] != 0) { - $agente = db_get_sql ("SELECT alias + $agente = ''; + if ($row['id_agente'] != 0) { + $agente = db_get_sql( + 'SELECT alias FROM tagente - WHERE id_agente = ". $row["id_agente"]); - $agente = $agente . " : "; - } - $output .= strtoupper($agente) . $row["evento"]. " , ". human_time_comparation($row["timestamp"]); - $output .= ".    .    .    .    .    .    . "; + WHERE id_agente = '.$row['id_agente'] + ); + $agente = $agente.' : '; + } + + $output .= strtoupper($agente).$row['evento'].' , '.human_time_comparation($row['timestamp']); + $output .= '.    .    .    .    .    .    . '; } -echo ""; -echo ""; -echo "" . __("%s - Latest events", get_product_name()) . ""; +echo ''; +echo ''; +echo ''.__('%s - Latest events', get_product_name()).''; $query = ui_get_full_url(); -echo ''; -echo ''; -echo ""; +echo ''; +echo ''; +echo ''; echo ""; -echo "

                "; -echo "
                "; +echo '

                '; +echo '
                '; echo "
                "; echo "$output"; -echo "
                "; -echo ""; -echo ""; - -?> +echo '
                '; +echo ''; +echo ''; diff --git a/pandora_console/operation/events/events_rss.php b/pandora_console/operation/events/events_rss.php index 6dc9238d66..2a38643a9c 100644 --- a/pandora_console/operation/events/events_rss.php +++ b/pandora_console/operation/events/events_rss.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,26 +11,30 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - -ini_set ('display_errors', 0); //Don't display other errors, messes up XML - -require_once "../../include/config.php"; -require_once "../../include/functions.php"; -require_once "../../include/functions_db.php"; -require_once "../../include/functions_api.php"; -require_once "../../include/functions_agents.php"; -require_once "../../include/functions_users.php"; -require_once "../../include/functions_tags.php"; -require_once "../../include/functions_groups.php"; +ini_set('display_errors', 0); +// Don't display other errors, messes up XML +require_once '../../include/config.php'; +require_once '../../include/functions.php'; +require_once '../../include/functions_db.php'; +require_once '../../include/functions_api.php'; +require_once '../../include/functions_agents.php'; +require_once '../../include/functions_users.php'; +require_once '../../include/functions_tags.php'; +require_once '../../include/functions_groups.php'; $ipOrigin = $_SERVER['REMOTE_ADDR']; // Uncoment this to activate ACL on RSS Events if (!isInACL($ipOrigin)) { - rss_error_handler(null, null, null, null, - __("Your IP is not into the IP list with API access.")); - - exit; + rss_error_handler( + null, + null, + null, + null, + __('Your IP is not into the IP list with API access.') + ); + + exit; } // Check user credentials @@ -42,169 +45,194 @@ $pss = get_user_info($user); $hashup2 = md5($user.$pss['password']); if ($hashup != $hashup2) { - rss_error_handler(null, null, null, null, - __("The URL of your feed has bad hash.")); - - exit; + rss_error_handler( + null, + null, + null, + null, + __('The URL of your feed has bad hash.') + ); + + exit; } -header("Content-Type: application/xml; charset=UTF-8"); //Send header before starting to output +header('Content-Type: application/xml; charset=UTF-8'); +// Send header before starting to output +function rss_error_handler($errno, $errstr, $errfile, $errline, $error_human_description=null) +{ + $url = ui_get_full_url(false); + $selfurl = ui_get_full_url('?'.$_SERVER['QUERY_STRING'], false, true); -function rss_error_handler ($errno, $errstr, $errfile, $errline, $error_human_description = null) { - $url = ui_get_full_url(false); - $selfurl = ui_get_full_url('?' . $_SERVER['QUERY_STRING'], false, true); - - $rss_feed = ''; //' Fixes certain highlighters freaking out on the PHP closing tag - $rss_feed .= "\n"; - $rss_feed .= ''; - $rss_feed .= "\n"; - $rss_feed .= ''; - $rss_feed .= "\n"; - $rss_feed .= '' . get_product_name() . ' RSS Feed'; - $rss_feed .= "\n"; - $rss_feed .= 'Latest events on ' . get_product_name() . ''; - $rss_feed .= "\n"; - $rss_feed .= ''.date (DATE_RFC822, 0).''; - $rss_feed .= "\n"; - $rss_feed .= '' . $url . ''; //Link back to the main Pandora page - $rss_feed .= "\n"; - $rss_feed .= ''; //Alternative for Atom feeds. It's the same. - $rss_feed .= "\n"; - $rss_feed .= ''; - $rss_feed .= "\n"; - $rss_feed .= ''.$url.'/index.php?sec=eventos&sec2=operation/events/events'; - $rss_feed .= "\n"; - $rss_feed .= 'Error creating feed'; - $rss_feed .= "\n"; - - if (empty($error_human_description)) { - $rss_feed .= 'There was an error creating the feed: '.$errno.' - '.$errstr.' in '.$errfile.' on line '.$errline.''; - } - else { - $rss_feed .= '' . xml_entities(io_safe_input($error_human_description)) .''; - } - $rss_feed .= "\n"; - $rss_feed .= ''.$url.'/index.php?sec=eventos&sec2=operation/events/events'; - $rss_feed .= "\n"; - $rss_feed .= ''; - $rss_feed .= "\n"; - $rss_feed .= ''; - $rss_feed .= "\n"; - $rss_feed .= ''; - - exit ($rss_feed); //Exit by displaying the feed + $rss_feed = ''; + // ' Fixes certain highlighters freaking out on the PHP closing tag + $rss_feed .= "\n"; + $rss_feed .= ''; + $rss_feed .= "\n"; + $rss_feed .= ''; + $rss_feed .= "\n"; + $rss_feed .= ''.get_product_name().' RSS Feed'; + $rss_feed .= "\n"; + $rss_feed .= 'Latest events on '.get_product_name().''; + $rss_feed .= "\n"; + $rss_feed .= ''.date(DATE_RFC822, 0).''; + $rss_feed .= "\n"; + $rss_feed .= ''.$url.''; + // Link back to the main Pandora page + $rss_feed .= "\n"; + $rss_feed .= ''; + // Alternative for Atom feeds. It's the same. + $rss_feed .= "\n"; + $rss_feed .= ''; + $rss_feed .= "\n"; + $rss_feed .= ''.$url.'/index.php?sec=eventos&sec2=operation/events/events'; + $rss_feed .= "\n"; + $rss_feed .= 'Error creating feed'; + $rss_feed .= "\n"; + + if (empty($error_human_description)) { + $rss_feed .= 'There was an error creating the feed: '.$errno.' - '.$errstr.' in '.$errfile.' on line '.$errline.''; + } else { + $rss_feed .= ''.xml_entities(io_safe_input($error_human_description)).''; + } + + $rss_feed .= "\n"; + $rss_feed .= ''.$url.'/index.php?sec=eventos&sec2=operation/events/events'; + $rss_feed .= "\n"; + $rss_feed .= ''; + $rss_feed .= "\n"; + $rss_feed .= ''; + $rss_feed .= "\n"; + $rss_feed .= ''; + + exit($rss_feed); + // Exit by displaying the feed } -set_error_handler ('rss_error_handler', E_ERROR); //Errors output as RSS -$id_group = get_parameter ("id_group", 0); // group -$event_type = get_parameter ("event_type", ''); // 0 all -$severity = (int) get_parameter ("severity", -1); // -1 all -$status = (int) get_parameter ("status", 0); // -1 all, 0 only red, 1 only green -$id_agent = (int) get_parameter ("id_agent", -1); +set_error_handler('rss_error_handler', E_ERROR); +// Errors output as RSS +$id_group = get_parameter('id_group', 0); +// group +$event_type = get_parameter('event_type', ''); +// 0 all +$severity = (int) get_parameter('severity', -1); +// -1 all +$status = (int) get_parameter('status', 0); +// -1 all, 0 only red, 1 only green +$id_agent = (int) get_parameter('id_agent', -1); -$id_event = (int) get_parameter ("id_event", -1); //This will allow to select only 1 event (eg. RSS) -$event_view_hr = (int) get_parameter ("event_view_hr", 0); -$id_user_ack = get_parameter ("id_user_ack", 0); -$search = io_safe_output(preg_replace ("/&([A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", rawurldecode (get_parameter ("search")))); -$text_agent = (string) get_parameter("text_agent", __("All")); +$id_event = (int) get_parameter('id_event', -1); +// This will allow to select only 1 event (eg. RSS) +$event_view_hr = (int) get_parameter('event_view_hr', 0); +$id_user_ack = get_parameter('id_user_ack', 0); +$search = io_safe_output(preg_replace('/&([A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&', rawurldecode(get_parameter('search')))); +$text_agent = (string) get_parameter('text_agent', __('All')); -$tag_with_json = base64_decode(get_parameter("tag_with", '')) ; +$tag_with_json = base64_decode(get_parameter('tag_with', '')); $tag_with_json_clean = io_safe_output($tag_with_json); $tag_with_base64 = base64_encode($tag_with_json_clean); $tag_with = json_decode($tag_with_json_clean, true); -if (empty($tag_with)) $tag_with = array(); -$tag_with = array_diff($tag_with, array(0 => 0)); +if (empty($tag_with)) { + $tag_with = []; +} -$tag_without_json = base64_decode(get_parameter("tag_without", '')); +$tag_with = array_diff($tag_with, [0 => 0]); + +$tag_without_json = base64_decode(get_parameter('tag_without', '')); $tag_without_json_clean = io_safe_output($tag_without_json); $tag_without_base64 = base64_encode($tag_without_json_clean); $tag_without = json_decode($tag_without_json_clean, true); -if (empty($tag_without)) $tag_without = array(); -$tag_without = array_diff($tag_without, array(0 => 0)); +if (empty($tag_without)) { + $tag_without = []; +} -$filter_only_alert = (int)get_parameter('filter_only_alert', -1); +$tag_without = array_diff($tag_without, [0 => 0]); -//////////////////////////////////////////////////////////////////////// +$filter_only_alert = (int) get_parameter('filter_only_alert', -1); + +// // Build the condition of the events query -$sql_post = ""; +$sql_post = ''; $meta = false; $id_user = $user; -require('events.build_query.php'); +require 'events.build_query.php'; // Now $sql_post have all the where condition -//////////////////////////////////////////////////////////////////////// - -$sql = "SELECT * +// +$sql = 'SELECT * FROM tevento te LEFT JOIN tagent_secondary_group tasg ON te.id_grupo = tasg.id_group - WHERE 1=1 " . $sql_post . " - ORDER BY utimestamp DESC"; + WHERE 1=1 '.$sql_post.' + ORDER BY utimestamp DESC'; -$result = db_get_all_rows_sql ($sql); +$result = db_get_all_rows_sql($sql); $url = ui_get_full_url(false); -$selfurl = ui_get_full_url('?' . $_SERVER['QUERY_STRING'], false, true); +$selfurl = ui_get_full_url('?'.$_SERVER['QUERY_STRING'], false, true); -if (empty ($result)) { - $lastbuild = 0; //Last build in 1970 -} -else { - $lastbuild = (int) $result[0]['utimestamp']; +if (empty($result)) { + $lastbuild = 0; + // Last build in 1970 +} else { + $lastbuild = (int) $result[0]['utimestamp']; } -$rss_feed = '' . "\n"; // ' ' . "\n"; -$rss_feed .= ''. "\n"; -$rss_feed .= '' . get_product_name() . ' RSS Feed'. "\n"; -$rss_feed .= 'Latest events on ' . get_product_name() . '' . "\n"; -$rss_feed .= ''.date (DATE_RFC822, $lastbuild).''. "\n"; //Last build date is the last event - that way readers won't mark it as having new posts -$rss_feed .= ''.$url.''. "\n"; //Link back to the main Pandora page -$rss_feed .= ''. "\n";; //Alternative for Atom feeds. It's the same. - -if (empty ($result)) { - $result = array(); - $rss_feed .= '' . xml_entities(io_safe_input ($url.'/index.php?sec=eventos&sec2=operation/events/events')) . 'No results'; - $rss_feed .= 'There are no results. Click on the link to see all Pending events'; - $rss_feed .= '' . xml_entities(io_safe_input ($url.'/index.php?sec=eventos&sec2=operation/events/events')) . ''. "\n"; +$rss_feed = ''."\n"; +// ' '."\n"; +$rss_feed .= ''."\n"; +$rss_feed .= ''.get_product_name().' RSS Feed'."\n"; +$rss_feed .= 'Latest events on '.get_product_name().''."\n"; +$rss_feed .= ''.date(DATE_RFC822, $lastbuild).''."\n"; +// Last build date is the last event - that way readers won't mark it as having new posts +$rss_feed .= ''.$url.''."\n"; +// Link back to the main Pandora page +$rss_feed .= ''."\n"; +; +// Alternative for Atom feeds. It's the same. +if (empty($result)) { + $result = []; + $rss_feed .= ''.xml_entities(io_safe_input($url.'/index.php?sec=eventos&sec2=operation/events/events')).'No results'; + $rss_feed .= 'There are no results. Click on the link to see all Pending events'; + $rss_feed .= ''.xml_entities(io_safe_input($url.'/index.php?sec=eventos&sec2=operation/events/events')).''."\n"; } foreach ($result as $row) { - if (!check_acl($user, $row["id_grupo"], "ER")) { - continue; - } - if ($row["event_type"] == "system") { - $agent_name = __('System'); - } - elseif ($row["id_agente"] > 0) { - // Agent name - $agent_name = agents_get_alias($row["id_agente"]); - } - else { - $agent_name = __('Alert').__('SNMP'); - } - - //This is mandatory - $rss_feed .= ''; - $rss_feed .= xml_entities(io_safe_input($url . "/index.php?sec=eventos&sec2=operation/events/events&id_event=" . $row['id_evento'])); - $rss_feed .= ''; - $rss_feed .= xml_entities($agent_name); - $rss_feed .= ''; - $rss_feed .= xml_entities($row['evento']); - if ($row['estado'] == 1) { - $rss_feed .= xml_entities(io_safe_input('

                '.'Validated by ' . $row['id_usuario'])); - } - $rss_feed .= '
                '; - $rss_feed .= xml_entities(io_safe_input($url . "/index.php?sec=eventos&sec2=operation/events/events&id_event=" . $row["id_evento"])); - $rss_feed .= ''; + if (!check_acl($user, $row['id_grupo'], 'ER')) { + continue; + } -//The rest is optional - $rss_feed .= '' . date(DATE_RFC822, $row['utimestamp']) . ''; - -//This is mandatory again - $rss_feed .= '
                ' . "\n"; + if ($row['event_type'] == 'system') { + $agent_name = __('System'); + } else if ($row['id_agente'] > 0) { + // Agent name + $agent_name = agents_get_alias($row['id_agente']); + } else { + $agent_name = __('Alert').__('SNMP'); + } + + // This is mandatory + $rss_feed .= ''; + $rss_feed .= xml_entities(io_safe_input($url.'/index.php?sec=eventos&sec2=operation/events/events&id_event='.$row['id_evento'])); + $rss_feed .= ''; + $rss_feed .= xml_entities($agent_name); + $rss_feed .= ''; + $rss_feed .= xml_entities($row['evento']); + if ($row['estado'] == 1) { + $rss_feed .= xml_entities(io_safe_input('

                '.'Validated by '.$row['id_usuario'])); + } + + $rss_feed .= '
                '; + $rss_feed .= xml_entities(io_safe_input($url.'/index.php?sec=eventos&sec2=operation/events/events&id_event='.$row['id_evento'])); + $rss_feed .= ''; + + // The rest is optional + $rss_feed .= ''.date(DATE_RFC822, $row['utimestamp']).''; + + // This is mandatory again + $rss_feed .= '
                '."\n"; } $rss_feed .= "
                \n\n"; @@ -212,33 +240,33 @@ $rss_feed .= "
                \n\n"; echo $rss_feed; -function xml_entities($str) { - - if (!is_string($str)) { - return ""; - } - - if (preg_match_all('/(&[^;]+;)/', $str, $matches) != 0) { - - $matches = $matches[0]; - - foreach ($matches as $entity) { - $char = html_entity_decode($entity, ENT_COMPAT | ENT_HTML401, 'UTF-8'); - - $html_entity_numeric = "&#" . uniord($char) . ";"; - - $str = str_replace($entity, $html_entity_numeric, $str); - } - } - - return $str; +function xml_entities($str) +{ + if (!is_string($str)) { + return ''; + } + + if (preg_match_all('/(&[^;]+;)/', $str, $matches) != 0) { + $matches = $matches[0]; + + foreach ($matches as $entity) { + $char = html_entity_decode($entity, (ENT_COMPAT | ENT_HTML401), 'UTF-8'); + + $html_entity_numeric = '&#'.uniord($char).';'; + + $str = str_replace($entity, $html_entity_numeric, $str); + } + } + + return $str; } -function uniord($u) { - $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8'); - $k1 = ord(substr($k, 0, 1)); - $k2 = ord(substr($k, 1, 1)); - - return $k2 * 256 + $k1; + +function uniord($u) +{ + $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8'); + $k1 = ord(substr($k, 0, 1)); + $k2 = ord(substr($k, 1, 1)); + + return ($k2 * 256 + $k1); } -?> diff --git a/pandora_console/operation/events/export_csv.php b/pandora_console/operation/events/export_csv.php index 84c3e849e8..dbc20abb6a 100644 --- a/pandora_console/operation/events/export_csv.php +++ b/pandora_console/operation/events/export_csv.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2009 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,139 +11,146 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Don't start a session before this import. // The session is configured and started inside the config process. -require_once ("../../include/config.php"); -require_once ("../../include/auth/mysql.php"); -require_once ("../../include/functions.php"); -require_once ("../../include/functions_db.php"); -require_once ("../../include/functions_events.php"); -require_once ("../../include/functions_agents.php"); -require_once ('../../include/functions_groups.php'); +require_once '../../include/config.php'; +require_once '../../include/auth/mysql.php'; +require_once '../../include/functions.php'; +require_once '../../include/functions_db.php'; +require_once '../../include/functions_events.php'; +require_once '../../include/functions_agents.php'; +require_once '../../include/functions_groups.php'; -$config["id_user"] = $_SESSION["id_usuario"]; +$config['id_user'] = $_SESSION['id_usuario']; -if (! check_acl ($config["id_user"], 0, "ER") && ! check_acl ($config["id_user"], 0, "EW") && ! check_acl ($config["id_user"], 0, "EM")) { - exit; +if (! check_acl($config['id_user'], 0, 'ER') && ! check_acl($config['id_user'], 0, 'EW') && ! check_acl($config['id_user'], 0, 'EM')) { + exit; } global $config; // loading l10n tables, because of being invoked not through index.php. -$l10n = NULL; -if (file_exists ($config['homedir'].'/include/languages/'.$user_language.'.mo')) { - $l10n = new gettext_reader (new CachedFileReader ($config['homedir'].'/include/languages/'.$user_language.'.mo')); - $l10n->load_tables(); +$l10n = null; +if (file_exists($config['homedir'].'/include/languages/'.$user_language.'.mo')) { + $l10n = new gettext_reader(new CachedFileReader($config['homedir'].'/include/languages/'.$user_language.'.mo')); + $l10n->load_tables(); } -$offset = (int) get_parameter ("offset"); -$id_group = (int) get_parameter ("id_group"); // group -$event_type = (string) get_parameter ("event_type", "all"); // 0 all -$severity = (int) get_parameter ("severity", -1); // -1 all -$status = (int) get_parameter ("status", -1); // -1 all, 0 only red, 1 only green -$id_agent = (int) get_parameter ("id_agent", -1); +$offset = (int) get_parameter('offset'); +$id_group = (int) get_parameter('id_group'); +// group +$event_type = (string) get_parameter('event_type', 'all'); +// 0 all +$severity = (int) get_parameter('severity', -1); +// -1 all +$status = (int) get_parameter('status', -1); +// -1 all, 0 only red, 1 only green +$id_agent = (int) get_parameter('id_agent', -1); -$id_event = (int) get_parameter ("id_event", -1); -$event_view_hr = (int) get_parameter ("event_view_hr", $config["event_view_hr"]); -$id_user_ack = get_parameter ("id_user_ack", 0); -$search = io_safe_output(preg_replace ("/&([A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", rawurldecode (get_parameter ("search")))); -$text_agent = (string)get_parameter('text_agent', __("All")); +$id_event = (int) get_parameter('id_event', -1); +$event_view_hr = (int) get_parameter('event_view_hr', $config['event_view_hr']); +$id_user_ack = get_parameter('id_user_ack', 0); +$search = io_safe_output(preg_replace('/&([A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&', rawurldecode(get_parameter('search')))); +$text_agent = (string) get_parameter('text_agent', __('All')); -$tag_with_json = base64_decode(get_parameter("tag_with", '')) ; +$tag_with_json = base64_decode(get_parameter('tag_with', '')); $tag_with_json_clean = io_safe_output($tag_with_json); $tag_with_base64 = base64_encode($tag_with_json_clean); $tag_with = json_decode($tag_with_json_clean, true); -if (empty($tag_with)) $tag_with = array(); -$tag_with = array_diff($tag_with, array(0 => 0)); +if (empty($tag_with)) { + $tag_with = []; +} -$tag_without_json = base64_decode(get_parameter("tag_without", '')); +$tag_with = array_diff($tag_with, [0 => 0]); + +$tag_without_json = base64_decode(get_parameter('tag_without', '')); $tag_without_json_clean = io_safe_output($tag_without_json); $tag_without_base64 = base64_encode($tag_without_json_clean); $tag_without = json_decode($tag_without_json_clean, true); -if (empty($tag_without)) $tag_without = array(); -$tag_without = array_diff($tag_without, array(0 => 0)); +if (empty($tag_without)) { + $tag_without = []; +} -$filter_only_alert = (int)get_parameter('filter_only_alert', -1); +$tag_without = array_diff($tag_without, [0 => 0]); -///////////////////////////////////////////// +$filter_only_alert = (int) get_parameter('filter_only_alert', -1); + +// // Build the condition of the events query - -$sql_post = ""; +$sql_post = ''; $meta = false; $id_user = $config['id_user']; -require('events.build_query.php'); +require 'events.build_query.php'; // Now $sql_post have all the where condition -///////////////////////////////////////////// - -switch ($config["dbtype"]) { - case "mysql": - case "postgresql": - case "oracle": - $sql = "SELECT * +// +switch ($config['dbtype']) { + case 'mysql': + case 'postgresql': + case 'oracle': + $sql = 'SELECT * FROM tevento te LEFT JOIN tagent_secondary_group tasg ON te.id_grupo = tasg.id_group - WHERE 1=1 ".$sql_post." - ORDER BY utimestamp DESC"; - break; + WHERE 1=1 '.$sql_post.' + ORDER BY utimestamp DESC'; + break; } -$now = date ("Y-m-d"); +$now = date('Y-m-d'); -// Show contentype header -Header ("Content-type: text/txt"); -header ('Content-Disposition: attachment; filename="pandora_export_event'.$now.'.csv"'); +// Show contentype header +header('Content-type: text/txt'); +header('Content-Disposition: attachment; filename="pandora_export_event'.$now.'.csv"'); -echo "timestamp"; -echo $config["csv_divider"]; -echo "agent"; -echo $config["csv_divider"]; -echo "group"; -echo $config["csv_divider"]; -echo "event"; -echo $config["csv_divider"]; -echo "status"; -echo $config["csv_divider"]; -echo "user"; -echo $config["csv_divider"]; -echo "event_type"; -echo $config["csv_divider"]; -echo "severity"; -echo $config["csv_divider"]; -echo "id"; -echo chr (13); +echo 'timestamp'; +echo $config['csv_divider']; +echo 'agent'; +echo $config['csv_divider']; +echo 'group'; +echo $config['csv_divider']; +echo 'event'; +echo $config['csv_divider']; +echo 'status'; +echo $config['csv_divider']; +echo 'user'; +echo $config['csv_divider']; +echo 'event_type'; +echo $config['csv_divider']; +echo 'severity'; +echo $config['csv_divider']; +echo 'id'; +echo chr(13); $new = true; while ($event = db_get_all_row_by_steps_sql($new, $result, $sql)) { - $new = false; - $alias = db_get_value ("alias","tagente","id_agente",$event["id_agente"]); - if ((!check_acl($config["id_user"], $event["id_grupo"], "ER") && - !check_acl($config["id_user"], $event["id_grupo"], "EW") && !check_acl($config["id_user"], $event["id_grupo"], "EM") ) || - (!check_acl($config["id_user"], 0, "PM") && $event["event_type"] == 'system')) - continue; - - echo date($config["date_format"], $event["utimestamp"]); - echo $config["csv_divider"]; - echo io_safe_output($alias); - echo $config["csv_divider"]; - echo io_safe_output(groups_get_name($event["id_grupo"])); - echo $config["csv_divider"]; - echo io_safe_output($event["evento"]); - echo $config["csv_divider"]; - echo io_safe_output($event["estado"]); - echo $config["csv_divider"]; - echo io_safe_output($event["id_usuario"]); - echo $config["csv_divider"]; - echo io_safe_output($event["event_type"]); - echo $config["csv_divider"]; - echo $event["criticity"]; - echo $config["csv_divider"]; - echo $event["id_evento"]; - echo chr (13); -} -?> + $new = false; + $alias = db_get_value('alias', 'tagente', 'id_agente', $event['id_agente']); + if ((!check_acl($config['id_user'], $event['id_grupo'], 'ER') + && !check_acl($config['id_user'], $event['id_grupo'], 'EW') && !check_acl($config['id_user'], $event['id_grupo'], 'EM') ) + || (!check_acl($config['id_user'], 0, 'PM') && $event['event_type'] == 'system') + ) { + continue; + } + echo date($config['date_format'], $event['utimestamp']); + echo $config['csv_divider']; + echo io_safe_output($alias); + echo $config['csv_divider']; + echo io_safe_output(groups_get_name($event['id_grupo'])); + echo $config['csv_divider']; + echo io_safe_output($event['evento']); + echo $config['csv_divider']; + echo io_safe_output($event['estado']); + echo $config['csv_divider']; + echo io_safe_output($event['id_usuario']); + echo $config['csv_divider']; + echo io_safe_output($event['event_type']); + echo $config['csv_divider']; + echo $event['criticity']; + echo $config['csv_divider']; + echo $event['id_evento']; + echo chr(13); +} diff --git a/pandora_console/operation/events/sound_events.php b/pandora_console/operation/events/sound_events.php index a7fbce6667..1bd1dcc444 100644 --- a/pandora_console/operation/events/sound_events.php +++ b/pandora_console/operation/events/sound_events.php @@ -4,7 +4,6 @@ // ================================================== // Copyright (c) 2005-2010 Artica Soluciones Tecnologicas // Please see http://pandorafms.org for full contribution list - // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation for version 2. @@ -12,54 +11,53 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. - // Don't start a session before this import. // The session is configured and started inside the config process. -require_once ('../../include/config.php'); -require_once ('../../include/functions.php'); -require_once ('../../include/functions_db.php'); -require_once ('../../include/auth/mysql.php'); +require_once '../../include/config.php'; +require_once '../../include/functions.php'; +require_once '../../include/functions_db.php'; +require_once '../../include/auth/mysql.php'; global $config; // Check user -check_login (); -$config["id_user"] = $_SESSION["id_usuario"]; +check_login(); +$config['id_user'] = $_SESSION['id_usuario']; -$event_a = check_acl ($config['id_user'], 0, "ER"); -$event_w = check_acl ($config['id_user'], 0, "EW"); -$event_m = check_acl ($config['id_user'], 0, "EM"); +$event_a = check_acl($config['id_user'], 0, 'ER'); +$event_w = check_acl($config['id_user'], 0, 'EW'); +$event_m = check_acl($config['id_user'], 0, 'EM'); $access = ($event_a == true) ? 'ER' : (($event_w == true) ? 'EW' : (($event_m == true) ? 'EM' : 'ER')); -if (! check_acl ($config['id_user'], 0, "ER") && ! check_acl ($config['id_user'], 0, "EW") && ! check_acl ($config['id_user'], 0, "EM")) { - db_pandora_audit("ACL Violation","Trying to access event viewer"); - require ("general/noaccess.php"); - - return; +if (! check_acl($config['id_user'], 0, 'ER') && ! check_acl($config['id_user'], 0, 'EW') && ! check_acl($config['id_user'], 0, 'EM')) { + db_pandora_audit('ACL Violation', 'Trying to access event viewer'); + include 'general/noaccess.php'; + + return; } -$agents = agents_get_group_agents(0, false, "none", false, true); +$agents = agents_get_group_agents(0, false, 'none', false, true); -echo ""; -echo ""; -echo "" . __("Sound Events") . ""; +echo ''; +echo ''; +echo ''.__('Sound Events').''; ?> '; +echo ''; echo ''; -echo ""; +echo ''; echo ""; -echo "

                " . __("Sound console"). "

                "; +echo "

                ".__('Sound console').'

                '; $table = null; $table->width = '100%'; @@ -71,19 +69,16 @@ $table->style[1] = 'font-weight: bold; vertical-align: top;'; $table->style[2] = 'font-weight: bold; vertical-align: top;'; $table->data[0][0] = __('Group'); -$table->data[0][1] = html_print_select_groups(false, $access, true, 'group', '', 'changeGroup();', '', 0, true, false, true, '', false, 'max-width:200px;') . '
                ' . '
                '; +$table->data[0][1] = html_print_select_groups(false, $access, true, 'group', '', 'changeGroup();', '', 0, true, false, true, '', false, 'max-width:200px;').'
                '.'
                '; $table->data[0][2] = __('Type'); -$table->data[0][3] = html_print_checkbox('alert_fired', 'alert_fired', true, true, false, 'changeType();') . __('Alert fired') . '
                ' . - html_print_checkbox('critical', 'critical', true, true, false, 'changeType();') . __('Monitor critical') . '
                ' . - html_print_checkbox('unknown', 'unknown', true, true, false, 'changeType();') . __('Monitor unknown') . '
                ' . - html_print_checkbox('warning', 'warning', true, true, false, 'changeType();') . __('Monitor warning') . '
                '; +$table->data[0][3] = html_print_checkbox('alert_fired', 'alert_fired', true, true, false, 'changeType();').__('Alert fired').'
                '.html_print_checkbox('critical', 'critical', true, true, false, 'changeType();').__('Monitor critical').'
                '.html_print_checkbox('unknown', 'unknown', true, true, false, 'changeType();').__('Monitor unknown').'
                '.html_print_checkbox('warning', 'warning', true, true, false, 'changeType();').__('Monitor warning').'
                '; $table->data[1][0] = __('Agent'); -$table->data[1][1] = html_print_select($agents, 'id_agents[]', true, false, '', '', true, true,'','','','width:120px; height:100px','',false,'','',true); +$table->data[1][1] = html_print_select($agents, 'id_agents[]', true, false, '', '', true, true, '', '', '', 'width:120px; height:100px', '', false, '', '', true); $table->data[1][2] = __('Event'); -$table->data[1][3] = html_print_textarea ("events_fired", 200, 20, '', 'readonly="readonly" style="max-height:100px; background: #ddd; resize:none;"', true); +$table->data[1][3] = html_print_textarea('events_fired', 200, 20, '', 'readonly="readonly" style="max-height:100px; background: #ddd; resize:none;"', true); html_print_table($table); @@ -94,22 +89,15 @@ $table->styleTable = 'padding-top:16px;padding-bottom:16px;'; $table->class = ' '; $table->bgcolor = 'white'; -$table->data[0][0] = '' . - html_print_image("images/play.button.png", true, array("id" => "button")) . - ''; +$table->data[0][0] = ''.html_print_image('images/play.button.png', true, ['id' => 'button']).''; -$table->data[0][1] .= '' . - html_print_image("images/ok.button.png", true, array("style" => "margin-left: 15px;")) . - ''; +$table->data[0][1] .= ''.html_print_image('images/ok.button.png', true, ['style' => 'margin-left: 15px;']).''; -$table->data[0][2] .= '' . - html_print_image("images/icono_test.png", true, array("id" => "button_try", "style" => "margin-left: 15px;")) . - ''; +$table->data[0][2] .= ''.html_print_image('images/icono_test.png', true, ['id' => 'button_try', 'style' => 'margin-left: 15px;']).''; + +$table->data[0][3] .= html_print_image('images/tick_sound_events.png', true, ['id' => 'button_status', 'style' => 'margin-left: 15px;']); -$table->data[0][3] .= html_print_image("images/tick_sound_events.png", true, array("id" => "button_status", "style" => "margin-left: 15px;")); - html_print_table($table); - ?> @@ -130,154 +118,154 @@ var button_play_status = "play"; var test_sound = false; function test_sound_button() { - if (!test_sound) { - $("#button_try").attr('src', '../../images/icono_test.png'); - $('body').append("